Update website to show 7.8.01 as current release
[org-mode/org-mode-NeilSmithlineMods.git] / lisp / org.el
blob476173889945a5e3bf720fe17e5e244815185f1f
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.01
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.01"
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 ":" (org-link-escape
9573 path org-link-escape-chars-browser))))
9575 ((string= type "doi")
9576 (browse-url (concat "http://dx.doi.org/"
9577 (org-link-escape
9578 path org-link-escape-chars-browser))))
9580 ((member type '("message"))
9581 (browse-url (concat type ":" path)))
9583 ((string= type "tags")
9584 (org-tags-view arg path))
9586 ((string= type "tree-match")
9587 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9589 ((string= type "file")
9590 (if (string-match "::\\([0-9]+\\)\\'" path)
9591 (setq line (string-to-number (match-string 1 path))
9592 path (substring path 0 (match-beginning 0)))
9593 (if (string-match "::\\(.+\\)\\'" path)
9594 (setq search (match-string 1 path)
9595 path (substring path 0 (match-beginning 0)))))
9596 (if (string-match "[*?{]" (file-name-nondirectory path))
9597 (dired path)
9598 (org-open-file path arg line search)))
9600 ((string= type "shell")
9601 (let ((cmd path))
9602 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9603 (string-match org-confirm-shell-link-not-regexp cmd))
9604 (not org-confirm-shell-link-function)
9605 (funcall org-confirm-shell-link-function
9606 (format "Execute \"%s\" in shell? "
9607 (org-add-props cmd nil
9608 'face 'org-warning))))
9609 (progn
9610 (message "Executing %s" cmd)
9611 (shell-command cmd))
9612 (error "Abort"))))
9614 ((string= type "elisp")
9615 (let ((cmd path))
9616 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9617 (string-match org-confirm-elisp-link-not-regexp cmd))
9618 (not org-confirm-elisp-link-function)
9619 (funcall org-confirm-elisp-link-function
9620 (format "Execute \"%s\" as elisp? "
9621 (org-add-props cmd nil
9622 'face 'org-warning))))
9623 (message "%s => %s" cmd
9624 (if (equal (string-to-char cmd) ?\()
9625 (eval (read cmd))
9626 (call-interactively (read cmd))))
9627 (error "Abort"))))
9629 ((and (string= type "thisfile")
9630 (run-hook-with-args-until-success
9631 'org-open-link-functions path)))
9633 ((string= type "thisfile")
9634 (if arg
9635 (switch-to-buffer-other-window
9636 (org-get-buffer-for-internal-link (current-buffer)))
9637 (org-mark-ring-push))
9638 (let ((cmd `(org-link-search
9639 ,path
9640 ,(cond ((equal arg '(4)) ''occur)
9641 ((equal arg '(16)) ''org-occur)
9642 (t nil))
9643 ,pos)))
9644 (condition-case nil (let ((org-link-search-inhibit-query t))
9645 (eval cmd))
9646 (error (progn (widen) (eval cmd))))))
9649 (browse-url-at-point)))))))
9650 (move-marker org-open-link-marker nil)
9651 (run-hook-with-args 'org-follow-link-hook)))
9653 (defun org-offer-links-in-entry (&optional nth zero)
9654 "Offer links in the current entry and follow the selected link.
9655 If there is only one link, follow it immediately as well.
9656 If NTH is an integer, immediately pick the NTH link found.
9657 If ZERO is a string, check also this string for a link, and if
9658 there is one, offer it as link number zero."
9659 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9660 "\\(" org-angle-link-re "\\)\\|"
9661 "\\(" org-plain-link-re "\\)"))
9662 (cnt ?0)
9663 (in-emacs (if (integerp nth) nil nth))
9664 have-zero end links link c)
9665 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9666 (push (match-string 0 zero) links)
9667 (setq cnt (1- cnt) have-zero t))
9668 (save-excursion
9669 (org-back-to-heading t)
9670 (setq end (save-excursion (outline-next-heading) (point)))
9671 (while (re-search-forward re end t)
9672 (push (match-string 0) links))
9673 (setq links (org-uniquify (reverse links))))
9675 (cond
9676 ((null links)
9677 (message "No links"))
9678 ((equal (length links) 1)
9679 (setq link (list (car links))))
9680 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9681 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9682 (t ; we have to select a link
9683 (save-excursion
9684 (save-window-excursion
9685 (delete-other-windows)
9686 (with-output-to-temp-buffer "*Select Link*"
9687 (mapc (lambda (l)
9688 (if (not (string-match org-bracket-link-regexp l))
9689 (princ (format "[%c] %s\n" (incf cnt)
9690 (org-remove-angle-brackets l)))
9691 (if (match-end 3)
9692 (princ (format "[%c] %s (%s)\n" (incf cnt)
9693 (match-string 3 l) (match-string 1 l)))
9694 (princ (format "[%c] %s\n" (incf cnt)
9695 (match-string 1 l))))))
9696 links))
9697 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9698 (message "Select link to open, RET to open all:")
9699 (setq c (read-char-exclusive))
9700 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9701 (when (equal c ?q) (error "Abort"))
9702 (if (equal c ?\C-m)
9703 (setq link links)
9704 (setq nth (- c ?0))
9705 (if have-zero (setq nth (1+ nth)))
9706 (unless (and (integerp nth) (>= (length links) nth))
9707 (error "Invalid link selection"))
9708 (setq link (list (nth (1- nth) links))))))
9709 (if link
9710 (let ((buf (current-buffer)))
9711 (dolist (l link)
9712 (org-open-link-from-string l in-emacs buf))
9714 nil)))
9716 ;; Add special file links that specify the way of opening
9718 (org-add-link-type "file+sys" 'org-open-file-with-system)
9719 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9720 (defun org-open-file-with-system (path)
9721 "Open file at PATH using the system way of opening it."
9722 (org-open-file path 'system))
9723 (defun org-open-file-with-emacs (path)
9724 "Open file at PATH in Emacs."
9725 (org-open-file path 'emacs))
9726 (defun org-remove-file-link-modifiers ()
9727 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9728 (goto-char (point-min))
9729 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9730 (org-if-unprotected
9731 (replace-match "file:" t t))))
9732 (eval-after-load "org-exp"
9733 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9734 'org-remove-file-link-modifiers))
9736 ;;;; Time estimates
9738 (defun org-get-effort (&optional pom)
9739 "Get the effort estimate for the current entry."
9740 (org-entry-get pom org-effort-property))
9742 ;;; File search
9744 (defvar org-create-file-search-functions nil
9745 "List of functions to construct the right search string for a file link.
9746 These functions are called in turn with point at the location to
9747 which the link should point.
9749 A function in the hook should first test if it would like to
9750 handle this file type, for example by checking the `major-mode'
9751 or the file extension. If it decides not to handle this file, it
9752 should just return nil to give other functions a chance. If it
9753 does handle the file, it must return the search string to be used
9754 when following the link. The search string will be part of the
9755 file link, given after a double colon, and `org-open-at-point'
9756 will automatically search for it. If special measures must be
9757 taken to make the search successful, another function should be
9758 added to the companion hook `org-execute-file-search-functions',
9759 which see.
9761 A function in this hook may also use `setq' to set the variable
9762 `description' to provide a suggestion for the descriptive text to
9763 be used for this link when it gets inserted into an Org-mode
9764 buffer with \\[org-insert-link].")
9766 (defvar org-execute-file-search-functions nil
9767 "List of functions to execute a file search triggered by a link.
9769 Functions added to this hook must accept a single argument, the
9770 search string that was part of the file link, the part after the
9771 double colon. The function must first check if it would like to
9772 handle this search, for example by checking the `major-mode' or
9773 the file extension. If it decides not to handle this search, it
9774 should just return nil to give other functions a chance. If it
9775 does handle the search, it must return a non-nil value to keep
9776 other functions from trying.
9778 Each function can access the current prefix argument through the
9779 variable `current-prefix-argument'. Note that a single prefix is
9780 used to force opening a link in Emacs, so it may be good to only
9781 use a numeric or double prefix to guide the search function.
9783 In case this is needed, a function in this hook can also restore
9784 the window configuration before `org-open-at-point' was called using:
9786 (set-window-configuration org-window-config-before-follow-link)")
9788 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9789 (defun org-link-search (s &optional type avoid-pos stealth)
9790 "Search for a link search option.
9791 If S is surrounded by forward slashes, it is interpreted as a
9792 regular expression. In org-mode files, this will create an `org-occur'
9793 sparse tree. In ordinary files, `occur' will be used to list matches.
9794 If the current buffer is in `dired-mode', grep will be used to search
9795 in all files. If AVOID-POS is given, ignore matches near that position.
9797 When optional argument STEALTH is non-nil, do not modify
9798 visibility around point, thus ignoring
9799 `org-show-hierarchy-above', `org-show-following-heading' and
9800 `org-show-siblings' variables."
9801 (let ((case-fold-search t)
9802 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9803 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9804 (append '(("") (" ") ("\t") ("\n"))
9805 org-emphasis-alist)
9806 "\\|") "\\)"))
9807 (pos (point))
9808 (pre nil) (post nil)
9809 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9810 (cond
9811 ;; First check if there are any special search functions
9812 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9813 ;; Now try the builtin stuff
9814 ((and (equal (string-to-char s0) ?#)
9815 (> (length s0) 1)
9816 (save-excursion
9817 (goto-char (point-min))
9818 (and
9819 (re-search-forward
9820 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9821 (setq type 'dedicated
9822 pos (match-beginning 0))))
9823 ;; There is an exact target for this
9824 (goto-char pos)
9825 (org-back-to-heading t)))
9826 ((save-excursion
9827 (goto-char (point-min))
9828 (and
9829 (re-search-forward
9830 (concat "<<" (regexp-quote s0) ">>") nil t)
9831 (setq type 'dedicated
9832 pos (match-beginning 0))))
9833 ;; There is an exact target for this
9834 (goto-char pos))
9835 ((and (string-match "^(\\(.*\\))$" s0)
9836 (save-excursion
9837 (goto-char (point-min))
9838 (and
9839 (re-search-forward
9840 (concat "[^[]" (regexp-quote
9841 (format org-coderef-label-format
9842 (match-string 1 s0))))
9843 nil t)
9844 (setq type 'dedicated
9845 pos (1+ (match-beginning 0))))))
9846 ;; There is a coderef target for this
9847 (goto-char pos))
9848 ((string-match "^/\\(.*\\)/$" s)
9849 ;; A regular expression
9850 (cond
9851 ((eq major-mode 'org-mode)
9852 (org-occur (match-string 1 s)))
9853 ;;((eq major-mode 'dired-mode)
9854 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9855 (t (org-do-occur (match-string 1 s)))))
9856 ((and (eq major-mode 'org-mode) org-link-search-must-match-exact-headline)
9857 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9858 (goto-char (point-min))
9859 (cond
9860 ((let (case-fold-search)
9861 (re-search-forward (format org-complex-heading-regexp-format
9862 (regexp-quote s))
9863 nil t))
9864 ;; OK, found a match
9865 (setq type 'dedicated)
9866 (goto-char (match-beginning 0)))
9867 ((and (not org-link-search-inhibit-query)
9868 (eq org-link-search-must-match-exact-headline 'query-to-create)
9869 (y-or-n-p "No match - create this as a new heading? "))
9870 (goto-char (point-max))
9871 (or (bolp) (newline))
9872 (insert "* " s "\n")
9873 (beginning-of-line 0))
9875 (goto-char pos)
9876 (error "No match"))))
9878 ;; A normal search string
9879 (when (equal (string-to-char s) ?*)
9880 ;; Anchor on headlines, post may include tags.
9881 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9882 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9883 s (substring s 1)))
9884 (remove-text-properties
9885 0 (length s)
9886 '(face nil mouse-face nil keymap nil fontified nil) s)
9887 ;; Make a series of regular expressions to find a match
9888 (setq words (org-split-string s "[ \n\r\t]+")
9890 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9891 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9892 "\\)" markers)
9893 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9894 re2a (concat "[ \t\r\n]" re2a_)
9895 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9896 re4 (concat "[^a-zA-Z_]" re4_)
9898 re1 (concat pre re2 post)
9899 re3 (concat pre (if pre re4_ re4) post)
9900 re5 (concat pre ".*" re4)
9901 re2 (concat pre re2)
9902 re2a (concat pre (if pre re2a_ re2a))
9903 re4 (concat pre (if pre re4_ re4))
9904 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9905 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9906 re5 "\\)"
9908 (cond
9909 ((eq type 'org-occur) (org-occur reall))
9910 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9911 (t (goto-char (point-min))
9912 (setq type 'fuzzy)
9913 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9914 (org-search-not-self 1 re1 nil t)
9915 (org-search-not-self 1 re2 nil t)
9916 (org-search-not-self 1 re2a nil t)
9917 (org-search-not-self 1 re3 nil t)
9918 (org-search-not-self 1 re4 nil t)
9919 (org-search-not-self 1 re5 nil t)
9921 (goto-char (match-beginning 1))
9922 (goto-char pos)
9923 (error "No match"))))))
9924 (and (eq major-mode 'org-mode)
9925 (not stealth)
9926 (org-show-context 'link-search))
9927 type))
9929 (defun org-search-not-self (group &rest args)
9930 "Execute `re-search-forward', but only accept matches that do not
9931 enclose the position of `org-open-link-marker'."
9932 (let ((m org-open-link-marker))
9933 (catch 'exit
9934 (while (apply 're-search-forward args)
9935 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9936 (goto-char (match-end group))
9937 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9938 (> (match-beginning 0) (marker-position m))
9939 (< (match-end 0) (marker-position m)))
9940 (save-match-data
9941 (or (not (org-in-regexp
9942 org-bracket-link-analytic-regexp 1))
9943 (not (match-end 4)) ; no description
9944 (and (<= (match-beginning 4) (point))
9945 (>= (match-end 4) (point))))))
9946 (throw 'exit (point))))))))
9948 (defun org-get-buffer-for-internal-link (buffer)
9949 "Return a buffer to be used for displaying the link target of internal links."
9950 (cond
9951 ((not org-display-internal-link-with-indirect-buffer)
9952 buffer)
9953 ((string-match "(Clone)$" (buffer-name buffer))
9954 (message "Buffer is already a clone, not making another one")
9955 ;; we also do not modify visibility in this case
9956 buffer)
9957 (t ; make a new indirect buffer for displaying the link
9958 (let* ((bn (buffer-name buffer))
9959 (ibn (concat bn "(Clone)"))
9960 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9961 (with-current-buffer ib (org-overview))
9962 ib))))
9964 (defun org-do-occur (regexp &optional cleanup)
9965 "Call the Emacs command `occur'.
9966 If CLEANUP is non-nil, remove the printout of the regular expression
9967 in the *Occur* buffer. This is useful if the regex is long and not useful
9968 to read."
9969 (occur regexp)
9970 (when cleanup
9971 (let ((cwin (selected-window)) win beg end)
9972 (when (setq win (get-buffer-window "*Occur*"))
9973 (select-window win))
9974 (goto-char (point-min))
9975 (when (re-search-forward "match[a-z]+" nil t)
9976 (setq beg (match-end 0))
9977 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9978 (setq end (1- (match-beginning 0)))))
9979 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9980 (goto-char (point-min))
9981 (select-window cwin))))
9983 ;;; The mark ring for links jumps
9985 (defvar org-mark-ring nil
9986 "Mark ring for positions before jumps in Org-mode.")
9987 (defvar org-mark-ring-last-goto nil
9988 "Last position in the mark ring used to go back.")
9989 ;; Fill and close the ring
9990 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9991 (loop for i from 1 to org-mark-ring-length do
9992 (push (make-marker) org-mark-ring))
9993 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9994 org-mark-ring)
9996 (defun org-mark-ring-push (&optional pos buffer)
9997 "Put the current position or POS into the mark ring and rotate it."
9998 (interactive)
9999 (setq pos (or pos (point)))
10000 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10001 (move-marker (car org-mark-ring)
10002 (or pos (point))
10003 (or buffer (current-buffer)))
10004 (message "%s"
10005 (substitute-command-keys
10006 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10008 (defun org-mark-ring-goto (&optional n)
10009 "Jump to the previous position in the mark ring.
10010 With prefix arg N, jump back that many stored positions. When
10011 called several times in succession, walk through the entire ring.
10012 Org-mode commands jumping to a different position in the current file,
10013 or to another Org-mode file, automatically push the old position
10014 onto the ring."
10015 (interactive "p")
10016 (let (p m)
10017 (if (eq last-command this-command)
10018 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10019 (setq p org-mark-ring))
10020 (setq org-mark-ring-last-goto p)
10021 (setq m (car p))
10022 (org-pop-to-buffer-same-window (marker-buffer m))
10023 (goto-char m)
10024 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10026 (defun org-remove-angle-brackets (s)
10027 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10028 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10030 (defun org-add-angle-brackets (s)
10031 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10032 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10034 (defun org-remove-double-quotes (s)
10035 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10036 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10039 ;;; Following specific links
10041 (defun org-follow-timestamp-link ()
10042 (cond
10043 ((org-at-date-range-p t)
10044 (let ((org-agenda-start-on-weekday)
10045 (t1 (match-string 1))
10046 (t2 (match-string 2)))
10047 (setq t1 (time-to-days (org-time-string-to-time t1))
10048 t2 (time-to-days (org-time-string-to-time t2)))
10049 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10050 ((org-at-timestamp-p t)
10051 (org-agenda-list nil (time-to-days (org-time-string-to-time
10052 (substring (match-string 1) 0 10)))
10054 (t (error "This should not happen"))))
10057 ;;; Following file links
10058 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10059 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10060 (declare-function mailcap-mime-info
10061 "mailcap" (string &optional request no-decode))
10062 (defvar org-wait nil)
10063 (defun org-open-file (path &optional in-emacs line search)
10064 "Open the file at PATH.
10065 First, this expands any special file name abbreviations. Then the
10066 configuration variable `org-file-apps' is checked if it contains an
10067 entry for this file type, and if yes, the corresponding command is launched.
10069 If no application is found, Emacs simply visits the file.
10071 With optional prefix argument IN-EMACS, Emacs will visit the file.
10072 With a double \\[universal-argument] \\[universal-argument] \
10073 prefix arg, Org tries to avoid opening in Emacs
10074 and to use an external application to visit the file.
10076 Optional LINE specifies a line to go to, optional SEARCH a string
10077 to search for. If LINE or SEARCH is given, the file will be
10078 opened in Emacs, unless an entry from org-file-apps that makes
10079 use of groups in a regexp matches.
10081 If you want to change the way frames are used when following a
10082 link, please customize `org-link-frame-setup'.
10084 If the file does not exist, an error is thrown."
10085 (let* ((file (if (equal path "")
10086 buffer-file-name
10087 (substitute-in-file-name (expand-file-name path))))
10088 (file-apps (append org-file-apps (org-default-apps)))
10089 (apps (org-remove-if
10090 'org-file-apps-entry-match-against-dlink-p file-apps))
10091 (apps-dlink (org-remove-if-not
10092 'org-file-apps-entry-match-against-dlink-p file-apps))
10093 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10094 (dirp (if remp nil (file-directory-p file)))
10095 (file (if (and dirp org-open-directory-means-index-dot-org)
10096 (concat (file-name-as-directory file) "index.org")
10097 file))
10098 (a-m-a-p (assq 'auto-mode apps))
10099 (dfile (downcase file))
10100 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10101 (link (cond ((and (eq line nil)
10102 (eq search nil))
10103 file)
10104 (line
10105 (concat file "::" (number-to-string line)))
10106 (search
10107 (concat file "::" search))))
10108 (dlink (downcase link))
10109 (old-buffer (current-buffer))
10110 (old-pos (point))
10111 (old-mode major-mode)
10112 ext cmd link-match-data)
10113 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10114 (setq ext (match-string 1 dfile))
10115 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10116 (setq ext (match-string 1 dfile))))
10117 (cond
10118 ((member in-emacs '((16) system))
10119 (setq cmd (cdr (assoc 'system apps))))
10120 (in-emacs (setq cmd 'emacs))
10122 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10123 (and dirp (cdr (assoc 'directory apps)))
10124 ; first, try matching against apps-dlink
10125 ; if we get a match here, store the match data for later
10126 (let ((match (assoc-default dlink apps-dlink
10127 'string-match)))
10128 (if match
10129 (progn (setq link-match-data (match-data))
10130 match)
10131 (progn (setq in-emacs (or in-emacs line search))
10132 nil))) ; if we have no match in apps-dlink,
10133 ; always open the file in emacs if line or search
10134 ; is given (for backwards compatibility)
10135 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10136 'string-match)
10137 (cdr (assoc ext apps))
10138 (cdr (assoc t apps))))))
10139 (when (eq cmd 'system)
10140 (setq cmd (cdr (assoc 'system apps))))
10141 (when (eq cmd 'default)
10142 (setq cmd (cdr (assoc t apps))))
10143 (when (eq cmd 'mailcap)
10144 (require 'mailcap)
10145 (mailcap-parse-mailcaps)
10146 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10147 (command (mailcap-mime-info mime-type)))
10148 (if (stringp command)
10149 (setq cmd command)
10150 (setq cmd 'emacs))))
10151 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10152 (not (file-exists-p file))
10153 (not org-open-non-existing-files))
10154 (error "No such file: %s" file))
10155 (cond
10156 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10157 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10158 (while (string-match "['\"]%s['\"]" cmd)
10159 (setq cmd (replace-match "%s" t t cmd)))
10160 (while (string-match "%s" cmd)
10161 (setq cmd (replace-match
10162 (save-match-data
10163 (shell-quote-argument
10164 (convert-standard-filename file)))
10165 t t cmd)))
10167 ;; Replace "%1", "%2" etc. in command with group matches from regex
10168 (save-match-data
10169 (let ((match-index 1)
10170 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10171 (set-match-data link-match-data)
10172 (while (<= match-index number-of-groups)
10173 (let ((regex (concat "%" (number-to-string match-index)))
10174 (replace-with (match-string match-index dlink)))
10175 (while (string-match regex cmd)
10176 (setq cmd (replace-match replace-with t t cmd))))
10177 (setq match-index (+ match-index 1)))))
10179 (save-window-excursion
10180 (start-process-shell-command cmd nil cmd)
10181 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10183 ((or (stringp cmd)
10184 (eq cmd 'emacs))
10185 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10186 (widen)
10187 (if line (org-goto-line line)
10188 (if search (org-link-search search))))
10189 ((consp cmd)
10190 (let ((file (convert-standard-filename file)))
10191 (save-match-data
10192 (set-match-data link-match-data)
10193 (eval cmd))))
10194 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10195 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
10196 (or (not (equal old-buffer (current-buffer)))
10197 (not (equal old-pos (point))))
10198 (org-mark-ring-push old-pos old-buffer))))
10200 (defun org-file-apps-entry-match-against-dlink-p (entry)
10201 "This function returns non-nil if `entry' uses a regular
10202 expression which should be matched against the whole link by
10203 org-open-file.
10205 It assumes that is the case when the entry uses a regular
10206 expression which has at least one grouping construct and the
10207 action is either a lisp form or a command string containing
10208 '%1', i.e. using at least one subexpression match as a
10209 parameter."
10210 (let ((selector (car entry))
10211 (action (cdr entry)))
10212 (if (stringp selector)
10213 (and (> (regexp-opt-depth selector) 0)
10214 (or (and (stringp action)
10215 (string-match "%[0-9]" action))
10216 (consp action)))
10217 nil)))
10219 (defun org-default-apps ()
10220 "Return the default applications for this operating system."
10221 (cond
10222 ((eq system-type 'darwin)
10223 org-file-apps-defaults-macosx)
10224 ((eq system-type 'windows-nt)
10225 org-file-apps-defaults-windowsnt)
10226 (t org-file-apps-defaults-gnu)))
10228 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10229 "Convert extensions to regular expressions in the cars of LIST.
10230 Also, weed out any non-string entries, because the return value is used
10231 only for regexp matching.
10232 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10233 point to the symbol `emacs', indicating that the file should
10234 be opened in Emacs."
10235 (append
10236 (delq nil
10237 (mapcar (lambda (x)
10238 (if (not (stringp (car x)))
10240 (if (string-match "\\W" (car x))
10242 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10243 list))
10244 (if add-auto-mode
10245 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10247 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10248 (defun org-file-remote-p (file)
10249 "Test whether FILE specifies a location on a remote system.
10250 Return non-nil if the location is indeed remote.
10252 For example, the filename \"/user@host:/foo\" specifies a location
10253 on the system \"/user@host:\"."
10254 (cond ((fboundp 'file-remote-p)
10255 (file-remote-p file))
10256 ((fboundp 'tramp-handle-file-remote-p)
10257 (tramp-handle-file-remote-p file))
10258 ((and (boundp 'ange-ftp-name-format)
10259 (string-match (car ange-ftp-name-format) file))
10261 (t nil)))
10264 ;;;; Refiling
10266 (defun org-get-org-file ()
10267 "Read a filename, with default directory `org-directory'."
10268 (let ((default (or org-default-notes-file remember-data-file)))
10269 (read-file-name (format "File name [%s]: " default)
10270 (file-name-as-directory org-directory)
10271 default)))
10273 (defun org-notes-order-reversed-p ()
10274 "Check if the current file should receive notes in reversed order."
10275 (cond
10276 ((not org-reverse-note-order) nil)
10277 ((eq t org-reverse-note-order) t)
10278 ((not (listp org-reverse-note-order)) nil)
10279 (t (catch 'exit
10280 (let ((all org-reverse-note-order)
10281 entry)
10282 (while (setq entry (pop all))
10283 (if (string-match (car entry) buffer-file-name)
10284 (throw 'exit (cdr entry))))
10285 nil)))))
10287 (defvar org-refile-target-table nil
10288 "The list of refile targets, created by `org-refile'.")
10290 (defvar org-agenda-new-buffers nil
10291 "Buffers created to visit agenda files.")
10293 (defvar org-refile-cache nil
10294 "Cache for refile targets.")
10296 (defvar org-refile-markers nil
10297 "All the markers used for caching refile locations.")
10299 (defun org-refile-marker (pos)
10300 "Get a new refile marker, but only if caching is in use."
10301 (if (not org-refile-use-cache)
10303 (let ((m (make-marker)))
10304 (move-marker m pos)
10305 (push m org-refile-markers)
10306 m)))
10308 (defun org-refile-cache-clear ()
10309 "Clear the refile cache and disable all the markers."
10310 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10311 (setq org-refile-markers nil)
10312 (setq org-refile-cache nil)
10313 (message "Refile cache has been cleared"))
10315 (defun org-refile-cache-check-set (set)
10316 "Check if all the markers in the cache still have live buffers."
10317 (let (marker)
10318 (catch 'exit
10319 (while (and set (setq marker (nth 3 (pop set))))
10320 ;; if org-refile-use-outline-path is 'file, marker may be nil
10321 (when (and marker (null (marker-buffer marker)))
10322 (message "not found") (sit-for 3)
10323 (throw 'exit nil)))
10324 t)))
10326 (defun org-refile-cache-put (set &rest identifiers)
10327 "Push the refile targets SET into the cache, under IDENTIFIERS."
10328 (let* ((key (sha1 (prin1-to-string identifiers)))
10329 (entry (assoc key org-refile-cache)))
10330 (if entry
10331 (setcdr entry set)
10332 (push (cons key set) org-refile-cache))))
10334 (defun org-refile-cache-get (&rest identifiers)
10335 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10336 (cond
10337 ((not org-refile-cache) nil)
10338 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10340 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10341 org-refile-cache))))
10342 (and set (org-refile-cache-check-set set) set)))))
10344 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10345 "Produce a table with refile targets."
10346 (let ((case-fold-search nil)
10347 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10348 (entries (or org-refile-targets '((nil . (:level . 1)))))
10349 targets tgs txt re files f desc descre fast-path-p level pos0)
10350 (message "Getting targets...")
10351 (with-current-buffer (or default-buffer (current-buffer))
10352 (while (setq entry (pop entries))
10353 (setq files (car entry) desc (cdr entry))
10354 (setq fast-path-p nil)
10355 (cond
10356 ((null files) (setq files (list (current-buffer))))
10357 ((eq files 'org-agenda-files)
10358 (setq files (org-agenda-files 'unrestricted)))
10359 ((and (symbolp files) (fboundp files))
10360 (setq files (funcall files)))
10361 ((and (symbolp files) (boundp files))
10362 (setq files (symbol-value files))))
10363 (if (stringp files) (setq files (list files)))
10364 (cond
10365 ((eq (car desc) :tag)
10366 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10367 ((eq (car desc) :todo)
10368 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10369 ((eq (car desc) :regexp)
10370 (setq descre (cdr desc)))
10371 ((eq (car desc) :level)
10372 (setq descre (concat "^\\*\\{" (number-to-string
10373 (if org-odd-levels-only
10374 (1- (* 2 (cdr desc)))
10375 (cdr desc)))
10376 "\\}[ \t]")))
10377 ((eq (car desc) :maxlevel)
10378 (setq fast-path-p t)
10379 (setq descre (concat "^\\*\\{1," (number-to-string
10380 (if org-odd-levels-only
10381 (1- (* 2 (cdr desc)))
10382 (cdr desc)))
10383 "\\}[ \t]")))
10384 (t (error "Bad refiling target description %s" desc)))
10385 (while (setq f (pop files))
10386 (with-current-buffer
10387 (if (bufferp f) f (org-get-agenda-file-buffer f))
10389 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10390 (progn
10391 (if (bufferp f) (setq f (buffer-file-name
10392 (buffer-base-buffer f))))
10393 (setq f (and f (expand-file-name f)))
10394 (if (eq org-refile-use-outline-path 'file)
10395 (push (list (file-name-nondirectory f) f nil nil) tgs))
10396 (save-excursion
10397 (save-restriction
10398 (widen)
10399 (goto-char (point-min))
10400 (while (re-search-forward descre nil t)
10401 (goto-char (setq pos0 (point-at-bol)))
10402 (catch 'next
10403 (when org-refile-target-verify-function
10404 (save-match-data
10405 (or (funcall org-refile-target-verify-function)
10406 (throw 'next t))))
10407 (when (and (looking-at org-complex-heading-regexp)
10408 (not (member (match-string 4) excluded-entries)))
10409 (setq level (org-reduced-level
10410 (- (match-end 1) (match-beginning 1)))
10411 txt (org-link-display-format (match-string 4))
10412 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10413 re (format org-complex-heading-regexp-format
10414 (regexp-quote (match-string 4))))
10415 (when org-refile-use-outline-path
10416 (setq txt (mapconcat
10417 'org-protect-slash
10418 (append
10419 (if (eq org-refile-use-outline-path
10420 'file)
10421 (list (file-name-nondirectory
10422 (buffer-file-name
10423 (buffer-base-buffer))))
10424 (if (eq org-refile-use-outline-path
10425 'full-file-path)
10426 (list (buffer-file-name
10427 (buffer-base-buffer)))))
10428 (org-get-outline-path fast-path-p
10429 level txt)
10430 (list txt))
10431 "/")))
10432 (push (list txt f re (org-refile-marker (point)))
10433 tgs)))
10434 (when (= (point) pos0)
10435 ;; verification function has not moved point
10436 (goto-char (point-at-eol))))))))
10437 (when org-refile-use-cache
10438 (org-refile-cache-put tgs (buffer-file-name) descre))
10439 (setq targets (append tgs targets))
10440 ))))
10441 (message "Getting targets...done")
10442 (nreverse targets)))
10444 (defun org-protect-slash (s)
10445 (while (string-match "/" s)
10446 (setq s (replace-match "\\" t t s)))
10449 (defvar org-olpa (make-vector 20 nil))
10451 (defun org-get-outline-path (&optional fastp level heading)
10452 "Return the outline path to the current entry, as a list.
10454 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10455 routine which makes outline path derivations for an entire file,
10456 avoiding backtracing. Refile target collection makes use of that."
10457 (if fastp
10458 (progn
10459 (if (> level 19)
10460 (error "Outline path failure, more than 19 levels"))
10461 (loop for i from level upto 19 do
10462 (aset org-olpa i nil))
10463 (prog1
10464 (delq nil (append org-olpa nil))
10465 (aset org-olpa level heading)))
10466 (let (rtn case-fold-search)
10467 (save-excursion
10468 (save-restriction
10469 (widen)
10470 (while (org-up-heading-safe)
10471 (when (looking-at org-complex-heading-regexp)
10472 (push (org-match-string-no-properties 4) rtn)))
10473 rtn)))))
10475 (defun org-format-outline-path (path &optional width prefix)
10476 "Format the outline path PATH for display.
10477 Width is the maximum number of characters that is available.
10478 Prefix is a prefix to be included in the returned string,
10479 such as the file name."
10480 (setq width (or width 79))
10481 (if prefix (setq width (- width (length prefix))))
10482 (if (not path)
10483 (or prefix "")
10484 (let* ((nsteps (length path))
10485 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10486 (maxwidth (if (<= total-width width)
10487 10000 ;; everything fits
10488 ;; we need to shorten the level headings
10489 (/ (- width nsteps) nsteps)))
10490 (org-odd-levels-only nil)
10491 (n 0)
10492 (total (1+ (length prefix))))
10493 (setq maxwidth (max maxwidth 10))
10494 (concat prefix
10495 (mapconcat
10496 (lambda (h)
10497 (setq n (1+ n))
10498 (if (and (= n nsteps) (< maxwidth 10000))
10499 (setq maxwidth (- total-width total)))
10500 (if (< (length h) maxwidth)
10501 (progn (setq total (+ total (length h) 1)) h)
10502 (setq h (substring h 0 (- maxwidth 2))
10503 total (+ total maxwidth 1))
10504 (if (string-match "[ \t]+\\'" h)
10505 (setq h (substring h 0 (match-beginning 0))))
10506 (setq h (concat h "..")))
10507 (org-add-props h nil 'face
10508 (nth (% (1- n) org-n-level-faces)
10509 org-level-faces))
10511 path "/")))))
10513 (defun org-display-outline-path (&optional file current)
10514 "Display the current outline path in the echo area."
10515 (interactive "P")
10516 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10517 (case-fold-search nil)
10518 (path (and (eq major-mode 'org-mode) (org-get-outline-path))))
10519 (if current (setq path (append path
10520 (save-excursion
10521 (org-back-to-heading t)
10522 (if (looking-at org-complex-heading-regexp)
10523 (list (match-string 4)))))))
10524 (message "%s"
10525 (org-format-outline-path
10526 path
10527 (1- (frame-width))
10528 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10530 (defvar org-refile-history nil
10531 "History for refiling operations.")
10533 (defvar org-after-refile-insert-hook nil
10534 "Hook run after `org-refile' has inserted its stuff at the new location.
10535 Note that this is still *before* the stuff will be removed from
10536 the *old* location.")
10538 (defvar org-capture-last-stored-marker)
10539 (defun org-refile (&optional goto default-buffer rfloc)
10540 "Move the entry or entries at point to another heading.
10541 The list of target headings is compiled using the information in
10542 `org-refile-targets', which see.
10544 At the target location, the entry is filed as a subitem of the target
10545 heading. Depending on `org-reverse-note-order', the new subitem will
10546 either be the first or the last subitem.
10548 If there is an active region, all entries in that region will be moved.
10549 However, the region must fulfill the requirement that the first heading
10550 is the first one sets the top-level of the moved text - at most siblings
10551 below it are allowed.
10553 With prefix arg GOTO, the command will only visit the target location
10554 and not actually move anything.
10556 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10557 go to the location where the last refiling operation has put the subtree.
10558 With a prefix argument of `2', refile to the running clock.
10560 RFLOC can be a refile location obtained in a different way.
10562 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10564 If you are using target caching (see `org-refile-use-cache'),
10565 You have to clear the target cache in order to find new targets.
10566 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10567 prefix argument (`C-u C-u C-u C-c C-w')."
10569 (interactive "P")
10570 (if (member goto '(0 (64)))
10571 (org-refile-cache-clear)
10572 (let* ((cbuf (current-buffer))
10573 (regionp (org-region-active-p))
10574 (region-start (and regionp (region-beginning)))
10575 (region-end (and regionp (region-end)))
10576 (region-length (and regionp (- region-end region-start)))
10577 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10578 pos it nbuf file re level reversed)
10579 (setq last-command nil)
10580 (when regionp
10581 (goto-char region-start)
10582 (or (bolp) (goto-char (point-at-bol)))
10583 (setq region-start (point))
10584 (unless (or (org-kill-is-subtree-p
10585 (buffer-substring region-start region-end))
10586 (prog1 org-refile-active-region-within-subtree
10587 (org-toggle-heading)))
10588 (error "The region is not a (sequence of) subtree(s)")))
10589 (if (equal goto '(16))
10590 (org-refile-goto-last-stored)
10591 (when (or
10592 (and (equal goto 2)
10593 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10594 (prog1
10595 (setq it (list (or org-clock-heading "running clock")
10596 (buffer-file-name
10597 (marker-buffer org-clock-hd-marker))
10599 (marker-position org-clock-hd-marker)))
10600 (setq goto nil)))
10601 (setq it (or rfloc
10602 (let (heading-text)
10603 (save-excursion
10604 (unless goto
10605 (org-back-to-heading t)
10606 (setq heading-text
10607 (nth 4 (org-heading-components))))
10608 (org-refile-get-location
10609 (cond (goto "Goto")
10610 (regionp "Refile region to")
10611 (t (concat "Refile subtree \""
10612 heading-text "\" to")))
10613 default-buffer
10614 org-refile-allow-creating-parent-nodes
10615 goto))))))
10616 (setq file (nth 1 it)
10617 re (nth 2 it)
10618 pos (nth 3 it))
10619 (if (and (not goto)
10621 (equal (buffer-file-name) file)
10622 (if regionp
10623 (and (>= pos region-start)
10624 (<= pos region-end))
10625 (and (>= pos (point))
10626 (< pos (save-excursion
10627 (org-end-of-subtree t t))))))
10628 (error "Cannot refile to position inside the tree or region"))
10630 (setq nbuf (or (find-buffer-visiting file)
10631 (find-file-noselect file)))
10632 (if goto
10633 (progn
10634 (org-pop-to-buffer-same-window nbuf)
10635 (goto-char pos)
10636 (org-show-context 'org-goto))
10637 (if regionp
10638 (progn
10639 (org-kill-new (buffer-substring region-start region-end))
10640 (org-save-markers-in-region region-start region-end))
10641 (org-copy-subtree 1 nil t))
10642 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10643 (find-file-noselect file)))
10644 (setq reversed (org-notes-order-reversed-p))
10645 (save-excursion
10646 (save-restriction
10647 (widen)
10648 (if pos
10649 (progn
10650 (goto-char pos)
10651 (looking-at org-outline-regexp)
10652 (setq level (org-get-valid-level (funcall outline-level) 1))
10653 (goto-char
10654 (if reversed
10655 (or (outline-next-heading) (point-max))
10656 (or (save-excursion (org-get-next-sibling))
10657 (org-end-of-subtree t t)
10658 (point-max)))))
10659 (setq level 1)
10660 (if (not reversed)
10661 (goto-char (point-max))
10662 (goto-char (point-min))
10663 (or (outline-next-heading) (goto-char (point-max)))))
10664 (if (not (bolp)) (newline))
10665 (org-paste-subtree level)
10666 (when org-log-refile
10667 (org-add-log-setup 'refile nil nil 'findpos
10668 org-log-refile)
10669 (unless (eq org-log-refile 'note)
10670 (save-excursion (org-add-log-note))))
10671 (and org-auto-align-tags (org-set-tags nil t))
10672 (bookmark-set "org-refile-last-stored")
10673 ;; If we are refiling for capture, make sure that the
10674 ;; last-capture pointers point here
10675 (when (org-bound-and-true-p org-refile-for-capture)
10676 (bookmark-set "org-capture-last-stored-marker")
10677 (move-marker org-capture-last-stored-marker (point)))
10678 (if (fboundp 'deactivate-mark) (deactivate-mark))
10679 (run-hooks 'org-after-refile-insert-hook))))
10680 (if regionp
10681 (delete-region (point) (+ (point) region-length))
10682 (org-cut-subtree))
10683 (when (featurep 'org-inlinetask)
10684 (org-inlinetask-remove-END-maybe))
10685 (setq org-markers-to-move nil)
10686 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10688 (defun org-refile-goto-last-stored ()
10689 "Go to the location where the last refile was stored."
10690 (interactive)
10691 (bookmark-jump "org-refile-last-stored")
10692 (message "This is the location of the last refile"))
10694 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10695 no-exclude)
10696 "Prompt the user for a refile location, using PROMPT.
10697 PROMPT should not be suffixed with a colon and a space, because
10698 this function appends the default value from
10699 `org-refile-history' automatically, if that is not empty.
10700 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10701 this is used for the GOTO interface."
10702 (let ((org-refile-targets org-refile-targets)
10703 (org-refile-use-outline-path org-refile-use-outline-path)
10704 excluded-entries)
10705 (when (and (eq major-mode 'org-mode)
10706 (not org-refile-use-cache)
10707 (not no-exclude))
10708 (org-map-tree
10709 (lambda()
10710 (setq excluded-entries
10711 (append excluded-entries (list (org-get-heading t t)))))))
10712 (setq org-refile-target-table
10713 (org-refile-get-targets default-buffer excluded-entries)))
10714 (unless org-refile-target-table
10715 (error "No refile targets"))
10716 (let* ((prompt (concat prompt
10717 (and (car org-refile-history)
10718 (concat " (default " (car org-refile-history) ")"))
10719 ": "))
10720 (cbuf (current-buffer))
10721 (partial-completion-mode nil)
10722 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10723 (cfunc (if (and org-refile-use-outline-path
10724 org-outline-path-complete-in-steps)
10725 'org-olpath-completing-read
10726 'org-icompleting-read))
10727 (extra (if org-refile-use-outline-path "/" ""))
10728 (filename (and cfn (expand-file-name cfn)))
10729 (tbl (mapcar
10730 (lambda (x)
10731 (if (and (not (member org-refile-use-outline-path
10732 '(file full-file-path)))
10733 (not (equal filename (nth 1 x))))
10734 (cons (concat (car x) extra " ("
10735 (file-name-nondirectory (nth 1 x)) ")")
10736 (cdr x))
10737 (cons (concat (car x) extra) (cdr x))))
10738 org-refile-target-table))
10739 (completion-ignore-case t)
10740 pa answ parent-target child parent old-hist)
10741 (setq old-hist org-refile-history)
10742 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10743 nil 'org-refile-history (car org-refile-history)))
10744 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10745 (org-refile-check-position pa)
10746 (if pa
10747 (progn
10748 (when (or (not org-refile-history)
10749 (not (eq old-hist org-refile-history))
10750 (not (equal (car pa) (car org-refile-history))))
10751 (setq org-refile-history
10752 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10753 org-refile-history
10754 (cdr org-refile-history))))
10755 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10756 (pop org-refile-history)))
10758 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10759 (progn
10760 (setq parent (match-string 1 answ)
10761 child (match-string 2 answ))
10762 (setq parent-target (or (assoc parent tbl)
10763 (assoc (concat parent "/") tbl)))
10764 (when (and parent-target
10765 (or (eq new-nodes t)
10766 (and (eq new-nodes 'confirm)
10767 (y-or-n-p (format "Create new node \"%s\"? "
10768 child)))))
10769 (org-refile-new-child parent-target child)))
10770 (error "Invalid target location")))))
10772 (defun org-refile-check-position (refile-pointer)
10773 "Check if the refile pointer matches the readline to which it points."
10774 (let* ((file (nth 1 refile-pointer))
10775 (re (nth 2 refile-pointer))
10776 (pos (nth 3 refile-pointer))
10777 buffer)
10778 (when (org-string-nw-p re)
10779 (setq buffer (if (markerp pos)
10780 (marker-buffer pos)
10781 (or (find-buffer-visiting file)
10782 (find-file-noselect file))))
10783 (with-current-buffer buffer
10784 (save-excursion
10785 (save-restriction
10786 (widen)
10787 (goto-char pos)
10788 (beginning-of-line 1)
10789 (unless (org-looking-at-p re)
10790 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10792 (defun org-refile-new-child (parent-target child)
10793 "Use refile target PARENT-TARGET to add new CHILD below it."
10794 (unless parent-target
10795 (error "Cannot find parent for new node"))
10796 (let ((file (nth 1 parent-target))
10797 (pos (nth 3 parent-target))
10798 level)
10799 (with-current-buffer (or (find-buffer-visiting file)
10800 (find-file-noselect file))
10801 (save-excursion
10802 (save-restriction
10803 (widen)
10804 (if pos
10805 (goto-char pos)
10806 (goto-char (point-max))
10807 (if (not (bolp)) (newline)))
10808 (when (looking-at org-outline-regexp)
10809 (setq level (funcall outline-level))
10810 (org-end-of-subtree t t))
10811 (org-back-over-empty-lines)
10812 (insert "\n" (make-string
10813 (if pos (org-get-valid-level level 1) 1) ?*)
10814 " " child "\n")
10815 (beginning-of-line 0)
10816 (list (concat (car parent-target) "/" child) file "" (point)))))))
10818 (defun org-olpath-completing-read (prompt collection &rest args)
10819 "Read an outline path like a file name."
10820 (let ((thetable collection)
10821 (org-completion-use-ido nil) ; does not work with ido.
10822 (org-completion-use-iswitchb nil)) ; or iswitchb
10823 (apply
10824 'org-icompleting-read prompt
10825 (lambda (string predicate &optional flag)
10826 (let (rtn r f (l (length string)))
10827 (cond
10828 ((eq flag nil)
10829 ;; try completion
10830 (try-completion string thetable))
10831 ((eq flag t)
10832 ;; all-completions
10833 (setq rtn (all-completions string thetable predicate))
10834 (mapcar
10835 (lambda (x)
10836 (setq r (substring x l))
10837 (if (string-match " ([^)]*)$" x)
10838 (setq f (match-string 0 x))
10839 (setq f ""))
10840 (if (string-match "/" r)
10841 (concat string (substring r 0 (match-end 0)) f)
10843 rtn))
10844 ((eq flag 'lambda)
10845 ;; exact match?
10846 (assoc string thetable)))
10848 args)))
10850 ;;;; Dynamic blocks
10852 (defun org-find-dblock (name)
10853 "Find the first dynamic block with name NAME in the buffer.
10854 If not found, stay at current position and return nil."
10855 (let (pos)
10856 (save-excursion
10857 (goto-char (point-min))
10858 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10859 nil t)
10860 (match-beginning 0))))
10861 (if pos (goto-char pos))
10862 pos))
10864 (defconst org-dblock-start-re
10865 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10866 "Matches the start line of a dynamic block, with parameters.")
10868 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10869 "Matches the end of a dynamic block.")
10871 (defun org-create-dblock (plist)
10872 "Create a dynamic block section, with parameters taken from PLIST.
10873 PLIST must contain a :name entry which is used as name of the block."
10874 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10875 (end-of-line 1)
10876 (newline))
10877 (let ((col (current-column))
10878 (name (plist-get plist :name)))
10879 (insert "#+BEGIN: " name)
10880 (while plist
10881 (if (eq (car plist) :name)
10882 (setq plist (cddr plist))
10883 (insert " " (prin1-to-string (pop plist)))))
10884 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10885 (beginning-of-line -2)))
10887 (defun org-prepare-dblock ()
10888 "Prepare dynamic block for refresh.
10889 This empties the block, puts the cursor at the insert position and returns
10890 the property list including an extra property :name with the block name."
10891 (unless (looking-at org-dblock-start-re)
10892 (error "Not at a dynamic block"))
10893 (let* ((begdel (1+ (match-end 0)))
10894 (name (org-no-properties (match-string 1)))
10895 (params (append (list :name name)
10896 (read (concat "(" (match-string 3) ")")))))
10897 (save-excursion
10898 (beginning-of-line 1)
10899 (skip-chars-forward " \t")
10900 (setq params (plist-put params :indentation-column (current-column))))
10901 (unless (re-search-forward org-dblock-end-re nil t)
10902 (error "Dynamic block not terminated"))
10903 (setq params
10904 (append params
10905 (list :content (buffer-substring
10906 begdel (match-beginning 0)))))
10907 (delete-region begdel (match-beginning 0))
10908 (goto-char begdel)
10909 (open-line 1)
10910 params))
10912 (defun org-map-dblocks (&optional command)
10913 "Apply COMMAND to all dynamic blocks in the current buffer.
10914 If COMMAND is not given, use `org-update-dblock'."
10915 (let ((cmd (or command 'org-update-dblock)))
10916 (save-excursion
10917 (goto-char (point-min))
10918 (while (re-search-forward org-dblock-start-re nil t)
10919 (goto-char (match-beginning 0))
10920 (save-excursion
10921 (condition-case nil
10922 (funcall cmd)
10923 (error (message "Error during update of dynamic block"))))
10924 (unless (re-search-forward org-dblock-end-re nil t)
10925 (error "Dynamic block not terminated"))))))
10927 (defun org-dblock-update (&optional arg)
10928 "User command for updating dynamic blocks.
10929 Update the dynamic block at point. With prefix ARG, update all dynamic
10930 blocks in the buffer."
10931 (interactive "P")
10932 (if arg
10933 (org-update-all-dblocks)
10934 (or (looking-at org-dblock-start-re)
10935 (org-beginning-of-dblock))
10936 (org-update-dblock)))
10938 (defun org-update-dblock ()
10939 "Update the dynamic block at point.
10940 This means to empty the block, parse for parameters and then call
10941 the correct writing function."
10942 (interactive)
10943 (save-window-excursion
10944 (let* ((pos (point))
10945 (line (org-current-line))
10946 (params (org-prepare-dblock))
10947 (name (plist-get params :name))
10948 (indent (plist-get params :indentation-column))
10949 (cmd (intern (concat "org-dblock-write:" name))))
10950 (message "Updating dynamic block `%s' at line %d..." name line)
10951 (funcall cmd params)
10952 (message "Updating dynamic block `%s' at line %d...done" name line)
10953 (goto-char pos)
10954 (when (and indent (> indent 0))
10955 (setq indent (make-string indent ?\ ))
10956 (save-excursion
10957 (org-beginning-of-dblock)
10958 (forward-line 1)
10959 (while (not (looking-at org-dblock-end-re))
10960 (insert indent)
10961 (beginning-of-line 2))
10962 (when (looking-at org-dblock-end-re)
10963 (and (looking-at "[ \t]+")
10964 (replace-match ""))
10965 (insert indent)))))))
10967 (defun org-beginning-of-dblock ()
10968 "Find the beginning of the dynamic block at point.
10969 Error if there is no such block at point."
10970 (let ((pos (point))
10971 beg)
10972 (end-of-line 1)
10973 (if (and (re-search-backward org-dblock-start-re nil t)
10974 (setq beg (match-beginning 0))
10975 (re-search-forward org-dblock-end-re nil t)
10976 (> (match-end 0) pos))
10977 (goto-char beg)
10978 (goto-char pos)
10979 (error "Not in a dynamic block"))))
10981 (defun org-update-all-dblocks ()
10982 "Update all dynamic blocks in the buffer.
10983 This function can be used in a hook."
10984 (interactive)
10985 (when (eq major-mode 'org-mode)
10986 (org-map-dblocks 'org-update-dblock)))
10989 ;;;; Completion
10991 (defconst org-additional-option-like-keywords
10992 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
10993 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
10994 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
10995 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
10996 "BEGIN:" "END:"
10997 "ORGTBL" "TBLFM:" "TBLNAME:"
10998 "BEGIN_EXAMPLE" "END_EXAMPLE"
10999 "BEGIN_QUOTE" "END_QUOTE"
11000 "BEGIN_VERSE" "END_VERSE"
11001 "BEGIN_CENTER" "END_CENTER"
11002 "BEGIN_SRC" "END_SRC"
11003 "BEGIN_RESULT" "END_RESULT"
11004 "NAME:" "RESULTS:"
11005 "HEADER:" "HEADERS:"
11006 "CATEGORY:" "COLUMNS:" "PROPERTY:"
11007 "CAPTION:" "LABEL:"
11008 "SETUPFILE:"
11009 "INCLUDE:"
11010 "BIND:"
11011 "MACRO:"))
11013 (defcustom org-structure-template-alist
11015 ("s" "#+begin_src ?\n\n#+end_src"
11016 "<src lang=\"?\">\n\n</src>")
11017 ("e" "#+begin_example\n?\n#+end_example"
11018 "<example>\n?\n</example>")
11019 ("q" "#+begin_quote\n?\n#+end_quote"
11020 "<quote>\n?\n</quote>")
11021 ("v" "#+begin_verse\n?\n#+end_verse"
11022 "<verse>\n?\n/verse>")
11023 ("c" "#+begin_center\n?\n#+end_center"
11024 "<center>\n?\n/center>")
11025 ("l" "#+begin_latex\n?\n#+end_latex"
11026 "<literal style=\"latex\">\n?\n</literal>")
11027 ("L" "#+latex: "
11028 "<literal style=\"latex\">?</literal>")
11029 ("h" "#+begin_html\n?\n#+end_html"
11030 "<literal style=\"html\">\n?\n</literal>")
11031 ("H" "#+html: "
11032 "<literal style=\"html\">?</literal>")
11033 ("a" "#+begin_ascii\n?\n#+end_ascii")
11034 ("A" "#+ascii: ")
11035 ("i" "#+index: ?"
11036 "#+index: ?")
11037 ("I" "#+include %file ?"
11038 "<include file=%file markup=\"?\">")
11040 "Structure completion elements.
11041 This is a list of abbreviation keys and values. The value gets inserted
11042 if you type `<' followed by the key and then press the completion key,
11043 usually `M-TAB'. %file will be replaced by a file name after prompting
11044 for the file using completion. The cursor will be placed at the position
11045 of the `?` in the template.
11046 There are two templates for each key, the first uses the original Org syntax,
11047 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11048 the default when the /org-mtags.el/ module has been loaded. See also the
11049 variable `org-mtags-prefer-muse-templates'.
11050 This is an experimental feature, it is undecided if it is going to stay in."
11051 :group 'org-completion
11052 :type '(repeat
11053 (string :tag "Key")
11054 (string :tag "Template")
11055 (string :tag "Muse Template")))
11057 (defun org-try-structure-completion ()
11058 "Try to complete a structure template before point.
11059 This looks for strings like \"<e\" on an otherwise empty line and
11060 expands them."
11061 (let ((l (buffer-substring (point-at-bol) (point)))
11063 (when (and (looking-at "[ \t]*$")
11064 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11065 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11066 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11067 (match-beginning 1)) a)
11068 t)))
11070 (defun org-complete-expand-structure-template (start cell)
11071 "Expand a structure template."
11072 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11073 (rpl (nth (if musep 2 1) cell))
11074 (ind ""))
11075 (delete-region start (point))
11076 (when (string-match "\\`#\\+" rpl)
11077 (cond
11078 ((bolp))
11079 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11080 (setq ind (buffer-substring (point-at-bol) (point))))
11081 (t (newline))))
11082 (setq start (point))
11083 (if (string-match "%file" rpl)
11084 (setq rpl (replace-match
11085 (concat
11086 "\""
11087 (save-match-data
11088 (abbreviate-file-name (read-file-name "Include file: ")))
11089 "\"")
11090 t t rpl)))
11091 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11092 (concat "\n" ind)))
11093 (insert rpl)
11094 (if (re-search-backward "\\?" start t) (delete-char 1))))
11096 ;;;; TODO, DEADLINE, Comments
11098 (defun org-toggle-comment ()
11099 "Change the COMMENT state of an entry."
11100 (interactive)
11101 (save-excursion
11102 (org-back-to-heading)
11103 (let (case-fold-search)
11104 (cond
11105 ((looking-at (format org-heading-keyword-regexp-format
11106 org-comment-string))
11107 (goto-char (match-end 1))
11108 (looking-at (concat " +" org-comment-string))
11109 (replace-match "" t t)
11110 (when (eolp) (insert " ")))
11111 ((looking-at org-outline-regexp)
11112 (goto-char (match-end 0))
11113 (insert org-comment-string " "))))))
11115 (defvar org-last-todo-state-is-todo nil
11116 "This is non-nil when the last TODO state change led to a TODO state.
11117 If the last change removed the TODO tag or switched to DONE, then
11118 this is nil.")
11120 (defvar org-setting-tags nil) ; dynamically skipped
11122 (defvar org-todo-setup-filter-hook nil
11123 "Hook for functions that pre-filter todo specs.
11124 Each function takes a todo spec and returns either nil or the spec
11125 transformed into canonical form." )
11127 (defvar org-todo-get-default-hook nil
11128 "Hook for functions that get a default item for todo.
11129 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11130 nil or a string to be used for the todo mark." )
11132 (defvar org-agenda-headline-snapshot-before-repeat)
11134 (defun org-current-effective-time ()
11135 "Return current time adjusted for `org-extend-today-until' variable"
11136 (let* ((ct (org-current-time))
11137 (dct (decode-time ct))
11138 (ct1
11139 (if (and org-use-effective-time
11140 (< (nth 2 dct) org-extend-today-until))
11141 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11142 ct)))
11143 ct1))
11145 (defun org-todo-yesterday (&optional arg)
11146 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11147 (interactive "P")
11148 (if (eq major-mode 'org-agenda-mode)
11149 (apply 'org-agenda-todo-yesterday arg)
11150 (let* ((hour (third (decode-time
11151 (org-current-time))))
11152 (org-extend-today-until (1+ hour)))
11153 (org-todo arg))))
11155 (defun org-todo (&optional arg)
11156 "Change the TODO state of an item.
11157 The state of an item is given by a keyword at the start of the heading,
11158 like
11159 *** TODO Write paper
11160 *** DONE Call mom
11162 The different keywords are specified in the variable `org-todo-keywords'.
11163 By default the available states are \"TODO\" and \"DONE\".
11164 So for this example: when the item starts with TODO, it is changed to DONE.
11165 When it starts with DONE, the DONE is removed. And when neither TODO nor
11166 DONE are present, add TODO at the beginning of the heading.
11168 With \\[universal-argument] prefix arg, use completion to determine the new \
11169 state.
11170 With numeric prefix arg, switch to that state.
11171 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11172 keywords (nextset).
11173 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11174 With a numeric prefix arg of 0, inhibit note taking for the change.
11176 For calling through lisp, arg is also interpreted in the following way:
11177 'none -> empty state
11178 \"\"(empty string) -> switch to empty state
11179 'done -> switch to DONE
11180 'nextset -> switch to the next set of keywords
11181 'previousset -> switch to the previous set of keywords
11182 \"WAITING\" -> switch to the specified keyword, but only if it
11183 really is a member of `org-todo-keywords'."
11184 (interactive "P")
11185 (if (equal arg '(16)) (setq arg 'nextset))
11186 (let ((org-blocker-hook org-blocker-hook)
11187 (case-fold-search nil))
11188 (when (equal arg '(64))
11189 (setq arg nil org-blocker-hook nil))
11190 (when (and org-blocker-hook
11191 (or org-inhibit-blocking
11192 (org-entry-get nil "NOBLOCKING")))
11193 (setq org-blocker-hook nil))
11194 (save-excursion
11195 (catch 'exit
11196 (org-back-to-heading t)
11197 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11198 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11199 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11200 (let* ((match-data (match-data))
11201 (startpos (point-at-bol))
11202 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11203 (org-log-done org-log-done)
11204 (org-log-repeat org-log-repeat)
11205 (org-todo-log-states org-todo-log-states)
11206 (org-inhibit-logging
11207 (if (equal arg 0)
11208 (progn (setq arg nil) 'note) org-inhibit-logging))
11209 (this (match-string 1))
11210 (hl-pos (match-beginning 0))
11211 (head (org-get-todo-sequence-head this))
11212 (ass (assoc head org-todo-kwd-alist))
11213 (interpret (nth 1 ass))
11214 (done-word (nth 3 ass))
11215 (final-done-word (nth 4 ass))
11216 (last-state (or this ""))
11217 (completion-ignore-case t)
11218 (member (member this org-todo-keywords-1))
11219 (tail (cdr member))
11220 (state (cond
11221 ((and org-todo-key-trigger
11222 (or (and (equal arg '(4))
11223 (eq org-use-fast-todo-selection 'prefix))
11224 (and (not arg) org-use-fast-todo-selection
11225 (not (eq org-use-fast-todo-selection
11226 'prefix)))))
11227 ;; Use fast selection
11228 (org-fast-todo-selection))
11229 ((and (equal arg '(4))
11230 (or (not org-use-fast-todo-selection)
11231 (not org-todo-key-trigger)))
11232 ;; Read a state with completion
11233 (org-icompleting-read
11234 "State: " (mapcar (lambda(x) (list x))
11235 org-todo-keywords-1)
11236 nil t))
11237 ((eq arg 'right)
11238 (if this
11239 (if tail (car tail) nil)
11240 (car org-todo-keywords-1)))
11241 ((eq arg 'left)
11242 (if (equal member org-todo-keywords-1)
11244 (if this
11245 (nth (- (length org-todo-keywords-1)
11246 (length tail) 2)
11247 org-todo-keywords-1)
11248 (org-last org-todo-keywords-1))))
11249 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11250 (setq arg nil))) ; hack to fall back to cycling
11251 (arg
11252 ;; user or caller requests a specific state
11253 (cond
11254 ((equal arg "") nil)
11255 ((eq arg 'none) nil)
11256 ((eq arg 'done) (or done-word (car org-done-keywords)))
11257 ((eq arg 'nextset)
11258 (or (car (cdr (member head org-todo-heads)))
11259 (car org-todo-heads)))
11260 ((eq arg 'previousset)
11261 (let ((org-todo-heads (reverse org-todo-heads)))
11262 (or (car (cdr (member head org-todo-heads)))
11263 (car org-todo-heads))))
11264 ((car (member arg org-todo-keywords-1)))
11265 ((stringp arg)
11266 (error "State `%s' not valid in this file" arg))
11267 ((nth (1- (prefix-numeric-value arg))
11268 org-todo-keywords-1))))
11269 ((null member) (or head (car org-todo-keywords-1)))
11270 ((equal this final-done-word) nil) ;; -> make empty
11271 ((null tail) nil) ;; -> first entry
11272 ((memq interpret '(type priority))
11273 (if (eq this-command last-command)
11274 (car tail)
11275 (if (> (length tail) 0)
11276 (or done-word (car org-done-keywords))
11277 nil)))
11279 (car tail))))
11280 (state (or
11281 (run-hook-with-args-until-success
11282 'org-todo-get-default-hook state last-state)
11283 state))
11284 (next (if state (concat " " state " ") " "))
11285 (change-plist (list :type 'todo-state-change :from this :to state
11286 :position startpos))
11287 dolog now-done-p)
11288 (when org-blocker-hook
11289 (setq org-last-todo-state-is-todo
11290 (not (member this org-done-keywords)))
11291 (unless (save-excursion
11292 (save-match-data
11293 (org-with-wide-buffer
11294 (run-hook-with-args-until-failure
11295 'org-blocker-hook change-plist))))
11296 (if (org-called-interactively-p 'interactive)
11297 (error "TODO state change from %s to %s blocked" this state)
11298 ;; fail silently
11299 (message "TODO state change from %s to %s blocked" this state)
11300 (throw 'exit nil))))
11301 (store-match-data match-data)
11302 (replace-match next t t)
11303 (unless (pos-visible-in-window-p hl-pos)
11304 (message "TODO state changed to %s" (org-trim next)))
11305 (unless head
11306 (setq head (org-get-todo-sequence-head state)
11307 ass (assoc head org-todo-kwd-alist)
11308 interpret (nth 1 ass)
11309 done-word (nth 3 ass)
11310 final-done-word (nth 4 ass)))
11311 (when (memq arg '(nextset previousset))
11312 (message "Keyword-Set %d/%d: %s"
11313 (- (length org-todo-sets) -1
11314 (length (memq (assoc state org-todo-sets) org-todo-sets)))
11315 (length org-todo-sets)
11316 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11317 (setq org-last-todo-state-is-todo
11318 (not (member state org-done-keywords)))
11319 (setq now-done-p (and (member state org-done-keywords)
11320 (not (member this org-done-keywords))))
11321 (and logging (org-local-logging logging))
11322 (when (and (or org-todo-log-states org-log-done)
11323 (not (eq org-inhibit-logging t))
11324 (not (memq arg '(nextset previousset))))
11325 ;; we need to look at recording a time and note
11326 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
11327 (nth 2 (assoc this org-todo-log-states))))
11328 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11329 (setq dolog 'time))
11330 (when (and state
11331 (member state org-not-done-keywords)
11332 (not (member this org-not-done-keywords)))
11333 ;; This is now a todo state and was not one before
11334 ;; If there was a CLOSED time stamp, get rid of it.
11335 (org-add-planning-info nil nil 'closed))
11336 (when (and now-done-p org-log-done)
11337 ;; It is now done, and it was not done before
11338 (org-add-planning-info 'closed (org-current-effective-time))
11339 (if (and (not dolog) (eq 'note org-log-done))
11340 (org-add-log-setup 'done state this 'findpos 'note)))
11341 (when (and state dolog)
11342 ;; This is a non-nil state, and we need to log it
11343 (org-add-log-setup 'state state this 'findpos dolog)))
11344 ;; Fixup tag positioning
11345 (org-todo-trigger-tag-changes state)
11346 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11347 (when org-provide-todo-statistics
11348 (org-update-parent-todo-statistics))
11349 (run-hooks 'org-after-todo-state-change-hook)
11350 (if (and arg (not (member state org-done-keywords)))
11351 (setq head (org-get-todo-sequence-head state)))
11352 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11353 ;; Do we need to trigger a repeat?
11354 (when now-done-p
11355 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11356 ;; This is for the agenda, take a snapshot of the headline.
11357 (save-match-data
11358 (setq org-agenda-headline-snapshot-before-repeat
11359 (org-get-heading))))
11360 (org-auto-repeat-maybe state))
11361 ;; Fixup cursor location if close to the keyword
11362 (if (and (outline-on-heading-p)
11363 (not (bolp))
11364 (save-excursion (beginning-of-line 1)
11365 (looking-at org-todo-line-regexp))
11366 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11367 (progn
11368 (goto-char (or (match-end 2) (match-end 1)))
11369 (and (looking-at " ") (just-one-space))))
11370 (when org-trigger-hook
11371 (save-excursion
11372 (run-hook-with-args 'org-trigger-hook change-plist))))))))
11374 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11375 "Block turning an entry into a TODO, using the hierarchy.
11376 This checks whether the current task should be blocked from state
11377 changes. Such blocking occurs when:
11379 1. The task has children which are not all in a completed state.
11381 2. A task has a parent with the property :ORDERED:, and there
11382 are siblings prior to the current task with incomplete
11383 status.
11385 3. The parent of the task is blocked because it has siblings that should
11386 be done first, or is child of a block grandparent TODO entry."
11388 (if (not org-enforce-todo-dependencies)
11389 t ; if locally turned off don't block
11390 (catch 'dont-block
11391 ;; If this is not a todo state change, or if this entry is already DONE,
11392 ;; do not block
11393 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11394 (member (plist-get change-plist :from)
11395 (cons 'done org-done-keywords))
11396 (member (plist-get change-plist :to)
11397 (cons 'todo org-not-done-keywords))
11398 (not (plist-get change-plist :to)))
11399 (throw 'dont-block t))
11400 ;; If this task has children, and any are undone, it's blocked
11401 (save-excursion
11402 (org-back-to-heading t)
11403 (let ((this-level (funcall outline-level)))
11404 (outline-next-heading)
11405 (let ((child-level (funcall outline-level)))
11406 (while (and (not (eobp))
11407 (> child-level this-level))
11408 ;; this todo has children, check whether they are all
11409 ;; completed
11410 (if (and (not (org-entry-is-done-p))
11411 (org-entry-is-todo-p))
11412 (throw 'dont-block nil))
11413 (outline-next-heading)
11414 (setq child-level (funcall outline-level))))))
11415 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11416 ;; any previous siblings are undone, it's blocked
11417 (save-excursion
11418 (org-back-to-heading t)
11419 (let* ((pos (point))
11420 (parent-pos (and (org-up-heading-safe) (point))))
11421 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11422 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11423 (forward-line 1)
11424 (re-search-forward org-not-done-heading-regexp pos t))
11425 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11426 ;; Search further up the hierarchy, to see if an anchestor is blocked
11427 (while t
11428 (goto-char parent-pos)
11429 (if (not (looking-at org-not-done-heading-regexp))
11430 (throw 'dont-block t)) ; do not block, parent is not a TODO
11431 (setq pos (point))
11432 (setq parent-pos (and (org-up-heading-safe) (point)))
11433 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11434 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11435 (forward-line 1)
11436 (re-search-forward org-not-done-heading-regexp pos t))
11437 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11439 (defcustom org-track-ordered-property-with-tag nil
11440 "Should the ORDERED property also be shown as a tag?
11441 The ORDERED property decides if an entry should require subtasks to be
11442 completed in sequence. Since a property is not very visible, setting
11443 this option means that toggling the ORDERED property with the command
11444 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11445 not relevant for the behavior, but it makes things more visible.
11447 Note that toggling the tag with tags commands will not change the property
11448 and therefore not influence behavior!
11450 This can be t, meaning the tag ORDERED should be used, It can also be a
11451 string to select a different tag for this task."
11452 :group 'org-todo
11453 :type '(choice
11454 (const :tag "No tracking" nil)
11455 (const :tag "Track with ORDERED tag" t)
11456 (string :tag "Use other tag")))
11458 (defun org-toggle-ordered-property ()
11459 "Toggle the ORDERED property of the current entry.
11460 For better visibility, you can track the value of this property with a tag.
11461 See variable `org-track-ordered-property-with-tag'."
11462 (interactive)
11463 (let* ((t1 org-track-ordered-property-with-tag)
11464 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11465 (save-excursion
11466 (org-back-to-heading)
11467 (if (org-entry-get nil "ORDERED")
11468 (progn
11469 (org-delete-property "ORDERED")
11470 (and tag (org-toggle-tag tag 'off))
11471 (message "Subtasks can be completed in arbitrary order"))
11472 (org-entry-put nil "ORDERED" "t")
11473 (and tag (org-toggle-tag tag 'on))
11474 (message "Subtasks must be completed in sequence")))))
11476 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11477 (defun org-block-todo-from-checkboxes (change-plist)
11478 "Block turning an entry into a TODO, using checkboxes.
11479 This checks whether the current task should be blocked from state
11480 changes because there are unchecked boxes in this entry."
11481 (if (not org-enforce-todo-checkbox-dependencies)
11482 t ; if locally turned off don't block
11483 (catch 'dont-block
11484 ;; If this is not a todo state change, or if this entry is already DONE,
11485 ;; do not block
11486 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11487 (member (plist-get change-plist :from)
11488 (cons 'done org-done-keywords))
11489 (member (plist-get change-plist :to)
11490 (cons 'todo org-not-done-keywords))
11491 (not (plist-get change-plist :to)))
11492 (throw 'dont-block t))
11493 ;; If this task has checkboxes that are not checked, it's blocked
11494 (save-excursion
11495 (org-back-to-heading t)
11496 (let ((beg (point)) end)
11497 (outline-next-heading)
11498 (setq end (point))
11499 (goto-char beg)
11500 (if (org-list-search-forward
11501 (concat (org-item-beginning-re)
11502 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11503 "\\[[- ]\\]")
11504 end t)
11505 (progn
11506 (if (boundp 'org-blocked-by-checkboxes)
11507 (setq org-blocked-by-checkboxes t))
11508 (throw 'dont-block nil)))))
11509 t))) ; do not block
11511 (defun org-entry-blocked-p ()
11512 "Is the current entry blocked?"
11513 (if (org-entry-get nil "NOBLOCKING")
11514 nil ;; Never block this entry
11515 (not
11516 (run-hook-with-args-until-failure
11517 'org-blocker-hook
11518 (list :type 'todo-state-change
11519 :position (point)
11520 :from 'todo
11521 :to 'done)))))
11523 (defun org-update-statistics-cookies (all)
11524 "Update the statistics cookie, either from TODO or from checkboxes.
11525 This should be called with the cursor in a line with a statistics cookie."
11526 (interactive "P")
11527 (if all
11528 (progn
11529 (org-update-checkbox-count 'all)
11530 (org-map-entries 'org-update-parent-todo-statistics))
11531 (if (not (org-on-heading-p))
11532 (org-update-checkbox-count)
11533 (let ((pos (move-marker (make-marker) (point)))
11534 end l1 l2)
11535 (ignore-errors (org-back-to-heading t))
11536 (if (not (org-on-heading-p))
11537 (org-update-checkbox-count)
11538 (setq l1 (org-outline-level))
11539 (setq end (save-excursion
11540 (outline-next-heading)
11541 (if (org-on-heading-p) (setq l2 (org-outline-level)))
11542 (point)))
11543 (if (and (save-excursion
11544 (re-search-forward
11545 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11546 (not (save-excursion (re-search-forward
11547 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11548 (org-update-checkbox-count)
11549 (if (and l2 (> l2 l1))
11550 (progn
11551 (goto-char end)
11552 (org-update-parent-todo-statistics))
11553 (goto-char pos)
11554 (beginning-of-line 1)
11555 (while (re-search-forward
11556 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11557 (point-at-eol) t)
11558 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11559 (goto-char pos)
11560 (move-marker pos nil)))))
11562 (defvar org-entry-property-inherited-from) ;; defined below
11563 (defun org-update-parent-todo-statistics ()
11564 "Update any statistics cookie in the parent of the current headline.
11565 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11566 the entire subtree and this will travel up the hierarchy and update
11567 statistics everywhere."
11568 (let* ((prop (save-excursion (org-up-heading-safe)
11569 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11570 (recursive (or (not org-hierarchical-todo-statistics)
11571 (and prop (string-match "\\<recursive\\>" prop))))
11572 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11574 (first t)
11575 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11576 level ltoggle l1 new ndel
11577 (cnt-all 0) (cnt-done 0) is-percent kwd
11578 checkbox-beg ov ovs ove cookie-present)
11579 (catch 'exit
11580 (save-excursion
11581 (beginning-of-line 1)
11582 (setq ltoggle (funcall outline-level))
11583 ;; Three situations are to consider:
11585 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11586 ;; to the top-level ancestor on the headline;
11588 ;; 2. If parent has "recursive" property, repeat up to the
11589 ;; headline setting that property, taking inheritance into
11590 ;; account;
11592 ;; 3. Else, move up to direct parent and proceed only once.
11593 (while (and (setq level (org-up-heading-safe))
11594 (or recursive first)
11595 (>= (point) lim))
11596 (setq first nil cookie-present nil)
11597 (unless (and level
11598 (not (string-match
11599 "\\<checkbox\\>"
11600 (downcase (or (org-entry-get nil "COOKIE_DATA")
11601 "")))))
11602 (throw 'exit nil))
11603 (while (re-search-forward box-re (point-at-eol) t)
11604 (setq cnt-all 0 cnt-done 0 cookie-present t)
11605 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11606 (save-match-data
11607 (unless (outline-next-heading) (throw 'exit nil))
11608 (while (and (looking-at org-complex-heading-regexp)
11609 (> (setq l1 (length (match-string 1))) level))
11610 (setq kwd (and (or recursive (= l1 ltoggle))
11611 (match-string 2)))
11612 (if (or (eq org-provide-todo-statistics 'all-headlines)
11613 (and (listp org-provide-todo-statistics)
11614 (or (member kwd org-provide-todo-statistics)
11615 (member kwd org-done-keywords))))
11616 (setq cnt-all (1+ cnt-all))
11617 (if (eq org-provide-todo-statistics t)
11618 (and kwd (setq cnt-all (1+ cnt-all)))))
11619 (and (member kwd org-done-keywords)
11620 (setq cnt-done (1+ cnt-done)))
11621 (outline-next-heading)))
11622 (setq new
11623 (if is-percent
11624 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11625 (format "[%d/%d]" cnt-done cnt-all))
11626 ndel (- (match-end 0) checkbox-beg))
11627 ;; handle overlays when updating cookie from column view
11628 (when (setq ov (car (overlays-at checkbox-beg)))
11629 (setq ovs (overlay-start ov) ove (overlay-end ov))
11630 (delete-overlay ov))
11631 (goto-char checkbox-beg)
11632 (insert new)
11633 (delete-region (point) (+ (point) ndel))
11634 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11635 (when ov (move-overlay ov ovs ove)))
11636 (when cookie-present
11637 (run-hook-with-args 'org-after-todo-statistics-hook
11638 cnt-done (- cnt-all cnt-done))))))
11639 (run-hooks 'org-todo-statistics-hook)))
11641 (defvar org-after-todo-statistics-hook nil
11642 "Hook that is called after a TODO statistics cookie has been updated.
11643 Each function is called with two arguments: the number of not-done entries
11644 and the number of done entries.
11646 For example, the following function, when added to this hook, will switch
11647 an entry to DONE when all children are done, and back to TODO when new
11648 entries are set to a TODO status. Note that this hook is only called
11649 when there is a statistics cookie in the headline!
11651 (defun org-summary-todo (n-done n-not-done)
11652 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11653 (let (org-log-done org-log-states) ; turn off logging
11654 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11657 (defvar org-todo-statistics-hook nil
11658 "Hook that is run whenever Org thinks TODO statistics should be updated.
11659 This hook runs even if there is no statistics cookie present, in which case
11660 `org-after-todo-statistics-hook' would not run.")
11662 (defun org-todo-trigger-tag-changes (state)
11663 "Apply the changes defined in `org-todo-state-tags-triggers'."
11664 (let ((l org-todo-state-tags-triggers)
11665 changes)
11666 (when (or (not state) (equal state ""))
11667 (setq changes (append changes (cdr (assoc "" l)))))
11668 (when (and (stringp state) (> (length state) 0))
11669 (setq changes (append changes (cdr (assoc state l)))))
11670 (when (member state org-not-done-keywords)
11671 (setq changes (append changes (cdr (assoc 'todo l)))))
11672 (when (member state org-done-keywords)
11673 (setq changes (append changes (cdr (assoc 'done l)))))
11674 (dolist (c changes)
11675 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11677 (defun org-local-logging (value)
11678 "Get logging settings from a property VALUE."
11679 (let* (words w a)
11680 ;; directly set the variables, they are already local.
11681 (setq org-log-done nil
11682 org-log-repeat nil
11683 org-todo-log-states nil)
11684 (setq words (org-split-string value))
11685 (while (setq w (pop words))
11686 (cond
11687 ((setq a (assoc w org-startup-options))
11688 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11689 (set (nth 1 a) (nth 2 a))))
11690 ((setq a (org-extract-log-state-settings w))
11691 (and (member (car a) org-todo-keywords-1)
11692 (push a org-todo-log-states)))))))
11694 (defun org-get-todo-sequence-head (kwd)
11695 "Return the head of the TODO sequence to which KWD belongs.
11696 If KWD is not set, check if there is a text property remembering the
11697 right sequence."
11698 (let (p)
11699 (cond
11700 ((not kwd)
11701 (or (get-text-property (point-at-bol) 'org-todo-head)
11702 (progn
11703 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11704 nil (point-at-eol)))
11705 (get-text-property p 'org-todo-head))))
11706 ((not (member kwd org-todo-keywords-1))
11707 (car org-todo-keywords-1))
11708 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11710 (defun org-fast-todo-selection ()
11711 "Fast TODO keyword selection with single keys.
11712 Returns the new TODO keyword, or nil if no state change should occur."
11713 (let* ((fulltable org-todo-key-alist)
11714 (done-keywords org-done-keywords) ;; needed for the faces.
11715 (maxlen (apply 'max (mapcar
11716 (lambda (x)
11717 (if (stringp (car x)) (string-width (car x)) 0))
11718 fulltable)))
11719 (expert nil)
11720 (fwidth (+ maxlen 3 1 3))
11721 (ncol (/ (- (window-width) 4) fwidth))
11722 tg cnt e c tbl
11723 groups ingroup)
11724 (save-excursion
11725 (save-window-excursion
11726 (if expert
11727 (set-buffer (get-buffer-create " *Org todo*"))
11728 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11729 (erase-buffer)
11730 (org-set-local 'org-done-keywords done-keywords)
11731 (setq tbl fulltable cnt 0)
11732 (while (setq e (pop tbl))
11733 (cond
11734 ((equal e '(:startgroup))
11735 (push '() groups) (setq ingroup t)
11736 (when (not (= cnt 0))
11737 (setq cnt 0)
11738 (insert "\n"))
11739 (insert "{ "))
11740 ((equal e '(:endgroup))
11741 (setq ingroup nil cnt 0)
11742 (insert "}\n"))
11743 ((equal e '(:newline))
11744 (when (not (= cnt 0))
11745 (setq cnt 0)
11746 (insert "\n")
11747 (setq e (car tbl))
11748 (while (equal (car tbl) '(:newline))
11749 (insert "\n")
11750 (setq tbl (cdr tbl)))))
11752 (setq tg (car e) c (cdr e))
11753 (if ingroup (push tg (car groups)))
11754 (setq tg (org-add-props tg nil 'face
11755 (org-get-todo-face tg)))
11756 (if (and (= cnt 0) (not ingroup)) (insert " "))
11757 (insert "[" c "] " tg (make-string
11758 (- fwidth 4 (length tg)) ?\ ))
11759 (when (= (setq cnt (1+ cnt)) ncol)
11760 (insert "\n")
11761 (if ingroup (insert " "))
11762 (setq cnt 0)))))
11763 (insert "\n")
11764 (goto-char (point-min))
11765 (if (not expert) (org-fit-window-to-buffer))
11766 (message "[a-z..]:Set [SPC]:clear")
11767 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11768 (cond
11769 ((or (= c ?\C-g)
11770 (and (= c ?q) (not (rassoc c fulltable))))
11771 (setq quit-flag t))
11772 ((= c ?\ ) nil)
11773 ((setq e (rassoc c fulltable) tg (car e))
11775 (t (setq quit-flag t)))))))
11777 (defun org-entry-is-todo-p ()
11778 (member (org-get-todo-state) org-not-done-keywords))
11780 (defun org-entry-is-done-p ()
11781 (member (org-get-todo-state) org-done-keywords))
11783 (defun org-get-todo-state ()
11784 (save-excursion
11785 (org-back-to-heading t)
11786 (and (looking-at org-todo-line-regexp)
11787 (match-end 2)
11788 (match-string 2))))
11790 (defun org-at-date-range-p (&optional inactive-ok)
11791 "Is the cursor inside a date range?"
11792 (interactive)
11793 (save-excursion
11794 (catch 'exit
11795 (let ((pos (point)))
11796 (skip-chars-backward "^[<\r\n")
11797 (skip-chars-backward "<[")
11798 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11799 (>= (match-end 0) pos)
11800 (throw 'exit t))
11801 (skip-chars-backward "^<[\r\n")
11802 (skip-chars-backward "<[")
11803 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11804 (>= (match-end 0) pos)
11805 (throw 'exit t)))
11806 nil)))
11808 (defun org-get-repeat (&optional tagline)
11809 "Check if there is a deadline/schedule with repeater in this entry."
11810 (save-match-data
11811 (save-excursion
11812 (org-back-to-heading t)
11813 (and (re-search-forward (if tagline
11814 (concat tagline "\\s-*" org-repeat-re)
11815 org-repeat-re)
11816 (org-entry-end-position) t)
11817 (match-string-no-properties 1)))))
11819 (defvar org-last-changed-timestamp)
11820 (defvar org-last-inserted-timestamp)
11821 (defvar org-log-post-message)
11822 (defvar org-log-note-purpose)
11823 (defvar org-log-note-how)
11824 (defvar org-log-note-extra)
11825 (defun org-auto-repeat-maybe (done-word)
11826 "Check if the current headline contains a repeated deadline/schedule.
11827 If yes, set TODO state back to what it was and change the base date
11828 of repeating deadline/scheduled time stamps to new date.
11829 This function is run automatically after each state change to a DONE state."
11830 ;; last-state is dynamically scoped into this function
11831 (let* ((repeat (org-get-repeat))
11832 (aa (assoc last-state org-todo-kwd-alist))
11833 (interpret (nth 1 aa))
11834 (head (nth 2 aa))
11835 (whata '(("d" . day) ("m" . month) ("y" . year)))
11836 (msg "Entry repeats: ")
11837 (org-log-done nil)
11838 (org-todo-log-states nil)
11839 re type n what ts time to-state)
11840 (when repeat
11841 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11842 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11843 org-todo-repeat-to-state))
11844 (unless (and to-state (member to-state org-todo-keywords-1))
11845 (setq to-state (if (eq interpret 'type) last-state head)))
11846 (org-todo to-state)
11847 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11848 (org-entry-put nil "LAST_REPEAT" (format-time-string
11849 (org-time-stamp-format t t))))
11850 (when org-log-repeat
11851 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11852 (memq 'org-add-log-note post-command-hook))
11853 ;; OK, we are already setup for some record
11854 (if (eq org-log-repeat 'note)
11855 ;; make sure we take a note, not only a time stamp
11856 (setq org-log-note-how 'note))
11857 ;; Set up for taking a record
11858 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11859 last-state
11860 'findpos org-log-repeat)))
11861 (org-back-to-heading t)
11862 (org-add-planning-info nil nil 'closed)
11863 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11864 org-deadline-time-regexp "\\)\\|\\("
11865 org-ts-regexp "\\)"))
11866 (while (re-search-forward
11867 re (save-excursion (outline-next-heading) (point)) t)
11868 (setq type (if (match-end 1) org-scheduled-string
11869 (if (match-end 3) org-deadline-string "Plain:"))
11870 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11871 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11872 (setq n (string-to-number (match-string 2 ts))
11873 what (match-string 3 ts))
11874 (if (equal what "w") (setq n (* n 7) what "d"))
11875 ;; Preparation, see if we need to modify the start date for the change
11876 (when (match-end 1)
11877 (setq time (save-match-data (org-time-string-to-time ts)))
11878 (cond
11879 ((equal (match-string 1 ts) ".")
11880 ;; Shift starting date to today
11881 (org-timestamp-change
11882 (- (org-today) (time-to-days time))
11883 'day))
11884 ((equal (match-string 1 ts) "+")
11885 (let ((nshiftmax 10) (nshift 0))
11886 (while (or (= nshift 0)
11887 (<= (time-to-days time)
11888 (time-to-days (current-time))))
11889 (when (= (incf nshift) nshiftmax)
11890 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11891 (error "Abort")))
11892 (org-timestamp-change n (cdr (assoc what whata)))
11893 (org-at-timestamp-p t)
11894 (setq ts (match-string 1))
11895 (setq time (save-match-data (org-time-string-to-time ts)))))
11896 (org-timestamp-change (- n) (cdr (assoc what whata)))
11897 ;; rematch, so that we have everything in place for the real shift
11898 (org-at-timestamp-p t)
11899 (setq ts (match-string 1))
11900 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11901 (org-timestamp-change n (cdr (assoc what whata)))
11902 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11903 (setq org-log-post-message msg)
11904 (message "%s" msg))))
11906 (defun org-show-todo-tree (arg)
11907 "Make a compact tree which shows all headlines marked with TODO.
11908 The tree will show the lines where the regexp matches, and all higher
11909 headlines above the match.
11910 With a \\[universal-argument] prefix, prompt for a regexp to match.
11911 With a numeric prefix N, construct a sparse tree for the Nth element
11912 of `org-todo-keywords-1'."
11913 (interactive "P")
11914 (let ((case-fold-search nil)
11915 (kwd-re
11916 (cond ((null arg) org-not-done-regexp)
11917 ((equal arg '(4))
11918 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11919 (mapcar 'list org-todo-keywords-1))))
11920 (concat "\\("
11921 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11922 "\\)\\>")))
11923 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11924 (regexp-quote (nth (1- (prefix-numeric-value arg))
11925 org-todo-keywords-1)))
11926 (t (error "Invalid prefix argument: %s" arg)))))
11927 (message "%d TODO entries found"
11928 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
11930 (defun org-deadline (&optional remove time)
11931 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11932 With argument REMOVE, remove any deadline from the item.
11933 With argument TIME, set the deadline at the corresponding date. TIME
11934 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
11935 (interactive "P")
11936 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11937 (let (org-loop-over-headlines-in-active-region)
11938 (org-map-entries
11939 `(org-deadline ',remove ,time) org-loop-over-headlines-in-active-region 'region (if (outline-invisible-p) (org-end-of-subtree nil t))))
11940 (let* ((old-date (org-entry-get nil "DEADLINE"))
11941 (repeater (and old-date
11942 (string-match
11943 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11944 old-date)
11945 (match-string 1 old-date))))
11946 (if remove
11947 (progn
11948 (when (and old-date org-log-redeadline)
11949 (org-add-log-setup 'deldeadline nil old-date 'findpos
11950 org-log-redeadline))
11951 (org-remove-timestamp-with-keyword org-deadline-string)
11952 (message "Item no longer has a deadline."))
11953 (org-add-planning-info 'deadline time 'closed)
11954 (when (and old-date org-log-redeadline
11955 (not (equal old-date
11956 (substring org-last-inserted-timestamp 1 -1))))
11957 (org-add-log-setup 'redeadline nil old-date 'findpos
11958 org-log-redeadline))
11959 (when repeater
11960 (save-excursion
11961 (org-back-to-heading t)
11962 (when (re-search-forward (concat org-deadline-string " "
11963 org-last-inserted-timestamp)
11964 (save-excursion
11965 (outline-next-heading) (point)) t)
11966 (goto-char (1- (match-end 0)))
11967 (insert " " repeater)
11968 (setq org-last-inserted-timestamp
11969 (concat (substring org-last-inserted-timestamp 0 -1)
11970 " " repeater
11971 (substring org-last-inserted-timestamp -1))))))
11972 (message "Deadline on %s" org-last-inserted-timestamp)))))
11974 (defun org-schedule (&optional remove time)
11975 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11976 With argument REMOVE, remove any scheduling date from the item.
11977 With argument TIME, scheduled at the corresponding date. TIME can
11978 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
11979 (interactive "P")
11980 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11981 (let (org-loop-over-headlines-in-active-region)
11982 (org-map-entries
11983 `(org-schedule ',remove ,time) org-loop-over-headlines-in-active-region 'region (if (outline-invisible-p) (org-end-of-subtree nil t))))
11984 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11985 (repeater (and old-date
11986 (string-match
11987 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11988 old-date)
11989 (match-string 1 old-date))))
11990 (if remove
11991 (progn
11992 (when (and old-date org-log-reschedule)
11993 (org-add-log-setup 'delschedule nil old-date 'findpos
11994 org-log-reschedule))
11995 (org-remove-timestamp-with-keyword org-scheduled-string)
11996 (message "Item is no longer scheduled."))
11997 (org-add-planning-info 'scheduled time 'closed)
11998 (when (and old-date org-log-reschedule
11999 (not (equal old-date
12000 (substring org-last-inserted-timestamp 1 -1))))
12001 (org-add-log-setup 'reschedule nil old-date 'findpos
12002 org-log-reschedule))
12003 (when repeater
12004 (save-excursion
12005 (org-back-to-heading t)
12006 (when (re-search-forward (concat org-scheduled-string " "
12007 org-last-inserted-timestamp)
12008 (save-excursion
12009 (outline-next-heading) (point)) t)
12010 (goto-char (1- (match-end 0)))
12011 (insert " " repeater)
12012 (setq org-last-inserted-timestamp
12013 (concat (substring org-last-inserted-timestamp 0 -1)
12014 " " repeater
12015 (substring org-last-inserted-timestamp -1))))))
12016 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12018 (defun org-get-scheduled-time (pom &optional inherit)
12019 "Get the scheduled time as a time tuple, of a format suitable
12020 for calling org-schedule with, or if there is no scheduling,
12021 returns nil."
12022 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12023 (when time
12024 (apply 'encode-time (org-parse-time-string time)))))
12026 (defun org-get-deadline-time (pom &optional inherit)
12027 "Get the deadline as a time tuple, of a format suitable for
12028 calling org-deadline with, or if there is no scheduling, returns
12029 nil."
12030 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12031 (when time
12032 (apply 'encode-time (org-parse-time-string time)))))
12034 (defun org-remove-timestamp-with-keyword (keyword)
12035 "Remove all time stamps with KEYWORD in the current entry."
12036 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12037 beg)
12038 (save-excursion
12039 (org-back-to-heading t)
12040 (setq beg (point))
12041 (outline-next-heading)
12042 (while (re-search-backward re beg t)
12043 (replace-match "")
12044 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12045 (equal (char-before) ?\ ))
12046 (backward-delete-char 1)
12047 (if (string-match "^[ \t]*$" (buffer-substring
12048 (point-at-bol) (point-at-eol)))
12049 (delete-region (point-at-bol)
12050 (min (point-max) (1+ (point-at-eol))))))))))
12052 (defun org-add-planning-info (what &optional time &rest remove)
12053 "Insert new timestamp with keyword in the line directly after the headline.
12054 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12055 If non is given, the user is prompted for a date.
12056 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12057 be removed."
12058 (interactive)
12059 (let (org-time-was-given org-end-time-was-given ts
12060 end default-time default-input)
12062 (catch 'exit
12063 (when (and (memq what '(scheduled deadline))
12064 (or (not time)
12065 (and (stringp time)
12066 (string-match "^[-+]+[0-9]" time))))
12067 ;; Try to get a default date/time from existing timestamp
12068 (save-excursion
12069 (org-back-to-heading t)
12070 (setq end (save-excursion (outline-next-heading) (point)))
12071 (when (re-search-forward (if (eq what 'scheduled)
12072 org-scheduled-time-regexp
12073 org-deadline-time-regexp)
12074 end t)
12075 (setq ts (match-string 1)
12076 default-time
12077 (apply 'encode-time (org-parse-time-string ts))
12078 default-input (and ts (org-get-compact-tod ts))))))
12079 (when what
12080 (setq time
12081 (if (stringp time)
12082 ;; This is a string (relative or absolute), set proper date
12083 (apply 'encode-time
12084 (org-read-date-analyze
12085 time default-time (decode-time default-time)))
12086 ;; If necessary, get the time from the user
12087 (or time (org-read-date nil 'to-time nil nil
12088 default-time default-input)))))
12090 (when (and org-insert-labeled-timestamps-at-point
12091 (member what '(scheduled deadline)))
12092 (insert
12093 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12094 (org-insert-time-stamp time org-time-was-given
12095 nil nil nil (list org-end-time-was-given))
12096 (setq what nil))
12097 (save-excursion
12098 (save-restriction
12099 (let (col list elt ts buffer-invisibility-spec)
12100 (org-back-to-heading t)
12101 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12102 (goto-char (match-end 1))
12103 (setq col (current-column))
12104 (goto-char (match-end 0))
12105 (if (eobp) (insert "\n") (forward-char 1))
12106 (when (and (not what)
12107 (not (looking-at
12108 (concat "[ \t]*"
12109 org-keyword-time-not-clock-regexp))))
12110 ;; Nothing to add, nothing to remove...... :-)
12111 (throw 'exit nil))
12112 (if (and (not (looking-at org-outline-regexp))
12113 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12114 "[^\r\n]*"))
12115 (not (equal (match-string 1) org-clock-string)))
12116 (narrow-to-region (match-beginning 0) (match-end 0))
12117 (insert-before-markers "\n")
12118 (backward-char 1)
12119 (narrow-to-region (point) (point))
12120 (and org-adapt-indentation (org-indent-to-column col)))
12121 ;; Check if we have to remove something.
12122 (setq list (cons what remove))
12123 (while list
12124 (setq elt (pop list))
12125 (when (or (and (eq elt 'scheduled)
12126 (re-search-forward org-scheduled-time-regexp nil t))
12127 (and (eq elt 'deadline)
12128 (re-search-forward org-deadline-time-regexp nil t))
12129 (and (eq elt 'closed)
12130 (re-search-forward org-closed-time-regexp nil t)))
12131 (replace-match "")
12132 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12133 (and (looking-at "[ \t]+") (replace-match ""))
12134 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12135 (when what
12136 (insert
12137 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12138 (cond ((eq what 'scheduled) org-scheduled-string)
12139 ((eq what 'deadline) org-deadline-string)
12140 ((eq what 'closed) org-closed-string))
12141 " ")
12142 (setq ts (org-insert-time-stamp
12143 time
12144 (or org-time-was-given
12145 (and (eq what 'closed) org-log-done-with-time))
12146 (eq what 'closed)
12147 nil nil (list org-end-time-was-given)))
12148 (insert
12149 (if (not (or (bolp) (eq (char-before) ?\ )
12150 (memq (char-after) '(32 10))
12151 (eobp))) " " ""))
12152 (end-of-line 1))
12153 (goto-char (point-min))
12154 (widen)
12155 (if (and (looking-at "[ \t]*\n")
12156 (equal (char-before) ?\n))
12157 (delete-region (1- (point)) (point-at-eol)))
12158 ts))))))
12160 (defvar org-log-note-marker (make-marker))
12161 (defvar org-log-note-purpose nil)
12162 (defvar org-log-note-state nil)
12163 (defvar org-log-note-previous-state nil)
12164 (defvar org-log-note-how nil)
12165 (defvar org-log-note-extra nil)
12166 (defvar org-log-note-window-configuration nil)
12167 (defvar org-log-note-return-to (make-marker))
12168 (defvar org-log-note-effective-time nil
12169 "Remembered current time so that dynamically scoped
12170 `org-extend-today-until' affects tha timestamps in state change
12171 log")
12173 (defvar org-log-post-message nil
12174 "Message to be displayed after a log note has been stored.
12175 The auto-repeater uses this.")
12177 (defun org-add-note ()
12178 "Add a note to the current entry.
12179 This is done in the same way as adding a state change note."
12180 (interactive)
12181 (org-add-log-setup 'note nil nil 'findpos nil))
12183 (defvar org-property-end-re)
12184 (defun org-add-log-setup (&optional purpose state prev-state
12185 findpos how extra)
12186 "Set up the post command hook to take a note.
12187 If this is about to TODO state change, the new state is expected in STATE.
12188 When FINDPOS is non-nil, find the correct position for the note in
12189 the current entry. If not, assume that it can be inserted at point.
12190 HOW is an indicator what kind of note should be created.
12191 EXTRA is additional text that will be inserted into the notes buffer."
12192 (let* ((org-log-into-drawer (org-log-into-drawer))
12193 (drawer (cond ((stringp org-log-into-drawer)
12194 org-log-into-drawer)
12195 (org-log-into-drawer "LOGBOOK")
12196 (t nil))))
12197 (save-restriction
12198 (save-excursion
12199 (when findpos
12200 (org-back-to-heading t)
12201 (narrow-to-region (point) (save-excursion
12202 (outline-next-heading) (point)))
12203 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12204 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12205 "[^\r\n]*\\)?"))
12206 (goto-char (match-end 0))
12207 (cond
12208 (drawer
12209 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12210 nil t)
12211 (progn
12212 (goto-char (match-end 0))
12213 (or org-log-states-order-reversed
12214 (and (re-search-forward org-property-end-re nil t)
12215 (goto-char (1- (match-beginning 0))))))
12216 (insert "\n:" drawer ":\n:END:")
12217 (beginning-of-line 0)
12218 (org-indent-line-function)
12219 (beginning-of-line 2)
12220 (org-indent-line-function)
12221 (end-of-line 0)))
12222 ((and org-log-state-notes-insert-after-drawers
12223 (save-excursion
12224 (forward-line) (looking-at org-drawer-regexp)))
12225 (forward-line)
12226 (while (looking-at org-drawer-regexp)
12227 (goto-char (match-end 0))
12228 (re-search-forward org-property-end-re (point-max) t)
12229 (forward-line))
12230 (forward-line -1)))
12231 (unless org-log-states-order-reversed
12232 (and (= (char-after) ?\n) (forward-char 1))
12233 (org-skip-over-state-notes)
12234 (skip-chars-backward " \t\n\r")))
12235 (move-marker org-log-note-marker (point))
12236 (setq org-log-note-purpose purpose
12237 org-log-note-state state
12238 org-log-note-previous-state prev-state
12239 org-log-note-how how
12240 org-log-note-extra extra
12241 org-log-note-effective-time (org-current-effective-time))
12242 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12244 (defun org-skip-over-state-notes ()
12245 "Skip past the list of State notes in an entry."
12246 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12247 (when (ignore-errors (goto-char (org-in-item-p)))
12248 (let* ((struct (org-list-struct))
12249 (prevs (org-list-prevs-alist struct)))
12250 (while (looking-at "[ \t]*- State")
12251 (goto-char (or (org-list-get-next-item (point) struct prevs)
12252 (org-list-get-item-end (point) struct)))))))
12254 (defun org-add-log-note (&optional purpose)
12255 "Pop up a window for taking a note, and add this note later at point."
12256 (remove-hook 'post-command-hook 'org-add-log-note)
12257 (setq org-log-note-window-configuration (current-window-configuration))
12258 (delete-other-windows)
12259 (move-marker org-log-note-return-to (point))
12260 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12261 (goto-char org-log-note-marker)
12262 (org-switch-to-buffer-other-window "*Org Note*")
12263 (erase-buffer)
12264 (if (memq org-log-note-how '(time state))
12265 (let (current-prefix-arg) (org-store-log-note))
12266 (let ((org-inhibit-startup t)) (org-mode))
12267 (insert (format "# Insert note for %s.
12268 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12269 (cond
12270 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12271 ((eq org-log-note-purpose 'done) "closed todo item")
12272 ((eq org-log-note-purpose 'state)
12273 (format "state change from \"%s\" to \"%s\""
12274 (or org-log-note-previous-state "")
12275 (or org-log-note-state "")))
12276 ((eq org-log-note-purpose 'reschedule)
12277 "rescheduling")
12278 ((eq org-log-note-purpose 'delschedule)
12279 "no longer scheduled")
12280 ((eq org-log-note-purpose 'redeadline)
12281 "changing deadline")
12282 ((eq org-log-note-purpose 'deldeadline)
12283 "removing deadline")
12284 ((eq org-log-note-purpose 'refile)
12285 "refiling")
12286 ((eq org-log-note-purpose 'note)
12287 "this entry")
12288 (t (error "This should not happen")))))
12289 (if org-log-note-extra (insert org-log-note-extra))
12290 (org-set-local 'org-finish-function 'org-store-log-note)
12291 (run-hooks 'org-log-buffer-setup-hook)))
12293 (defvar org-note-abort nil) ; dynamically scoped
12294 (defun org-store-log-note ()
12295 "Finish taking a log note, and insert it to where it belongs."
12296 (let ((txt (buffer-string))
12297 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12298 lines ind bul)
12299 (kill-buffer (current-buffer))
12300 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12301 (setq txt (replace-match "" t t txt)))
12302 (if (string-match "\\s-+\\'" txt)
12303 (setq txt (replace-match "" t t txt)))
12304 (setq lines (org-split-string txt "\n"))
12305 (when (and note (string-match "\\S-" note))
12306 (setq note
12307 (org-replace-escapes
12308 note
12309 (list (cons "%u" (user-login-name))
12310 (cons "%U" user-full-name)
12311 (cons "%t" (format-time-string
12312 (org-time-stamp-format 'long 'inactive)
12313 org-log-note-effective-time))
12314 (cons "%T" (format-time-string
12315 (org-time-stamp-format 'long nil)
12316 org-log-note-effective-time))
12317 (cons "%d" (format-time-string
12318 (org-time-stamp-format nil 'inactive)
12319 org-log-note-effective-time))
12320 (cons "%D" (format-time-string
12321 (org-time-stamp-format nil nil)
12322 org-log-note-effective-time))
12323 (cons "%s" (if org-log-note-state
12324 (concat "\"" org-log-note-state "\"")
12325 ""))
12326 (cons "%S" (if org-log-note-previous-state
12327 (concat "\"" org-log-note-previous-state "\"")
12328 "\"\"")))))
12329 (if lines (setq note (concat note " \\\\")))
12330 (push note lines))
12331 (when (or current-prefix-arg org-note-abort)
12332 (when org-log-into-drawer
12333 (org-remove-empty-drawer-at
12334 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12335 org-log-note-marker))
12336 (setq lines nil))
12337 (when lines
12338 (with-current-buffer (marker-buffer org-log-note-marker)
12339 (save-excursion
12340 (goto-char org-log-note-marker)
12341 (move-marker org-log-note-marker nil)
12342 (end-of-line 1)
12343 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12344 (setq ind (save-excursion
12345 (if (ignore-errors (goto-char (org-in-item-p)))
12346 (let ((struct (org-list-struct)))
12347 (org-list-get-ind
12348 (org-list-get-top-point struct) struct))
12349 (skip-chars-backward " \r\t\n")
12350 (cond
12351 ((and (org-at-heading-p)
12352 org-adapt-indentation)
12353 (1+ (org-current-level)))
12354 ((org-at-heading-p) 0)
12355 (t (org-get-indentation))))))
12356 (setq bul (org-list-bullet-string "-"))
12357 (org-indent-line-to ind)
12358 (insert bul (pop lines))
12359 (let ((ind-body (+ (length bul) ind)))
12360 (while lines
12361 (insert "\n")
12362 (org-indent-line-to ind-body)
12363 (insert (pop lines))))
12364 (message "Note stored")
12365 (org-back-to-heading t)
12366 (org-cycle-hide-drawers 'children)))))
12367 (set-window-configuration org-log-note-window-configuration)
12368 (with-current-buffer (marker-buffer org-log-note-return-to)
12369 (goto-char org-log-note-return-to))
12370 (move-marker org-log-note-return-to nil)
12371 (and org-log-post-message (message "%s" org-log-post-message)))
12373 (defun org-remove-empty-drawer-at (drawer pos)
12374 "Remove an empty drawer DRAWER at position POS.
12375 POS may also be a marker."
12376 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12377 (save-excursion
12378 (save-restriction
12379 (widen)
12380 (goto-char pos)
12381 (if (org-in-regexp
12382 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12383 (replace-match ""))))))
12385 (defun org-sparse-tree (&optional arg)
12386 "Create a sparse tree, prompt for the details.
12387 This command can create sparse trees. You first need to select the type
12388 of match used to create the tree:
12390 t Show all TODO entries.
12391 T Show entries with a specific TODO keyword.
12392 m Show entries selected by a tags/property match.
12393 p Enter a property name and its value (both with completion on existing
12394 names/values) and show entries with that property.
12395 r Show entries matching a regular expression (`/' can be used as well)
12396 d Show deadlines due within `org-deadline-warning-days'.
12397 b Show deadlines and scheduled items before a date.
12398 a Show deadlines and scheduled items after a date."
12399 (interactive "P")
12400 (let (ans kwd value)
12401 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date")
12402 (setq ans (read-char-exclusive))
12403 (cond
12404 ((equal ans ?d)
12405 (call-interactively 'org-check-deadlines))
12406 ((equal ans ?b)
12407 (call-interactively 'org-check-before-date))
12408 ((equal ans ?a)
12409 (call-interactively 'org-check-after-date))
12410 ((equal ans ?t)
12411 (org-show-todo-tree nil))
12412 ((equal ans ?T)
12413 (org-show-todo-tree '(4)))
12414 ((member ans '(?T ?m))
12415 (call-interactively 'org-match-sparse-tree))
12416 ((member ans '(?p ?P))
12417 (setq kwd (org-icompleting-read "Property: "
12418 (mapcar 'list (org-buffer-property-keys))))
12419 (setq value (org-icompleting-read "Value: "
12420 (mapcar 'list (org-property-values kwd))))
12421 (unless (string-match "\\`{.*}\\'" value)
12422 (setq value (concat "\"" value "\"")))
12423 (org-match-sparse-tree arg (concat kwd "=" value)))
12424 ((member ans '(?r ?R ?/))
12425 (call-interactively 'org-occur))
12426 (t (error "No such sparse tree command \"%c\"" ans)))))
12428 (defvar org-occur-highlights nil
12429 "List of overlays used for occur matches.")
12430 (make-variable-buffer-local 'org-occur-highlights)
12431 (defvar org-occur-parameters nil
12432 "Parameters of the active org-occur calls.
12433 This is a list, each call to org-occur pushes as cons cell,
12434 containing the regular expression and the callback, onto the list.
12435 The list can contain several entries if `org-occur' has been called
12436 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12437 will only contain one set of parameters. When the highlights are
12438 removed (for example with `C-c C-c', or with the next edit (depending
12439 on `org-remove-highlights-with-change'), this variable is emptied
12440 as well.")
12441 (make-variable-buffer-local 'org-occur-parameters)
12443 (defun org-occur (regexp &optional keep-previous callback)
12444 "Make a compact tree which shows all matches of REGEXP.
12445 The tree will show the lines where the regexp matches, and all higher
12446 headlines above the match. It will also show the heading after the match,
12447 to make sure editing the matching entry is easy.
12448 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12449 call to `org-occur' will be kept, to allow stacking of calls to this
12450 command.
12451 If CALLBACK is non-nil, it is a function which is called to confirm
12452 that the match should indeed be shown."
12453 (interactive "sRegexp: \nP")
12454 (when (equal regexp "")
12455 (error "Regexp cannot be empty"))
12456 (unless keep-previous
12457 (org-remove-occur-highlights nil nil t))
12458 (push (cons regexp callback) org-occur-parameters)
12459 (let ((cnt 0))
12460 (save-excursion
12461 (goto-char (point-min))
12462 (if (or (not keep-previous) ; do not want to keep
12463 (not org-occur-highlights)) ; no previous matches
12464 ;; hide everything
12465 (org-overview))
12466 (while (re-search-forward regexp nil t)
12467 (when (or (not callback)
12468 (save-match-data (funcall callback)))
12469 (setq cnt (1+ cnt))
12470 (when org-highlight-sparse-tree-matches
12471 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12472 (org-show-context 'occur-tree))))
12473 (when org-remove-highlights-with-change
12474 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12475 nil 'local))
12476 (unless org-sparse-tree-open-archived-trees
12477 (org-hide-archived-subtrees (point-min) (point-max)))
12478 (run-hooks 'org-occur-hook)
12479 (if (org-called-interactively-p 'interactive)
12480 (message "%d match(es) for regexp %s" cnt regexp))
12481 cnt))
12483 (defun org-occur-next-match (&optional n reset)
12484 "Function for `next-error-function' to find sparse tree matches.
12485 N is the number of matches to move, when negative move backwards.
12486 RESET is entirely ignored - this function always goes back to the
12487 starting point when no match is found."
12488 (let* ((limit (if (< n 0) (point-min) (point-max)))
12489 (search-func (if (< n 0)
12490 'previous-single-char-property-change
12491 'next-single-char-property-change))
12492 (n (abs n))
12493 (pos (point))
12495 (catch 'exit
12496 (while (setq p1 (funcall search-func (point) 'org-type))
12497 (when (equal p1 limit)
12498 (goto-char pos)
12499 (error "No more matches"))
12500 (when (equal (get-char-property p1 'org-type) 'org-occur)
12501 (setq n (1- n))
12502 (when (= n 0)
12503 (goto-char p1)
12504 (throw 'exit (point))))
12505 (goto-char p1))
12506 (goto-char p1)
12507 (error "No more matches"))))
12509 (defun org-show-context (&optional key)
12510 "Make sure point and context are visible.
12511 How much context is shown depends upon the variables
12512 `org-show-hierarchy-above', `org-show-following-heading'. and
12513 `org-show-siblings'."
12514 (let ((heading-p (org-on-heading-p t))
12515 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12516 (following-p (org-get-alist-option org-show-following-heading key))
12517 (entry-p (org-get-alist-option org-show-entry-below key))
12518 (siblings-p (org-get-alist-option org-show-siblings key)))
12519 (catch 'exit
12520 ;; Show heading or entry text
12521 (if (and heading-p (not entry-p))
12522 (org-flag-heading nil) ; only show the heading
12523 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12524 (org-show-hidden-entry))) ; show entire entry
12525 (when following-p
12526 ;; Show next sibling, or heading below text
12527 (save-excursion
12528 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12529 (org-flag-heading nil))))
12530 (when siblings-p (org-show-siblings))
12531 (when hierarchy-p
12532 ;; show all higher headings, possibly with siblings
12533 (save-excursion
12534 (while (and (condition-case nil
12535 (progn (org-up-heading-all 1) t)
12536 (error nil))
12537 (not (bobp)))
12538 (org-flag-heading nil)
12539 (when siblings-p (org-show-siblings))))))))
12541 (defvar org-reveal-start-hook nil
12542 "Hook run before revealing a location.")
12544 (defun org-reveal (&optional siblings)
12545 "Show current entry, hierarchy above it, and the following headline.
12546 This can be used to show a consistent set of context around locations
12547 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12548 not t for the search context.
12550 With optional argument SIBLINGS, on each level of the hierarchy all
12551 siblings are shown. This repairs the tree structure to what it would
12552 look like when opened with hierarchical calls to `org-cycle'.
12553 With double optional argument \\[universal-argument] \\[universal-argument], \
12554 go to the parent and show the
12555 entire tree."
12556 (interactive "P")
12557 (run-hooks 'org-reveal-start-hook)
12558 (let ((org-show-hierarchy-above t)
12559 (org-show-following-heading t)
12560 (org-show-siblings (if siblings t org-show-siblings)))
12561 (org-show-context nil))
12562 (when (equal siblings '(16))
12563 (save-excursion
12564 (when (org-up-heading-safe)
12565 (org-show-subtree)
12566 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12568 (defun org-highlight-new-match (beg end)
12569 "Highlight from BEG to END and mark the highlight is an occur headline."
12570 (let ((ov (make-overlay beg end)))
12571 (overlay-put ov 'face 'secondary-selection)
12572 (overlay-put ov 'org-type 'org-occur)
12573 (push ov org-occur-highlights)))
12575 (defun org-remove-occur-highlights (&optional beg end noremove)
12576 "Remove the occur highlights from the buffer.
12577 BEG and END are ignored. If NOREMOVE is nil, remove this function
12578 from the `before-change-functions' in the current buffer."
12579 (interactive)
12580 (unless org-inhibit-highlight-removal
12581 (mapc 'delete-overlay org-occur-highlights)
12582 (setq org-occur-highlights nil)
12583 (setq org-occur-parameters nil)
12584 (unless noremove
12585 (remove-hook 'before-change-functions
12586 'org-remove-occur-highlights 'local))))
12588 ;;;; Priorities
12590 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12591 "Regular expression matching the priority indicator.")
12593 (defvar org-remove-priority-next-time nil)
12595 (defun org-priority-up ()
12596 "Increase the priority of the current item."
12597 (interactive)
12598 (org-priority 'up))
12600 (defun org-priority-down ()
12601 "Decrease the priority of the current item."
12602 (interactive)
12603 (org-priority 'down))
12605 (defun org-priority (&optional action)
12606 "Change the priority of an item by ARG.
12607 ACTION can be `set', `up', `down', or a character."
12608 (interactive)
12609 (unless org-enable-priority-commands
12610 (error "Priority commands are disabled"))
12611 (setq action (or action 'set))
12612 (let (current new news have remove)
12613 (save-excursion
12614 (org-back-to-heading t)
12615 (if (looking-at org-priority-regexp)
12616 (setq current (string-to-char (match-string 2))
12617 have t))
12618 (cond
12619 ((eq action 'remove)
12620 (setq remove t new ?\ ))
12621 ((or (eq action 'set)
12622 (if (featurep 'xemacs) (characterp action) (integerp action)))
12623 (if (not (eq action 'set))
12624 (setq new action)
12625 (message "Priority %c-%c, SPC to remove: "
12626 org-highest-priority org-lowest-priority)
12627 (save-match-data
12628 (setq new (read-char-exclusive))))
12629 (if (and (= (upcase org-highest-priority) org-highest-priority)
12630 (= (upcase org-lowest-priority) org-lowest-priority))
12631 (setq new (upcase new)))
12632 (cond ((equal new ?\ ) (setq remove t))
12633 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12634 (error "Priority must be between `%c' and `%c'"
12635 org-highest-priority org-lowest-priority))))
12636 ((eq action 'up)
12637 (setq new (if have
12638 (1- current) ; normal cycling
12639 ;; last priority was empty
12640 (if (eq last-command this-command)
12641 org-lowest-priority ; wrap around empty to lowest
12642 ;; default
12643 (if org-priority-start-cycle-with-default
12644 org-default-priority
12645 (1- org-default-priority))))))
12646 ((eq action 'down)
12647 (setq new (if have
12648 (1+ current) ; normal cycling
12649 ;; last priority was empty
12650 (if (eq last-command this-command)
12651 org-highest-priority ; wrap around empty to highest
12652 ;; default
12653 (if org-priority-start-cycle-with-default
12654 org-default-priority
12655 (1+ org-default-priority))))))
12656 (t (error "Invalid action")))
12657 (if (or (< (upcase new) org-highest-priority)
12658 (> (upcase new) org-lowest-priority))
12659 (if (and (memq action '(up down))
12660 (not have) (not (eq last-command this-command)))
12661 ;; `new' is from default priority
12662 (error
12663 "The default can not be set, see `org-default-priority' why")
12664 ;; normal cycling: `new' is beyond highest/lowest priority
12665 ;; and is wrapped around to the empty priority
12666 (setq remove t)))
12667 (setq news (format "%c" new))
12668 (if have
12669 (if remove
12670 (replace-match "" t t nil 1)
12671 (replace-match news t t nil 2))
12672 (if remove
12673 (error "No priority cookie found in line")
12674 (let ((case-fold-search nil))
12675 (looking-at org-todo-line-regexp))
12676 (if (match-end 2)
12677 (progn
12678 (goto-char (match-end 2))
12679 (insert " [#" news "]"))
12680 (goto-char (match-beginning 3))
12681 (insert "[#" news "] "))))
12682 (org-preserve-lc (org-set-tags nil 'align)))
12683 (if remove
12684 (message "Priority removed")
12685 (message "Priority of current item set to %s" news))))
12687 (defun org-get-priority (s)
12688 "Find priority cookie and return priority."
12689 (if (functionp org-get-priority-function)
12690 (funcall org-get-priority-function)
12691 (save-match-data
12692 (if (not (string-match org-priority-regexp s))
12693 (* 1000 (- org-lowest-priority org-default-priority))
12694 (* 1000 (- org-lowest-priority
12695 (string-to-char (match-string 2 s))))))))
12697 ;;;; Tags
12699 (defvar org-agenda-archives-mode)
12700 (defvar org-map-continue-from nil
12701 "Position from where mapping should continue.
12702 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
12704 (defvar org-scanner-tags nil
12705 "The current tag list while the tags scanner is running.")
12706 (defvar org-trust-scanner-tags nil
12707 "Should `org-get-tags-at' use the tags for the scanner.
12708 This is for internal dynamical scoping only.
12709 When this is non-nil, the function `org-get-tags-at' will return the value
12710 of `org-scanner-tags' instead of building the list by itself. This
12711 can lead to large speed-ups when the tags scanner is used in a file with
12712 many entries, and when the list of tags is retrieved, for example to
12713 obtain a list of properties. Building the tags list for each entry in such
12714 a file becomes an N^2 operation - but with this variable set, it scales
12715 as N.")
12717 (defun org-scan-tags (action matcher &optional todo-only)
12718 "Scan headline tags with inheritance and produce output ACTION.
12720 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12721 or `agenda' to produce an entry list for an agenda view. It can also be
12722 a Lisp form or a function that should be called at each matched headline, in
12723 this case the return value is a list of all return values from these calls.
12725 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12726 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12727 only lines with a TODO keyword are included in the output."
12728 (require 'org-agenda)
12729 (let* ((re (concat "^" org-outline-regexp " *\\(\\<\\("
12730 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12731 (org-re
12732 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12733 (props (list 'face 'default
12734 'done-face 'org-agenda-done
12735 'undone-face 'default
12736 'mouse-face 'highlight
12737 'org-not-done-regexp org-not-done-regexp
12738 'org-todo-regexp org-todo-regexp
12739 'org-complex-heading-regexp org-complex-heading-regexp
12740 'help-echo
12741 (format "mouse-2 or RET jump to org file %s"
12742 (abbreviate-file-name
12743 (or (buffer-file-name (buffer-base-buffer))
12744 (buffer-name (buffer-base-buffer)))))))
12745 (case-fold-search nil)
12746 (org-map-continue-from nil)
12747 lspos tags tags-list
12748 (tags-alist (list (cons 0 org-file-tags)))
12749 (llast 0) rtn rtn1 level category i txt
12750 todo marker entry priority)
12751 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12752 (setq action (list 'lambda nil action)))
12753 (save-excursion
12754 (goto-char (point-min))
12755 (when (eq action 'sparse-tree)
12756 (org-overview)
12757 (org-remove-occur-highlights))
12758 (while (re-search-forward re nil t)
12759 (catch :skip
12760 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12761 tags (if (match-end 4) (org-match-string-no-properties 4)))
12762 (goto-char (setq lspos (match-beginning 0)))
12763 (setq level (org-reduced-level (funcall outline-level))
12764 category (org-get-category))
12765 (setq i llast llast level)
12766 ;; remove tag lists from same and sublevels
12767 (while (>= i level)
12768 (when (setq entry (assoc i tags-alist))
12769 (setq tags-alist (delete entry tags-alist)))
12770 (setq i (1- i)))
12771 ;; add the next tags
12772 (when tags
12773 (setq tags (org-split-string tags ":")
12774 tags-alist
12775 (cons (cons level tags) tags-alist)))
12776 ;; compile tags for current headline
12777 (setq tags-list
12778 (if org-use-tag-inheritance
12779 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12780 tags)
12781 org-scanner-tags tags-list)
12782 (when org-use-tag-inheritance
12783 (setcdr (car tags-alist)
12784 (mapcar (lambda (x)
12785 (setq x (copy-sequence x))
12786 (org-add-prop-inherited x))
12787 (cdar tags-alist))))
12788 (when (and tags org-use-tag-inheritance
12789 (or (not (eq t org-use-tag-inheritance))
12790 org-tags-exclude-from-inheritance))
12791 ;; selective inheritance, remove uninherited ones
12792 (setcdr (car tags-alist)
12793 (org-remove-uninherited-tags (cdar tags-alist))))
12794 (when (and
12796 ;; eval matcher only when the todo condition is OK
12797 (and (or (not todo-only) (member todo org-not-done-keywords))
12798 (let ((case-fold-search t)) (eval matcher)))
12800 ;; Call the skipper, but return t if it does not skip,
12801 ;; so that the `and' form continues evaluating
12802 (progn
12803 (unless (eq action 'sparse-tree) (org-agenda-skip))
12806 ;; Check if timestamps are deselecting this entry
12807 (or (not todo-only)
12808 (and (member todo org-not-done-keywords)
12809 (or (not org-agenda-tags-todo-honor-ignore-options)
12810 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12812 ;; Extra check for the archive tag
12813 ;; FIXME: Does the skipper already do this????
12815 (not (member org-archive-tag tags-list))
12816 ;; we have an archive tag, should we use this anyway?
12817 (or (not org-agenda-skip-archived-trees)
12818 (and (eq action 'agenda) org-agenda-archives-mode))))
12820 ;; select this headline
12822 (cond
12823 ((eq action 'sparse-tree)
12824 (and org-highlight-sparse-tree-matches
12825 (org-get-heading) (match-end 0)
12826 (org-highlight-new-match
12827 (match-beginning 0) (match-beginning 1)))
12828 (org-show-context 'tags-tree))
12829 ((eq action 'agenda)
12830 (setq txt (org-agenda-format-item
12832 (concat
12833 (if (eq org-tags-match-list-sublevels 'indented)
12834 (make-string (1- level) ?.) "")
12835 (org-get-heading))
12836 category
12837 tags-list
12839 priority (org-get-priority txt))
12840 (goto-char lspos)
12841 (setq marker (org-agenda-new-marker))
12842 (org-add-props txt props
12843 'org-marker marker 'org-hd-marker marker 'org-category category
12844 'todo-state todo
12845 'priority priority 'type "tagsmatch")
12846 (push txt rtn))
12847 ((functionp action)
12848 (setq org-map-continue-from nil)
12849 (save-excursion
12850 (setq rtn1 (funcall action))
12851 (push rtn1 rtn)))
12852 (t (error "Invalid action")))
12854 ;; if we are to skip sublevels, jump to end of subtree
12855 (unless org-tags-match-list-sublevels
12856 (org-end-of-subtree t)
12857 (backward-char 1))))
12858 ;; Get the correct position from where to continue
12859 (if org-map-continue-from
12860 (goto-char org-map-continue-from)
12861 (and (= (point) lspos) (end-of-line 1)))))
12862 (when (and (eq action 'sparse-tree)
12863 (not org-sparse-tree-open-archived-trees))
12864 (org-hide-archived-subtrees (point-min) (point-max)))
12865 (nreverse rtn)))
12867 (defun org-remove-uninherited-tags (tags)
12868 "Remove all tags that are not inherited from the list TAGS."
12869 (cond
12870 ((eq org-use-tag-inheritance t)
12871 (if org-tags-exclude-from-inheritance
12872 (org-delete-all org-tags-exclude-from-inheritance tags)
12873 tags))
12874 ((not org-use-tag-inheritance) nil)
12875 ((stringp org-use-tag-inheritance)
12876 (delq nil (mapcar
12877 (lambda (x)
12878 (if (and (string-match org-use-tag-inheritance x)
12879 (not (member x org-tags-exclude-from-inheritance)))
12880 x nil))
12881 tags)))
12882 ((listp org-use-tag-inheritance)
12883 (delq nil (mapcar
12884 (lambda (x)
12885 (if (member x org-use-tag-inheritance) x nil))
12886 tags)))))
12888 (defvar todo-only) ;; dynamically scoped
12890 (defun org-match-sparse-tree (&optional todo-only match)
12891 "Create a sparse tree according to tags string MATCH.
12892 MATCH can contain positive and negative selection of tags, like
12893 \"+WORK+URGENT-WITHBOSS\".
12894 If optional argument TODO-ONLY is non-nil, only select lines that are
12895 also TODO lines."
12896 (interactive "P")
12897 (org-prepare-agenda-buffers (list (current-buffer)))
12898 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12900 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12902 (defvar org-cached-props nil)
12903 (defun org-cached-entry-get (pom property)
12904 (if (or (eq t org-use-property-inheritance)
12905 (and (stringp org-use-property-inheritance)
12906 (string-match org-use-property-inheritance property))
12907 (and (listp org-use-property-inheritance)
12908 (member property org-use-property-inheritance)))
12909 ;; Caching is not possible, check it directly
12910 (org-entry-get pom property 'inherit)
12911 ;; Get all properties, so that we can do complicated checks easily
12912 (cdr (assoc property (or org-cached-props
12913 (setq org-cached-props
12914 (org-entry-properties pom)))))))
12916 (defun org-global-tags-completion-table (&optional files)
12917 "Return the list of all tags in all agenda buffer/files.
12918 Optional FILES argument is a list of files to which can be used
12919 instead of the agenda files."
12920 (save-excursion
12921 (org-uniquify
12922 (delq nil
12923 (apply 'append
12924 (mapcar
12925 (lambda (file)
12926 (set-buffer (find-file-noselect file))
12927 (append (org-get-buffer-tags)
12928 (mapcar (lambda (x) (if (stringp (car-safe x))
12929 (list (car-safe x)) nil))
12930 org-tag-alist)))
12931 (if (and files (car files))
12932 files
12933 (org-agenda-files))))))))
12935 (defun org-make-tags-matcher (match)
12936 "Create the TAGS/TODO matcher form for the selection string MATCH."
12937 ;; todo-only is scoped dynamically into this function, and the function
12938 ;; may change it if the matcher asks for it.
12939 (unless match
12940 ;; Get a new match request, with completion
12941 (let ((org-last-tags-completion-table
12942 (org-global-tags-completion-table)))
12943 (setq match (org-completing-read-no-i
12944 "Match: " 'org-tags-completion-function nil nil nil
12945 'org-tags-history))))
12947 ;; Parse the string and create a lisp form
12948 (let ((match0 match)
12949 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
12950 minus tag mm
12951 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12952 orterms term orlist re-p str-p level-p level-op time-p
12953 prop-p pn pv po gv rest)
12954 (if (string-match "/+" match)
12955 ;; match contains also a todo-matching request
12956 (progn
12957 (setq tagsmatch (substring match 0 (match-beginning 0))
12958 todomatch (substring match (match-end 0)))
12959 (if (string-match "^!" todomatch)
12960 (setq todo-only t todomatch (substring todomatch 1)))
12961 (if (string-match "^\\s-*$" todomatch)
12962 (setq todomatch nil)))
12963 ;; only matching tags
12964 (setq tagsmatch match todomatch nil))
12966 ;; Make the tags matcher
12967 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12968 (setq tagsmatcher t)
12969 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12970 (while (setq term (pop orterms))
12971 (while (and (equal (substring term -1) "\\") orterms)
12972 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12973 (while (string-match re term)
12974 (setq rest (substring term (match-end 0))
12975 minus (and (match-end 1)
12976 (equal (match-string 1 term) "-"))
12977 tag (save-match-data (replace-regexp-in-string
12978 "\\\\-" "-"
12979 (match-string 2 term)))
12980 re-p (equal (string-to-char tag) ?{)
12981 level-p (match-end 4)
12982 prop-p (match-end 5)
12983 mm (cond
12984 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12985 (level-p
12986 (setq level-op (org-op-to-function (match-string 3 term)))
12987 `(,level-op level ,(string-to-number
12988 (match-string 4 term))))
12989 (prop-p
12990 (setq pn (match-string 5 term)
12991 po (match-string 6 term)
12992 pv (match-string 7 term)
12993 re-p (equal (string-to-char pv) ?{)
12994 str-p (equal (string-to-char pv) ?\")
12995 time-p (save-match-data
12996 (string-match "^\"[[<].*[]>]\"$" pv))
12997 pv (if (or re-p str-p) (substring pv 1 -1) pv))
12998 (if time-p (setq pv (org-matcher-time pv)))
12999 (setq po (org-op-to-function po (if time-p 'time str-p)))
13000 (cond
13001 ((equal pn "CATEGORY")
13002 (setq gv '(get-text-property (point) 'org-category)))
13003 ((equal pn "TODO")
13004 (setq gv 'todo))
13006 (setq gv `(org-cached-entry-get nil ,pn))))
13007 (if re-p
13008 (if (eq po 'org<>)
13009 `(not (string-match ,pv (or ,gv "")))
13010 `(string-match ,pv (or ,gv "")))
13011 (if str-p
13012 `(,po (or ,gv "") ,pv)
13013 `(,po (string-to-number (or ,gv ""))
13014 ,(string-to-number pv) ))))
13015 (t `(member ,tag tags-list)))
13016 mm (if minus (list 'not mm) mm)
13017 term rest)
13018 (push mm tagsmatcher))
13019 (push (if (> (length tagsmatcher) 1)
13020 (cons 'and tagsmatcher)
13021 (car tagsmatcher))
13022 orlist)
13023 (setq tagsmatcher nil))
13024 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13025 (setq tagsmatcher
13026 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13027 ;; Make the todo matcher
13028 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13029 (setq todomatcher t)
13030 (setq orterms (org-split-string todomatch "|") orlist nil)
13031 (while (setq term (pop orterms))
13032 (while (string-match re term)
13033 (setq minus (and (match-end 1)
13034 (equal (match-string 1 term) "-"))
13035 kwd (match-string 2 term)
13036 re-p (equal (string-to-char kwd) ?{)
13037 term (substring term (match-end 0))
13038 mm (if re-p
13039 `(string-match ,(substring kwd 1 -1) todo)
13040 (list 'equal 'todo kwd))
13041 mm (if minus (list 'not mm) mm))
13042 (push mm todomatcher))
13043 (push (if (> (length todomatcher) 1)
13044 (cons 'and todomatcher)
13045 (car todomatcher))
13046 orlist)
13047 (setq todomatcher nil))
13048 (setq todomatcher (if (> (length orlist) 1)
13049 (cons 'or orlist) (car orlist))))
13051 ;; Return the string and lisp forms of the matcher
13052 (setq matcher (if todomatcher
13053 (list 'and tagsmatcher todomatcher)
13054 tagsmatcher))
13055 (cons match0 matcher)))
13057 (defun org-op-to-function (op &optional stringp)
13058 "Turn an operator into the appropriate function."
13059 (setq op
13060 (cond
13061 ((equal op "<" ) '(< string< org-time<))
13062 ((equal op ">" ) '(> org-string> org-time>))
13063 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13064 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13065 ((member op '("=" "==")) '(= string= org-time=))
13066 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13067 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13069 (defun org<> (a b) (not (= a b)))
13070 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13071 (defun org-string>= (a b) (not (string< a b)))
13072 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13073 (defun org-string<> (a b) (not (string= a b)))
13074 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13075 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13076 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13077 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13078 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13079 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13080 (defun org-2ft (s)
13081 "Convert S to a floating point time.
13082 If S is already a number, just return it. If it is a string, parse
13083 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13084 (cond
13085 ((numberp s) s)
13086 ((stringp s)
13087 (condition-case nil
13088 (float-time (apply 'encode-time (org-parse-time-string s)))
13089 (error 0.)))
13090 (t 0.)))
13092 (defun org-time-today ()
13093 "Time in seconds today at 0:00.
13094 Returns the float number of seconds since the beginning of the
13095 epoch to the beginning of today (00:00)."
13096 (float-time (apply 'encode-time
13097 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13099 (defun org-matcher-time (s)
13100 "Interpret a time comparison value."
13101 (save-match-data
13102 (cond
13103 ((string= s "<now>") (float-time))
13104 ((string= s "<today>") (org-time-today))
13105 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13106 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13107 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
13108 (+ (org-time-today)
13109 (* (string-to-number (match-string 1 s))
13110 (cdr (assoc (match-string 2 s)
13111 '(("d" . 86400.0) ("w" . 604800.0)
13112 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13113 (t (org-2ft s)))))
13115 (defun org-match-any-p (re list)
13116 "Does re match any element of list?"
13117 (setq list (mapcar (lambda (x) (string-match re x)) list))
13118 (delq nil list))
13120 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13121 (defvar org-tags-overlay (make-overlay 1 1))
13122 (org-detach-overlay org-tags-overlay)
13124 (defun org-get-local-tags-at (&optional pos)
13125 "Get a list of tags defined in the current headline."
13126 (org-get-tags-at pos 'local))
13128 (defun org-get-local-tags ()
13129 "Get a list of tags defined in the current headline."
13130 (org-get-tags-at nil 'local))
13132 (defun org-get-tags-at (&optional pos local)
13133 "Get a list of all headline tags applicable at POS.
13134 POS defaults to point. If tags are inherited, the list contains
13135 the targets in the same sequence as the headlines appear, i.e.
13136 the tags of the current headline come last.
13137 When LOCAL is non-nil, only return tags from the current headline,
13138 ignore inherited ones."
13139 (interactive)
13140 (if (and org-trust-scanner-tags
13141 (or (not pos) (equal pos (point)))
13142 (not local))
13143 org-scanner-tags
13144 (let (tags ltags lastpos parent)
13145 (save-excursion
13146 (save-restriction
13147 (widen)
13148 (goto-char (or pos (point)))
13149 (save-match-data
13150 (catch 'done
13151 (condition-case nil
13152 (progn
13153 (org-back-to-heading t)
13154 (while (not (equal lastpos (point)))
13155 (setq lastpos (point))
13156 (when (looking-at
13157 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13158 (setq ltags (org-split-string
13159 (org-match-string-no-properties 1) ":"))
13160 (when parent
13161 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13162 (setq tags (append
13163 (if parent
13164 (org-remove-uninherited-tags ltags)
13165 ltags)
13166 tags)))
13167 (or org-use-tag-inheritance (throw 'done t))
13168 (if local (throw 'done t))
13169 (or (org-up-heading-safe) (error nil))
13170 (setq parent t)))
13171 (error nil)))))
13172 (if local
13173 tags
13174 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13176 (defun org-add-prop-inherited (s)
13177 (add-text-properties 0 (length s) '(inherited t) s)
13180 (defun org-toggle-tag (tag &optional onoff)
13181 "Toggle the tag TAG for the current line.
13182 If ONOFF is `on' or `off', don't toggle but set to this state."
13183 (let (res current)
13184 (save-excursion
13185 (org-back-to-heading t)
13186 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13187 (point-at-eol) t)
13188 (progn
13189 (setq current (match-string 1))
13190 (replace-match ""))
13191 (setq current ""))
13192 (setq current (nreverse (org-split-string current ":")))
13193 (cond
13194 ((eq onoff 'on)
13195 (setq res t)
13196 (or (member tag current) (push tag current)))
13197 ((eq onoff 'off)
13198 (or (not (member tag current)) (setq current (delete tag current))))
13199 (t (if (member tag current)
13200 (setq current (delete tag current))
13201 (setq res t)
13202 (push tag current))))
13203 (end-of-line 1)
13204 (if current
13205 (progn
13206 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13207 (org-set-tags nil t))
13208 (delete-horizontal-space))
13209 (run-hooks 'org-after-tags-change-hook))
13210 res))
13212 (defun org-align-tags-here (to-col)
13213 ;; Assumes that this is a headline
13214 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13215 (beginning-of-line 1)
13216 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13217 (< pos (match-beginning 2)))
13218 (progn
13219 (setq tags-l (- (match-end 2) (match-beginning 2)))
13220 (goto-char (match-beginning 1))
13221 (insert " ")
13222 (delete-region (point) (1+ (match-beginning 2)))
13223 (setq ncol (max (current-column)
13224 (1+ col)
13225 (if (> to-col 0)
13226 to-col
13227 (- (abs to-col) tags-l))))
13228 (setq p (point))
13229 (insert (make-string (- ncol (current-column)) ?\ ))
13230 (setq ncol (current-column))
13231 (when indent-tabs-mode (tabify p (point-at-eol)))
13232 (org-move-to-column (min ncol col) t))
13233 (goto-char pos))))
13235 (defun org-set-tags-command (&optional arg just-align)
13236 "Call the set-tags command for the current entry."
13237 (interactive "P")
13238 (if (org-on-heading-p)
13239 (org-set-tags arg just-align)
13240 (save-excursion
13241 (org-back-to-heading t)
13242 (org-set-tags arg just-align))))
13244 (defun org-set-tags-to (data)
13245 "Set the tags of the current entry to DATA, replacing the current tags.
13246 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13247 If DATA is nil or the empty string, any tags will be removed."
13248 (interactive "sTags: ")
13249 (setq data
13250 (cond
13251 ((eq data nil) "")
13252 ((equal data "") "")
13253 ((stringp data)
13254 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13255 ":"))
13256 ((listp data)
13257 (concat ":" (mapconcat 'identity data ":") ":"))
13258 (t nil)))
13259 (when data
13260 (save-excursion
13261 (org-back-to-heading t)
13262 (when (looking-at org-complex-heading-regexp)
13263 (if (match-end 5)
13264 (progn
13265 (goto-char (match-beginning 5))
13266 (insert data)
13267 (delete-region (point) (point-at-eol))
13268 (org-set-tags nil 'align))
13269 (goto-char (point-at-eol))
13270 (insert " " data)
13271 (org-set-tags nil 'align)))
13272 (beginning-of-line 1)
13273 (if (looking-at ".*?\\([ \t]+\\)$")
13274 (delete-region (match-beginning 1) (match-end 1))))))
13276 (defun org-align-all-tags ()
13277 "Align the tags i all headings."
13278 (interactive)
13279 (save-excursion
13280 (or (ignore-errors (org-back-to-heading t))
13281 (outline-next-heading))
13282 (if (org-on-heading-p)
13283 (org-set-tags t)
13284 (message "No headings"))))
13286 (defvar org-indent-indentation-per-level)
13287 (defun org-set-tags (&optional arg just-align)
13288 "Set the tags for the current headline.
13289 With prefix ARG, realign all tags in headings in the current buffer."
13290 (interactive "P")
13291 (let* ((re org-outline-regexp-bol)
13292 (current (org-get-tags-string))
13293 (col (current-column))
13294 (org-setting-tags t)
13295 table current-tags inherited-tags ; computed below when needed
13296 tags p0 c0 c1 rpl di tc level)
13297 (if arg
13298 (save-excursion
13299 (goto-char (point-min))
13300 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13301 (while (re-search-forward re nil t)
13302 (org-set-tags nil t)
13303 (end-of-line 1)))
13304 (message "All tags realigned to column %d" org-tags-column))
13305 (if just-align
13306 (setq tags current)
13307 ;; Get a new set of tags from the user
13308 (save-excursion
13309 (setq table (append org-tag-persistent-alist
13310 (or org-tag-alist (org-get-buffer-tags))
13311 (and
13312 org-complete-tags-always-offer-all-agenda-tags
13313 (org-global-tags-completion-table
13314 (org-agenda-files))))
13315 org-last-tags-completion-table table
13316 current-tags (org-split-string current ":")
13317 inherited-tags (nreverse
13318 (nthcdr (length current-tags)
13319 (nreverse (org-get-tags-at))))
13320 tags
13321 (if (or (eq t org-use-fast-tag-selection)
13322 (and org-use-fast-tag-selection
13323 (delq nil (mapcar 'cdr table))))
13324 (org-fast-tag-selection
13325 current-tags inherited-tags table
13326 (if org-fast-tag-selection-include-todo
13327 org-todo-key-alist))
13328 (let ((org-add-colon-after-tag-completion t))
13329 (org-trim
13330 (org-icompleting-read "Tags: "
13331 'org-tags-completion-function
13332 nil nil current 'org-tags-history))))))
13333 (while (string-match "[-+&]+" tags)
13334 ;; No boolean logic, just a list
13335 (setq tags (replace-match ":" t t tags))))
13337 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13339 (if org-tags-sort-function
13340 (setq tags (mapconcat 'identity
13341 (sort (org-split-string
13342 tags (org-re "[^[:alnum:]_@#%]+"))
13343 org-tags-sort-function) ":")))
13345 (if (string-match "\\`[\t ]*\\'" tags)
13346 (setq tags "")
13347 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13348 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13350 ;; Insert new tags at the correct column
13351 (beginning-of-line 1)
13352 (setq level (or (and (looking-at org-outline-regexp)
13353 (- (match-end 0) (point) 1))
13355 (cond
13356 ((and (equal current "") (equal tags "")))
13357 ((re-search-forward
13358 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13359 (point-at-eol) t)
13360 (if (equal tags "")
13361 (setq rpl "")
13362 (goto-char (match-beginning 0))
13363 (setq c0 (current-column)
13364 ;; compute offset for the case of org-indent-mode active
13365 di (if org-indent-mode
13366 (* (1- org-indent-indentation-per-level) (1- level))
13368 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13369 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13370 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13371 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13372 (replace-match rpl t t)
13373 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13374 tags)
13375 (t (error "Tags alignment failed")))
13376 (org-move-to-column col)
13377 (unless just-align
13378 (run-hooks 'org-after-tags-change-hook)))))
13380 (defun org-change-tag-in-region (beg end tag off)
13381 "Add or remove TAG for each entry in the region.
13382 This works in the agenda, and also in an org-mode buffer."
13383 (interactive
13384 (list (region-beginning) (region-end)
13385 (let ((org-last-tags-completion-table
13386 (if (eq major-mode 'org-mode)
13387 (org-get-buffer-tags)
13388 (org-global-tags-completion-table))))
13389 (org-icompleting-read
13390 "Tag: " 'org-tags-completion-function nil nil nil
13391 'org-tags-history))
13392 (progn
13393 (message "[s]et or [r]emove? ")
13394 (equal (read-char-exclusive) ?r))))
13395 (if (fboundp 'deactivate-mark) (deactivate-mark))
13396 (let ((agendap (equal major-mode 'org-agenda-mode))
13397 l1 l2 m buf pos newhead (cnt 0))
13398 (goto-char end)
13399 (setq l2 (1- (org-current-line)))
13400 (goto-char beg)
13401 (setq l1 (org-current-line))
13402 (loop for l from l1 to l2 do
13403 (org-goto-line l)
13404 (setq m (get-text-property (point) 'org-hd-marker))
13405 (when (or (and (eq major-mode 'org-mode) (org-on-heading-p))
13406 (and agendap m))
13407 (setq buf (if agendap (marker-buffer m) (current-buffer))
13408 pos (if agendap m (point)))
13409 (with-current-buffer buf
13410 (save-excursion
13411 (save-restriction
13412 (goto-char pos)
13413 (setq cnt (1+ cnt))
13414 (org-toggle-tag tag (if off 'off 'on))
13415 (setq newhead (org-get-heading)))))
13416 (and agendap (org-agenda-change-all-lines newhead m))))
13417 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13419 (defun org-tags-completion-function (string predicate &optional flag)
13420 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13421 (confirm (lambda (x) (stringp (car x)))))
13422 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13423 (setq s1 (match-string 1 string)
13424 s2 (match-string 2 string))
13425 (setq s1 "" s2 string))
13426 (cond
13427 ((eq flag nil)
13428 ;; try completion
13429 (setq rtn (try-completion s2 ctable confirm))
13430 (if (stringp rtn)
13431 (setq rtn
13432 (concat s1 s2 (substring rtn (length s2))
13433 (if (and org-add-colon-after-tag-completion
13434 (assoc rtn ctable))
13435 ":" ""))))
13436 rtn)
13437 ((eq flag t)
13438 ;; all-completions
13439 (all-completions s2 ctable confirm)
13441 ((eq flag 'lambda)
13442 ;; exact match?
13443 (assoc s2 ctable)))
13446 (defun org-fast-tag-insert (kwd tags face &optional end)
13447 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13448 (insert (format "%-12s" (concat kwd ":"))
13449 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13450 (or end "")))
13452 (defun org-fast-tag-show-exit (flag)
13453 (save-excursion
13454 (org-goto-line 3)
13455 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13456 (replace-match ""))
13457 (when flag
13458 (end-of-line 1)
13459 (org-move-to-column (- (window-width) 19) t)
13460 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13462 (defun org-set-current-tags-overlay (current prefix)
13463 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13464 (if (featurep 'xemacs)
13465 (org-overlay-display org-tags-overlay (concat prefix s)
13466 'secondary-selection)
13467 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13468 (org-overlay-display org-tags-overlay (concat prefix s)))))
13470 (defvar org-last-tag-selection-key nil)
13471 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13472 "Fast tag selection with single keys.
13473 CURRENT is the current list of tags in the headline, INHERITED is the
13474 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13475 possibly with grouping information. TODO-TABLE is a similar table with
13476 TODO keywords, should these have keys assigned to them.
13477 If the keys are nil, a-z are automatically assigned.
13478 Returns the new tags string, or nil to not change the current settings."
13479 (let* ((fulltable (append table todo-table))
13480 (maxlen (apply 'max (mapcar
13481 (lambda (x)
13482 (if (stringp (car x)) (string-width (car x)) 0))
13483 fulltable)))
13484 (buf (current-buffer))
13485 (expert (eq org-fast-tag-selection-single-key 'expert))
13486 (buffer-tags nil)
13487 (fwidth (+ maxlen 3 1 3))
13488 (ncol (/ (- (window-width) 4) fwidth))
13489 (i-face 'org-done)
13490 (c-face 'org-todo)
13491 tg cnt e c char c1 c2 ntable tbl rtn
13492 ov-start ov-end ov-prefix
13493 (exit-after-next org-fast-tag-selection-single-key)
13494 (done-keywords org-done-keywords)
13495 groups ingroup)
13496 (save-excursion
13497 (beginning-of-line 1)
13498 (if (looking-at
13499 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13500 (setq ov-start (match-beginning 1)
13501 ov-end (match-end 1)
13502 ov-prefix "")
13503 (setq ov-start (1- (point-at-eol))
13504 ov-end (1+ ov-start))
13505 (skip-chars-forward "^\n\r")
13506 (setq ov-prefix
13507 (concat
13508 (buffer-substring (1- (point)) (point))
13509 (if (> (current-column) org-tags-column)
13511 (make-string (- org-tags-column (current-column)) ?\ ))))))
13512 (move-overlay org-tags-overlay ov-start ov-end)
13513 (save-window-excursion
13514 (if expert
13515 (set-buffer (get-buffer-create " *Org tags*"))
13516 (delete-other-windows)
13517 (split-window-vertically)
13518 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13519 (erase-buffer)
13520 (org-set-local 'org-done-keywords done-keywords)
13521 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13522 (org-fast-tag-insert "Current" current c-face "\n\n")
13523 (org-fast-tag-show-exit exit-after-next)
13524 (org-set-current-tags-overlay current ov-prefix)
13525 (setq tbl fulltable char ?a cnt 0)
13526 (while (setq e (pop tbl))
13527 (cond
13528 ((equal (car e) :startgroup)
13529 (push '() groups) (setq ingroup t)
13530 (when (not (= cnt 0))
13531 (setq cnt 0)
13532 (insert "\n"))
13533 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13534 ((equal (car e) :endgroup)
13535 (setq ingroup nil cnt 0)
13536 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13537 ((equal e '(:newline))
13538 (when (not (= cnt 0))
13539 (setq cnt 0)
13540 (insert "\n")
13541 (setq e (car tbl))
13542 (while (equal (car tbl) '(:newline))
13543 (insert "\n")
13544 (setq tbl (cdr tbl)))))
13546 (setq tg (copy-sequence (car e)) c2 nil)
13547 (if (cdr e)
13548 (setq c (cdr e))
13549 ;; automatically assign a character.
13550 (setq c1 (string-to-char
13551 (downcase (substring
13552 tg (if (= (string-to-char tg) ?@) 1 0)))))
13553 (if (or (rassoc c1 ntable) (rassoc c1 table))
13554 (while (or (rassoc char ntable) (rassoc char table))
13555 (setq char (1+ char)))
13556 (setq c2 c1))
13557 (setq c (or c2 char)))
13558 (if ingroup (push tg (car groups)))
13559 (setq tg (org-add-props tg nil 'face
13560 (cond
13561 ((not (assoc tg table))
13562 (org-get-todo-face tg))
13563 ((member tg current) c-face)
13564 ((member tg inherited) i-face)
13565 (t nil))))
13566 (if (and (= cnt 0) (not ingroup)) (insert " "))
13567 (insert "[" c "] " tg (make-string
13568 (- fwidth 4 (length tg)) ?\ ))
13569 (push (cons tg c) ntable)
13570 (when (= (setq cnt (1+ cnt)) ncol)
13571 (insert "\n")
13572 (if ingroup (insert " "))
13573 (setq cnt 0)))))
13574 (setq ntable (nreverse ntable))
13575 (insert "\n")
13576 (goto-char (point-min))
13577 (if (not expert) (org-fit-window-to-buffer))
13578 (setq rtn
13579 (catch 'exit
13580 (while t
13581 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13582 (if (not groups) "no " "")
13583 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13584 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13585 (setq org-last-tag-selection-key c)
13586 (cond
13587 ((= c ?\r) (throw 'exit t))
13588 ((= c ?!)
13589 (setq groups (not groups))
13590 (goto-char (point-min))
13591 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13592 ((= c ?\C-c)
13593 (if (not expert)
13594 (org-fast-tag-show-exit
13595 (setq exit-after-next (not exit-after-next)))
13596 (setq expert nil)
13597 (delete-other-windows)
13598 (set-window-buffer (split-window-vertically) " *Org tags*")
13599 (org-switch-to-buffer-other-window " *Org tags*")
13600 (org-fit-window-to-buffer)))
13601 ((or (= c ?\C-g)
13602 (and (= c ?q) (not (rassoc c ntable))))
13603 (org-detach-overlay org-tags-overlay)
13604 (setq quit-flag t))
13605 ((= c ?\ )
13606 (setq current nil)
13607 (if exit-after-next (setq exit-after-next 'now)))
13608 ((= c ?\t)
13609 (condition-case nil
13610 (setq tg (org-icompleting-read
13611 "Tag: "
13612 (or buffer-tags
13613 (with-current-buffer buf
13614 (org-get-buffer-tags)))))
13615 (quit (setq tg "")))
13616 (when (string-match "\\S-" tg)
13617 (add-to-list 'buffer-tags (list tg))
13618 (if (member tg current)
13619 (setq current (delete tg current))
13620 (push tg current)))
13621 (if exit-after-next (setq exit-after-next 'now)))
13622 ((setq e (rassoc c todo-table) tg (car e))
13623 (with-current-buffer buf
13624 (save-excursion (org-todo tg)))
13625 (if exit-after-next (setq exit-after-next 'now)))
13626 ((setq e (rassoc c ntable) tg (car e))
13627 (if (member tg current)
13628 (setq current (delete tg current))
13629 (loop for g in groups do
13630 (if (member tg g)
13631 (mapc (lambda (x)
13632 (setq current (delete x current)))
13633 g)))
13634 (push tg current))
13635 (if exit-after-next (setq exit-after-next 'now))))
13637 ;; Create a sorted list
13638 (setq current
13639 (sort current
13640 (lambda (a b)
13641 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13642 (if (eq exit-after-next 'now) (throw 'exit t))
13643 (goto-char (point-min))
13644 (beginning-of-line 2)
13645 (delete-region (point) (point-at-eol))
13646 (org-fast-tag-insert "Current" current c-face)
13647 (org-set-current-tags-overlay current ov-prefix)
13648 (while (re-search-forward
13649 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13650 (setq tg (match-string 1))
13651 (add-text-properties
13652 (match-beginning 1) (match-end 1)
13653 (list 'face
13654 (cond
13655 ((member tg current) c-face)
13656 ((member tg inherited) i-face)
13657 (t (get-text-property (match-beginning 1) 'face))))))
13658 (goto-char (point-min)))))
13659 (org-detach-overlay org-tags-overlay)
13660 (if rtn
13661 (mapconcat 'identity current ":")
13662 nil))))
13664 (defun org-get-tags-string ()
13665 "Get the TAGS string in the current headline."
13666 (unless (org-on-heading-p t)
13667 (error "Not on a heading"))
13668 (save-excursion
13669 (beginning-of-line 1)
13670 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13671 (org-match-string-no-properties 1)
13672 "")))
13674 (defun org-get-tags ()
13675 "Get the list of tags specified in the current headline."
13676 (org-split-string (org-get-tags-string) ":"))
13678 (defun org-get-buffer-tags ()
13679 "Get a table of all tags used in the buffer, for completion."
13680 (let (tags)
13681 (save-excursion
13682 (goto-char (point-min))
13683 (while (re-search-forward
13684 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13685 (when (equal (char-after (point-at-bol 0)) ?*)
13686 (mapc (lambda (x) (add-to-list 'tags x))
13687 (org-split-string (org-match-string-no-properties 1) ":")))))
13688 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13689 (mapcar 'list tags)))
13691 ;;;; The mapping API
13693 ;;;###autoload
13694 (defun org-map-entries (func &optional match scope &rest skip)
13695 "Call FUNC at each headline selected by MATCH in SCOPE.
13697 FUNC is a function or a lisp form. The function will be called without
13698 arguments, with the cursor positioned at the beginning of the headline.
13699 The return values of all calls to the function will be collected and
13700 returned as a list.
13702 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13703 does not need to preserve point. After evaluation, the cursor will be
13704 moved to the end of the line (presumably of the headline of the
13705 processed entry) and search continues from there. Under some
13706 circumstances, this may not produce the wanted results. For example,
13707 if you have removed (e.g. archived) the current (sub)tree it could
13708 mean that the next entry will be skipped entirely. In such cases, you
13709 can specify the position from where search should continue by making
13710 FUNC set the variable `org-map-continue-from' to the desired buffer
13711 position.
13713 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13714 Only headlines that are matched by this query will be considered during
13715 the iteration. When MATCH is nil or t, all headlines will be
13716 visited by the iteration.
13718 SCOPE determines the scope of this command. It can be any of:
13720 nil The current buffer, respecting the restriction if any
13721 tree The subtree started with the entry at point
13722 region The entries within the active region, if any
13723 file The current buffer, without restriction
13724 file-with-archives
13725 The current buffer, and any archives associated with it
13726 agenda All agenda files
13727 agenda-with-archives
13728 All agenda files with any archive files associated with them
13729 \(file1 file2 ...)
13730 If this is a list, all files in the list will be scanned
13732 The remaining args are treated as settings for the skipping facilities of
13733 the scanner. The following items can be given here:
13735 archive skip trees with the archive tag.
13736 comment skip trees with the COMMENT keyword
13737 function or Emacs Lisp form:
13738 will be used as value for `org-agenda-skip-function', so whenever
13739 the function returns t, FUNC will not be called for that
13740 entry and search will continue from the point where the
13741 function leaves it.
13743 If your function needs to retrieve the tags including inherited tags
13744 at the *current* entry, you can use the value of the variable
13745 `org-scanner-tags' which will be much faster than getting the value
13746 with `org-get-tags-at'. If your function gets properties with
13747 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13748 to t around the call to `org-entry-properties' to get the same speedup.
13749 Note that if your function moves around to retrieve tags and properties at
13750 a *different* entry, you cannot use these techniques."
13751 (unless (and (eq scope 'region) (not (org-region-active-p)))
13752 (let* ((org-agenda-archives-mode nil) ; just to make sure
13753 (org-agenda-skip-archived-trees (memq 'archive skip))
13754 (org-agenda-skip-comment-trees (memq 'comment skip))
13755 (org-agenda-skip-function
13756 (car (org-delete-all '(comment archive) skip)))
13757 (org-tags-match-list-sublevels t)
13758 matcher file res
13759 org-todo-keywords-for-agenda
13760 org-done-keywords-for-agenda
13761 org-todo-keyword-alist-for-agenda
13762 org-drawers-for-agenda
13763 org-tag-alist-for-agenda)
13765 (cond
13766 ((eq match t) (setq matcher t))
13767 ((eq match nil) (setq matcher t))
13768 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13770 (save-excursion
13771 (save-restriction
13772 (cond ((eq scope 'tree)
13773 (org-back-to-heading t)
13774 (org-narrow-to-subtree)
13775 (setq scope nil))
13776 ((and (eq scope 'region) (org-region-active-p))
13777 (narrow-to-region (region-beginning)
13778 (save-excursion
13779 (goto-char (region-end))
13780 (unless (and (bolp) (org-at-heading-p))
13781 (outline-next-heading))
13782 (point)))
13783 (setq scope nil)))
13785 (if (not scope)
13786 (progn
13787 (org-prepare-agenda-buffers
13788 (list (buffer-file-name (current-buffer))))
13789 (setq res (org-scan-tags func matcher)))
13790 ;; Get the right scope
13791 (cond
13792 ((and scope (listp scope) (symbolp (car scope)))
13793 (setq scope (eval scope)))
13794 ((eq scope 'agenda)
13795 (setq scope (org-agenda-files t)))
13796 ((eq scope 'agenda-with-archives)
13797 (setq scope (org-agenda-files t))
13798 (setq scope (org-add-archive-files scope)))
13799 ((eq scope 'file)
13800 (setq scope (list (buffer-file-name))))
13801 ((eq scope 'file-with-archives)
13802 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13803 (org-prepare-agenda-buffers scope)
13804 (while (setq file (pop scope))
13805 (with-current-buffer (org-find-base-buffer-visiting file)
13806 (save-excursion
13807 (save-restriction
13808 (widen)
13809 (goto-char (point-min))
13810 (setq res (append res (org-scan-tags func matcher))))))))))
13811 res)))
13813 ;;;; Properties
13815 ;;; Setting and retrieving properties
13817 (defconst org-special-properties
13818 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13819 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13820 "The special properties valid in Org-mode.
13822 These are properties that are not defined in the property drawer,
13823 but in some other way.")
13825 (defconst org-default-properties
13826 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13827 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13828 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13829 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13830 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13831 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13832 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13833 "Some properties that are used by Org-mode for various purposes.
13834 Being in this list makes sure that they are offered for completion.")
13836 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13837 "Regular expression matching the first line of a property drawer.")
13839 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13840 "Regular expression matching the last line of a property drawer.")
13842 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13843 "Regular expression matching the first line of a property drawer.")
13845 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13846 "Regular expression matching the first line of a property drawer.")
13848 (defconst org-property-drawer-re
13849 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13850 org-property-end-re "\\)\n?")
13851 "Matches an entire property drawer.")
13853 (defconst org-clock-drawer-re
13854 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13855 org-property-end-re "\\)\n?")
13856 "Matches an entire clock drawer.")
13858 (defsubst org-re-property (property)
13859 "Return a regexp matching PROPERTY.
13860 Match group 1 will be set to the value "
13861 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
13863 (defun org-property-action ()
13864 "Do an action on properties."
13865 (interactive)
13866 (let (c)
13867 (org-at-property-p)
13868 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13869 (setq c (read-char-exclusive))
13870 (cond
13871 ((equal c ?s)
13872 (call-interactively 'org-set-property))
13873 ((equal c ?d)
13874 (call-interactively 'org-delete-property))
13875 ((equal c ?D)
13876 (call-interactively 'org-delete-property-globally))
13877 ((equal c ?c)
13878 (call-interactively 'org-compute-property-at-point))
13879 (t (error "No such property action %c" c)))))
13881 (defun org-set-effort (&optional value)
13882 "Set the effort property of the current entry.
13883 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13884 allowed value."
13885 (interactive "P")
13886 (if (equal value 0) (setq value 10))
13887 (let* ((completion-ignore-case t)
13888 (prop org-effort-property)
13889 (cur (org-entry-get nil prop))
13890 (allowed (org-property-get-allowed-values nil prop 'table))
13891 (existing (mapcar 'list (org-property-values prop)))
13893 (val (cond
13894 ((stringp value) value)
13895 ((and allowed (integerp value))
13896 (or (car (nth (1- value) allowed))
13897 (car (org-last allowed))))
13898 (allowed
13899 (message "Select 1-9,0, [RET%s]: %s"
13900 (if cur (concat "=" cur) "")
13901 (mapconcat 'car allowed " "))
13902 (setq rpl (read-char-exclusive))
13903 (if (equal rpl ?\r)
13905 (setq rpl (- rpl ?0))
13906 (if (equal rpl 0) (setq rpl 10))
13907 (if (and (> rpl 0) (<= rpl (length allowed)))
13908 (car (nth (1- rpl) allowed))
13909 (org-completing-read "Effort: " allowed nil))))
13911 (let (org-completion-use-ido org-completion-use-iswitchb)
13912 (org-completing-read
13913 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13914 (concat "[" cur "]") "")
13915 ": ")
13916 existing nil nil "" nil cur))))))
13917 (unless (equal (org-entry-get nil prop) val)
13918 (org-entry-put nil prop val))
13919 (message "%s is now %s" prop val)))
13921 (defun org-at-property-p ()
13922 "Is cursor inside a property drawer?"
13923 (save-excursion
13924 (beginning-of-line 1)
13925 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13926 (save-match-data ;; Used by calling procedures
13927 (let ((p (point))
13928 (range (unless (org-before-first-heading-p)
13929 (org-get-property-block))))
13930 (and range (<= (car range) p) (< p (cdr range))))))))
13932 (defun org-get-property-block (&optional beg end force)
13933 "Return the (beg . end) range of the body of the property drawer.
13934 BEG and END can be beginning and end of subtree, if not given
13935 they will be found.
13936 If the drawer does not exist and FORCE is non-nil, create the drawer."
13937 (catch 'exit
13938 (save-excursion
13939 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13940 (end (or end (progn (outline-next-heading) (point)))))
13941 (goto-char beg)
13942 (if (re-search-forward org-property-start-re end t)
13943 (setq beg (1+ (match-end 0)))
13944 (if force
13945 (save-excursion
13946 (org-insert-property-drawer)
13947 (setq end (progn (outline-next-heading) (point))))
13948 (throw 'exit nil))
13949 (goto-char beg)
13950 (if (re-search-forward org-property-start-re end t)
13951 (setq beg (1+ (match-end 0)))))
13952 (if (re-search-forward org-property-end-re end t)
13953 (setq end (match-beginning 0))
13954 (or force (throw 'exit nil))
13955 (goto-char beg)
13956 (setq end beg)
13957 (org-indent-line-function)
13958 (insert ":END:\n"))
13959 (cons beg end)))))
13961 (defun org-entry-properties (&optional pom which specific)
13962 "Get all properties of the entry at point-or-marker POM.
13963 This includes the TODO keyword, the tags, time strings for deadline,
13964 scheduled, and clocking, and any additional properties defined in the
13965 entry. The return value is an alist, keys may occur multiple times
13966 if the property key was used several times.
13967 POM may also be nil, in which case the current entry is used.
13968 If WHICH is nil or `all', get all properties. If WHICH is
13969 `special' or `standard', only get that subclass. If WHICH
13970 is a string only get exactly this property. SPECIFIC can be a string, the
13971 specific property we are interested in. Specifying it can speed
13972 things up because then unnecessary parsing is avoided."
13973 (setq which (or which 'all))
13974 (org-with-point-at pom
13975 (let ((clockstr (substring org-clock-string 0 -1))
13976 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13977 (case-fold-search nil)
13978 beg end range props sum-props key key1 value string clocksum)
13979 (save-excursion
13980 (when (condition-case nil
13981 (and (eq major-mode 'org-mode) (org-back-to-heading t))
13982 (error nil))
13983 (setq beg (point))
13984 (setq sum-props (get-text-property (point) 'org-summaries))
13985 (setq clocksum (get-text-property (point) :org-clock-minutes))
13986 (outline-next-heading)
13987 (setq end (point))
13988 (when (memq which '(all special))
13989 ;; Get the special properties, like TODO and tags
13990 (goto-char beg)
13991 (when (and (or (not specific) (string= specific "TODO"))
13992 (looking-at org-todo-line-regexp) (match-end 2))
13993 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13994 (when (and (or (not specific) (string= specific "PRIORITY"))
13995 (looking-at org-priority-regexp))
13996 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13997 (when (or (not specific) (string= specific "FILE"))
13998 (push (cons "FILE" buffer-file-name) props))
13999 (when (and (or (not specific) (string= specific "TAGS"))
14000 (setq value (org-get-tags-string))
14001 (string-match "\\S-" value))
14002 (push (cons "TAGS" value) props))
14003 (when (and (or (not specific) (string= specific "ALLTAGS"))
14004 (setq value (org-get-tags-at)))
14005 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14006 ":"))
14007 props))
14008 (when (or (not specific) (string= specific "BLOCKED"))
14009 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14010 (when (or (not specific)
14011 (member specific
14012 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14013 "TIMESTAMP" "TIMESTAMP_IA")))
14014 (catch 'match
14015 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14016 (setq key (if (match-end 1)
14017 (substring (org-match-string-no-properties 1)
14018 0 -1))
14019 string (if (equal key clockstr)
14020 (org-no-properties
14021 (org-trim
14022 (buffer-substring
14023 (match-beginning 3) (goto-char
14024 (point-at-eol)))))
14025 (substring (org-match-string-no-properties 3)
14026 1 -1)))
14027 ;; Get the correct property name from the key. This is
14028 ;; necessary if the user has configured time keywords.
14029 (setq key1 (concat key ":"))
14030 (cond
14031 ((not key)
14032 (setq key
14033 (if (= (char-after (match-beginning 3)) ?\[)
14034 "TIMESTAMP_IA" "TIMESTAMP")))
14035 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14036 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14037 ((equal key1 org-closed-string) (setq key "CLOSED"))
14038 ((equal key1 org-clock-string) (setq key "CLOCK")))
14039 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14040 (progn
14041 (push (cons key string) props)
14042 ;; no need to search further if match is found
14043 (throw 'match t))
14044 (when (or (equal key "CLOCK") (not (assoc key props)))
14045 (push (cons key string) props))))))
14048 (when (memq which '(all standard))
14049 ;; Get the standard properties, like :PROP: ...
14050 (setq range (org-get-property-block beg end))
14051 (when range
14052 (goto-char (car range))
14053 (while (re-search-forward
14054 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14055 (cdr range) t)
14056 (setq key (org-match-string-no-properties 1)
14057 value (org-trim (or (org-match-string-no-properties 2) "")))
14058 (unless (member key excluded)
14059 (push (cons key (or value "")) props)))))
14060 (if clocksum
14061 (push (cons "CLOCKSUM"
14062 (org-columns-number-to-string (/ (float clocksum) 60.)
14063 'add_times))
14064 props))
14065 (unless (assoc "CATEGORY" props)
14066 (push (cons "CATEGORY" (org-get-category)) props))
14067 (append sum-props (nreverse props)))))))
14069 (defun org-entry-get (pom property &optional inherit literal-nil)
14070 "Get value of PROPERTY for entry at point-or-marker POM.
14071 If INHERIT is non-nil and the entry does not have the property,
14072 then also check higher levels of the hierarchy.
14073 If INHERIT is the symbol `selective', use inheritance only if the setting
14074 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14075 If the property is present but empty, the return value is the empty string.
14076 If the property is not present at all, nil is returned.
14078 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14079 do not interpret it as the list atom nil. This is used for inheritance
14080 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14081 (org-with-point-at pom
14082 (if (and inherit (if (eq inherit 'selective)
14083 (org-property-inherit-p property)
14085 (org-entry-get-with-inheritance property literal-nil)
14086 (if (member property org-special-properties)
14087 ;; We need a special property. Use `org-entry-properties' to
14088 ;; retrieve it, but specify the wanted property
14089 (cdr (assoc property (org-entry-properties nil 'special property)))
14090 (let ((range (unless (org-before-first-heading-p)
14091 (org-get-property-block))))
14092 (when (and range (goto-char (car range)))
14093 ((lambda (val) (when val (if literal-nil val (org-not-nil val))))
14094 (cond
14095 ((re-search-forward
14096 (org-re-property property) (cdr range) t)
14097 (if (match-end 1) (org-match-string-no-properties 1) ""))
14098 ((re-search-forward
14099 (org-re-property (concat property "+")) (cdr range) t)
14100 (cdr (assoc
14101 property
14102 (org-update-property-plist
14103 (concat property "+")
14104 (if (match-end 1) (org-match-string-no-properties 1) "")
14105 (list (or (assoc property org-file-properties)
14106 (assoc property org-global-properties)
14107 (assoc property org-global-properties-fixed)
14108 ))))))))))))))
14110 (defun org-property-or-variable-value (var &optional inherit)
14111 "Check if there is a property fixing the value of VAR.
14112 If yes, return this value. If not, return the current value of the variable."
14113 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14114 (if (and prop (stringp prop) (string-match "\\S-" prop))
14115 (read prop)
14116 (symbol-value var))))
14118 (defun org-entry-delete (pom property)
14119 "Delete the property PROPERTY from entry at point-or-marker POM."
14120 (org-with-point-at pom
14121 (if (member property org-special-properties)
14122 nil ; cannot delete these properties.
14123 (let ((range (org-get-property-block)))
14124 (if (and range
14125 (goto-char (car range))
14126 (re-search-forward
14127 (org-re-property property)
14128 (cdr range) t))
14129 (progn
14130 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14132 nil)))))
14134 ;; Multi-values properties are properties that contain multiple values
14135 ;; These values are assumed to be single words, separated by whitespace.
14136 (defun org-entry-add-to-multivalued-property (pom property value)
14137 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14138 (let* ((old (org-entry-get pom property))
14139 (values (and old (org-split-string old "[ \t]"))))
14140 (setq value (org-entry-protect-space value))
14141 (unless (member value values)
14142 (setq values (cons value values))
14143 (org-entry-put pom property
14144 (mapconcat 'identity values " ")))))
14146 (defun org-entry-remove-from-multivalued-property (pom property value)
14147 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14148 (let* ((old (org-entry-get pom property))
14149 (values (and old (org-split-string old "[ \t]"))))
14150 (setq value (org-entry-protect-space value))
14151 (when (member value values)
14152 (setq values (delete value values))
14153 (org-entry-put pom property
14154 (mapconcat 'identity values " ")))))
14156 (defun org-entry-member-in-multivalued-property (pom property value)
14157 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14158 (let* ((old (org-entry-get pom property))
14159 (values (and old (org-split-string old "[ \t]"))))
14160 (setq value (org-entry-protect-space value))
14161 (member value values)))
14163 (defun org-entry-get-multivalued-property (pom property)
14164 "Return a list of values in a multivalued property."
14165 (let* ((value (org-entry-get pom property))
14166 (values (and value (org-split-string value "[ \t]"))))
14167 (mapcar 'org-entry-restore-space values)))
14169 (defun org-entry-put-multivalued-property (pom property &rest values)
14170 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14171 VALUES should be a list of strings. Spaces will be protected."
14172 (org-entry-put pom property
14173 (mapconcat 'org-entry-protect-space values " "))
14174 (let* ((value (org-entry-get pom property))
14175 (values (and value (org-split-string value "[ \t]"))))
14176 (mapcar 'org-entry-restore-space values)))
14178 (defun org-entry-protect-space (s)
14179 "Protect spaces and newline in string S."
14180 (while (string-match " " s)
14181 (setq s (replace-match "%20" t t s)))
14182 (while (string-match "\n" s)
14183 (setq s (replace-match "%0A" t t s)))
14186 (defun org-entry-restore-space (s)
14187 "Restore spaces and newline in string S."
14188 (while (string-match "%20" s)
14189 (setq s (replace-match " " t t s)))
14190 (while (string-match "%0A" s)
14191 (setq s (replace-match "\n" t t s)))
14194 (defvar org-entry-property-inherited-from (make-marker)
14195 "Marker pointing to the entry from where a property was inherited.
14196 Each call to `org-entry-get-with-inheritance' will set this marker to the
14197 location of the entry where the inheritance search matched. If there was
14198 no match, the marker will point nowhere.
14199 Note that also `org-entry-get' calls this function, if the INHERIT flag
14200 is set.")
14202 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14203 "Get entry property, and search higher levels if not present.
14204 The search will stop at the first ancestor which has the property defined.
14205 If the value found is \"nil\", return nil to show that the property
14206 should be considered as undefined (this is the meaning of nil here).
14207 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14208 (move-marker org-entry-property-inherited-from nil)
14209 (let (tmp)
14210 (unless (org-before-first-heading-p)
14211 (save-excursion
14212 (save-restriction
14213 (widen)
14214 (catch 'ex
14215 (while t
14216 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14217 (org-back-to-heading t)
14218 (move-marker org-entry-property-inherited-from (point))
14219 (throw 'ex tmp))
14220 (or (org-up-heading-safe) (throw 'ex nil)))))))
14221 (setq tmp (or tmp
14222 (cdr (assoc property org-file-properties))
14223 (cdr (assoc property org-global-properties))
14224 (cdr (assoc property org-global-properties-fixed))))
14225 (if literal-nil tmp (org-not-nil tmp))))
14227 (defvar org-property-changed-functions nil
14228 "Hook called when the value of a property has changed.
14229 Each hook function should accept two arguments, the name of the property
14230 and the new value.")
14232 (defun org-entry-put (pom property value)
14233 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14234 (org-with-point-at pom
14235 (org-back-to-heading t)
14236 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14237 range)
14238 (cond
14239 ((equal property "TODO")
14240 (when (and (stringp value) (string-match "\\S-" value)
14241 (not (member value org-todo-keywords-1)))
14242 (error "\"%s\" is not a valid TODO state" value))
14243 (if (or (not value)
14244 (not (string-match "\\S-" value)))
14245 (setq value 'none))
14246 (org-todo value)
14247 (org-set-tags nil 'align))
14248 ((equal property "PRIORITY")
14249 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14250 (string-to-char value) ?\ ))
14251 (org-set-tags nil 'align))
14252 ((equal property "SCHEDULED")
14253 (if (re-search-forward org-scheduled-time-regexp end t)
14254 (cond
14255 ((eq value 'earlier) (org-timestamp-change -1 'day))
14256 ((eq value 'later) (org-timestamp-change 1 'day))
14257 (t (call-interactively 'org-schedule)))
14258 (call-interactively 'org-schedule)))
14259 ((equal property "DEADLINE")
14260 (if (re-search-forward org-deadline-time-regexp end t)
14261 (cond
14262 ((eq value 'earlier) (org-timestamp-change -1 'day))
14263 ((eq value 'later) (org-timestamp-change 1 'day))
14264 (t (call-interactively 'org-deadline)))
14265 (call-interactively 'org-deadline)))
14266 ((member property org-special-properties)
14267 (error "The %s property can not yet be set with `org-entry-put'"
14268 property))
14269 (t ; a non-special property
14270 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14271 (setq range (org-get-property-block beg end 'force))
14272 (goto-char (car range))
14273 (if (re-search-forward
14274 (org-re-property property) (cdr range) t)
14275 (progn
14276 (delete-region (match-beginning 0) (match-end 0))
14277 (goto-char (match-beginning 0)))
14278 (goto-char (cdr range))
14279 (insert "\n")
14280 (backward-char 1)
14281 (org-indent-line-function))
14282 (insert ":" property ":")
14283 (and value (insert " " value))
14284 (org-indent-line-function)))))
14285 (run-hook-with-args 'org-property-changed-functions property value)))
14287 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14288 "Get all property keys in the current buffer.
14289 With INCLUDE-SPECIALS, also list the special properties that reflect things
14290 like tags and TODO state.
14291 With INCLUDE-DEFAULTS, also include properties that has special meaning
14292 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14293 and others.
14294 With INCLUDE-COLUMNS, also include property names given in COLUMN
14295 formats in the current buffer."
14296 (let (rtn range cfmt s p)
14297 (save-excursion
14298 (save-restriction
14299 (widen)
14300 (goto-char (point-min))
14301 (while (re-search-forward org-property-start-re nil t)
14302 (setq range (org-get-property-block))
14303 (goto-char (car range))
14304 (while (re-search-forward
14305 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14306 (cdr range) t)
14307 (add-to-list 'rtn (org-match-string-no-properties 1)))
14308 (outline-next-heading))))
14310 (when include-specials
14311 (setq rtn (append org-special-properties rtn)))
14313 (when include-defaults
14314 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14315 (add-to-list 'rtn org-effort-property))
14317 (when include-columns
14318 (save-excursion
14319 (save-restriction
14320 (widen)
14321 (goto-char (point-min))
14322 (while (re-search-forward
14323 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14324 nil t)
14325 (setq cfmt (match-string 2) s 0)
14326 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14327 cfmt s)
14328 (setq s (match-end 0)
14329 p (match-string 1 cfmt))
14330 (unless (or (equal p "ITEM")
14331 (member p org-special-properties))
14332 (add-to-list 'rtn (match-string 1 cfmt))))))))
14334 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14336 (defun org-property-values (key)
14337 "Return a list of all values of property KEY in the current buffer."
14338 (save-excursion
14339 (save-restriction
14340 (widen)
14341 (goto-char (point-min))
14342 (let ((re (org-re-property key))
14343 values)
14344 (while (re-search-forward re nil t)
14345 (add-to-list 'values (org-trim (match-string 1))))
14346 (delete "" values)))))
14348 (defun org-insert-property-drawer ()
14349 "Insert a property drawer into the current entry."
14350 (interactive)
14351 (org-back-to-heading t)
14352 (looking-at org-outline-regexp)
14353 (let ((indent (if org-adapt-indentation
14354 (- (match-end 0)(match-beginning 0))
14356 (beg (point))
14357 (re (concat "^[ \t]*" org-keyword-time-regexp))
14358 end hiddenp)
14359 (outline-next-heading)
14360 (setq end (point))
14361 (goto-char beg)
14362 (while (re-search-forward re end t))
14363 (setq hiddenp (outline-invisible-p))
14364 (end-of-line 1)
14365 (and (equal (char-after) ?\n) (forward-char 1))
14366 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14367 (if (member (match-string 1) '("CLOCK:" ":END:"))
14368 ;; just skip this line
14369 (beginning-of-line 2)
14370 ;; Drawer start, find the end
14371 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14372 (beginning-of-line 1)))
14373 (org-skip-over-state-notes)
14374 (skip-chars-backward " \t\n\r")
14375 (if (eq (char-before) ?*) (forward-char 1))
14376 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14377 (beginning-of-line 0)
14378 (org-indent-to-column indent)
14379 (beginning-of-line 2)
14380 (org-indent-to-column indent)
14381 (beginning-of-line 0)
14382 (if hiddenp
14383 (save-excursion
14384 (org-back-to-heading t)
14385 (hide-entry))
14386 (org-flag-drawer t))))
14388 (defvar org-property-set-functions-alist nil
14389 "Property set function alist.
14390 Each entry should have the following format:
14392 (PROPERTY . READ-FUNCTION)
14394 The read function will be called with the same argument as
14395 `org-completing-read'.")
14397 (defun org-set-property-function (property)
14398 "Get the function that should be used to set PROPERTY.
14399 This is computed according to `org-property-set-functions-alist'."
14400 (or (cdr (assoc property org-property-set-functions-alist))
14401 'org-completing-read))
14403 (defun org-read-property-value (property)
14404 "Read PROPERTY value from user."
14405 (let* ((completion-ignore-case t)
14406 (allowed (org-property-get-allowed-values nil property 'table))
14407 (cur (org-entry-get nil property))
14408 (prompt (concat property " value"
14409 (if (and cur (string-match "\\S-" cur))
14410 (concat " [" cur "]") "") ": "))
14411 (set-function (org-set-property-function property))
14412 (val (if allowed
14413 (funcall set-function prompt allowed nil
14414 (not (get-text-property 0 'org-unrestricted
14415 (caar allowed))))
14416 (let (org-completion-use-ido org-completion-use-iswitchb)
14417 (funcall set-function prompt
14418 (mapcar 'list (org-property-values property))
14419 nil nil "" nil cur)))))
14420 (if (equal val "")
14422 val)))
14424 (defvar org-last-set-property nil)
14425 (defun org-read-property-name ()
14426 "Read a property name."
14427 (let* ((completion-ignore-case t)
14428 (keys (org-buffer-property-keys nil t t))
14429 (default-prop (or (save-excursion
14430 (save-match-data
14431 (beginning-of-line)
14432 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14433 (null (string= (match-string 1) "END"))
14434 (match-string 1))))
14435 org-last-set-property))
14436 (property (org-icompleting-read
14437 (concat "Property"
14438 (if default-prop (concat " [" default-prop "]") "")
14439 ": ")
14440 (mapcar 'list keys)
14441 nil nil nil nil
14442 default-prop
14444 (if (member property keys)
14445 property
14446 (or (cdr (assoc (downcase property)
14447 (mapcar (lambda (x) (cons (downcase x) x))
14448 keys)))
14449 property))))
14451 (defun org-set-property (property value)
14452 "In the current entry, set PROPERTY to VALUE.
14453 When called interactively, this will prompt for a property name, offering
14454 completion on existing and default properties. And then it will prompt
14455 for a value, offering completion either on allowed values (via an inherited
14456 xxx_ALL property) or on existing values in other instances of this property
14457 in the current file."
14458 (interactive (list nil nil))
14459 (let* ((property (or property (org-read-property-name)))
14460 (value (or value (org-read-property-value property)))
14461 (fn (assoc property org-properties-postprocess-alist)))
14462 (setq org-last-set-property property)
14463 ;; Possibly postprocess the inserted value:
14464 (when fn (setq value (funcall (cadr fn) value)))
14465 (unless (equal (org-entry-get nil property) value)
14466 (org-entry-put nil property value))))
14468 (defun org-delete-property (property)
14469 "In the current entry, delete PROPERTY."
14470 (interactive
14471 (let* ((completion-ignore-case t)
14472 (prop (org-icompleting-read "Property: "
14473 (org-entry-properties nil 'standard))))
14474 (list prop)))
14475 (message "Property %s %s" property
14476 (if (org-entry-delete nil property)
14477 "deleted"
14478 "was not present in the entry")))
14480 (defun org-delete-property-globally (property)
14481 "Remove PROPERTY globally, from all entries."
14482 (interactive
14483 (let* ((completion-ignore-case t)
14484 (prop (org-icompleting-read
14485 "Globally remove property: "
14486 (mapcar 'list (org-buffer-property-keys)))))
14487 (list prop)))
14488 (save-excursion
14489 (save-restriction
14490 (widen)
14491 (goto-char (point-min))
14492 (let ((cnt 0))
14493 (while (re-search-forward
14494 (org-re-property property)
14495 nil t)
14496 (setq cnt (1+ cnt))
14497 (replace-match ""))
14498 (message "Property \"%s\" removed from %d entries" property cnt)))))
14500 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14502 (defun org-compute-property-at-point ()
14503 "Compute the property at point.
14504 This looks for an enclosing column format, extracts the operator and
14505 then applies it to the property in the column format's scope."
14506 (interactive)
14507 (unless (org-at-property-p)
14508 (error "Not at a property"))
14509 (let ((prop (org-match-string-no-properties 2)))
14510 (org-columns-get-format-and-top-level)
14511 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14512 (error "No operator defined for property %s" prop))
14513 (org-columns-compute prop)))
14515 (defvar org-property-allowed-value-functions nil
14516 "Hook for functions supplying allowed values for a specific property.
14517 The functions must take a single argument, the name of the property, and
14518 return a flat list of allowed values. If \":ETC\" is one of
14519 the values, this means that these values are intended as defaults for
14520 completion, but that other values should be allowed too.
14521 The functions must return nil if they are not responsible for this
14522 property.")
14524 (defun org-property-get-allowed-values (pom property &optional table)
14525 "Get allowed values for the property PROPERTY.
14526 When TABLE is non-nil, return an alist that can directly be used for
14527 completion."
14528 (let (vals)
14529 (cond
14530 ((equal property "TODO")
14531 (setq vals (org-with-point-at pom
14532 (append org-todo-keywords-1 '("")))))
14533 ((equal property "PRIORITY")
14534 (let ((n org-lowest-priority))
14535 (while (>= n org-highest-priority)
14536 (push (char-to-string n) vals)
14537 (setq n (1- n)))))
14538 ((member property org-special-properties))
14539 ((setq vals (run-hook-with-args-until-success
14540 'org-property-allowed-value-functions property)))
14542 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14543 (when (and vals (string-match "\\S-" vals))
14544 (setq vals (car (read-from-string (concat "(" vals ")"))))
14545 (setq vals (mapcar (lambda (x)
14546 (cond ((stringp x) x)
14547 ((numberp x) (number-to-string x))
14548 ((symbolp x) (symbol-name x))
14549 (t "???")))
14550 vals)))))
14551 (when (member ":ETC" vals)
14552 (setq vals (remove ":ETC" vals))
14553 (org-add-props (car vals) '(org-unrestricted t)))
14554 (if table (mapcar 'list vals) vals)))
14556 (defun org-property-previous-allowed-value (&optional previous)
14557 "Switch to the next allowed value for this property."
14558 (interactive)
14559 (org-property-next-allowed-value t))
14561 (defun org-property-next-allowed-value (&optional previous)
14562 "Switch to the next allowed value for this property."
14563 (interactive)
14564 (unless (org-at-property-p)
14565 (error "Not at a property"))
14566 (let* ((key (match-string 2))
14567 (value (match-string 3))
14568 (allowed (or (org-property-get-allowed-values (point) key)
14569 (and (member value '("[ ]" "[-]" "[X]"))
14570 '("[ ]" "[X]"))))
14571 nval)
14572 (unless allowed
14573 (error "Allowed values for this property have not been defined"))
14574 (if previous (setq allowed (reverse allowed)))
14575 (if (member value allowed)
14576 (setq nval (car (cdr (member value allowed)))))
14577 (setq nval (or nval (car allowed)))
14578 (if (equal nval value)
14579 (error "Only one allowed value for this property"))
14580 (org-at-property-p)
14581 (replace-match (concat " :" key ": " nval) t t)
14582 (org-indent-line-function)
14583 (beginning-of-line 1)
14584 (skip-chars-forward " \t")
14585 (run-hook-with-args 'org-property-changed-functions key nval)))
14587 (defun org-find-olp (path &optional this-buffer)
14588 "Return a marker pointing to the entry at outline path OLP.
14589 If anything goes wrong, throw an error.
14590 You can wrap this call to catch the error like this:
14592 (condition-case msg
14593 (org-mobile-locate-entry (match-string 4))
14594 (error (nth 1 msg)))
14596 The return value will then be either a string with the error message,
14597 or a marker if everything is OK.
14599 If THIS-BUFFER is set, the outline path does not contain a file,
14600 only headings."
14601 (let* ((file (if this-buffer buffer-file-name (pop path)))
14602 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14603 (level 1)
14604 (lmin 1)
14605 (lmax 1)
14606 limit re end found pos heading cnt flevel)
14607 (unless buffer (error "File not found :%s" file))
14608 (with-current-buffer buffer
14609 (save-excursion
14610 (save-restriction
14611 (widen)
14612 (setq limit (point-max))
14613 (goto-char (point-min))
14614 (while (setq heading (pop path))
14615 (setq re (format org-complex-heading-regexp-format
14616 (regexp-quote heading)))
14617 (setq cnt 0 pos (point))
14618 (while (re-search-forward re end t)
14619 (setq level (- (match-end 1) (match-beginning 1)))
14620 (if (and (>= level lmin) (<= level lmax))
14621 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14622 (when (= cnt 0) (error "Heading not found on level %d: %s"
14623 lmax heading))
14624 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14625 lmax heading))
14626 (goto-char found)
14627 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14628 (setq end (save-excursion (org-end-of-subtree t t))))
14629 (when (org-on-heading-p)
14630 (move-marker (make-marker) (point))))))))
14632 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14633 "Find node HEADING in BUFFER.
14634 Return a marker to the heading if it was found, or nil if not.
14635 If POS-ONLY is set, return just the position instead of a marker.
14637 The heading text must match exact, but it may have a TODO keyword,
14638 a priority cookie and tags in the standard locations."
14639 (with-current-buffer (or buffer (current-buffer))
14640 (save-excursion
14641 (save-restriction
14642 (widen)
14643 (goto-char (point-min))
14644 (let (case-fold-search)
14645 (if (re-search-forward
14646 (format org-complex-heading-regexp-format
14647 (regexp-quote heading)) nil t)
14648 (if pos-only
14649 (match-beginning 0)
14650 (move-marker (make-marker) (match-beginning 0)))))))))
14652 (defun org-find-exact-heading-in-directory (heading &optional dir)
14653 "Find Org node headline HEADING in all .org files in directory DIR.
14654 When the target headline is found, return a marker to this location."
14655 (let ((files (directory-files (or dir default-directory)
14656 nil "\\`[^.#].*\\.org\\'"))
14657 file visiting m buffer)
14658 (catch 'found
14659 (while (setq file (pop files))
14660 (message "trying %s" file)
14661 (setq visiting (org-find-base-buffer-visiting file))
14662 (setq buffer (or visiting (find-file-noselect file)))
14663 (setq m (org-find-exact-headline-in-buffer
14664 heading buffer))
14665 (when (and (not m) (not visiting)) (kill-buffer buffer))
14666 (and m (throw 'found m))))))
14668 (defun org-find-entry-with-id (ident)
14669 "Locate the entry that contains the ID property with exact value IDENT.
14670 IDENT can be a string, a symbol or a number, this function will search for
14671 the string representation of it.
14672 Return the position where this entry starts, or nil if there is no such entry."
14673 (interactive "sID: ")
14674 (let ((id (cond
14675 ((stringp ident) ident)
14676 ((symbol-name ident) (symbol-name ident))
14677 ((numberp ident) (number-to-string ident))
14678 (t (error "IDENT %s must be a string, symbol or number" ident))))
14679 (case-fold-search nil))
14680 (save-excursion
14681 (save-restriction
14682 (widen)
14683 (goto-char (point-min))
14684 (when (re-search-forward
14685 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14686 nil t)
14687 (org-back-to-heading t)
14688 (point))))))
14690 ;;;; Timestamps
14692 (defvar org-last-changed-timestamp nil)
14693 (defvar org-last-inserted-timestamp nil
14694 "The last time stamp inserted with `org-insert-time-stamp'.")
14695 (defvar org-time-was-given) ; dynamically scoped parameter
14696 (defvar org-end-time-was-given) ; dynamically scoped parameter
14697 (defvar org-ts-what) ; dynamically scoped parameter
14699 (defun org-time-stamp (arg &optional inactive)
14700 "Prompt for a date/time and insert a time stamp.
14701 If the user specifies a time like HH:MM, or if this command is called
14702 with a prefix argument, the time stamp will contain date and time.
14703 Otherwise, only the date will be included. All parts of a date not
14704 specified by the user will be filled in from the current date/time.
14705 So if you press just return without typing anything, the time stamp
14706 will represent the current date/time. If there is already a timestamp
14707 at the cursor, it will be modified."
14708 (interactive "P")
14709 (let* ((ts nil)
14710 (default-time
14711 ;; Default time is either today, or, when entering a range,
14712 ;; the range start.
14713 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14714 (save-excursion
14715 (re-search-backward
14716 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14717 (- (point) 20) t)))
14718 (apply 'encode-time (org-parse-time-string (match-string 1)))
14719 (current-time)))
14720 (default-input (and ts (org-get-compact-tod ts)))
14721 (repeater (save-excursion
14722 (save-match-data
14723 (beginning-of-line)
14724 (when (re-search-forward
14725 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14726 (save-excursion (progn (end-of-line) (point))) t)
14727 (match-string 0)))))
14728 org-time-was-given org-end-time-was-given time)
14729 (cond
14730 ((and (org-at-timestamp-p t)
14731 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14732 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14733 (insert "--")
14734 (setq time (let ((this-command this-command))
14735 (org-read-date arg 'totime nil nil
14736 default-time default-input)))
14737 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14738 ((org-at-timestamp-p t)
14739 (setq time (let ((this-command this-command))
14740 (org-read-date arg 'totime nil nil default-time default-input)))
14741 (when (org-at-timestamp-p t) ; just to get the match data
14742 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14743 (replace-match "")
14744 (setq org-last-changed-timestamp
14745 (org-insert-time-stamp
14746 time (or org-time-was-given arg)
14747 inactive nil nil (list org-end-time-was-given)))
14748 (when repeater (goto-char (1- (point))) (insert " " repeater)
14749 (setq org-last-changed-timestamp
14750 (concat (substring org-last-inserted-timestamp 0 -1)
14751 " " repeater ">"))))
14752 (message "Timestamp updated"))
14754 (setq time (let ((this-command this-command))
14755 (org-read-date arg 'totime nil nil default-time default-input)))
14756 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14757 nil nil (list org-end-time-was-given))))))
14759 ;; FIXME: can we use this for something else, like computing time differences?
14760 (defun org-get-compact-tod (s)
14761 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14762 (let* ((t1 (match-string 1 s))
14763 (h1 (string-to-number (match-string 2 s)))
14764 (m1 (string-to-number (match-string 3 s)))
14765 (t2 (and (match-end 4) (match-string 5 s)))
14766 (h2 (and t2 (string-to-number (match-string 6 s))))
14767 (m2 (and t2 (string-to-number (match-string 7 s))))
14768 dh dm)
14769 (if (not t2)
14771 (setq dh (- h2 h1) dm (- m2 m1))
14772 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14773 (concat t1 "+" (number-to-string dh)
14774 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14776 (defun org-time-stamp-inactive (&optional arg)
14777 "Insert an inactive time stamp.
14778 An inactive time stamp is enclosed in square brackets instead of angle
14779 brackets. It is inactive in the sense that it does not trigger agenda entries,
14780 does not link to the calendar and cannot be changed with the S-cursor keys.
14781 So these are more for recording a certain time/date."
14782 (interactive "P")
14783 (org-time-stamp arg 'inactive))
14785 (defvar org-date-ovl (make-overlay 1 1))
14786 (overlay-put org-date-ovl 'face 'org-warning)
14787 (org-detach-overlay org-date-ovl)
14789 (defvar org-ans1) ; dynamically scoped parameter
14790 (defvar org-ans2) ; dynamically scoped parameter
14792 (defvar org-plain-time-of-day-regexp) ; defined below
14794 (defvar org-overriding-default-time nil) ; dynamically scoped
14795 (defvar org-read-date-overlay nil)
14796 (defvar org-dcst nil) ; dynamically scoped
14797 (defvar org-read-date-history nil)
14798 (defvar org-read-date-final-answer nil)
14799 (defvar org-read-date-analyze-futurep nil)
14800 (defvar org-read-date-analyze-forced-year nil)
14802 (defun org-read-date (&optional with-time to-time from-string prompt
14803 default-time default-input)
14804 "Read a date, possibly a time, and make things smooth for the user.
14805 The prompt will suggest to enter an ISO date, but you can also enter anything
14806 which will at least partially be understood by `parse-time-string'.
14807 Unrecognized parts of the date will default to the current day, month, year,
14808 hour and minute. If this command is called to replace a timestamp at point,
14809 or to enter the second timestamp of a range, the default time is taken
14810 from the existing stamp. Furthermore, the command prefers the future,
14811 so if you are giving a date where the year is not given, and the day-month
14812 combination is already past in the current year, it will assume you
14813 mean next year. For details, see the manual. A few examples:
14815 3-2-5 --> 2003-02-05
14816 feb 15 --> currentyear-02-15
14817 2/15 --> currentyear-02-15
14818 sep 12 9 --> 2009-09-12
14819 12:45 --> today 12:45
14820 22 sept 0:34 --> currentyear-09-22 0:34
14821 12 --> currentyear-currentmonth-12
14822 Fri --> nearest Friday (today or later)
14823 etc.
14825 Furthermore you can specify a relative date by giving, as the *first* thing
14826 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14827 change in days weeks, months, years.
14828 With a single plus or minus, the date is relative to today. With a double
14829 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14830 +4d --> four days from today
14831 +4 --> same as above
14832 +2w --> two weeks from today
14833 ++5 --> five days from default date
14835 The function understands only English month and weekday abbreviations,
14836 but this can be configured with the variables `parse-time-months' and
14837 `parse-time-weekdays'.
14839 While prompting, a calendar is popped up - you can also select the
14840 date with the mouse (button 1). The calendar shows a period of three
14841 months. To scroll it to other months, use the keys `>' and `<'.
14842 If you don't like the calendar, turn it off with
14843 \(setq org-read-date-popup-calendar nil)
14845 With optional argument TO-TIME, the date will immediately be converted
14846 to an internal time.
14847 With an optional argument WITH-TIME, the prompt will suggest to also
14848 insert a time. Note that when WITH-TIME is not set, you can still
14849 enter a time, and this function will inform the calling routine about
14850 this change. The calling routine may then choose to change the format
14851 used to insert the time stamp into the buffer to include the time.
14852 With optional argument FROM-STRING, read from this string instead from
14853 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14854 the time/date that is used for everything that is not specified by the
14855 user."
14856 (require 'parse-time)
14857 (let* ((org-time-stamp-rounding-minutes
14858 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14859 (org-dcst org-display-custom-times)
14860 (ct (org-current-time))
14861 (def (or org-overriding-default-time default-time ct))
14862 (defdecode (decode-time def))
14863 (dummy (progn
14864 (when (< (nth 2 defdecode) org-extend-today-until)
14865 (setcar (nthcdr 2 defdecode) -1)
14866 (setcar (nthcdr 1 defdecode) 59)
14867 (setq def (apply 'encode-time defdecode)
14868 defdecode (decode-time def)))))
14869 (calendar-frame-setup nil)
14870 (calendar-setup nil)
14871 (calendar-move-hook nil)
14872 (calendar-view-diary-initially-flag nil)
14873 (calendar-view-holidays-initially-flag nil)
14874 (timestr (format-time-string
14875 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14876 (prompt (concat (if prompt (concat prompt " ") "")
14877 (format "Date+time [%s]: " timestr)))
14878 ans (org-ans0 "") org-ans1 org-ans2 final)
14880 (cond
14881 (from-string (setq ans from-string))
14882 (org-read-date-popup-calendar
14883 (save-excursion
14884 (save-window-excursion
14885 (calendar)
14886 (unwind-protect
14887 (progn
14888 (calendar-forward-day (- (time-to-days def)
14889 (calendar-absolute-from-gregorian
14890 (calendar-current-date))))
14891 (org-eval-in-calendar nil t)
14892 (let* ((old-map (current-local-map))
14893 (map (copy-keymap calendar-mode-map))
14894 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14895 (org-defkey map (kbd "RET") 'org-calendar-select)
14896 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14897 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14898 (org-defkey minibuffer-local-map [(meta shift left)]
14899 (lambda () (interactive)
14900 (org-eval-in-calendar '(calendar-backward-month 1))))
14901 (org-defkey minibuffer-local-map [(meta shift right)]
14902 (lambda () (interactive)
14903 (org-eval-in-calendar '(calendar-forward-month 1))))
14904 (org-defkey minibuffer-local-map [(meta shift up)]
14905 (lambda () (interactive)
14906 (org-eval-in-calendar '(calendar-backward-year 1))))
14907 (org-defkey minibuffer-local-map [(meta shift down)]
14908 (lambda () (interactive)
14909 (org-eval-in-calendar '(calendar-forward-year 1))))
14910 (org-defkey minibuffer-local-map [?\e (shift left)]
14911 (lambda () (interactive)
14912 (org-eval-in-calendar '(calendar-backward-month 1))))
14913 (org-defkey minibuffer-local-map [?\e (shift right)]
14914 (lambda () (interactive)
14915 (org-eval-in-calendar '(calendar-forward-month 1))))
14916 (org-defkey minibuffer-local-map [?\e (shift up)]
14917 (lambda () (interactive)
14918 (org-eval-in-calendar '(calendar-backward-year 1))))
14919 (org-defkey minibuffer-local-map [?\e (shift down)]
14920 (lambda () (interactive)
14921 (org-eval-in-calendar '(calendar-forward-year 1))))
14922 (org-defkey minibuffer-local-map [(shift up)]
14923 (lambda () (interactive)
14924 (org-eval-in-calendar '(calendar-backward-week 1))))
14925 (org-defkey minibuffer-local-map [(shift down)]
14926 (lambda () (interactive)
14927 (org-eval-in-calendar '(calendar-forward-week 1))))
14928 (org-defkey minibuffer-local-map [(shift left)]
14929 (lambda () (interactive)
14930 (org-eval-in-calendar '(calendar-backward-day 1))))
14931 (org-defkey minibuffer-local-map [(shift right)]
14932 (lambda () (interactive)
14933 (org-eval-in-calendar '(calendar-forward-day 1))))
14934 (org-defkey minibuffer-local-map ">"
14935 (lambda () (interactive)
14936 (org-eval-in-calendar '(scroll-calendar-left 1))))
14937 (org-defkey minibuffer-local-map "<"
14938 (lambda () (interactive)
14939 (org-eval-in-calendar '(scroll-calendar-right 1))))
14940 (org-defkey minibuffer-local-map "\C-v"
14941 (lambda () (interactive)
14942 (org-eval-in-calendar
14943 '(calendar-scroll-left-three-months 1))))
14944 (org-defkey minibuffer-local-map "\M-v"
14945 (lambda () (interactive)
14946 (org-eval-in-calendar
14947 '(calendar-scroll-right-three-months 1))))
14948 (run-hooks 'org-read-date-minibuffer-setup-hook)
14949 (unwind-protect
14950 (progn
14951 (use-local-map map)
14952 (add-hook 'post-command-hook 'org-read-date-display)
14953 (setq org-ans0 (read-string prompt default-input
14954 'org-read-date-history nil))
14955 ;; org-ans0: from prompt
14956 ;; org-ans1: from mouse click
14957 ;; org-ans2: from calendar motion
14958 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14959 (remove-hook 'post-command-hook 'org-read-date-display)
14960 (use-local-map old-map)
14961 (when org-read-date-overlay
14962 (delete-overlay org-read-date-overlay)
14963 (setq org-read-date-overlay nil)))))
14964 (bury-buffer "*Calendar*")))))
14966 (t ; Naked prompt only
14967 (unwind-protect
14968 (setq ans (read-string prompt default-input
14969 'org-read-date-history timestr))
14970 (when org-read-date-overlay
14971 (delete-overlay org-read-date-overlay)
14972 (setq org-read-date-overlay nil)))))
14974 (setq final (org-read-date-analyze ans def defdecode))
14976 (when org-read-date-analyze-forced-year
14977 (message "Year was forced into %s"
14978 (if org-read-date-force-compatible-dates
14979 "compatible range (1970-2037)"
14980 "range representable on this machine"))
14981 (ding))
14983 ;; One round trip to get rid of 34th of August and stuff like that....
14984 (setq final (decode-time (apply 'encode-time final)))
14986 (setq org-read-date-final-answer ans)
14988 (if to-time
14989 (apply 'encode-time final)
14990 (if (and (boundp 'org-time-was-given) org-time-was-given)
14991 (format "%04d-%02d-%02d %02d:%02d"
14992 (nth 5 final) (nth 4 final) (nth 3 final)
14993 (nth 2 final) (nth 1 final))
14994 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
14996 (defvar def)
14997 (defvar defdecode)
14998 (defvar with-time)
14999 (defun org-read-date-display ()
15000 "Display the current date prompt interpretation in the minibuffer."
15001 (when org-read-date-display-live
15002 (when org-read-date-overlay
15003 (delete-overlay org-read-date-overlay))
15004 (let ((p (point)))
15005 (end-of-line 1)
15006 (while (not (equal (buffer-substring
15007 (max (point-min) (- (point) 4)) (point))
15008 " "))
15009 (insert " "))
15010 (goto-char p))
15011 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15012 " " (or org-ans1 org-ans2)))
15013 (org-end-time-was-given nil)
15014 (f (org-read-date-analyze ans def defdecode))
15015 (fmts (if org-dcst
15016 org-time-stamp-custom-formats
15017 org-time-stamp-formats))
15018 (fmt (if (or with-time
15019 (and (boundp 'org-time-was-given) org-time-was-given))
15020 (cdr fmts)
15021 (car fmts)))
15022 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
15023 (when (and org-end-time-was-given
15024 (string-match org-plain-time-of-day-regexp txt))
15025 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15026 org-end-time-was-given
15027 (substring txt (match-end 0)))))
15028 (when org-read-date-analyze-futurep
15029 (setq txt (concat txt " (=>F)")))
15030 (setq org-read-date-overlay
15031 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15032 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
15034 (defun org-read-date-analyze (ans def defdecode)
15035 "Analyze the combined answer of the date prompt."
15036 ;; FIXME: cleanup and comment
15037 (let ((nowdecode (decode-time (current-time)))
15038 delta deltan deltaw deltadef year month day
15039 hour minute second wday pm h2 m2 tl wday1
15040 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15041 (setq org-read-date-analyze-futurep nil
15042 org-read-date-analyze-forced-year nil)
15043 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15044 (setq ans "+0"))
15046 (when (setq delta (org-read-date-get-relative ans (current-time) def))
15047 (setq ans (replace-match "" t t ans)
15048 deltan (car delta)
15049 deltaw (nth 1 delta)
15050 deltadef (nth 2 delta)))
15052 ;; Check if there is an iso week date in there
15053 ;; If yes, store the info and postpone interpreting it until the rest
15054 ;; of the parsing is done
15055 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15056 (setq iso-year (if (match-end 1)
15057 (org-small-year-to-year
15058 (string-to-number (match-string 1 ans))))
15059 iso-weekday (if (match-end 3)
15060 (string-to-number (match-string 3 ans)))
15061 iso-week (string-to-number (match-string 2 ans)))
15062 (setq ans (replace-match "" t t ans)))
15064 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15065 (when (string-match
15066 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15067 (setq year (if (match-end 2)
15068 (string-to-number (match-string 2 ans))
15069 (progn (setq kill-year t)
15070 (string-to-number (format-time-string "%Y"))))
15071 month (string-to-number (match-string 3 ans))
15072 day (string-to-number (match-string 4 ans)))
15073 (if (< year 100) (setq year (+ 2000 year)))
15074 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15075 t nil ans)))
15077 ;; Help matching dottet european dates
15078 (when (string-match
15079 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15080 (setq year (if (match-end 3)
15081 (string-to-number (match-string 3 ans))
15082 (progn (setq kill-year t)
15083 (string-to-number (format-time-string "%Y"))))
15084 day (string-to-number (match-string 1 ans))
15085 month (string-to-number (match-string 2 ans))
15086 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15087 t nil ans)))
15089 ;; Help matching american dates, like 5/30 or 5/30/7
15090 (when (string-match
15091 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15092 (setq year (if (match-end 4)
15093 (string-to-number (match-string 4 ans))
15094 (progn (setq kill-year t)
15095 (string-to-number (format-time-string "%Y"))))
15096 month (string-to-number (match-string 1 ans))
15097 day (string-to-number (match-string 2 ans)))
15098 (if (< year 100) (setq year (+ 2000 year)))
15099 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15100 t nil ans)))
15101 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15102 ;; If there is a time with am/pm, and *no* time without it, we convert
15103 ;; so that matching will be successful.
15104 (loop for i from 1 to 2 do ; twice, for end time as well
15105 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15106 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15107 (setq hour (string-to-number (match-string 1 ans))
15108 minute (if (match-end 3)
15109 (string-to-number (match-string 3 ans))
15111 pm (equal ?p
15112 (string-to-char (downcase (match-string 4 ans)))))
15113 (if (and (= hour 12) (not pm))
15114 (setq hour 0)
15115 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15116 (setq ans (replace-match (format "%02d:%02d" hour minute)
15117 t t ans))))
15119 ;; Check if a time range is given as a duration
15120 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15121 (setq hour (string-to-number (match-string 1 ans))
15122 h2 (+ hour (string-to-number (match-string 3 ans)))
15123 minute (string-to-number (match-string 2 ans))
15124 m2 (+ minute (if (match-end 5) (string-to-number
15125 (match-string 5 ans))0)))
15126 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15127 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15128 t t ans)))
15130 ;; Check if there is a time range
15131 (when (boundp 'org-end-time-was-given)
15132 (setq org-time-was-given nil)
15133 (when (and (string-match org-plain-time-of-day-regexp ans)
15134 (match-end 8))
15135 (setq org-end-time-was-given (match-string 8 ans))
15136 (setq ans (concat (substring ans 0 (match-beginning 7))
15137 (substring ans (match-end 7))))))
15139 (setq tl (parse-time-string ans)
15140 day (or (nth 3 tl) (nth 3 defdecode))
15141 month (or (nth 4 tl)
15142 (if (and org-read-date-prefer-future
15143 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15144 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15145 (nth 4 defdecode)))
15146 year (or (and (not kill-year) (nth 5 tl))
15147 (if (and org-read-date-prefer-future
15148 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15149 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15150 (nth 5 defdecode)))
15151 hour (or (nth 2 tl) (nth 2 defdecode))
15152 minute (or (nth 1 tl) (nth 1 defdecode))
15153 second (or (nth 0 tl) 0)
15154 wday (nth 6 tl))
15156 (when (and (eq org-read-date-prefer-future 'time)
15157 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15158 (equal day (nth 3 nowdecode))
15159 (equal month (nth 4 nowdecode))
15160 (equal year (nth 5 nowdecode))
15161 (nth 2 tl)
15162 (or (< (nth 2 tl) (nth 2 nowdecode))
15163 (and (= (nth 2 tl) (nth 2 nowdecode))
15164 (nth 1 tl)
15165 (< (nth 1 tl) (nth 1 nowdecode)))))
15166 (setq day (1+ day)
15167 futurep t))
15169 ;; Special date definitions below
15170 (cond
15171 (iso-week
15172 ;; There was an iso week
15173 (require 'cal-iso)
15174 (setq futurep nil)
15175 (setq year (or iso-year year)
15176 day (or iso-weekday wday 1)
15177 wday nil ; to make sure that the trigger below does not match
15178 iso-date (calendar-gregorian-from-absolute
15179 (calendar-absolute-from-iso
15180 (list iso-week day year))))
15181 ; FIXME: Should we also push ISO weeks into the future?
15182 ; (when (and org-read-date-prefer-future
15183 ; (not iso-year)
15184 ; (< (calendar-absolute-from-gregorian iso-date)
15185 ; (time-to-days (current-time))))
15186 ; (setq year (1+ year)
15187 ; iso-date (calendar-gregorian-from-absolute
15188 ; (calendar-absolute-from-iso
15189 ; (list iso-week day year)))))
15190 (setq month (car iso-date)
15191 year (nth 2 iso-date)
15192 day (nth 1 iso-date)))
15193 (deltan
15194 (setq futurep nil)
15195 (unless deltadef
15196 (let ((now (decode-time (current-time))))
15197 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15198 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15199 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15200 ((equal deltaw "m") (setq month (+ month deltan)))
15201 ((equal deltaw "y") (setq year (+ year deltan)))))
15202 ((and wday (not (nth 3 tl)))
15203 (setq futurep nil)
15204 ;; Weekday was given, but no day, so pick that day in the week
15205 ;; on or after the derived date.
15206 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15207 (unless (equal wday wday1)
15208 (setq day (+ day (% (- wday wday1 -7) 7))))))
15209 (if (and (boundp 'org-time-was-given)
15210 (nth 2 tl))
15211 (setq org-time-was-given t))
15212 (if (< year 100) (setq year (+ 2000 year)))
15213 ;; Check of the date is representable
15214 (if org-read-date-force-compatible-dates
15215 (progn
15216 (if (< year 1970)
15217 (setq year 1970 org-read-date-analyze-forced-year t))
15218 (if (> year 2037)
15219 (setq year 2037 org-read-date-analyze-forced-year t)))
15220 (condition-case nil
15221 (ignore (encode-time second minute hour day month year))
15222 (error
15223 (setq year (nth 5 defdecode))
15224 (setq org-read-date-analyze-forced-year t))))
15225 (setq org-read-date-analyze-futurep futurep)
15226 (list second minute hour day month year)))
15228 (defvar parse-time-weekdays)
15230 (defun org-read-date-get-relative (s today default)
15231 "Check string S for special relative date string.
15232 TODAY and DEFAULT are internal times, for today and for a default.
15233 Return shift list (N what def-flag)
15234 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15235 N is the number of WHATs to shift.
15236 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15237 the DEFAULT date rather than TODAY."
15238 (require 'parse-time)
15239 (when (and
15240 (string-match
15241 (concat
15242 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15243 "\\([0-9]+\\)?"
15244 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15245 "\\([ \t]\\|$\\)") s)
15246 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15247 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15248 (string-to-char (substring (match-string 1 s) -1))
15249 ?+))
15250 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15251 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15252 (what (if (match-end 3) (match-string 3 s) "d"))
15253 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15254 (date (if rel default today))
15255 (wday (nth 6 (decode-time date)))
15256 delta)
15257 (if wday1
15258 (progn
15259 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15260 (if (= dir ?-) (setq delta (- delta 7)))
15261 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15262 (list delta "d" rel))
15263 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15265 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15266 "Turn a user-specified date into the internal representation.
15267 The internal representation needed by the calendar is (month day year).
15268 This is a wrapper to handle the brain-dead convention in calendar that
15269 user function argument order change dependent on argument order."
15270 (if (boundp 'calendar-date-style)
15271 (cond
15272 ((eq calendar-date-style 'american)
15273 (list arg1 arg2 arg3))
15274 ((eq calendar-date-style 'european)
15275 (list arg2 arg1 arg3))
15276 ((eq calendar-date-style 'iso)
15277 (list arg2 arg3 arg1)))
15278 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15279 (if (org-bound-and-true-p european-calendar-style)
15280 (list arg2 arg1 arg3)
15281 (list arg1 arg2 arg3)))))
15283 (defun org-eval-in-calendar (form &optional keepdate)
15284 "Eval FORM in the calendar window and return to current window.
15285 Also, store the cursor date in variable org-ans2."
15286 (let ((sf (selected-frame))
15287 (sw (selected-window)))
15288 (select-window (get-buffer-window "*Calendar*" t))
15289 (eval form)
15290 (when (and (not keepdate) (calendar-cursor-to-date))
15291 (let* ((date (calendar-cursor-to-date))
15292 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15293 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15294 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15295 (select-window sw)
15296 (org-select-frame-set-input-focus sf)))
15298 (defun org-calendar-select ()
15299 "Return to `org-read-date' with the date currently selected.
15300 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15301 (interactive)
15302 (when (calendar-cursor-to-date)
15303 (let* ((date (calendar-cursor-to-date))
15304 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15305 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15306 (if (active-minibuffer-window) (exit-minibuffer))))
15308 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15309 "Insert a date stamp for the date given by the internal TIME.
15310 WITH-HM means use the stamp format that includes the time of the day.
15311 INACTIVE means use square brackets instead of angular ones, so that the
15312 stamp will not contribute to the agenda.
15313 PRE and POST are optional strings to be inserted before and after the
15314 stamp.
15315 The command returns the inserted time stamp."
15316 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15317 stamp)
15318 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15319 (insert-before-markers (or pre ""))
15320 (when (listp extra)
15321 (setq extra (car extra))
15322 (if (and (stringp extra)
15323 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15324 (setq extra (format "-%02d:%02d"
15325 (string-to-number (match-string 1 extra))
15326 (string-to-number (match-string 2 extra))))
15327 (setq extra nil)))
15328 (when extra
15329 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15330 (insert-before-markers (setq stamp (format-time-string fmt time)))
15331 (insert-before-markers (or post ""))
15332 (setq org-last-inserted-timestamp stamp)))
15334 (defun org-toggle-time-stamp-overlays ()
15335 "Toggle the use of custom time stamp formats."
15336 (interactive)
15337 (setq org-display-custom-times (not org-display-custom-times))
15338 (unless org-display-custom-times
15339 (let ((p (point-min)) (bmp (buffer-modified-p)))
15340 (while (setq p (next-single-property-change p 'display))
15341 (if (and (get-text-property p 'display)
15342 (eq (get-text-property p 'face) 'org-date))
15343 (remove-text-properties
15344 p (setq p (next-single-property-change p 'display))
15345 '(display t))))
15346 (set-buffer-modified-p bmp)))
15347 (if (featurep 'xemacs)
15348 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15349 (org-restart-font-lock)
15350 (setq org-table-may-need-update t)
15351 (if org-display-custom-times
15352 (message "Time stamps are overlaid with custom format")
15353 (message "Time stamp overlays removed")))
15355 (defun org-display-custom-time (beg end)
15356 "Overlay modified time stamp format over timestamp between BEG and END."
15357 (let* ((ts (buffer-substring beg end))
15358 t1 w1 with-hm tf time str w2 (off 0))
15359 (save-match-data
15360 (setq t1 (org-parse-time-string ts t))
15361 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15362 (setq off (- (match-end 0) (match-beginning 0)))))
15363 (setq end (- end off))
15364 (setq w1 (- end beg)
15365 with-hm (and (nth 1 t1) (nth 2 t1))
15366 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15367 time (org-fix-decoded-time t1)
15368 str (org-add-props
15369 (format-time-string
15370 (substring tf 1 -1) (apply 'encode-time time))
15371 nil 'mouse-face 'highlight)
15372 w2 (length str))
15373 (if (not (= w2 w1))
15374 (add-text-properties (1+ beg) (+ 2 beg)
15375 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15376 (if (featurep 'xemacs)
15377 (progn
15378 (put-text-property beg end 'invisible t)
15379 (put-text-property beg end 'end-glyph (make-glyph str)))
15380 (put-text-property beg end 'display str))))
15382 (defun org-translate-time (string)
15383 "Translate all timestamps in STRING to custom format.
15384 But do this only if the variable `org-display-custom-times' is set."
15385 (when org-display-custom-times
15386 (save-match-data
15387 (let* ((start 0)
15388 (re org-ts-regexp-both)
15389 t1 with-hm inactive tf time str beg end)
15390 (while (setq start (string-match re string start))
15391 (setq beg (match-beginning 0)
15392 end (match-end 0)
15393 t1 (save-match-data
15394 (org-parse-time-string (substring string beg end) t))
15395 with-hm (and (nth 1 t1) (nth 2 t1))
15396 inactive (equal (substring string beg (1+ beg)) "[")
15397 tf (funcall (if with-hm 'cdr 'car)
15398 org-time-stamp-custom-formats)
15399 time (org-fix-decoded-time t1)
15400 str (format-time-string
15401 (concat
15402 (if inactive "[" "<") (substring tf 1 -1)
15403 (if inactive "]" ">"))
15404 (apply 'encode-time time))
15405 string (replace-match str t t string)
15406 start (+ start (length str)))))))
15407 string)
15409 (defun org-fix-decoded-time (time)
15410 "Set 0 instead of nil for the first 6 elements of time.
15411 Don't touch the rest."
15412 (let ((n 0))
15413 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15415 (defun org-days-to-time (timestamp-string)
15416 "Difference between TIMESTAMP-STRING and now in days."
15417 (- (time-to-days (org-time-string-to-time timestamp-string))
15418 (time-to-days (current-time))))
15420 (defun org-deadline-close (timestamp-string &optional ndays)
15421 "Is the time in TIMESTAMP-STRING close to the current date?"
15422 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15423 (and (< (org-days-to-time timestamp-string) ndays)
15424 (not (org-entry-is-done-p))))
15426 (defun org-get-wdays (ts)
15427 "Get the deadline lead time appropriate for timestring TS."
15428 (cond
15429 ((<= org-deadline-warning-days 0)
15430 ;; 0 or negative, enforce this value no matter what
15431 (- org-deadline-warning-days))
15432 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15433 ;; lead time is specified.
15434 (floor (* (string-to-number (match-string 1 ts))
15435 (cdr (assoc (match-string 2 ts)
15436 '(("d" . 1) ("w" . 7)
15437 ("m" . 30.4) ("y" . 365.25)))))))
15438 ;; go for the default.
15439 (t org-deadline-warning-days)))
15441 (defun org-calendar-select-mouse (ev)
15442 "Return to `org-read-date' with the date currently selected.
15443 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15444 (interactive "e")
15445 (mouse-set-point ev)
15446 (when (calendar-cursor-to-date)
15447 (let* ((date (calendar-cursor-to-date))
15448 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15449 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15450 (if (active-minibuffer-window) (exit-minibuffer))))
15452 (defun org-check-deadlines (ndays)
15453 "Check if there are any deadlines due or past due.
15454 A deadline is considered due if it happens within `org-deadline-warning-days'
15455 days from today's date. If the deadline appears in an entry marked DONE,
15456 it is not shown. The prefix arg NDAYS can be used to test that many
15457 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15458 (interactive "P")
15459 (let* ((org-warn-days
15460 (cond
15461 ((equal ndays '(4)) 100000)
15462 (ndays (prefix-numeric-value ndays))
15463 (t (abs org-deadline-warning-days))))
15464 (case-fold-search nil)
15465 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15466 (callback
15467 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15469 (message "%d deadlines past-due or due within %d days"
15470 (org-occur regexp nil callback)
15471 org-warn-days)))
15473 (defun org-check-before-date (date)
15474 "Check if there are deadlines or scheduled entries before DATE."
15475 (interactive (list (org-read-date)))
15476 (let ((case-fold-search nil)
15477 (regexp (concat "\\<\\(" org-deadline-string
15478 "\\|" org-scheduled-string
15479 "\\) *<\\([^>]+\\)>"))
15480 (callback
15481 (lambda () (time-less-p
15482 (org-time-string-to-time (match-string 2))
15483 (org-time-string-to-time date)))))
15484 (message "%d entries before %s"
15485 (org-occur regexp nil callback) date)))
15487 (defun org-check-after-date (date)
15488 "Check if there are deadlines or scheduled entries after DATE."
15489 (interactive (list (org-read-date)))
15490 (let ((case-fold-search nil)
15491 (regexp (concat "\\<\\(" org-deadline-string
15492 "\\|" org-scheduled-string
15493 "\\) *<\\([^>]+\\)>"))
15494 (callback
15495 (lambda () (not
15496 (time-less-p
15497 (org-time-string-to-time (match-string 2))
15498 (org-time-string-to-time date))))))
15499 (message "%d entries after %s"
15500 (org-occur regexp nil callback) date)))
15502 (defun org-evaluate-time-range (&optional to-buffer)
15503 "Evaluate a time range by computing the difference between start and end.
15504 Normally the result is just printed in the echo area, but with prefix arg
15505 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15506 If the time range is actually in a table, the result is inserted into the
15507 next column.
15508 For time difference computation, a year is assumed to be exactly 365
15509 days in order to avoid rounding problems."
15510 (interactive "P")
15512 (org-clock-update-time-maybe)
15513 (save-excursion
15514 (unless (org-at-date-range-p t)
15515 (goto-char (point-at-bol))
15516 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15517 (if (not (org-at-date-range-p t))
15518 (error "Not at a time-stamp range, and none found in current line")))
15519 (let* ((ts1 (match-string 1))
15520 (ts2 (match-string 2))
15521 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15522 (match-end (match-end 0))
15523 (time1 (org-time-string-to-time ts1))
15524 (time2 (org-time-string-to-time ts2))
15525 (t1 (org-float-time time1))
15526 (t2 (org-float-time time2))
15527 (diff (abs (- t2 t1)))
15528 (negative (< (- t2 t1) 0))
15529 ;; (ys (floor (* 365 24 60 60)))
15530 (ds (* 24 60 60))
15531 (hs (* 60 60))
15532 (fy "%dy %dd %02d:%02d")
15533 (fy1 "%dy %dd")
15534 (fd "%dd %02d:%02d")
15535 (fd1 "%dd")
15536 (fh "%02d:%02d")
15537 y d h m align)
15538 (if havetime
15539 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15541 d (floor (/ diff ds)) diff (mod diff ds)
15542 h (floor (/ diff hs)) diff (mod diff hs)
15543 m (floor (/ diff 60)))
15544 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15546 d (floor (+ (/ diff ds) 0.5))
15547 h 0 m 0))
15548 (if (not to-buffer)
15549 (message "%s" (org-make-tdiff-string y d h m))
15550 (if (org-at-table-p)
15551 (progn
15552 (goto-char match-end)
15553 (setq align t)
15554 (and (looking-at " *|") (goto-char (match-end 0))))
15555 (goto-char match-end))
15556 (if (looking-at
15557 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15558 (replace-match ""))
15559 (if negative (insert " -"))
15560 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15561 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15562 (insert " " (format fh h m))))
15563 (if align (org-table-align))
15564 (message "Time difference inserted")))))
15566 (defun org-make-tdiff-string (y d h m)
15567 (let ((fmt "")
15568 (l nil))
15569 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15570 l (push y l)))
15571 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15572 l (push d l)))
15573 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15574 l (push h l)))
15575 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15576 l (push m l)))
15577 (apply 'format fmt (nreverse l))))
15579 (defun org-time-string-to-time (s &optional buffer pos)
15580 (condition-case errdata
15581 (apply 'encode-time (org-parse-time-string s))
15582 (error (error "Bad timestamp `%s'%s\nError was: %s"
15583 s (if (not (and buffer pos))
15585 (format " at %d in buffer `%s'" pos buffer))
15586 (cdr errdata)))))
15588 (defun org-time-string-to-seconds (s)
15589 (org-float-time (org-time-string-to-time s)))
15591 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15592 "Convert a time stamp to an absolute day number.
15593 If there is a specifier for a cyclic time stamp, get the closest date to
15594 DAYNR.
15595 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15596 The variable date is bound by the calendar when this is called."
15597 (cond
15598 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15599 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15600 daynr
15601 (+ daynr 1000)))
15602 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15603 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15604 (time-to-days (current-time))) (match-string 0 s)
15605 prefer show-all))
15606 (t (time-to-days
15607 (condition-case errdata
15608 (apply 'encode-time (org-parse-time-string s))
15609 (error (error "Bad timestamp `%s'%s\nError was: %s"
15610 s (if (not (and buffer pos))
15612 (format " at %d in buffer `%s'" pos buffer))
15613 (cdr errdata))))))))
15615 (defun org-days-to-iso-week (days)
15616 "Return the iso week number."
15617 (require 'cal-iso)
15618 (car (calendar-iso-from-absolute days)))
15620 (defun org-small-year-to-year (year)
15621 "Convert 2-digit years into 4-digit years.
15622 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15623 The year 2000 cannot be abbreviated. Any year larger than 99
15624 is returned unchanged."
15625 (if (< year 38)
15626 (setq year (+ 2000 year))
15627 (if (< year 100)
15628 (setq year (+ 1900 year))))
15629 year)
15631 (defun org-time-from-absolute (d)
15632 "Return the time corresponding to date D.
15633 D may be an absolute day number, or a calendar-type list (month day year)."
15634 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15635 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15637 (defun org-calendar-holiday ()
15638 "List of holidays, for Diary display in Org-mode."
15639 (require 'holidays)
15640 (let ((hl (funcall
15641 (if (fboundp 'calendar-check-holidays)
15642 'calendar-check-holidays 'check-calendar-holidays) date)))
15643 (if hl (mapconcat 'identity hl "; "))))
15645 (defun org-diary-sexp-entry (sexp entry date)
15646 "Process a SEXP diary ENTRY for DATE."
15647 (require 'diary-lib)
15648 (let ((result (if calendar-debug-sexp
15649 (let ((stack-trace-on-error t))
15650 (eval (car (read-from-string sexp))))
15651 (condition-case nil
15652 (eval (car (read-from-string sexp)))
15653 (error
15654 (beep)
15655 (message "Bad sexp at line %d in %s: %s"
15656 (org-current-line)
15657 (buffer-file-name) sexp)
15658 (sleep-for 2))))))
15659 (cond ((stringp result) (split-string result "; "))
15660 ((and (consp result)
15661 (not (consp (cdr result)))
15662 (stringp (cdr result))) (cdr result))
15663 ((and (consp result)
15664 (stringp (car result))) result)
15665 (result entry)
15666 (t nil))))
15668 (defun org-diary-to-ical-string (frombuf)
15669 "Get iCalendar entries from diary entries in buffer FROMBUF.
15670 This uses the icalendar.el library."
15671 (let* ((tmpdir (if (featurep 'xemacs)
15672 (temp-directory)
15673 temporary-file-directory))
15674 (tmpfile (make-temp-name
15675 (expand-file-name "orgics" tmpdir)))
15676 buf rtn b e)
15677 (with-current-buffer frombuf
15678 (icalendar-export-region (point-min) (point-max) tmpfile)
15679 (setq buf (find-buffer-visiting tmpfile))
15680 (set-buffer buf)
15681 (goto-char (point-min))
15682 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15683 (setq b (match-beginning 0)))
15684 (goto-char (point-max))
15685 (if (re-search-backward "^END:VEVENT" nil t)
15686 (setq e (match-end 0)))
15687 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15688 (kill-buffer buf)
15689 (delete-file tmpfile)
15690 rtn))
15692 (defun org-closest-date (start current change prefer show-all)
15693 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15694 When PREFER is `past', return a date that is either CURRENT or past.
15695 When PREFER is `future', return a date that is either CURRENT or future.
15696 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15697 ;; Make the proper lists from the dates
15698 (catch 'exit
15699 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15700 dn dw sday cday n1 n2 n0
15701 d m y y1 y2 date1 date2 nmonths nm ny m2)
15703 (setq start (org-date-to-gregorian start)
15704 current (org-date-to-gregorian
15705 (if show-all
15706 current
15707 (time-to-days (current-time))))
15708 sday (calendar-absolute-from-gregorian start)
15709 cday (calendar-absolute-from-gregorian current))
15711 (if (<= cday sday) (throw 'exit sday))
15713 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15714 (setq dn (string-to-number (match-string 1 change))
15715 dw (cdr (assoc (match-string 2 change) a1)))
15716 (error "Invalid change specifier: %s" change))
15717 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15718 (cond
15719 ((eq dw 'day)
15720 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15721 n2 (+ n1 dn)))
15722 ((eq dw 'year)
15723 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15724 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15725 (setq date1 (list m d y1)
15726 n1 (calendar-absolute-from-gregorian date1)
15727 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15728 n2 (calendar-absolute-from-gregorian date2)))
15729 ((eq dw 'month)
15730 ;; approx number of month between the two dates
15731 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15732 ;; How often does dn fit in there?
15733 (setq d (nth 1 start) m (car start) y (nth 2 start)
15734 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15735 m (+ m nm)
15736 ny (floor (/ m 12))
15737 y (+ y ny)
15738 m (- m (* ny 12)))
15739 (while (> m 12) (setq m (- m 12) y (1+ y)))
15740 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15741 (setq m2 (+ m dn) y2 y)
15742 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15743 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15744 (while (<= n2 cday)
15745 (setq n1 n2 m m2 y y2)
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 ;; Make sure n1 is the earlier date
15750 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15751 (if show-all
15752 (cond
15753 ((eq prefer 'past) (if (= cday n2) n2 n1))
15754 ((eq prefer 'future) (if (= cday n1) n1 n2))
15755 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15756 (cond
15757 ((eq prefer 'past) (if (= cday n2) n2 n1))
15758 ((eq prefer 'future) (if (= cday n1) n1 n2))
15759 (t (if (= cday n1) n1 n2)))))))
15761 (defun org-date-to-gregorian (date)
15762 "Turn any specification of DATE into a Gregorian date for the calendar."
15763 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15764 ((and (listp date) (= (length date) 3)) date)
15765 ((stringp date)
15766 (setq date (org-parse-time-string date))
15767 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15768 ((listp date)
15769 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15771 (defun org-parse-time-string (s &optional nodefault)
15772 "Parse the standard Org-mode time string.
15773 This should be a lot faster than the normal `parse-time-string'.
15774 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15775 hour and minute fields will be nil if not given."
15776 (if (string-match org-ts-regexp0 s)
15777 (list 0
15778 (if (or (match-beginning 8) (not nodefault))
15779 (string-to-number (or (match-string 8 s) "0")))
15780 (if (or (match-beginning 7) (not nodefault))
15781 (string-to-number (or (match-string 7 s) "0")))
15782 (string-to-number (match-string 4 s))
15783 (string-to-number (match-string 3 s))
15784 (string-to-number (match-string 2 s))
15785 nil nil nil)
15786 (error "Not a standard Org-mode time string: %s" s)))
15788 (defun org-timestamp-up (&optional arg)
15789 "Increase the date item at the cursor by one.
15790 If the cursor is on the year, change the year. If it is on the month,
15791 the day or the time, change that.
15792 With prefix ARG, change by that many units."
15793 (interactive "p")
15794 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15796 (defun org-timestamp-down (&optional arg)
15797 "Decrease the date item at the cursor by one.
15798 If the cursor is on the year, change the year. If it is on the month,
15799 the day or the time, change that.
15800 With prefix ARG, change by that many units."
15801 (interactive "p")
15802 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15804 (defun org-timestamp-up-day (&optional arg)
15805 "Increase the date in the time stamp by one day.
15806 With prefix ARG, change that many days."
15807 (interactive "p")
15808 (if (and (not (org-at-timestamp-p t))
15809 (org-on-heading-p))
15810 (org-todo 'up)
15811 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15813 (defun org-timestamp-down-day (&optional arg)
15814 "Decrease the date in the time stamp by one day.
15815 With prefix ARG, change that many days."
15816 (interactive "p")
15817 (if (and (not (org-at-timestamp-p t))
15818 (org-on-heading-p))
15819 (org-todo 'down)
15820 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15822 (defun org-at-timestamp-p (&optional inactive-ok)
15823 "Determine if the cursor is in or at a timestamp."
15824 (interactive)
15825 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15826 (pos (point))
15827 (ans (or (looking-at tsr)
15828 (save-excursion
15829 (skip-chars-backward "^[<\n\r\t")
15830 (if (> (point) (point-min)) (backward-char 1))
15831 (and (looking-at tsr)
15832 (> (- (match-end 0) pos) -1))))))
15833 (and ans
15834 (boundp 'org-ts-what)
15835 (setq org-ts-what
15836 (cond
15837 ((= pos (match-beginning 0)) 'bracket)
15838 ;; Point is considered to be "on the bracket" whether
15839 ;; it's really on it or right after it.
15840 ((or (= pos (1- (match-end 0)))
15841 (= pos (match-end 0))) 'bracket)
15842 ((org-pos-in-match-range pos 2) 'year)
15843 ((org-pos-in-match-range pos 3) 'month)
15844 ((org-pos-in-match-range pos 7) 'hour)
15845 ((org-pos-in-match-range pos 8) 'minute)
15846 ((or (org-pos-in-match-range pos 4)
15847 (org-pos-in-match-range pos 5)) 'day)
15848 ((and (> pos (or (match-end 8) (match-end 5)))
15849 (< pos (match-end 0)))
15850 (- pos (or (match-end 8) (match-end 5))))
15851 (t 'day))))
15852 ans))
15854 (defun org-toggle-timestamp-type ()
15855 "Toggle the type (<active> or [inactive]) of a time stamp."
15856 (interactive)
15857 (when (org-at-timestamp-p t)
15858 (let ((beg (match-beginning 0)) (end (match-end 0))
15859 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
15860 (save-excursion
15861 (goto-char beg)
15862 (while (re-search-forward "[][<>]" end t)
15863 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
15864 t t)))
15865 (message "Timestamp is now %sactive"
15866 (if (equal (char-after beg) ?<) "" "in")))))
15868 (defun org-timestamp-change (n &optional what updown)
15869 "Change the date in the time stamp at point.
15870 The date will be changed by N times WHAT. WHAT can be `day', `month',
15871 `year', `minute', `second'. If WHAT is not given, the cursor position
15872 in the timestamp determines what will be changed."
15873 (let ((origin (point)) origin-cat
15874 with-hm inactive
15875 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
15876 org-ts-what
15877 extra rem
15878 ts time time0)
15879 (if (not (org-at-timestamp-p t))
15880 (error "Not at a timestamp"))
15881 (if (and (not what) (eq org-ts-what 'bracket))
15882 (org-toggle-timestamp-type)
15883 ;; Point isn't on brackets. Remember the part of the time-stamp
15884 ;; the point was in. Indeed, size of time-stamps may change,
15885 ;; but point must be kept in the same category nonetheless.
15886 (setq origin-cat org-ts-what)
15887 (if (and (not what) (not (eq org-ts-what 'day))
15888 org-display-custom-times
15889 (get-text-property (point) 'display)
15890 (not (get-text-property (1- (point)) 'display)))
15891 (setq org-ts-what 'day))
15892 (setq org-ts-what (or what org-ts-what)
15893 inactive (= (char-after (match-beginning 0)) ?\[)
15894 ts (match-string 0))
15895 (replace-match "")
15896 (if (string-match
15897 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
15899 (setq extra (match-string 1 ts)))
15900 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15901 (setq with-hm t))
15902 (setq time0 (org-parse-time-string ts))
15903 (when (and updown
15904 (eq org-ts-what 'minute)
15905 (not current-prefix-arg))
15906 ;; This looks like s-up and s-down. Change by one rounding step.
15907 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
15908 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
15909 (setcar (cdr time0) (+ (nth 1 time0)
15910 (if (> n 0) (- rem) (- dm rem))))))
15911 (setq time
15912 (encode-time (or (car time0) 0)
15913 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
15914 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
15915 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
15916 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
15917 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
15918 (nthcdr 6 time0)))
15919 (when (and (member org-ts-what '(hour minute))
15920 extra
15921 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
15922 (setq extra (org-modify-ts-extra
15923 extra
15924 (if (eq org-ts-what 'hour) 2 5)
15925 n dm)))
15926 (when (integerp org-ts-what)
15927 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
15928 (if (eq what 'calendar)
15929 (let ((cal-date (org-get-date-from-calendar)))
15930 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15931 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15932 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15933 (setcar time0 (or (car time0) 0))
15934 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15935 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15936 (setq time (apply 'encode-time time0))))
15937 ;; Insert the new time-stamp, and ensure point stays in the same
15938 ;; category as before (i.e. not after the last position in that
15939 ;; category).
15940 (let ((pos (point)))
15941 ;; Stay before inserted string. `save-excursion' is of no use.
15942 (setq org-last-changed-timestamp
15943 (org-insert-time-stamp time with-hm inactive nil nil extra))
15944 (goto-char pos))
15945 (save-match-data
15946 (looking-at org-ts-regexp3)
15947 (goto-char (cond
15948 ;; `day' category ends before `hour' if any, or at
15949 ;; the end of the day name.
15950 ((eq origin-cat 'day)
15951 (min (or (match-beginning 7) (1- (match-end 5))) origin))
15952 ((eq origin-cat 'hour) (min (match-end 7) origin))
15953 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
15954 ((integerp origin-cat) (min (1- (match-end 0)) origin))
15955 ;; `year' and `month' have both fixed size: point
15956 ;; couldn't have moved into another part.
15957 (t origin))))
15958 ;; Update clock if on a CLOCK line.
15959 (org-clock-update-time-maybe)
15960 ;; Try to recenter the calendar window, if any.
15961 (if (and org-calendar-follow-timestamp-change
15962 (get-buffer-window "*Calendar*" t)
15963 (memq org-ts-what '(day month year)))
15964 (org-recenter-calendar (time-to-days time))))))
15966 (defun org-modify-ts-extra (s pos n dm)
15967 "Change the different parts of the lead-time and repeat fields in timestamp."
15968 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15969 ng h m new rem)
15970 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15971 (cond
15972 ((or (org-pos-in-match-range pos 2)
15973 (org-pos-in-match-range pos 3))
15974 (setq m (string-to-number (match-string 3 s))
15975 h (string-to-number (match-string 2 s)))
15976 (if (org-pos-in-match-range pos 2)
15977 (setq h (+ h n))
15978 (setq n (* dm (org-no-warnings (signum n))))
15979 (when (not (= 0 (setq rem (% m dm))))
15980 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
15981 (setq m (+ m n)))
15982 (if (< m 0) (setq m (+ m 60) h (1- h)))
15983 (if (> m 59) (setq m (- m 60) h (1+ h)))
15984 (setq h (min 24 (max 0 h)))
15985 (setq ng 1 new (format "-%02d:%02d" h m)))
15986 ((org-pos-in-match-range pos 6)
15987 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15988 ((org-pos-in-match-range pos 5)
15989 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
15991 ((org-pos-in-match-range pos 9)
15992 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
15993 ((org-pos-in-match-range pos 8)
15994 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
15996 (when ng
15997 (setq s (concat
15998 (substring s 0 (match-beginning ng))
16000 (substring s (match-end ng))))))
16003 (defun org-recenter-calendar (date)
16004 "If the calendar is visible, recenter it to DATE."
16005 (let* ((win (selected-window))
16006 (cwin (get-buffer-window "*Calendar*" t))
16007 (calendar-move-hook nil))
16008 (when cwin
16009 (select-window cwin)
16010 (calendar-goto-date (if (listp date) date
16011 (calendar-gregorian-from-absolute date)))
16012 (select-window win))))
16014 (defun org-goto-calendar (&optional arg)
16015 "Go to the Emacs calendar at the current date.
16016 If there is a time stamp in the current line, go to that date.
16017 A prefix ARG can be used to force the current date."
16018 (interactive "P")
16019 (let ((tsr org-ts-regexp) diff
16020 (calendar-move-hook nil)
16021 (calendar-view-holidays-initially-flag nil)
16022 (calendar-view-diary-initially-flag nil))
16023 (if (or (org-at-timestamp-p)
16024 (save-excursion
16025 (beginning-of-line 1)
16026 (looking-at (concat ".*" tsr))))
16027 (let ((d1 (time-to-days (current-time)))
16028 (d2 (time-to-days
16029 (org-time-string-to-time (match-string 1)))))
16030 (setq diff (- d2 d1))))
16031 (calendar)
16032 (calendar-goto-today)
16033 (if (and diff (not arg)) (calendar-forward-day diff))))
16035 (defun org-get-date-from-calendar ()
16036 "Return a list (month day year) of date at point in calendar."
16037 (with-current-buffer "*Calendar*"
16038 (save-match-data
16039 (calendar-cursor-to-date))))
16041 (defun org-date-from-calendar ()
16042 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16043 If there is already a time stamp at the cursor position, update it."
16044 (interactive)
16045 (if (org-at-timestamp-p t)
16046 (org-timestamp-change 0 'calendar)
16047 (let ((cal-date (org-get-date-from-calendar)))
16048 (org-insert-time-stamp
16049 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16051 (defun org-minutes-to-hh:mm-string (m)
16052 "Compute H:MM from a number of minutes."
16053 (let ((h (/ m 60)))
16054 (setq m (- m (* 60 h)))
16055 (format org-time-clocksum-format h m)))
16057 (defun org-hh:mm-string-to-minutes (s)
16058 "Convert a string H:MM to a number of minutes.
16059 If the string is just a number, interpret it as minutes.
16060 In fact, the first hh:mm or number in the string will be taken,
16061 there can be extra stuff in the string.
16062 If no number is found, the return value is 0."
16063 (cond
16064 ((integerp s) s)
16065 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16066 (+ (* (string-to-number (match-string 1 s)) 60)
16067 (string-to-number (match-string 2 s))))
16068 ((string-match "\\([0-9]+\\)" s)
16069 (string-to-number (match-string 1 s)))
16070 (t 0)))
16072 (defcustom org-effort-durations
16073 `(("h" . 60)
16074 ("d" . ,(* 60 8))
16075 ("w" . ,(* 60 8 5))
16076 ("m" . ,(* 60 8 5 4))
16077 ("y" . ,(* 60 8 5 40)))
16078 "Conversion factor to minutes for an effort modifier.
16080 Each entry has the form (MODIFIER . MINUTES).
16082 In an effort string, a number followed by MODIFIER is multiplied
16083 by the specified number of MINUTES to obtain an effort in
16084 minutes.
16086 For example, if the value of this variable is ((\"hours\" . 60)), then an
16087 effort string \"2hours\" is equivalent to 120 minutes."
16088 :group 'org-agenda
16089 :type '(alist :key-type (string :tag "Modifier")
16090 :value-type (number :tag "Minutes")))
16092 (defun org-duration-string-to-minutes (s)
16093 "Convert a duration string S to minutes.
16095 A bare number is interpreted as minutes, modifiers can be set by
16096 customizing `org-effort-durations' (which see).
16098 Entries containing a colon are interpreted as H:MM by
16099 `org-hh:mm-string-to-minutes'."
16100 (let ((result 0)
16101 (re (concat "\\([0-9]+\\) *\\("
16102 (regexp-opt (mapcar 'car org-effort-durations))
16103 "\\)")))
16104 (while (string-match re s)
16105 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16106 (string-to-number (match-string 1 s))))
16107 (setq s (replace-match "" nil t s)))
16108 (incf result (org-hh:mm-string-to-minutes s))
16109 result))
16111 ;;;; Files
16113 (defun org-save-all-org-buffers ()
16114 "Save all Org-mode buffers without user confirmation."
16115 (interactive)
16116 (message "Saving all Org-mode buffers...")
16117 (save-some-buffers t (lambda () (eq major-mode 'org-mode)))
16118 (when (featurep 'org-id) (org-id-locations-save))
16119 (message "Saving all Org-mode buffers... done"))
16121 (defun org-revert-all-org-buffers ()
16122 "Revert all Org-mode buffers.
16123 Prompt for confirmation when there are unsaved changes.
16124 Be sure you know what you are doing before letting this function
16125 overwrite your changes.
16127 This function is useful in a setup where one tracks org files
16128 with a version control system, to revert on one machine after pulling
16129 changes from another. I believe the procedure must be like this:
16131 1. M-x org-save-all-org-buffers
16132 2. Pull changes from the other machine, resolve conflicts
16133 3. M-x org-revert-all-org-buffers"
16134 (interactive)
16135 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16136 (error "Abort"))
16137 (save-excursion
16138 (save-window-excursion
16139 (mapc
16140 (lambda (b)
16141 (when (and (with-current-buffer b (eq major-mode 'org-mode))
16142 (with-current-buffer b buffer-file-name))
16143 (org-pop-to-buffer-same-window b)
16144 (revert-buffer t 'no-confirm)))
16145 (buffer-list))
16146 (when (and (featurep 'org-id) org-id-track-globally)
16147 (org-id-locations-load)))))
16149 ;;;; Agenda files
16151 ;;;###autoload
16152 (defun org-switchb (&optional arg)
16153 "Switch between Org buffers.
16154 With one prefix argument, restrict available buffers to files.
16155 With two prefix arguments, restrict available buffers to agenda files.
16157 Defaults to `iswitchb' for buffer name completion.
16158 Set `org-completion-use-ido' to make it use ido instead."
16159 (interactive "P")
16160 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16161 ((equal arg '(16)) (org-buffer-list 'agenda))
16162 (t (org-buffer-list))))
16163 (org-completion-use-iswitchb org-completion-use-iswitchb)
16164 (org-completion-use-ido org-completion-use-ido))
16165 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16166 (setq org-completion-use-iswitchb t))
16167 (org-pop-to-buffer-same-window
16168 (org-icompleting-read "Org buffer: "
16169 (mapcar 'list (mapcar 'buffer-name blist))
16170 nil t))))
16172 ;;; Define some older names previously used for this functionality
16173 ;;;###autoload
16174 (defalias 'org-ido-switchb 'org-switchb)
16175 ;;;###autoload
16176 (defalias 'org-iswitchb 'org-switchb)
16178 (defun org-buffer-list (&optional predicate exclude-tmp)
16179 "Return a list of Org buffers.
16180 PREDICATE can be `export', `files' or `agenda'.
16182 export restrict the list to Export buffers.
16183 files restrict the list to buffers visiting Org files.
16184 agenda restrict the list to buffers visiting agenda files.
16186 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16187 (let* ((bfn nil)
16188 (agenda-files (and (eq predicate 'agenda)
16189 (mapcar 'file-truename (org-agenda-files t))))
16190 (filter
16191 (cond
16192 ((eq predicate 'files)
16193 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
16194 ((eq predicate 'export)
16195 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16196 ((eq predicate 'agenda)
16197 (lambda (b)
16198 (with-current-buffer b
16199 (and (eq major-mode 'org-mode)
16200 (setq bfn (buffer-file-name b))
16201 (member (file-truename bfn) agenda-files)))))
16202 (t (lambda (b) (with-current-buffer b
16203 (or (eq major-mode 'org-mode)
16204 (string-match "\*Org .*Export"
16205 (buffer-name b)))))))))
16206 (delq nil
16207 (mapcar
16208 (lambda(b)
16209 (if (and (funcall filter b)
16210 (or (not exclude-tmp)
16211 (not (string-match "tmp" (buffer-name b)))))
16213 nil))
16214 (buffer-list)))))
16216 (defun org-agenda-files (&optional unrestricted archives)
16217 "Get the list of agenda files.
16218 Optional UNRESTRICTED means return the full list even if a restriction
16219 is currently in place.
16220 When ARCHIVES is t, include all archive files that are really being
16221 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16222 `org-agenda-archives-mode' is t."
16223 (let ((files
16224 (cond
16225 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16226 ((stringp org-agenda-files) (org-read-agenda-file-list))
16227 ((listp org-agenda-files) org-agenda-files)
16228 (t (error "Invalid value of `org-agenda-files'")))))
16229 (setq files (apply 'append
16230 (mapcar (lambda (f)
16231 (if (file-directory-p f)
16232 (directory-files
16233 f t org-agenda-file-regexp)
16234 (list f)))
16235 files)))
16236 (when org-agenda-skip-unavailable-files
16237 (setq files (delq nil
16238 (mapcar (function
16239 (lambda (file)
16240 (and (file-readable-p file) file)))
16241 files))))
16242 (when (or (eq archives t)
16243 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16244 (setq files (org-add-archive-files files)))
16245 files))
16247 (defun org-agenda-file-p (&optional file)
16248 "Return non-nil, if FILE is an agenda file.
16249 If FILE is omitted, use the file associated with the current
16250 buffer."
16251 (member (or file (buffer-file-name))
16252 (org-agenda-files t)))
16254 (defun org-edit-agenda-file-list ()
16255 "Edit the list of agenda files.
16256 Depending on setup, this either uses customize to edit the variable
16257 `org-agenda-files', or it visits the file that is holding the list. In the
16258 latter case, the buffer is set up in a way that saving it automatically kills
16259 the buffer and restores the previous window configuration."
16260 (interactive)
16261 (if (stringp org-agenda-files)
16262 (let ((cw (current-window-configuration)))
16263 (find-file org-agenda-files)
16264 (org-set-local 'org-window-configuration cw)
16265 (org-add-hook 'after-save-hook
16266 (lambda ()
16267 (set-window-configuration
16268 (prog1 org-window-configuration
16269 (kill-buffer (current-buffer))))
16270 (org-install-agenda-files-menu)
16271 (message "New agenda file list installed"))
16272 nil 'local)
16273 (message "%s" (substitute-command-keys
16274 "Edit list and finish with \\[save-buffer]")))
16275 (customize-variable 'org-agenda-files)))
16277 (defun org-store-new-agenda-file-list (list)
16278 "Set new value for the agenda file list and save it correctly."
16279 (if (stringp org-agenda-files)
16280 (let ((fe (org-read-agenda-file-list t)) b u)
16281 (while (setq b (find-buffer-visiting org-agenda-files))
16282 (kill-buffer b))
16283 (with-temp-file org-agenda-files
16284 (insert
16285 (mapconcat
16286 (lambda (f) ;; Keep un-expanded entries.
16287 (if (setq u (assoc f fe))
16288 (cdr u)
16290 list "\n")
16291 "\n")))
16292 (let ((org-mode-hook nil) (org-inhibit-startup t)
16293 (org-insert-mode-line-in-empty-file nil))
16294 (setq org-agenda-files list)
16295 (customize-save-variable 'org-agenda-files org-agenda-files))))
16297 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16298 "Read the list of agenda files from a file.
16299 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16300 filenames, used by `org-store-new-agenda-file-list' to write back
16301 un-expanded file names."
16302 (when (file-directory-p org-agenda-files)
16303 (error "`org-agenda-files' cannot be a single directory"))
16304 (when (stringp org-agenda-files)
16305 (with-temp-buffer
16306 (insert-file-contents org-agenda-files)
16307 (mapcar
16308 (lambda (f)
16309 (let ((e (expand-file-name (substitute-in-file-name f)
16310 org-directory)))
16311 (if pair-with-expansion
16312 (cons e f)
16313 e)))
16314 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16316 ;;;###autoload
16317 (defun org-cycle-agenda-files ()
16318 "Cycle through the files in `org-agenda-files'.
16319 If the current buffer visits an agenda file, find the next one in the list.
16320 If the current buffer does not, find the first agenda file."
16321 (interactive)
16322 (let* ((fs (org-agenda-files t))
16323 (files (append fs (list (car fs))))
16324 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16325 file)
16326 (unless files (error "No agenda files"))
16327 (catch 'exit
16328 (while (setq file (pop files))
16329 (if (equal (file-truename file) tcf)
16330 (when (car files)
16331 (find-file (car files))
16332 (throw 'exit t))))
16333 (find-file (car fs)))
16334 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16336 (defun org-agenda-file-to-front (&optional to-end)
16337 "Move/add the current file to the top of the agenda file list.
16338 If the file is not present in the list, it is added to the front. If it is
16339 present, it is moved there. With optional argument TO-END, add/move to the
16340 end of the list."
16341 (interactive "P")
16342 (let ((org-agenda-skip-unavailable-files nil)
16343 (file-alist (mapcar (lambda (x)
16344 (cons (file-truename x) x))
16345 (org-agenda-files t)))
16346 (ctf (file-truename buffer-file-name))
16347 x had)
16348 (setq x (assoc ctf file-alist) had x)
16350 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16351 (if to-end
16352 (setq file-alist (append (delq x file-alist) (list x)))
16353 (setq file-alist (cons x (delq x file-alist))))
16354 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16355 (org-install-agenda-files-menu)
16356 (message "File %s to %s of agenda file list"
16357 (if had "moved" "added") (if to-end "end" "front"))))
16359 (defun org-remove-file (&optional file)
16360 "Remove current file from the list of files in variable `org-agenda-files'.
16361 These are the files which are being checked for agenda entries.
16362 Optional argument FILE means use this file instead of the current."
16363 (interactive)
16364 (let* ((org-agenda-skip-unavailable-files nil)
16365 (file (or file buffer-file-name))
16366 (true-file (file-truename file))
16367 (afile (abbreviate-file-name file))
16368 (files (delq nil (mapcar
16369 (lambda (x)
16370 (if (equal true-file
16371 (file-truename x))
16372 nil x))
16373 (org-agenda-files t)))))
16374 (if (not (= (length files) (length (org-agenda-files t))))
16375 (progn
16376 (org-store-new-agenda-file-list files)
16377 (org-install-agenda-files-menu)
16378 (message "Removed file: %s" afile))
16379 (message "File was not in list: %s (not removed)" afile))))
16381 (defun org-file-menu-entry (file)
16382 (vector file (list 'find-file file) t))
16384 (defun org-check-agenda-file (file)
16385 "Make sure FILE exists. If not, ask user what to do."
16386 (when (not (file-exists-p file))
16387 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16388 (abbreviate-file-name file))
16389 (let ((r (downcase (read-char-exclusive))))
16390 (cond
16391 ((equal r ?r)
16392 (org-remove-file file)
16393 (throw 'nextfile t))
16394 (t (error "Abort"))))))
16396 (defun org-get-agenda-file-buffer (file)
16397 "Get a buffer visiting FILE. If the buffer needs to be created, add
16398 it to the list of buffers which might be released later."
16399 (let ((buf (org-find-base-buffer-visiting file)))
16400 (if buf
16401 buf ; just return it
16402 ;; Make a new buffer and remember it
16403 (setq buf (find-file-noselect file))
16404 (if buf (push buf org-agenda-new-buffers))
16405 buf)))
16407 (defun org-release-buffers (blist)
16408 "Release all buffers in list, asking the user for confirmation when needed.
16409 When a buffer is unmodified, it is just killed. When modified, it is saved
16410 \(if the user agrees) and then killed."
16411 (let (buf file)
16412 (while (setq buf (pop blist))
16413 (setq file (buffer-file-name buf))
16414 (when (and (buffer-modified-p buf)
16415 file
16416 (y-or-n-p (format "Save file %s? " file)))
16417 (with-current-buffer buf (save-buffer)))
16418 (kill-buffer buf))))
16420 (defun org-prepare-agenda-buffers (files)
16421 "Create buffers for all agenda files, protect archived trees and comments."
16422 (interactive)
16423 (let ((pa '(:org-archived t))
16424 (pc '(:org-comment t))
16425 (pall '(:org-archived t :org-comment t))
16426 (inhibit-read-only t)
16427 (rea (concat ":" org-archive-tag ":"))
16428 bmp file re)
16429 (save-excursion
16430 (save-restriction
16431 (while (setq file (pop files))
16432 (catch 'nextfile
16433 (if (bufferp file)
16434 (set-buffer file)
16435 (org-check-agenda-file file)
16436 (set-buffer (org-get-agenda-file-buffer file)))
16437 (widen)
16438 (setq bmp (buffer-modified-p))
16439 (org-refresh-category-properties)
16440 (setq org-todo-keywords-for-agenda
16441 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16442 (setq org-done-keywords-for-agenda
16443 (append org-done-keywords-for-agenda org-done-keywords))
16444 (setq org-todo-keyword-alist-for-agenda
16445 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16446 (setq org-drawers-for-agenda
16447 (append org-drawers-for-agenda org-drawers))
16448 (setq org-tag-alist-for-agenda
16449 (append org-tag-alist-for-agenda org-tag-alist))
16451 (save-excursion
16452 (remove-text-properties (point-min) (point-max) pall)
16453 (when org-agenda-skip-archived-trees
16454 (goto-char (point-min))
16455 (while (re-search-forward rea nil t)
16456 (if (org-on-heading-p t)
16457 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16458 (goto-char (point-min))
16459 (setq re (format org-heading-keyword-regexp-format
16460 org-comment-string))
16461 (while (re-search-forward re nil t)
16462 (add-text-properties
16463 (match-beginning 0) (org-end-of-subtree t) pc)))
16464 (set-buffer-modified-p bmp)))))
16465 (setq org-todo-keywords-for-agenda
16466 (org-uniquify org-todo-keywords-for-agenda))
16467 (setq org-todo-keyword-alist-for-agenda
16468 (org-uniquify org-todo-keyword-alist-for-agenda)
16469 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16471 ;;;; Embedded LaTeX
16473 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16474 "Keymap for the minor `org-cdlatex-mode'.")
16476 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16477 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16478 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16479 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16480 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16482 (defvar org-cdlatex-texmathp-advice-is-done nil
16483 "Flag remembering if we have applied the advice to texmathp already.")
16485 (define-minor-mode org-cdlatex-mode
16486 "Toggle the minor `org-cdlatex-mode'.
16487 This mode supports entering LaTeX environment and math in LaTeX fragments
16488 in Org-mode.
16489 \\{org-cdlatex-mode-map}"
16490 nil " OCDL" nil
16491 (when org-cdlatex-mode
16492 (require 'cdlatex)
16493 (run-hooks 'cdlatex-mode-hook)
16494 (cdlatex-compute-tables))
16495 (unless org-cdlatex-texmathp-advice-is-done
16496 (setq org-cdlatex-texmathp-advice-is-done t)
16497 (defadvice texmathp (around org-math-always-on activate)
16498 "Always return t in org-mode buffers.
16499 This is because we want to insert math symbols without dollars even outside
16500 the LaTeX math segments. If Orgmode thinks that point is actually inside
16501 an embedded LaTeX fragment, let texmathp do its job.
16502 \\[org-cdlatex-mode-map]"
16503 (interactive)
16504 (let (p)
16505 (cond
16506 ((not (eq major-mode 'org-mode)) ad-do-it)
16507 ((eq this-command 'cdlatex-math-symbol)
16508 (setq ad-return-value t
16509 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16511 (let ((p (org-inside-LaTeX-fragment-p)))
16512 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16513 (setq ad-return-value t
16514 texmathp-why '("Org-mode embedded math" . 0))
16515 (if p ad-do-it)))))))))
16517 (defun turn-on-org-cdlatex ()
16518 "Unconditionally turn on `org-cdlatex-mode'."
16519 (org-cdlatex-mode 1))
16521 (defun org-inside-LaTeX-fragment-p ()
16522 "Test if point is inside a LaTeX fragment.
16523 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16524 sequence appearing also before point.
16525 Even though the matchers for math are configurable, this function assumes
16526 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16527 delimiters are skipped when they have been removed by customization.
16528 The return value is nil, or a cons cell with the delimiter and the
16529 position of this delimiter.
16531 This function does a reasonably good job, but can locally be fooled by
16532 for example currency specifications. For example it will assume being in
16533 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16534 fragments that are properly closed, but during editing, we have to live
16535 with the uncertainty caused by missing closing delimiters. This function
16536 looks only before point, not after."
16537 (catch 'exit
16538 (let ((pos (point))
16539 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16540 (lim (progn
16541 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16542 (point)))
16543 dd-on str (start 0) m re)
16544 (goto-char pos)
16545 (when dodollar
16546 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16547 re (nth 1 (assoc "$" org-latex-regexps)))
16548 (while (string-match re str start)
16549 (cond
16550 ((= (match-end 0) (length str))
16551 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16552 ((= (match-end 0) (- (length str) 5))
16553 (throw 'exit nil))
16554 (t (setq start (match-end 0))))))
16555 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16556 (goto-char pos)
16557 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16558 (and (match-beginning 2) (throw 'exit nil))
16559 ;; count $$
16560 (while (re-search-backward "\\$\\$" lim t)
16561 (setq dd-on (not dd-on)))
16562 (goto-char pos)
16563 (if dd-on (cons "$$" m))))))
16565 (defun org-inside-latex-macro-p ()
16566 "Is point inside a LaTeX macro or its arguments?"
16567 (save-match-data
16568 (org-in-regexp
16569 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16571 (defun org-try-cdlatex-tab ()
16572 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16573 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16574 - inside a LaTeX fragment, or
16575 - after the first word in a line, where an abbreviation expansion could
16576 insert a LaTeX environment."
16577 (when org-cdlatex-mode
16578 (cond
16579 ;; Before any word on the line: No expansion possible.
16580 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
16581 ;; Just after first word on the line: Expand it. Make sure it
16582 ;; cannot happen on headlines, though.
16583 ((save-excursion
16584 (skip-chars-backward "a-zA-Z0-9*")
16585 (skip-chars-backward " \t")
16586 (and (bolp) (not (org-at-heading-p))))
16587 (cdlatex-tab) t)
16588 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
16590 (defun org-cdlatex-underscore-caret (&optional arg)
16591 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16592 Revert to the normal definition outside of these fragments."
16593 (interactive "P")
16594 (if (org-inside-LaTeX-fragment-p)
16595 (call-interactively 'cdlatex-sub-superscript)
16596 (let (org-cdlatex-mode)
16597 (call-interactively (key-binding (vector last-input-event))))))
16599 (defun org-cdlatex-math-modify (&optional arg)
16600 "Execute `cdlatex-math-modify' in LaTeX fragments.
16601 Revert to the normal definition outside of these fragments."
16602 (interactive "P")
16603 (if (org-inside-LaTeX-fragment-p)
16604 (call-interactively 'cdlatex-math-modify)
16605 (let (org-cdlatex-mode)
16606 (call-interactively (key-binding (vector last-input-event))))))
16608 (defvar org-latex-fragment-image-overlays nil
16609 "List of overlays carrying the images of latex fragments.")
16610 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16612 (defun org-remove-latex-fragment-image-overlays ()
16613 "Remove all overlays with LaTeX fragment images in current buffer."
16614 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16615 (setq org-latex-fragment-image-overlays nil))
16617 (defun org-preview-latex-fragment (&optional subtree)
16618 "Preview the LaTeX fragment at point, or all locally or globally.
16619 If the cursor is in a LaTeX fragment, create the image and overlay
16620 it over the source code. If there is no fragment at point, display
16621 all fragments in the current text, from one headline to the next. With
16622 prefix SUBTREE, display all fragments in the current subtree. With a
16623 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16624 the cursor is before the first headline,
16625 display all fragments in the buffer.
16626 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16627 (interactive "P")
16628 (org-remove-latex-fragment-image-overlays)
16629 (save-excursion
16630 (save-restriction
16631 (let (beg end at msg)
16632 (cond
16633 ((or (equal subtree '(16))
16634 (not (save-excursion
16635 (re-search-backward org-outline-regexp-bol nil t))))
16636 (setq beg (point-min) end (point-max)
16637 msg "Creating images for buffer...%s"))
16638 ((equal subtree '(4))
16639 (org-back-to-heading)
16640 (setq beg (point) end (org-end-of-subtree t)
16641 msg "Creating images for subtree...%s"))
16643 (if (setq at (org-inside-LaTeX-fragment-p))
16644 (goto-char (max (point-min) (- (cdr at) 2)))
16645 (org-back-to-heading))
16646 (setq beg (point) end (progn (outline-next-heading) (point))
16647 msg (if at "Creating image...%s"
16648 "Creating images for entry...%s"))))
16649 (message msg "")
16650 (narrow-to-region beg end)
16651 (goto-char beg)
16652 (org-format-latex
16653 (concat "ltxpng/" (file-name-sans-extension
16654 (file-name-nondirectory
16655 buffer-file-name)))
16656 default-directory 'overlays msg at 'forbuffer 'dvipng)
16657 (message msg "done. Use `C-c C-c' to remove images.")))))
16659 (defvar org-latex-regexps
16660 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16661 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16662 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16663 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16664 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16665 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16666 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16667 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16668 "Regular expressions for matching embedded LaTeX.")
16670 (defvar org-export-have-math nil) ;; dynamic scoping
16671 (defun org-format-latex (prefix &optional dir overlays msg at
16672 forbuffer processing-type)
16673 "Replace LaTeX fragments with links to an image, and produce images.
16674 Some of the options can be changed using the variable
16675 `org-format-latex-options'."
16676 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16677 (let* ((prefixnodir (file-name-nondirectory prefix))
16678 (absprefix (expand-file-name prefix dir))
16679 (todir (file-name-directory absprefix))
16680 (opt org-format-latex-options)
16681 (matchers (plist-get opt :matchers))
16682 (re-list org-latex-regexps)
16683 (org-format-latex-header-extra
16684 (plist-get (org-infile-export-plist) :latex-header-extra))
16685 (cnt 0) txt hash link beg end re e checkdir
16686 executables-checked string
16687 m n block-type block linkfile movefile ov)
16688 ;; Check the different regular expressions
16689 (while (setq e (pop re-list))
16690 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
16691 block (if block-type "\n\n" ""))
16692 (when (member m matchers)
16693 (goto-char (point-min))
16694 (while (re-search-forward re nil t)
16695 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16696 (not (get-text-property (match-beginning n)
16697 'org-protected))
16698 (or (not overlays)
16699 (not (eq (get-char-property (match-beginning n)
16700 'org-overlay-type)
16701 'org-latex-overlay))))
16702 (setq org-export-have-math t)
16703 (cond
16704 ((eq processing-type 'verbatim)
16705 ;; Leave the text verbatim, just protect it
16706 (add-text-properties (match-beginning n) (match-end n)
16707 '(org-protected t)))
16708 ((eq processing-type 'mathjax)
16709 ;; Prepare for MathJax processing
16710 (setq string (match-string n))
16711 (if (member m '("$" "$1"))
16712 (save-excursion
16713 (delete-region (match-beginning n) (match-end n))
16714 (goto-char (match-beginning n))
16715 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16716 "\\)")
16717 '(org-protected t))))
16718 (add-text-properties (match-beginning n) (match-end n)
16719 '(org-protected t))))
16720 ((eq processing-type 'dvipng)
16721 ;; Process to an image
16722 (setq txt (match-string n)
16723 beg (match-beginning n) end (match-end n)
16724 cnt (1+ cnt))
16725 (let (print-length print-level) ; make sure full list is printed
16726 (setq hash (sha1 (prin1-to-string
16727 (list org-format-latex-header
16728 org-format-latex-header-extra
16729 org-export-latex-default-packages-alist
16730 org-export-latex-packages-alist
16731 org-format-latex-options
16732 forbuffer txt)))
16733 linkfile (format "%s_%s.png" prefix hash)
16734 movefile (format "%s_%s.png" absprefix hash)))
16735 (setq link (concat block "[[file:" linkfile "]]" block))
16736 (if msg (message msg cnt))
16737 (goto-char beg)
16738 (unless checkdir ; make sure the directory exists
16739 (setq checkdir t)
16740 (or (file-directory-p todir) (make-directory todir t)))
16742 (unless executables-checked
16743 (org-check-external-command
16744 "latex" "needed to convert LaTeX fragments to images")
16745 (org-check-external-command
16746 "dvipng" "needed to convert LaTeX fragments to images")
16747 (setq executables-checked t))
16749 (unless (file-exists-p movefile)
16750 (org-create-formula-image
16751 txt movefile opt forbuffer))
16752 (if overlays
16753 (progn
16754 (mapc (lambda (o)
16755 (if (eq (overlay-get o 'org-overlay-type)
16756 'org-latex-overlay)
16757 (delete-overlay o)))
16758 (overlays-in beg end))
16759 (setq ov (make-overlay beg end))
16760 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16761 (if (featurep 'xemacs)
16762 (progn
16763 (overlay-put ov 'invisible t)
16764 (overlay-put
16765 ov 'end-glyph
16766 (make-glyph (vector 'png :file movefile))))
16767 (overlay-put
16768 ov 'display
16769 (list 'image :type 'png :file movefile :ascent 'center)))
16770 (push ov org-latex-fragment-image-overlays)
16771 (goto-char end))
16772 (delete-region beg end)
16773 (insert (org-add-props link
16774 (list 'org-latex-src
16775 (replace-regexp-in-string
16776 "\"" "" txt)
16777 'org-latex-src-embed-type
16778 (if block-type 'paragraph 'character))))))
16779 ((eq processing-type 'mathml)
16780 ;; Process to MathML
16781 (unless executables-checked
16782 (unless (save-match-data (org-format-latex-mathml-available-p))
16783 (error "LaTeX to MathML converter not configured"))
16784 (setq executables-checked t))
16785 (setq txt (match-string n)
16786 beg (match-beginning n) end (match-end n)
16787 cnt (1+ cnt))
16788 (if msg (message msg cnt))
16789 (goto-char beg)
16790 (delete-region beg end)
16791 (insert (org-format-latex-as-mathml
16792 txt block-type prefix dir)))
16794 (error "Unknown conversion type %s for latex fragments"
16795 processing-type)))))))))
16797 (defun org-create-math-formula (latex-frag &optional mathml-file)
16798 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
16799 Use `org-latex-to-mathml-convert-command'. If the conversion is
16800 sucessful, return the portion between \"<math...> </math>\"
16801 elements otherwise return nil. When MATHML-FILE is specified,
16802 write the results in to that file. When invoked as an
16803 interactive command, prompt for LATEX-FRAG, with initial value
16804 set to the current active region and echo the results for user
16805 inspection."
16806 (interactive (list (let ((frag (when (region-active-p)
16807 (buffer-substring-no-properties
16808 (region-beginning) (region-end)))))
16809 (read-string "LaTeX Fragment: " frag nil frag))))
16810 (unless latex-frag (error "Invalid latex-frag"))
16811 (let* ((tmp-in-file (file-relative-name
16812 (make-temp-name (expand-file-name "ltxmathml-in"))))
16813 (ignore (write-region latex-frag nil tmp-in-file))
16814 (tmp-out-file (file-relative-name
16815 (make-temp-name (expand-file-name "ltxmathml-out"))))
16816 (cmd (format-spec
16817 org-latex-to-mathml-convert-command
16818 `((?j . ,(shell-quote-argument
16819 (expand-file-name org-latex-to-mathml-jar-file)))
16820 (?I . ,(shell-quote-argument tmp-in-file))
16821 (?o . ,(shell-quote-argument tmp-out-file)))))
16822 mathml shell-command-output)
16823 (when (org-called-interactively-p 'any)
16824 (unless (org-format-latex-mathml-available-p)
16825 (error "LaTeX to MathML converter not configured")))
16826 (message "Running %s" cmd)
16827 (setq shell-command-output (shell-command-to-string cmd))
16828 (setq mathml
16829 (when (file-readable-p tmp-out-file)
16830 (with-current-buffer (find-file-noselect tmp-out-file t)
16831 (goto-char (point-min))
16832 (when (re-search-forward
16833 (concat
16834 (regexp-quote
16835 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
16836 "\\(.\\|\n\\)*"
16837 (regexp-quote "</math>")) nil t)
16838 (prog1 (match-string 0) (kill-buffer))))))
16839 (cond
16840 (mathml
16841 (setq mathml
16842 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
16843 (when mathml-file
16844 (write-region mathml nil mathml-file))
16845 (when (org-called-interactively-p 'any)
16846 (message mathml)))
16847 ((message "LaTeX to MathML conversion failed")
16848 (message shell-command-output)))
16849 (delete-file tmp-in-file)
16850 (when (file-exists-p tmp-out-file)
16851 (delete-file tmp-out-file))
16852 mathml))
16854 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
16855 prefix &optional dir)
16856 "Use `org-create-math-formula' but check local cache first."
16857 (let* ((absprefix (expand-file-name prefix dir))
16858 (print-length nil) (print-level nil)
16859 (formula-id (concat
16860 "formula-"
16861 (sha1
16862 (prin1-to-string
16863 (list latex-frag
16864 org-latex-to-mathml-convert-command)))))
16865 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
16866 (formula-cache-dir (file-name-directory formula-cache)))
16868 (unless (file-directory-p formula-cache-dir)
16869 (make-directory formula-cache-dir t))
16871 (unless (file-exists-p formula-cache)
16872 (org-create-math-formula latex-frag formula-cache))
16874 (if (file-exists-p formula-cache)
16875 ;; Successful conversion. Return the link to MathML file.
16876 (org-add-props
16877 (format "[[file:%s]]" (file-relative-name formula-cache dir))
16878 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
16879 'org-latex-src-embed-type (if latex-frag-type
16880 'paragraph 'character)))
16881 ;; Failed conversion. Return the LaTeX fragment verbatim
16882 (add-text-properties
16883 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
16884 latex-frag)))
16886 ;; This function borrows from Ganesh Swami's latex2png.el
16887 (defun org-create-formula-image (string tofile options buffer)
16888 "This calls dvipng."
16889 (require 'org-latex)
16890 (let* ((tmpdir (if (featurep 'xemacs)
16891 (temp-directory)
16892 temporary-file-directory))
16893 (texfilebase (make-temp-name
16894 (expand-file-name "orgtex" tmpdir)))
16895 (texfile (concat texfilebase ".tex"))
16896 (dvifile (concat texfilebase ".dvi"))
16897 (pngfile (concat texfilebase ".png"))
16898 (fnh (if (featurep 'xemacs)
16899 (font-height (get-face-font 'default))
16900 (face-attribute 'default :height nil)))
16901 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
16902 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
16903 (fg (or (plist-get options (if buffer :foreground :html-foreground))
16904 "Black"))
16905 (bg (or (plist-get options (if buffer :background :html-background))
16906 "Transparent")))
16907 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
16908 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
16909 (with-temp-file texfile
16910 (insert (org-splice-latex-header
16911 org-format-latex-header
16912 org-export-latex-default-packages-alist
16913 org-export-latex-packages-alist t
16914 org-format-latex-header-extra))
16915 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
16916 (require 'org-latex)
16917 (org-export-latex-fix-inputenc))
16918 (let ((dir default-directory))
16919 (condition-case nil
16920 (progn
16921 (cd tmpdir)
16922 (call-process "latex" nil nil nil texfile))
16923 (error nil))
16924 (cd dir))
16925 (if (not (file-exists-p dvifile))
16926 (progn (message "Failed to create dvi file from %s" texfile) nil)
16927 (condition-case nil
16928 (call-process "dvipng" nil nil nil
16929 "-fg" fg "-bg" bg
16930 "-D" dpi
16931 ;;"-x" scale "-y" scale
16932 "-T" "tight"
16933 "-o" pngfile
16934 dvifile)
16935 (error nil))
16936 (if (not (file-exists-p pngfile))
16937 (if org-format-latex-signal-error
16938 (error "Failed to create png file from %s" texfile)
16939 (message "Failed to create png file from %s" texfile)
16940 nil)
16941 ;; Use the requested file name and clean up
16942 (copy-file pngfile tofile 'replace)
16943 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16944 (delete-file (concat texfilebase e)))
16945 pngfile))))
16947 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
16948 "Fill a LaTeX header template TPL.
16949 In the template, the following place holders will be recognized:
16951 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
16952 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
16953 [PACKAGES] \\usepackage statements for PKG
16954 [NO-PACKAGES] do not include PKG
16955 [EXTRA] the string EXTRA
16956 [NO-EXTRA] do not include EXTRA
16958 For backward compatibility, if both the positive and the negative place
16959 holder is missing, the positive one (without the \"NO-\") will be
16960 assumed to be present at the end of the template.
16961 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
16962 EXTRA is a string.
16963 SNIPPETS-P indicates if this is run to create snippet images for HTML."
16964 (let (rpl (end ""))
16965 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
16966 (setq rpl (if (or (match-end 1) (not def-pkg))
16967 "" (org-latex-packages-to-string def-pkg snippets-p t))
16968 tpl (replace-match rpl t t tpl))
16969 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
16971 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
16972 (setq rpl (if (or (match-end 1) (not pkg))
16973 "" (org-latex-packages-to-string pkg snippets-p t))
16974 tpl (replace-match rpl t t tpl))
16975 (if pkg (setq end
16976 (concat end "\n"
16977 (org-latex-packages-to-string pkg snippets-p)))))
16979 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
16980 (setq rpl (if (or (match-end 1) (not extra))
16981 "" (concat extra "\n"))
16982 tpl (replace-match rpl t t tpl))
16983 (if (and extra (string-match "\\S-" extra))
16984 (setq end (concat end "\n" extra))))
16986 (if (string-match "\\S-" end)
16987 (concat tpl "\n" end)
16988 tpl)))
16990 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
16991 "Turn an alist of packages into a string with the \\usepackage macros."
16992 (setq pkg (mapconcat (lambda(p)
16993 (cond
16994 ((stringp p) p)
16995 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
16996 (format "%% Package %s omitted" (cadr p)))
16997 ((equal "" (car p))
16998 (format "\\usepackage{%s}" (cadr p)))
17000 (format "\\usepackage[%s]{%s}"
17001 (car p) (cadr p)))))
17003 "\n"))
17004 (if newline (concat pkg "\n") pkg))
17006 (defun org-dvipng-color (attr)
17007 "Return an rgb color specification for dvipng."
17008 (apply 'format "rgb %s %s %s"
17009 (mapcar 'org-normalize-color
17010 (color-values (face-attribute 'default attr nil)))))
17012 (defun org-normalize-color (value)
17013 "Return string to be used as color value for an RGB component."
17014 (format "%g" (/ value 65535.0)))
17016 ;; Image display
17019 (defvar org-inline-image-overlays nil)
17020 (make-variable-buffer-local 'org-inline-image-overlays)
17022 (defun org-toggle-inline-images (&optional include-linked)
17023 "Toggle the display of inline images.
17024 INCLUDE-LINKED is passed to `org-display-inline-images'."
17025 (interactive "P")
17026 (if org-inline-image-overlays
17027 (progn
17028 (org-remove-inline-images)
17029 (message "Inline image display turned off"))
17030 (org-display-inline-images include-linked)
17031 (if org-inline-image-overlays
17032 (message "%d images displayed inline"
17033 (length org-inline-image-overlays))
17034 (message "No images to display inline"))))
17036 (defun org-display-inline-images (&optional include-linked refresh beg end)
17037 "Display inline images.
17038 Normally only links without a description part are inlined, because this
17039 is how it will work for export. When INCLUDE-LINKED is set, also links
17040 with a description part will be inlined. This can be nice for a quick
17041 look at those images, but it does not reflect what exported files will look
17042 like.
17043 When REFRESH is set, refresh existing images between BEG and END.
17044 This will create new image displays only if necessary.
17045 BEG and END default to the buffer boundaries."
17046 (interactive "P")
17047 (unless refresh
17048 (org-remove-inline-images)
17049 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17050 (save-excursion
17051 (save-restriction
17052 (widen)
17053 (setq beg (or beg (point-min)) end (or end (point-max)))
17054 (goto-char (point-min))
17055 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17056 (substring (org-image-file-name-regexp) 0 -2)
17057 "\\)\\]" (if include-linked "" "\\]")))
17058 old file ov img)
17059 (while (re-search-forward re end t)
17060 (setq old (get-char-property-and-overlay (match-beginning 1)
17061 'org-image-overlay))
17062 (setq file (expand-file-name
17063 (concat (or (match-string 3) "") (match-string 4))))
17064 (when (file-exists-p file)
17065 (if (and (car-safe old) refresh)
17066 (image-refresh (overlay-get (cdr old) 'display))
17067 (setq img (save-match-data (create-image file)))
17068 (when img
17069 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17070 (overlay-put ov 'display img)
17071 (overlay-put ov 'face 'default)
17072 (overlay-put ov 'org-image-overlay t)
17073 (overlay-put ov 'modification-hooks
17074 (list 'org-display-inline-modification-hook))
17075 (push ov org-inline-image-overlays)))))))))
17077 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17078 "Remove inline-display overlay if a corresponding region is modified."
17079 (let ((inhibit-modification-hooks t))
17080 (when (and ov after)
17081 (delete ov org-inline-image-overlays)
17082 (delete-overlay ov))))
17084 (defun org-remove-inline-images ()
17085 "Remove inline display of images."
17086 (interactive)
17087 (mapc 'delete-overlay org-inline-image-overlays)
17088 (setq org-inline-image-overlays nil))
17090 ;;;; Key bindings
17092 ;; Outline functions from `outline-mode-prefix-map'
17093 ;; that can be remapped in Org:
17094 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17095 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17096 (define-key org-mode-map [remap outline-forward-same-level]
17097 'org-forward-same-level)
17098 (define-key org-mode-map [remap outline-backward-same-level]
17099 'org-backward-same-level)
17100 (define-key org-mode-map [remap show-branches]
17101 'org-kill-note-or-show-branches)
17102 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17103 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17104 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17106 ;; Outline functions from `outline-mode-prefix-map'
17107 ;; that can not be remapped in Org:
17108 ;; - the column "key binding" shows whether the Outline function is still
17109 ;; available in Org mode on the same key that it has been bound to in
17110 ;; Outline mode:
17111 ;; - "overridden": key used for a different functionality in Org mode
17112 ;; - else: key still bound to the same Outline function in Org mode
17113 ;; | Outline function | key binding | Org replacement |
17114 ;; |------------------------------------+-------------+-----------------------|
17115 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17116 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17117 ;; | `show-children' | `C-c C-i' | visibility cycling |
17118 ;; | `hide-subtree' | overridden | visibility cycling |
17119 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17120 ;; | `hide-body' | overridden | no replacement |
17121 ;; | `show-all' | overridden | no replacement |
17122 ;; | `hide-entry' | overridden | visibility cycling |
17123 ;; | `show-entry' | overridden | no replacement |
17124 ;; | `hide-leaves' | overridden | no replacement |
17125 ;; | `hide-sublevels' | overridden | no replacement |
17126 ;; | `hide-other' | overridden | no replacement |
17127 ;; | `outline-move-subtree-up' | `C-c C-^' | better: org-shiftup |
17128 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17130 ;; Make `C-c C-x' a prefix key
17131 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17133 ;; TAB key with modifiers
17134 (org-defkey org-mode-map "\C-i" 'org-cycle)
17135 (org-defkey org-mode-map [(tab)] 'org-cycle)
17136 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17137 (org-defkey org-mode-map [(meta tab)] 'pcomplete)
17138 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17139 (org-defkey org-mode-map "\M-\C-i" 'pcomplete)
17140 ;; The following line is necessary under Suse GNU/Linux
17141 (unless (featurep 'xemacs)
17142 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17143 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17144 (define-key org-mode-map [backtab] 'org-shifttab)
17146 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17147 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17148 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17150 ;; Cursor keys with modifiers
17151 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17152 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17153 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17154 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17156 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17157 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17158 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17159 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17161 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17162 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17163 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17164 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17166 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17167 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17168 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17169 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17171 ;; Babel keys
17172 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17173 (mapc (lambda (pair)
17174 (define-key org-babel-map (car pair) (cdr pair)))
17175 org-babel-key-bindings)
17177 ;;; Extra keys for tty access.
17178 ;; We only set them when really needed because otherwise the
17179 ;; menus don't show the simple keys
17181 (when (or org-use-extra-keys
17182 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17183 (not window-system))
17184 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17185 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17186 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17187 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17188 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17189 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17190 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17191 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17192 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17193 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17194 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17195 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17196 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17197 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17198 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17199 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17200 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17201 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17202 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17203 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17204 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17205 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17206 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17207 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17208 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17209 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17210 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17211 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17213 ;; All the other keys
17215 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17216 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17217 (if (boundp 'narrow-map)
17218 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17219 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17220 (if (boundp 'narrow-map)
17221 (org-defkey narrow-map "b" 'org-narrow-to-block)
17222 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17223 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17224 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17225 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17226 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17227 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17228 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17229 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17230 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17231 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17232 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17233 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17234 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17235 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17236 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17237 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17238 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17239 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17240 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17241 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17242 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17243 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17244 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17245 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17246 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17247 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17248 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17249 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17250 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17251 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17252 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17253 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17254 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17255 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17256 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17257 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17258 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17259 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17260 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17261 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17262 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17263 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17264 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17265 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17266 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17267 (org-defkey org-mode-map "\C-c^" 'org-sort)
17268 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17269 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17270 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17271 (org-defkey org-mode-map "\C-m" 'org-return)
17272 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17273 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17274 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17275 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17276 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17277 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17278 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17279 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17280 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17281 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17282 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17283 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17284 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17285 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17286 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17287 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17288 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17289 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17290 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17291 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17292 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17293 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17295 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17296 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17297 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17298 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17300 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17301 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17302 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17303 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17304 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17305 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17306 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17307 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17308 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17309 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17310 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17311 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17312 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17313 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17314 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17315 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17316 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17317 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17319 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17320 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17321 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17322 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17323 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17325 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17327 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17329 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17330 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17332 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17335 (when (featurep 'xemacs)
17336 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17339 (defconst org-speed-commands-default
17341 ("Outline Navigation")
17342 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17343 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17344 ("f" . (org-speed-move-safe 'org-forward-same-level))
17345 ("b" . (org-speed-move-safe 'org-backward-same-level))
17346 ("u" . (org-speed-move-safe 'outline-up-heading))
17347 ("j" . org-goto)
17348 ("g" . (org-refile t))
17349 ("Outline Visibility")
17350 ("c" . org-cycle)
17351 ("C" . org-shifttab)
17352 (" " . org-display-outline-path)
17353 ("Outline Structure Editing")
17354 ("U" . org-shiftmetaup)
17355 ("D" . org-shiftmetadown)
17356 ("r" . org-metaright)
17357 ("l" . org-metaleft)
17358 ("R" . org-shiftmetaright)
17359 ("L" . org-shiftmetaleft)
17360 ("i" . (progn (forward-char 1) (call-interactively
17361 'org-insert-heading-respect-content)))
17362 ("^" . org-sort)
17363 ("w" . org-refile)
17364 ("a" . org-archive-subtree-default-with-confirmation)
17365 ("." . org-mark-subtree)
17366 ("Clock Commands")
17367 ("I" . org-clock-in)
17368 ("O" . org-clock-out)
17369 ("Meta Data Editing")
17370 ("t" . org-todo)
17371 ("0" . (org-priority ?\ ))
17372 ("1" . (org-priority ?A))
17373 ("2" . (org-priority ?B))
17374 ("3" . (org-priority ?C))
17375 (";" . org-set-tags-command)
17376 ("e" . org-set-effort)
17377 ("Agenda Views etc")
17378 ("v" . org-agenda)
17379 ("/" . org-sparse-tree)
17380 ("Misc")
17381 ("o" . org-open-at-point)
17382 ("?" . org-speed-command-help)
17383 ("<" . (org-agenda-set-restriction-lock 'subtree))
17384 (">" . (org-agenda-remove-restriction-lock))
17386 "The default speed commands.")
17388 (defun org-print-speed-command (e)
17389 (if (> (length (car e)) 1)
17390 (progn
17391 (princ "\n")
17392 (princ (car e))
17393 (princ "\n")
17394 (princ (make-string (length (car e)) ?-))
17395 (princ "\n"))
17396 (princ (car e))
17397 (princ " ")
17398 (if (symbolp (cdr e))
17399 (princ (symbol-name (cdr e)))
17400 (prin1 (cdr e)))
17401 (princ "\n")))
17403 (defun org-speed-command-help ()
17404 "Show the available speed commands."
17405 (interactive)
17406 (if (not org-use-speed-commands)
17407 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17408 (with-output-to-temp-buffer "*Help*"
17409 (princ "User-defined Speed commands\n===========================\n")
17410 (mapc 'org-print-speed-command org-speed-commands-user)
17411 (princ "\n")
17412 (princ "Built-in Speed commands\n=======================\n")
17413 (mapc 'org-print-speed-command org-speed-commands-default))
17414 (with-current-buffer "*Help*"
17415 (setq truncate-lines t))))
17417 (defun org-speed-move-safe (cmd)
17418 "Execute CMD, but make sure that the cursor always ends up in a headline.
17419 If not, return to the original position and throw an error."
17420 (interactive)
17421 (let ((pos (point)))
17422 (call-interactively cmd)
17423 (unless (and (bolp) (org-on-heading-p))
17424 (goto-char pos)
17425 (error "Boundary reached while executing %s" cmd))))
17427 (defvar org-self-insert-command-undo-counter 0)
17429 (defvar org-table-auto-blank-field) ; defined in org-table.el
17430 (defvar org-speed-command nil)
17432 (defun org-speed-command-default-hook (keys)
17433 "Hook for activating single-letter speed commands.
17434 `org-speed-commands-default' specifies a minimal command set.
17435 Use `org-speed-commands-user' for further customization."
17436 (when (or (and (bolp) (looking-at org-outline-regexp))
17437 (and (functionp org-use-speed-commands)
17438 (funcall org-use-speed-commands)))
17439 (cdr (assoc keys (append org-speed-commands-user
17440 org-speed-commands-default)))))
17442 (defun org-babel-speed-command-hook (keys)
17443 "Hook for activating single-letter code block commands."
17444 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17445 (cdr (assoc keys org-babel-key-bindings))))
17447 (defcustom org-speed-command-hook
17448 '(org-speed-command-default-hook org-babel-speed-command-hook)
17449 "Hook for activating speed commands at strategic locations.
17450 Hook functions are called in sequence until a valid handler is
17451 found.
17453 Each hook takes a single argument, a user-pressed command key
17454 which is also a `self-insert-command' from the global map.
17456 Within the hook, examine the cursor position and the command key
17457 and return nil or a valid handler as appropriate. Handler could
17458 be one of an interactive command, a function, or a form.
17460 Set `org-use-speed-commands' to non-nil value to enable this
17461 hook. The default setting is `org-speed-command-default-hook'."
17462 :group 'org-structure
17463 :type 'hook)
17465 (defun org-self-insert-command (N)
17466 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17467 If the cursor is in a table looking at whitespace, the whitespace is
17468 overwritten, and the table is not marked as requiring realignment."
17469 (interactive "p")
17470 (org-check-before-invisible-edit 'insert)
17471 (cond
17472 ((and org-use-speed-commands
17473 (setq org-speed-command
17474 (run-hook-with-args-until-success
17475 'org-speed-command-hook (this-command-keys))))
17476 (cond
17477 ((commandp org-speed-command)
17478 (setq this-command org-speed-command)
17479 (call-interactively org-speed-command))
17480 ((functionp org-speed-command)
17481 (funcall org-speed-command))
17482 ((and org-speed-command (listp org-speed-command))
17483 (eval org-speed-command))
17484 (t (let (org-use-speed-commands)
17485 (call-interactively 'org-self-insert-command)))))
17486 ((and
17487 (org-table-p)
17488 (progn
17489 ;; check if we blank the field, and if that triggers align
17490 (and (featurep 'org-table) org-table-auto-blank-field
17491 (member last-command
17492 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17493 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17494 ;; got extra space, this field does not determine column width
17495 (let (org-table-may-need-update) (org-table-blank-field))
17496 ;; no extra space, this field may determine column width
17497 (org-table-blank-field)))
17499 (eq N 1)
17500 (looking-at "[^|\n]* |"))
17501 (let (org-table-may-need-update)
17502 (goto-char (1- (match-end 0)))
17503 (delete-char -1)
17504 (goto-char (match-beginning 0))
17505 (self-insert-command N)))
17507 (setq org-table-may-need-update t)
17508 (self-insert-command N)
17509 (org-fix-tags-on-the-fly)
17510 (if org-self-insert-cluster-for-undo
17511 (if (not (eq last-command 'org-self-insert-command))
17512 (setq org-self-insert-command-undo-counter 1)
17513 (if (>= org-self-insert-command-undo-counter 20)
17514 (setq org-self-insert-command-undo-counter 1)
17515 (and (> org-self-insert-command-undo-counter 0)
17516 buffer-undo-list (listp buffer-undo-list)
17517 (not (cadr buffer-undo-list)) ; remove nil entry
17518 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17519 (setq org-self-insert-command-undo-counter
17520 (1+ org-self-insert-command-undo-counter))))))))
17522 (defun org-check-before-invisible-edit (kind)
17523 "Check is editing if kind KIND would be dangerous with invisible text around.
17524 The detailed reaction depends on the user option `org-catch-invisible-edits'."
17525 ;; First, try to get out of here as quickly as possible, to reduce overhead
17526 (if (and org-catch-invisible-edits
17527 (or (not (boundp 'visible-mode)) (not visible-mode))
17528 (or (get-char-property (point) 'invisible)
17529 (get-char-property (max (point-min) (1- (point))) 'invisible)))
17530 ;; OK, we need to take a closer look
17531 (let* ((invisible-at-point (get-char-property (point) 'invisible))
17532 (invisible-before-point (if (bobp) nil (get-char-property
17533 (1- (point)) 'invisible)))
17534 (border-and-ok-direction
17536 ;; Check if we are acting predictably before invisible text
17537 (and invisible-at-point (not invisible-before-point)
17538 (memq kind '(insert delete-backward)))
17539 ;; Check if we are acting predictably after invisible text
17540 ;; This works not well, and I have turned it off. It seems
17541 ;; better to always show and stop after invisible text.
17542 ;; (and (not invisible-at-point) invisible-before-point
17543 ;; (memq kind '(insert delete)))
17546 (when (or (memq invisible-at-point '(outline org-hide-block))
17547 (memq invisible-before-point '(outline org-hide-block)))
17548 (if (eq org-catch-invisible-edits 'error)
17549 (error "Editing in invisible areas is prohibited - make visible first"))
17550 ;; Make the area visible
17551 (save-excursion
17552 (if invisible-before-point
17553 (goto-char (previous-single-char-property-change
17554 (point) 'invisible)))
17555 (org-cycle))
17556 (cond
17557 ((eq org-catch-invisible-edits 'show)
17558 ;; That's it, we do the edit after showing
17559 (message
17560 "Unfolding invisible region around point before editing")
17561 (sit-for 1))
17562 ((and (eq org-catch-invisible-edits 'smart)
17563 border-and-ok-direction)
17564 (message "Unfolding invisible region around point before editing"))
17566 ;; Don't do the edit, make the user repeat it in full visibility
17567 (error "Edit in invisible region aborted, repeat to confirm with text visible")))))))
17569 (defun org-fix-tags-on-the-fly ()
17570 (when (and (equal (char-after (point-at-bol)) ?*)
17571 (org-on-heading-p))
17572 (org-align-tags-here org-tags-column)))
17574 (defun org-delete-backward-char (N)
17575 "Like `delete-backward-char', insert whitespace at field end in tables.
17576 When deleting backwards, in tables this function will insert whitespace in
17577 front of the next \"|\" separator, to keep the table aligned. The table will
17578 still be marked for re-alignment if the field did fill the entire column,
17579 because, in this case the deletion might narrow the column."
17580 (interactive "p")
17581 (org-check-before-invisible-edit 'delete-backward)
17582 (if (and (org-table-p)
17583 (eq N 1)
17584 (string-match "|" (buffer-substring (point-at-bol) (point)))
17585 (looking-at ".*?|"))
17586 (let ((pos (point))
17587 (noalign (looking-at "[^|\n\r]* |"))
17588 (c org-table-may-need-update))
17589 (backward-delete-char N)
17590 (if (not overwrite-mode)
17591 (progn
17592 (skip-chars-forward "^|")
17593 (insert " ")
17594 (goto-char (1- pos))))
17595 ;; noalign: if there were two spaces at the end, this field
17596 ;; does not determine the width of the column.
17597 (if noalign (setq org-table-may-need-update c)))
17598 (backward-delete-char N)
17599 (org-fix-tags-on-the-fly)))
17601 (defun org-delete-char (N)
17602 "Like `delete-char', but insert whitespace at field end in tables.
17603 When deleting characters, in tables this function will insert whitespace in
17604 front of the next \"|\" separator, to keep the table aligned. The table will
17605 still be marked for re-alignment if the field did fill the entire column,
17606 because, in this case the deletion might narrow the column."
17607 (interactive "p")
17608 (org-check-before-invisible-edit 'delete)
17609 (if (and (org-table-p)
17610 (not (bolp))
17611 (not (= (char-after) ?|))
17612 (eq N 1))
17613 (if (looking-at ".*?|")
17614 (let ((pos (point))
17615 (noalign (looking-at "[^|\n\r]* |"))
17616 (c org-table-may-need-update))
17617 (replace-match (concat
17618 (substring (match-string 0) 1 -1)
17619 " |"))
17620 (goto-char pos)
17621 ;; noalign: if there were two spaces at the end, this field
17622 ;; does not determine the width of the column.
17623 (if noalign (setq org-table-may-need-update c)))
17624 (delete-char N))
17625 (delete-char N)
17626 (org-fix-tags-on-the-fly)))
17628 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17629 (put 'org-self-insert-command 'delete-selection t)
17630 (put 'orgtbl-self-insert-command 'delete-selection t)
17631 (put 'org-delete-char 'delete-selection 'supersede)
17632 (put 'org-delete-backward-char 'delete-selection 'supersede)
17633 (put 'org-yank 'delete-selection 'yank)
17635 ;; Make `flyspell-mode' delay after some commands
17636 (put 'org-self-insert-command 'flyspell-delayed t)
17637 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17638 (put 'org-delete-char 'flyspell-delayed t)
17639 (put 'org-delete-backward-char 'flyspell-delayed t)
17641 ;; Make pabbrev-mode expand after org-mode commands
17642 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17643 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17645 ;; How to do this: Measure non-white length of current string
17646 ;; If equal to column width, we should realign.
17648 (defun org-remap (map &rest commands)
17649 "In MAP, remap the functions given in COMMANDS.
17650 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17651 (let (new old)
17652 (while commands
17653 (setq old (pop commands) new (pop commands))
17654 (if (fboundp 'command-remapping)
17655 (org-defkey map (vector 'remap old) new)
17656 (substitute-key-definition old new map global-map)))))
17658 (when (eq org-enable-table-editor 'optimized)
17659 ;; If the user wants maximum table support, we need to hijack
17660 ;; some standard editing functions
17661 (org-remap org-mode-map
17662 'self-insert-command 'org-self-insert-command
17663 'delete-char 'org-delete-char
17664 'delete-backward-char 'org-delete-backward-char)
17665 (org-defkey org-mode-map "|" 'org-force-self-insert))
17667 (defvar org-ctrl-c-ctrl-c-hook nil
17668 "Hook for functions attaching themselves to `C-c C-c'.
17670 This can be used to add additional functionality to the C-c C-c
17671 key which executes context-dependent commands. This hook is run
17672 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
17673 run after the last test.
17675 Each function will be called with no arguments. The function
17676 must check if the context is appropriate for it to act. If yes,
17677 it should do its thing and then return a non-nil value. If the
17678 context is wrong, just do nothing and return nil.")
17680 (defvar org-ctrl-c-ctrl-c-final-hook nil
17681 "Hook for functions attaching themselves to `C-c C-c'.
17683 This can be used to add additional functionality to the C-c C-c
17684 key which executes context-dependent commands. This hook is run
17685 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
17686 before the first test.
17688 Each function will be called with no arguments. The function
17689 must check if the context is appropriate for it to act. If yes,
17690 it should do its thing and then return a non-nil value. If the
17691 context is wrong, just do nothing and return nil.")
17693 (defvar org-tab-first-hook nil
17694 "Hook for functions to attach themselves to TAB.
17695 See `org-ctrl-c-ctrl-c-hook' for more information.
17696 This hook runs as the first action when TAB is pressed, even before
17697 `org-cycle' messes around with the `outline-regexp' to cater for
17698 inline tasks and plain list item folding.
17699 If any function in this hook returns t, any other actions that
17700 would have been caused by TAB (such as table field motion or visibility
17701 cycling) will not occur.")
17703 (defvar org-tab-after-check-for-table-hook nil
17704 "Hook for functions to attach themselves to TAB.
17705 See `org-ctrl-c-ctrl-c-hook' for more information.
17706 This hook runs after it has been established that the cursor is not in a
17707 table, but before checking if the cursor is in a headline or if global cycling
17708 should be done.
17709 If any function in this hook returns t, not other actions like visibility
17710 cycling will be done.")
17712 (defvar org-tab-after-check-for-cycling-hook nil
17713 "Hook for functions to attach themselves to TAB.
17714 See `org-ctrl-c-ctrl-c-hook' for more information.
17715 This hook runs after it has been established that not table field motion and
17716 not visibility should be done because of current context. This is probably
17717 the place where a package like yasnippets can hook in.")
17719 (defvar org-tab-before-tab-emulation-hook nil
17720 "Hook for functions to attach themselves to TAB.
17721 See `org-ctrl-c-ctrl-c-hook' for more information.
17722 This hook runs after every other options for TAB have been exhausted, but
17723 before indentation and \t insertion takes place.")
17725 (defvar org-metaleft-hook nil
17726 "Hook for functions attaching themselves to `M-left'.
17727 See `org-ctrl-c-ctrl-c-hook' for more information.")
17728 (defvar org-metaright-hook nil
17729 "Hook for functions attaching themselves to `M-right'.
17730 See `org-ctrl-c-ctrl-c-hook' for more information.")
17731 (defvar org-metaup-hook nil
17732 "Hook for functions attaching themselves to `M-up'.
17733 See `org-ctrl-c-ctrl-c-hook' for more information.")
17734 (defvar org-metadown-hook nil
17735 "Hook for functions attaching themselves to `M-down'.
17736 See `org-ctrl-c-ctrl-c-hook' for more information.")
17737 (defvar org-shiftmetaleft-hook nil
17738 "Hook for functions attaching themselves to `M-S-left'.
17739 See `org-ctrl-c-ctrl-c-hook' for more information.")
17740 (defvar org-shiftmetaright-hook nil
17741 "Hook for functions attaching themselves to `M-S-right'.
17742 See `org-ctrl-c-ctrl-c-hook' for more information.")
17743 (defvar org-shiftmetaup-hook nil
17744 "Hook for functions attaching themselves to `M-S-up'.
17745 See `org-ctrl-c-ctrl-c-hook' for more information.")
17746 (defvar org-shiftmetadown-hook nil
17747 "Hook for functions attaching themselves to `M-S-down'.
17748 See `org-ctrl-c-ctrl-c-hook' for more information.")
17749 (defvar org-metareturn-hook nil
17750 "Hook for functions attaching themselves to `M-RET'.
17751 See `org-ctrl-c-ctrl-c-hook' for more information.")
17752 (defvar org-shiftup-hook nil
17753 "Hook for functions attaching themselves to `S-up'.
17754 See `org-ctrl-c-ctrl-c-hook' for more information.")
17755 (defvar org-shiftup-final-hook nil
17756 "Hook for functions attaching themselves to `S-up'.
17757 This one runs after all other options except shift-select have been excluded.
17758 See `org-ctrl-c-ctrl-c-hook' for more information.")
17759 (defvar org-shiftdown-hook nil
17760 "Hook for functions attaching themselves to `S-down'.
17761 See `org-ctrl-c-ctrl-c-hook' for more information.")
17762 (defvar org-shiftdown-final-hook nil
17763 "Hook for functions attaching themselves to `S-down'.
17764 This one runs after all other options except shift-select have been excluded.
17765 See `org-ctrl-c-ctrl-c-hook' for more information.")
17766 (defvar org-shiftleft-hook nil
17767 "Hook for functions attaching themselves to `S-left'.
17768 See `org-ctrl-c-ctrl-c-hook' for more information.")
17769 (defvar org-shiftleft-final-hook nil
17770 "Hook for functions attaching themselves to `S-left'.
17771 This one runs after all other options except shift-select have been excluded.
17772 See `org-ctrl-c-ctrl-c-hook' for more information.")
17773 (defvar org-shiftright-hook nil
17774 "Hook for functions attaching themselves to `S-right'.
17775 See `org-ctrl-c-ctrl-c-hook' for more information.")
17776 (defvar org-shiftright-final-hook nil
17777 "Hook for functions attaching themselves to `S-right'.
17778 This one runs after all other options except shift-select have been excluded.
17779 See `org-ctrl-c-ctrl-c-hook' for more information.")
17781 (defun org-modifier-cursor-error ()
17782 "Throw an error, a modified cursor command was applied in wrong context."
17783 (error "This command is active in special context like tables, headlines or items"))
17785 (defun org-shiftselect-error ()
17786 "Throw an error because Shift-Cursor command was applied in wrong context."
17787 (if (and (boundp 'shift-select-mode) shift-select-mode)
17788 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
17789 (error "This command works only in special context like headlines or timestamps")))
17791 (defun org-call-for-shift-select (cmd)
17792 (let ((this-command-keys-shift-translated t))
17793 (call-interactively cmd)))
17795 (defun org-shifttab (&optional arg)
17796 "Global visibility cycling or move to previous table field.
17797 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17798 on context.
17799 See the individual commands for more information."
17800 (interactive "P")
17801 (cond
17802 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17803 ((integerp arg)
17804 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
17805 (message "Content view to level: %d" arg)
17806 (org-content (prefix-numeric-value arg2))
17807 (setq org-cycle-global-status 'overview)))
17808 (t (call-interactively 'org-global-cycle))))
17810 (defun org-shiftmetaleft ()
17811 "Promote subtree or delete table column.
17812 Calls `org-promote-subtree', `org-outdent-item',
17813 or `org-table-delete-column', depending on context.
17814 See the individual commands for more information."
17815 (interactive)
17816 (cond
17817 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
17818 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17819 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
17820 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
17821 (t (org-modifier-cursor-error))))
17823 (defun org-shiftmetaright ()
17824 "Demote subtree or insert table column.
17825 Calls `org-demote-subtree', `org-indent-item',
17826 or `org-table-insert-column', depending on context.
17827 See the individual commands for more information."
17828 (interactive)
17829 (cond
17830 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
17831 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17832 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
17833 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
17834 (t (org-modifier-cursor-error))))
17836 (defun org-shiftmetaup (&optional arg)
17837 "Move subtree up or kill table row.
17838 Calls `org-move-subtree-up' or `org-table-kill-row' or
17839 `org-move-item-up' depending on context. See the individual commands
17840 for more information."
17841 (interactive "P")
17842 (cond
17843 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
17844 ((org-at-table-p) (call-interactively 'org-table-kill-row))
17845 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17846 ((org-at-item-p) (call-interactively 'org-move-item-up))
17847 (t (org-modifier-cursor-error))))
17849 (defun org-shiftmetadown (&optional arg)
17850 "Move subtree down or insert table row.
17851 Calls `org-move-subtree-down' or `org-table-insert-row' or
17852 `org-move-item-down', depending on context. See the individual
17853 commands for more information."
17854 (interactive "P")
17855 (cond
17856 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
17857 ((org-at-table-p) (call-interactively 'org-table-insert-row))
17858 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17859 ((org-at-item-p) (call-interactively 'org-move-item-down))
17860 (t (org-modifier-cursor-error))))
17862 (defsubst org-hidden-tree-error ()
17863 (error
17864 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
17866 (defun org-metaleft (&optional arg)
17867 "Promote heading or move table column to left.
17868 Calls `org-do-promote' or `org-table-move-column', depending on context.
17869 With no specific context, calls the Emacs default `backward-word'.
17870 See the individual commands for more information."
17871 (interactive "P")
17872 (cond
17873 ((run-hook-with-args-until-success 'org-metaleft-hook))
17874 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
17875 ((org-with-limited-levels
17876 (or (org-on-heading-p)
17877 (and (org-region-active-p)
17878 (save-excursion
17879 (goto-char (region-beginning))
17880 (org-on-heading-p)))))
17881 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17882 (call-interactively 'org-do-promote))
17883 ;; At an inline task.
17884 ((org-on-heading-p)
17885 (call-interactively 'org-inlinetask-promote))
17886 ((or (org-at-item-p)
17887 (and (org-region-active-p)
17888 (save-excursion
17889 (goto-char (region-beginning))
17890 (org-at-item-p))))
17891 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17892 (call-interactively 'org-outdent-item))
17893 (t (call-interactively 'backward-word))))
17895 (defun org-metaright (&optional arg)
17896 "Demote subtree or move table column to right.
17897 Calls `org-do-demote' or `org-table-move-column', depending on context.
17898 With no specific context, calls the Emacs default `forward-word'.
17899 See the individual commands for more information."
17900 (interactive "P")
17901 (cond
17902 ((run-hook-with-args-until-success 'org-metaright-hook))
17903 ((org-at-table-p) (call-interactively 'org-table-move-column))
17904 ((org-with-limited-levels
17905 (or (org-on-heading-p)
17906 (and (org-region-active-p)
17907 (save-excursion
17908 (goto-char (region-beginning))
17909 (org-on-heading-p)))))
17910 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17911 (call-interactively 'org-do-demote))
17912 ;; At an inline task.
17913 ((org-on-heading-p)
17914 (call-interactively 'org-inlinetask-demote))
17915 ((or (org-at-item-p)
17916 (and (org-region-active-p)
17917 (save-excursion
17918 (goto-char (region-beginning))
17919 (org-at-item-p))))
17920 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17921 (call-interactively 'org-indent-item))
17922 (t (call-interactively 'forward-word))))
17924 (defun org-check-for-hidden (what)
17925 "Check if there are hidden headlines/items in the current visual line.
17926 WHAT can be either `headlines' or `items'. If the current line is
17927 an outline or item heading and it has a folded subtree below it,
17928 this function returns t, nil otherwise."
17929 (let ((re (cond
17930 ((eq what 'headlines) org-outline-regexp-bol)
17931 ((eq what 'items) (org-item-beginning-re))
17932 (t (error "This should not happen"))))
17933 beg end)
17934 (save-excursion
17935 (catch 'exit
17936 (unless (org-region-active-p)
17937 (setq beg (point-at-bol))
17938 (beginning-of-line 2)
17939 (while (and (not (eobp)) ;; this is like `next-line'
17940 (get-char-property (1- (point)) 'invisible))
17941 (beginning-of-line 2))
17942 (setq end (point))
17943 (goto-char beg)
17944 (goto-char (point-at-eol))
17945 (setq end (max end (point)))
17946 (while (re-search-forward re end t)
17947 (if (get-char-property (match-beginning 0) 'invisible)
17948 (throw 'exit t))))
17949 nil))))
17951 (defun org-metaup (&optional arg)
17952 "Move subtree up or move table row up.
17953 Calls `org-move-subtree-up' or `org-table-move-row' or
17954 `org-move-item-up', depending on context. See the individual commands
17955 for more information."
17956 (interactive "P")
17957 (cond
17958 ((run-hook-with-args-until-success 'org-metaup-hook))
17959 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
17960 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17961 ((org-at-item-p) (call-interactively 'org-move-item-up))
17962 (t (transpose-lines 1) (beginning-of-line -1))))
17964 (defun org-metadown (&optional arg)
17965 "Move subtree down or move table row down.
17966 Calls `org-move-subtree-down' or `org-table-move-row' or
17967 `org-move-item-down', depending on context. See the individual
17968 commands for more information."
17969 (interactive "P")
17970 (cond
17971 ((run-hook-with-args-until-success 'org-metadown-hook))
17972 ((org-at-table-p) (call-interactively 'org-table-move-row))
17973 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17974 ((org-at-item-p) (call-interactively 'org-move-item-down))
17975 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
17977 (defun org-shiftup (&optional arg)
17978 "Increase item in timestamp or increase priority of current headline.
17979 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
17980 depending on context. See the individual commands for more information."
17981 (interactive "P")
17982 (cond
17983 ((run-hook-with-args-until-success 'org-shiftup-hook))
17984 ((and org-support-shift-select (org-region-active-p))
17985 (org-call-for-shift-select 'previous-line))
17986 ((org-at-timestamp-p t)
17987 (call-interactively (if org-edit-timestamp-down-means-later
17988 'org-timestamp-down 'org-timestamp-up)))
17989 ((and (not (eq org-support-shift-select 'always))
17990 org-enable-priority-commands
17991 (org-on-heading-p))
17992 (call-interactively 'org-priority-up))
17993 ((and (not org-support-shift-select) (org-at-item-p))
17994 (call-interactively 'org-previous-item))
17995 ((org-clocktable-try-shift 'up arg))
17996 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
17997 (org-support-shift-select
17998 (org-call-for-shift-select 'previous-line))
17999 (t (org-shiftselect-error))))
18001 (defun org-shiftdown (&optional arg)
18002 "Decrease item in timestamp or decrease priority of current headline.
18003 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18004 depending on context. See the individual commands for more information."
18005 (interactive "P")
18006 (cond
18007 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18008 ((and org-support-shift-select (org-region-active-p))
18009 (org-call-for-shift-select 'next-line))
18010 ((org-at-timestamp-p t)
18011 (call-interactively (if org-edit-timestamp-down-means-later
18012 'org-timestamp-up 'org-timestamp-down)))
18013 ((and (not (eq org-support-shift-select 'always))
18014 org-enable-priority-commands
18015 (org-on-heading-p))
18016 (call-interactively 'org-priority-down))
18017 ((and (not org-support-shift-select) (org-at-item-p))
18018 (call-interactively 'org-next-item))
18019 ((org-clocktable-try-shift 'down arg))
18020 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18021 (org-support-shift-select
18022 (org-call-for-shift-select 'next-line))
18023 (t (org-shiftselect-error))))
18025 (defun org-shiftright (&optional arg)
18026 "Cycle the thing at point or in the current line, depending on context.
18027 Depending on context, this does one of the following:
18029 - switch a timestamp at point one day into the future
18030 - on a headline, switch to the next TODO keyword.
18031 - on an item, switch entire list to the next bullet type
18032 - on a property line, switch to the next allowed value
18033 - on a clocktable definition line, move time block into the future"
18034 (interactive "P")
18035 (cond
18036 ((run-hook-with-args-until-success 'org-shiftright-hook))
18037 ((and org-support-shift-select (org-region-active-p))
18038 (org-call-for-shift-select 'forward-char))
18039 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18040 ((and (not (eq org-support-shift-select 'always))
18041 (org-on-heading-p))
18042 (let ((org-inhibit-logging
18043 (not org-treat-S-cursor-todo-selection-as-state-change))
18044 (org-inhibit-blocking
18045 (not org-treat-S-cursor-todo-selection-as-state-change)))
18046 (org-call-with-arg 'org-todo 'right)))
18047 ((or (and org-support-shift-select
18048 (not (eq org-support-shift-select 'always))
18049 (org-at-item-bullet-p))
18050 (and (not org-support-shift-select) (org-at-item-p)))
18051 (org-call-with-arg 'org-cycle-list-bullet nil))
18052 ((and (not (eq org-support-shift-select 'always))
18053 (org-at-property-p))
18054 (call-interactively 'org-property-next-allowed-value))
18055 ((org-clocktable-try-shift 'right arg))
18056 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18057 (org-support-shift-select
18058 (org-call-for-shift-select 'forward-char))
18059 (t (org-shiftselect-error))))
18061 (defun org-shiftleft (&optional arg)
18062 "Cycle the thing at point or in the current line, depending on context.
18063 Depending on context, this does one of the following:
18065 - switch a timestamp at point one day into the past
18066 - on a headline, switch to the previous TODO keyword.
18067 - on an item, switch entire list to the previous bullet type
18068 - on a property line, switch to the previous allowed value
18069 - on a clocktable definition line, move time block into the past"
18070 (interactive "P")
18071 (cond
18072 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18073 ((and org-support-shift-select (org-region-active-p))
18074 (org-call-for-shift-select 'backward-char))
18075 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18076 ((and (not (eq org-support-shift-select 'always))
18077 (org-on-heading-p))
18078 (let ((org-inhibit-logging
18079 (not org-treat-S-cursor-todo-selection-as-state-change))
18080 (org-inhibit-blocking
18081 (not org-treat-S-cursor-todo-selection-as-state-change)))
18082 (org-call-with-arg 'org-todo 'left)))
18083 ((or (and org-support-shift-select
18084 (not (eq org-support-shift-select 'always))
18085 (org-at-item-bullet-p))
18086 (and (not org-support-shift-select) (org-at-item-p)))
18087 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18088 ((and (not (eq org-support-shift-select 'always))
18089 (org-at-property-p))
18090 (call-interactively 'org-property-previous-allowed-value))
18091 ((org-clocktable-try-shift 'left arg))
18092 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18093 (org-support-shift-select
18094 (org-call-for-shift-select 'backward-char))
18095 (t (org-shiftselect-error))))
18097 (defun org-shiftcontrolright ()
18098 "Switch to next TODO set."
18099 (interactive)
18100 (cond
18101 ((and org-support-shift-select (org-region-active-p))
18102 (org-call-for-shift-select 'forward-word))
18103 ((and (not (eq org-support-shift-select 'always))
18104 (org-on-heading-p))
18105 (org-call-with-arg 'org-todo 'nextset))
18106 (org-support-shift-select
18107 (org-call-for-shift-select 'forward-word))
18108 (t (org-shiftselect-error))))
18110 (defun org-shiftcontrolleft ()
18111 "Switch to previous TODO set."
18112 (interactive)
18113 (cond
18114 ((and org-support-shift-select (org-region-active-p))
18115 (org-call-for-shift-select 'backward-word))
18116 ((and (not (eq org-support-shift-select 'always))
18117 (org-on-heading-p))
18118 (org-call-with-arg 'org-todo 'previousset))
18119 (org-support-shift-select
18120 (org-call-for-shift-select 'backward-word))
18121 (t (org-shiftselect-error))))
18123 (defun org-shiftcontrolup ()
18124 "Change timestamps synchronously up in CLOCK log lines."
18125 (interactive)
18126 (cond ((and (not org-support-shift-select)
18127 (org-at-clock-log-p)
18128 (org-at-timestamp-p t))
18129 (org-clock-timestamps-up))
18130 (t (org-shiftselect-error))))
18132 (defun org-shiftcontroldown ()
18133 "Change timestamps synchronously down in CLOCK log lines."
18134 (interactive)
18135 (cond ((and (not org-support-shift-select)
18136 (org-at-clock-log-p)
18137 (org-at-timestamp-p t))
18138 (org-clock-timestamps-down))
18139 (t (org-shiftselect-error))))
18141 (defun org-ctrl-c-ret ()
18142 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18143 (interactive)
18144 (cond
18145 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18146 (t (call-interactively 'org-insert-heading))))
18148 (defun org-find-visible ()
18149 (let ((s (point)))
18150 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18151 (get-char-property s 'invisible)))
18153 (defun org-find-invisible ()
18154 (let ((s (point)))
18155 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18156 (not (get-char-property s 'invisible))))
18159 (defun org-copy-visible (beg end)
18160 "Copy the visible parts of the region."
18161 (interactive "r")
18162 (let (snippets s)
18163 (save-excursion
18164 (save-restriction
18165 (narrow-to-region beg end)
18166 (setq s (goto-char (point-min)))
18167 (while (not (= (point) (point-max)))
18168 (goto-char (org-find-invisible))
18169 (push (buffer-substring s (point)) snippets)
18170 (setq s (goto-char (org-find-visible))))))
18171 (kill-new (apply 'concat (nreverse snippets)))))
18173 (defun org-copy-special ()
18174 "Copy region in table or copy current subtree.
18175 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18176 See the individual commands for more information."
18177 (interactive)
18178 (call-interactively
18179 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18181 (defun org-cut-special ()
18182 "Cut region in table or cut current subtree.
18183 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18184 See the individual commands for more information."
18185 (interactive)
18186 (call-interactively
18187 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18189 (defun org-paste-special (arg)
18190 "Paste rectangular region into table, or past subtree relative to level.
18191 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18192 See the individual commands for more information."
18193 (interactive "P")
18194 (if (org-at-table-p)
18195 (org-table-paste-rectangle)
18196 (org-paste-subtree arg)))
18198 (defun org-edit-special (&optional arg)
18199 "Call a special editor for the stuff at point.
18200 When at a table, call the formula editor with `org-table-edit-formulas'.
18201 When at the first line of an src example, call `org-edit-src-code'.
18202 When in an #+include line, visit the include file. Otherwise call
18203 `ffap' to visit the file at point."
18204 (interactive)
18205 ;; possibly prep session before editing source
18206 (when arg
18207 (let* ((info (org-babel-get-src-block-info))
18208 (lang (nth 0 info))
18209 (params (nth 2 info))
18210 (session (cdr (assoc :session params))))
18211 (when (and info session) ;; we are in a source-code block with a session
18212 (funcall
18213 (intern (concat "org-babel-prep-session:" lang)) session params))))
18214 (cond ;; proceed with `org-edit-special'
18215 ((save-excursion
18216 (beginning-of-line 1)
18217 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18218 (find-file (org-trim (match-string 1))))
18219 ((org-edit-src-code))
18220 ((org-edit-fixed-width-region))
18221 ((org-at-table.el-p)
18222 (org-edit-src-code))
18223 ((or (org-at-table-p)
18224 (save-excursion
18225 (beginning-of-line 1)
18226 (looking-at "[ \t]*#\\+TBLFM:")))
18227 (call-interactively 'org-table-edit-formulas))
18228 (t (call-interactively 'ffap))))
18230 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18231 (defun org-ctrl-c-ctrl-c (&optional arg)
18232 "Set tags in headline, or update according to changed information at point.
18234 This command does many different things, depending on context:
18236 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18237 this is what we do.
18239 - If the cursor is on a statistics cookie, update it.
18241 - If the cursor is in a headline, prompt for tags and insert them
18242 into the current line, aligned to `org-tags-column'. When called
18243 with prefix arg, realign all tags in the current buffer.
18245 - If the cursor is in one of the special #+KEYWORD lines, this
18246 triggers scanning the buffer for these lines and updating the
18247 information.
18249 - If the cursor is inside a table, realign the table. This command
18250 works even if the automatic table editor has been turned off.
18252 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18253 the entire table.
18255 - If the cursor is at a footnote reference or definition, jump to
18256 the corresponding definition or references, respectively.
18258 - If the cursor is a the beginning of a dynamic block, update it.
18260 - If the current buffer is a capture buffer, close note and file it.
18262 - If the cursor is on a <<<target>>>, update radio targets and
18263 corresponding links in this buffer.
18265 - If the cursor is on a numbered item in a plain list, renumber the
18266 ordered list.
18268 - If the cursor is on a checkbox, toggle it.
18270 - If the cursor is on a code block, evaluate it. The variable
18271 `org-confirm-babel-evaluate' can be used to control prompting
18272 before code block evaluation, by default every code block
18273 evaluation requires confirmation. Code block evaluation can be
18274 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18275 (interactive "P")
18276 (let ((org-enable-table-editor t))
18277 (cond
18278 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18279 org-occur-highlights
18280 org-latex-fragment-image-overlays)
18281 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18282 (org-remove-occur-highlights)
18283 (org-remove-latex-fragment-image-overlays)
18284 (message "Temporary highlights/overlays removed from current buffer"))
18285 ((and (local-variable-p 'org-finish-function (current-buffer))
18286 (fboundp org-finish-function))
18287 (funcall org-finish-function))
18288 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18289 ((org-in-regexp org-ts-regexp-both)
18290 (org-timestamp-change 0 'day))
18291 ((or (looking-at org-property-start-re)
18292 (org-at-property-p))
18293 (call-interactively 'org-property-action))
18294 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
18295 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18296 (or (org-on-heading-p) (org-at-item-p)))
18297 (call-interactively 'org-update-statistics-cookies))
18298 ((org-on-heading-p) (call-interactively 'org-set-tags))
18299 ((org-at-table.el-p)
18300 (message "Use C-c ' to edit table.el tables"))
18301 ((org-at-table-p)
18302 (org-table-maybe-eval-formula)
18303 (if arg
18304 (call-interactively 'org-table-recalculate)
18305 (org-table-maybe-recalculate-line))
18306 (call-interactively 'org-table-align)
18307 (orgtbl-send-table 'maybe))
18308 ((or (org-footnote-at-reference-p)
18309 (org-footnote-at-definition-p))
18310 (call-interactively 'org-footnote-action))
18311 ((org-at-item-checkbox-p)
18312 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18313 ;; list only if at top item.
18314 (let* ((cbox (match-string 1))
18315 (struct (org-list-struct))
18316 (old-struct (copy-tree struct))
18317 (parents (org-list-parents-alist struct))
18318 (orderedp (org-entry-get nil "ORDERED"))
18319 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18320 block-item)
18321 ;; Use a light version of `org-toggle-checkbox' to avoid
18322 ;; computing list structure twice.
18323 (org-list-set-checkbox (point-at-bol) struct
18324 (cond
18325 ((equal arg '(16)) "[-]")
18326 ((equal arg '(4)) nil)
18327 ((equal "[X]" cbox) "[ ]")
18328 (t "[X]")))
18329 ;; Replicate `org-list-write-struct', while grabbing a return
18330 ;; value from `org-list-struct-fix-box'.
18331 (org-list-struct-fix-ind struct parents 2)
18332 (org-list-struct-fix-item-end struct)
18333 (let ((prevs (org-list-prevs-alist struct)))
18334 (org-list-struct-fix-bul struct prevs)
18335 (org-list-struct-fix-ind struct parents)
18336 (setq block-item
18337 (org-list-struct-fix-box struct parents prevs orderedp)))
18338 (org-list-struct-apply-struct struct old-struct)
18339 (org-update-checkbox-count-maybe)
18340 (when block-item
18341 (message
18342 "Checkboxes were removed due to unchecked box at line %d"
18343 (org-current-line block-item)))
18344 (when firstp (org-list-send-list 'maybe))))
18345 ((org-at-item-p)
18346 ;; Cursor at an item: repair list. Do checkbox related actions
18347 ;; only if function was called with an argument. Send list only
18348 ;; if at top item.
18349 (let* ((struct (org-list-struct))
18350 (firstp (= (org-list-get-top-point struct) (point-at-bol))))
18351 (when arg (org-list-set-checkbox (point-at-bol) struct "[ ]"))
18352 (org-list-write-struct struct (org-list-parents-alist struct))
18353 (when arg (org-update-checkbox-count-maybe))
18354 (when firstp (org-list-send-list 'maybe))))
18355 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18356 ;; Dynamic block
18357 (beginning-of-line 1)
18358 (save-excursion (org-update-dblock)))
18359 ((save-excursion
18360 (beginning-of-line 1)
18361 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
18362 (cond
18363 ((equal (match-string 1) "TBLFM")
18364 ;; Recalculate the table before this line
18365 (save-excursion
18366 (beginning-of-line 1)
18367 (skip-chars-backward " \r\n\t")
18368 (if (org-at-table-p)
18369 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18371 (let ((org-inhibit-startup-visibility-stuff t)
18372 (org-startup-align-all-tables nil))
18373 (when (boundp 'org-table-coordinate-overlays)
18374 (mapc 'delete-overlay org-table-coordinate-overlays)
18375 (setq org-table-coordinate-overlays nil))
18376 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18377 (message "Local setup has been refreshed"))))
18378 ((org-clock-update-time-maybe))
18380 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18381 (error "C-c C-c can do nothing useful at this location"))))))
18383 (defun org-mode-restart ()
18384 "Restart Org-mode, to scan again for special lines.
18385 Also updates the keyword regular expressions."
18386 (interactive)
18387 (org-mode)
18388 (message "Org-mode restarted"))
18390 (defun org-kill-note-or-show-branches ()
18391 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18392 (interactive)
18393 (if (not org-finish-function)
18394 (progn
18395 (hide-subtree)
18396 (call-interactively 'show-branches))
18397 (let ((org-note-abort t))
18398 (funcall org-finish-function))))
18400 (defun org-return (&optional indent)
18401 "Goto next table row or insert a newline.
18402 Calls `org-table-next-row' or `newline', depending on context.
18403 See the individual commands for more information."
18404 (interactive)
18405 (cond
18406 ((bobp) (if indent (newline-and-indent) (newline)))
18407 ((org-at-table-p)
18408 (org-table-justify-field-maybe)
18409 (call-interactively 'org-table-next-row))
18410 ;; when `newline-and-indent' is called within a list, make sure
18411 ;; text moved stays inside the item.
18412 ((and (org-in-item-p) indent)
18413 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18414 (progn
18415 (save-match-data (newline))
18416 (org-indent-line-to (length (match-string 0))))
18417 (let ((ind (org-get-indentation)))
18418 (newline)
18419 (if (org-looking-back org-list-end-re)
18420 (org-indent-line-function)
18421 (org-indent-line-to ind)))))
18422 ((and org-return-follows-link
18423 (let ((tprop (get-text-property (point) 'face)))
18424 (or (eq tprop 'org-link)
18425 (and (listp tprop) (memq 'org-link tprop)))))
18426 (call-interactively 'org-open-at-point))
18427 ((and (org-at-heading-p)
18428 (looking-at
18429 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18430 (org-show-entry)
18431 (end-of-line 1)
18432 (newline))
18433 (t (if indent (newline-and-indent) (newline)))))
18435 (defun org-return-indent ()
18436 "Goto next table row or insert a newline and indent.
18437 Calls `org-table-next-row' or `newline-and-indent', depending on
18438 context. See the individual commands for more information."
18439 (interactive)
18440 (org-return t))
18442 (defun org-ctrl-c-star ()
18443 "Compute table, or change heading status of lines.
18444 Calls `org-table-recalculate' or `org-toggle-heading',
18445 depending on context."
18446 (interactive)
18447 (cond
18448 ((org-at-table-p)
18449 (call-interactively 'org-table-recalculate))
18451 ;; Convert all lines in region to list items
18452 (call-interactively 'org-toggle-heading))))
18454 (defun org-ctrl-c-minus ()
18455 "Insert separator line in table or modify bullet status of line.
18456 Also turns a plain line or a region of lines into list items.
18457 Calls `org-table-insert-hline', `org-toggle-item', or
18458 `org-cycle-list-bullet', depending on context."
18459 (interactive)
18460 (cond
18461 ((org-at-table-p)
18462 (call-interactively 'org-table-insert-hline))
18463 ((org-region-active-p)
18464 (call-interactively 'org-toggle-item))
18465 ((org-in-item-p)
18466 (call-interactively 'org-cycle-list-bullet))
18468 (call-interactively 'org-toggle-item))))
18470 (defun org-toggle-item (arg)
18471 "Convert headings or normal lines to items, items to normal lines.
18472 If there is no active region, only the current line is considered.
18474 If the first non blank line in the region is an headline, convert
18475 all headlines to items, shifting text accordingly.
18477 If it is an item, convert all items to normal lines.
18479 If it is normal text, change region into an item. With a prefix
18480 argument ARG, change each line in region into an item."
18481 (interactive "P")
18482 (let ((shift-text
18483 (function
18484 ;; Shift text in current section to IND, from point to END.
18485 ;; The function leaves point to END line.
18486 (lambda (ind end)
18487 (let ((min-i 1000) (end (copy-marker end)))
18488 ;; First determine the minimum indentation (MIN-I) of
18489 ;; the text.
18490 (save-excursion
18491 (catch 'exit
18492 (while (< (point) end)
18493 (let ((i (org-get-indentation)))
18494 (cond
18495 ;; Skip blank lines and inline tasks.
18496 ((looking-at "^[ \t]*$"))
18497 ((looking-at org-outline-regexp-bol))
18498 ;; We can't find less than 0 indentation.
18499 ((zerop i) (throw 'exit (setq min-i 0)))
18500 ((< i min-i) (setq min-i i))))
18501 (forward-line))))
18502 ;; Then indent each line so that a line indented to
18503 ;; MIN-I becomes indented to IND. Ignore blank lines
18504 ;; and inline tasks in the process.
18505 (let ((delta (- ind min-i)))
18506 (while (< (point) end)
18507 (unless (or (looking-at "^[ \t]*$")
18508 (looking-at org-outline-regexp-bol))
18509 (org-indent-line-to (+ (org-get-indentation) delta)))
18510 (forward-line)))))))
18511 (skip-blanks
18512 (function
18513 ;; Return beginning of first non-blank line, starting from
18514 ;; line at POS.
18515 (lambda (pos)
18516 (save-excursion
18517 (goto-char pos)
18518 (skip-chars-forward " \r\t\n")
18519 (point-at-bol)))))
18520 beg end)
18521 ;; Determine boundaries of changes.
18522 (if (org-region-active-p)
18523 (setq beg (funcall skip-blanks (region-beginning))
18524 end (copy-marker (region-end)))
18525 (setq beg (funcall skip-blanks (point-at-bol))
18526 end (copy-marker (point-at-eol))))
18527 ;; Depending on the starting line, choose an action on the text
18528 ;; between BEG and END.
18529 (org-with-limited-levels
18530 (save-excursion
18531 (goto-char beg)
18532 (cond
18533 ;; Case 1. Start at an item: de-itemize. Note that it only
18534 ;; happens when a region is active: `org-ctrl-c-minus'
18535 ;; would call `org-cycle-list-bullet' otherwise.
18536 ((org-at-item-p)
18537 (while (< (point) end)
18538 (when (org-at-item-p)
18539 (skip-chars-forward " \t")
18540 (delete-region (point) (match-end 0)))
18541 (forward-line)))
18542 ;; Case 2. Start at an heading: convert to items.
18543 ((org-on-heading-p)
18544 (let* ((bul (org-list-bullet-string "-"))
18545 (bul-len (length bul))
18546 ;; Indentation of the first heading. It should be
18547 ;; relative to the indentation of its parent, if any.
18548 (start-ind (save-excursion
18549 (cond
18550 ((not org-adapt-indentation) 0)
18551 ((not (outline-previous-heading)) 0)
18552 (t (length (match-string 0))))))
18553 ;; Level of first heading. Further headings will be
18554 ;; compared to it to determine hierarchy in the list.
18555 (ref-level (org-reduced-level (org-outline-level))))
18556 (while (< (point) end)
18557 (let* ((level (org-reduced-level (org-outline-level)))
18558 (delta (max 0 (- level ref-level))))
18559 ;; If current headline is less indented than the first
18560 ;; one, set it as reference, in order to preserve
18561 ;; subtrees.
18562 (when (< level ref-level) (setq ref-level level))
18563 (replace-match bul t t)
18564 (org-indent-line-to (+ start-ind (* delta bul-len)))
18565 ;; Ensure all text down to END (or SECTION-END) belongs
18566 ;; to the newly created item.
18567 (let ((section-end (save-excursion
18568 (or (outline-next-heading) (point)))))
18569 (forward-line)
18570 (funcall shift-text
18571 (+ start-ind (* (1+ delta) bul-len))
18572 (min end section-end)))))))
18573 ;; Case 3. Normal line with ARG: turn each non-item line into
18574 ;; an item.
18575 (arg
18576 (while (< (point) end)
18577 (unless (or (org-on-heading-p) (org-at-item-p))
18578 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
18579 (replace-match
18580 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
18581 (forward-line)))
18582 ;; Case 4. Normal line without ARG: make the first line of
18583 ;; region an item, and shift indentation of others
18584 ;; lines to set them as item's body.
18585 (t (let* ((bul (org-list-bullet-string "-"))
18586 (bul-len (length bul))
18587 (ref-ind (org-get-indentation)))
18588 (skip-chars-forward " \t")
18589 (insert bul)
18590 (forward-line)
18591 (while (< (point) end)
18592 ;; Ensure that lines less indented than first one
18593 ;; still get included in item body.
18594 (funcall shift-text
18595 (+ ref-ind bul-len)
18596 (min end (save-excursion (or (outline-next-heading)
18597 (point)))))
18598 (forward-line)))))))))
18600 (defun org-toggle-heading (&optional nstars)
18601 "Convert headings to normal text, or items or text to headings.
18602 If there is no active region, only the current line is considered.
18604 If the first non blank line is an headline, remove the stars from
18605 all headlines in the region.
18607 If it is a plain list item, turn all plain list items into headings.
18609 If it is a normal line, turn each and every normal line (i.e. not
18610 an heading or an item) in the region into a heading.
18612 When converting a line into a heading, the number of stars is chosen
18613 such that the lines become children of the current entry. However,
18614 when a prefix argument is given, its value determines the number of
18615 stars to add."
18616 (interactive "P")
18617 (let ((skip-blanks
18618 (function
18619 ;; Return beginning of first non-blank line, starting from
18620 ;; line at POS.
18621 (lambda (pos)
18622 (save-excursion
18623 (goto-char pos)
18624 (skip-chars-forward " \r\t\n")
18625 (point-at-bol)))))
18626 beg end)
18627 ;; Determine boundaries of changes. If region ends at a bol, do
18628 ;; not consider the last line to be in the region.
18629 (if (org-region-active-p)
18630 (setq beg (funcall skip-blanks (region-beginning))
18631 end (copy-marker (save-excursion
18632 (goto-char (region-end))
18633 (if (bolp) (point) (point-at-eol)))))
18634 (setq beg (funcall skip-blanks (point-at-bol))
18635 end (copy-marker (point-at-eol))))
18636 ;; Ensure inline tasks don't count as headings.
18637 (org-with-limited-levels
18638 (save-excursion
18639 (goto-char beg)
18640 (cond
18641 ;; Case 1. Started at an heading: de-star headings.
18642 ((org-on-heading-p)
18643 (while (< (point) end)
18644 (when (org-on-heading-p t)
18645 (looking-at org-outline-regexp) (replace-match ""))
18646 (forward-line)))
18647 ;; Case 2. Started at an item: change items into headlines.
18648 ;; One star will be added by `org-list-to-subtree'.
18649 ((org-at-item-p)
18650 (let* ((stars (make-string
18651 (if nstars
18652 ;; subtract the star that will be added again by
18653 ;; `org-list-to-subtree'
18654 (1- (prefix-numeric-value current-prefix-arg))
18655 (or (org-current-level) 0))
18656 ?*))
18657 (add-stars
18658 (cond (nstars "") ; stars from prefix only
18659 ((equal stars "") "") ; before first heading
18660 (org-odd-levels-only "*") ; inside heading, odd
18661 (t "")))) ; inside heading, oddeven
18662 (while (< (point) end)
18663 (when (org-at-item-p)
18664 ;; Pay attention to cases when region ends before list.
18665 (let* ((struct (org-list-struct))
18666 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18667 (save-restriction
18668 (narrow-to-region (point) list-end)
18669 (insert
18670 (org-list-to-subtree
18671 (org-list-parse-list t)
18672 '(:istart (concat stars add-stars (funcall get-stars depth))
18673 :icount (concat stars add-stars (funcall get-stars depth))))))))
18674 (forward-line))))
18675 ;; Case 3. Started at normal text: make every line an heading,
18676 ;; skipping headlines and items.
18677 (t (let* ((stars (make-string
18678 (if nstars
18679 (prefix-numeric-value current-prefix-arg)
18680 (or (org-current-level) 0))
18681 ?*))
18682 (add-stars
18683 (cond (nstars "") ; stars from prefix only
18684 ((equal stars "") "*") ; before first heading
18685 (org-odd-levels-only "**") ; inside heading, odd
18686 (t "*"))) ; inside heading, oddeven
18687 (rpl (concat stars add-stars " ")))
18688 (while (< (point) end)
18689 (when (and (not (org-on-heading-p)) (not (org-at-item-p))
18690 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18691 (replace-match (concat rpl (match-string 2))))
18692 (forward-line)))))))))
18694 (defun org-meta-return (&optional arg)
18695 "Insert a new heading or wrap a region in a table.
18696 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18697 See the individual commands for more information."
18698 (interactive "P")
18699 (cond
18700 ((run-hook-with-args-until-success 'org-metareturn-hook))
18701 ((org-at-table-p)
18702 (call-interactively 'org-table-wrap-region))
18703 (t (call-interactively 'org-insert-heading))))
18705 ;;; Menu entries
18707 ;; Define the Org-mode menus
18708 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18709 '("Tbl"
18710 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18711 ["Next Field" org-cycle (org-at-table-p)]
18712 ["Previous Field" org-shifttab (org-at-table-p)]
18713 ["Next Row" org-return (org-at-table-p)]
18714 "--"
18715 ["Blank Field" org-table-blank-field (org-at-table-p)]
18716 ["Edit Field" org-table-edit-field (org-at-table-p)]
18717 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18718 "--"
18719 ("Column"
18720 ["Move Column Left" org-metaleft (org-at-table-p)]
18721 ["Move Column Right" org-metaright (org-at-table-p)]
18722 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18723 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18724 ("Row"
18725 ["Move Row Up" org-metaup (org-at-table-p)]
18726 ["Move Row Down" org-metadown (org-at-table-p)]
18727 ["Delete Row" org-shiftmetaup (org-at-table-p)]
18728 ["Insert Row" org-shiftmetadown (org-at-table-p)]
18729 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
18730 "--"
18731 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
18732 ("Rectangle"
18733 ["Copy Rectangle" org-copy-special (org-at-table-p)]
18734 ["Cut Rectangle" org-cut-special (org-at-table-p)]
18735 ["Paste Rectangle" org-paste-special (org-at-table-p)]
18736 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
18737 "--"
18738 ("Calculate"
18739 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
18740 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
18741 ["Edit Formulas" org-edit-special (org-at-table-p)]
18742 "--"
18743 ["Recalculate line" org-table-recalculate (org-at-table-p)]
18744 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
18745 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
18746 "--"
18747 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
18748 "--"
18749 ["Sum Column/Rectangle" org-table-sum
18750 (or (org-at-table-p) (org-region-active-p))]
18751 ["Which Column?" org-table-current-column (org-at-table-p)])
18752 ["Debug Formulas"
18753 org-table-toggle-formula-debugger
18754 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
18755 ["Show Col/Row Numbers"
18756 org-table-toggle-coordinate-overlays
18757 :style toggle
18758 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
18759 "--"
18760 ["Create" org-table-create (and (not (org-at-table-p))
18761 org-enable-table-editor)]
18762 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
18763 ["Import from File" org-table-import (not (org-at-table-p))]
18764 ["Export to File" org-table-export (org-at-table-p)]
18765 "--"
18766 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
18768 (easy-menu-define org-org-menu org-mode-map "Org menu"
18769 '("Org"
18770 ("Show/Hide"
18771 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
18772 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
18773 ["Sparse Tree..." org-sparse-tree t]
18774 ["Reveal Context" org-reveal t]
18775 ["Show All" show-all t]
18776 "--"
18777 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
18778 "--"
18779 ["New Heading" org-insert-heading t]
18780 ("Navigate Headings"
18781 ["Up" outline-up-heading t]
18782 ["Next" outline-next-visible-heading t]
18783 ["Previous" outline-previous-visible-heading t]
18784 ["Next Same Level" outline-forward-same-level t]
18785 ["Previous Same Level" outline-backward-same-level t]
18786 "--"
18787 ["Jump" org-goto t])
18788 ("Edit Structure"
18789 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
18790 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
18791 "--"
18792 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
18793 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
18794 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
18795 "--"
18796 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
18797 "--"
18798 ["Copy visible text" org-copy-visible t]
18799 "--"
18800 ["Promote Heading" org-metaleft (not (org-at-table-p))]
18801 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
18802 ["Demote Heading" org-metaright (not (org-at-table-p))]
18803 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
18804 "--"
18805 ["Sort Region/Children" org-sort (not (org-at-table-p))]
18806 "--"
18807 ["Convert to odd levels" org-convert-to-odd-levels t]
18808 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
18809 ("Editing"
18810 ["Emphasis..." org-emphasize t]
18811 ["Edit Source Example" org-edit-special t]
18812 "--"
18813 ["Footnote new/jump" org-footnote-action t]
18814 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
18815 ("Archive"
18816 ["Archive (default method)" org-archive-subtree-default t]
18817 "--"
18818 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
18819 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
18820 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
18822 "--"
18823 ("Hyperlinks"
18824 ["Store Link (Global)" org-store-link t]
18825 ["Find existing link to here" org-occur-link-in-agenda-files t]
18826 ["Insert Link" org-insert-link t]
18827 ["Follow Link" org-open-at-point t]
18828 "--"
18829 ["Next link" org-next-link t]
18830 ["Previous link" org-previous-link t]
18831 "--"
18832 ["Descriptive Links"
18833 org-toggle-link-display
18834 :style radio
18835 :selected org-descriptive-links
18837 ["Literal Links"
18838 org-toggle-link-display
18839 :style radio
18840 :selected (not org-descriptive-links)])
18841 "--"
18842 ("TODO Lists"
18843 ["TODO/DONE/-" org-todo t]
18844 ("Select keyword"
18845 ["Next keyword" org-shiftright (org-on-heading-p)]
18846 ["Previous keyword" org-shiftleft (org-on-heading-p)]
18847 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
18848 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
18849 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
18850 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
18851 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
18852 "--"
18853 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
18854 :selected org-enforce-todo-dependencies :style toggle :active t]
18855 "Settings for tree at point"
18856 ["Do Children sequentially" org-toggle-ordered-property :style radio
18857 :selected (org-entry-get nil "ORDERED")
18858 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18859 ["Do Children parallel" org-toggle-ordered-property :style radio
18860 :selected (not (org-entry-get nil "ORDERED"))
18861 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18862 "--"
18863 ["Set Priority" org-priority t]
18864 ["Priority Up" org-shiftup t]
18865 ["Priority Down" org-shiftdown t]
18866 "--"
18867 ["Get news from all feeds" org-feed-update-all t]
18868 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
18869 ["Customize feeds" (customize-variable 'org-feed-alist) t])
18870 ("TAGS and Properties"
18871 ["Set Tags" org-set-tags-command t]
18872 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
18873 "--"
18874 ["Set property" org-set-property t]
18875 ["Column view of properties" org-columns t]
18876 ["Insert Column View DBlock" org-insert-columns-dblock t])
18877 ("Dates and Scheduling"
18878 ["Timestamp" org-time-stamp t]
18879 ["Timestamp (inactive)" org-time-stamp-inactive t]
18880 ("Change Date"
18881 ["1 Day Later" org-shiftright t]
18882 ["1 Day Earlier" org-shiftleft t]
18883 ["1 ... Later" org-shiftup t]
18884 ["1 ... Earlier" org-shiftdown t])
18885 ["Compute Time Range" org-evaluate-time-range t]
18886 ["Schedule Item" org-schedule t]
18887 ["Deadline" org-deadline t]
18888 "--"
18889 ["Custom time format" org-toggle-time-stamp-overlays
18890 :style radio :selected org-display-custom-times]
18891 "--"
18892 ["Goto Calendar" org-goto-calendar t]
18893 ["Date from Calendar" org-date-from-calendar t]
18894 "--"
18895 ["Start/Restart Timer" org-timer-start t]
18896 ["Pause/Continue Timer" org-timer-pause-or-continue t]
18897 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
18898 ["Insert Timer String" org-timer t]
18899 ["Insert Timer Item" org-timer-item t])
18900 ("Logging work"
18901 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
18902 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
18903 ["Clock out" org-clock-out t]
18904 ["Clock cancel" org-clock-cancel t]
18905 "--"
18906 ["Mark as default task" org-clock-mark-default-task t]
18907 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
18908 ["Goto running clock" org-clock-goto t]
18909 "--"
18910 ["Display times" org-clock-display t]
18911 ["Create clock table" org-clock-report t]
18912 "--"
18913 ["Record DONE time"
18914 (progn (setq org-log-done (not org-log-done))
18915 (message "Switching to %s will %s record a timestamp"
18916 (car org-done-keywords)
18917 (if org-log-done "automatically" "not")))
18918 :style toggle :selected org-log-done])
18919 "--"
18920 ["Agenda Command..." org-agenda t]
18921 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
18922 ("File List for Agenda")
18923 ("Special views current file"
18924 ["TODO Tree" org-show-todo-tree t]
18925 ["Check Deadlines" org-check-deadlines t]
18926 ["Timeline" org-timeline t]
18927 ["Tags/Property tree" org-match-sparse-tree t])
18928 "--"
18929 ["Export/Publish..." org-export t]
18930 ("LaTeX"
18931 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
18932 :selected org-cdlatex-mode]
18933 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
18934 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
18935 ["Modify math symbol" org-cdlatex-math-modify
18936 (org-inside-LaTeX-fragment-p)]
18937 ["Insert citation" org-reftex-citation t]
18938 "--"
18939 ["Template for BEAMER" org-insert-beamer-options-template t])
18940 "--"
18941 ("MobileOrg"
18942 ["Push Files and Views" org-mobile-push t]
18943 ["Get Captured and Flagged" org-mobile-pull t]
18944 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
18945 "--"
18946 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
18947 "--"
18948 ("Documentation"
18949 ["Show Version" org-version t]
18950 ["Info Documentation" org-info t])
18951 ("Customize"
18952 ["Browse Org Group" org-customize t]
18953 "--"
18954 ["Expand This Menu" org-create-customize-menu
18955 (fboundp 'customize-menu-create)])
18956 ["Send bug report" org-submit-bug-report t]
18957 "--"
18958 ("Refresh/Reload"
18959 ["Refresh setup current buffer" org-mode-restart t]
18960 ["Reload Org (after update)" org-reload t]
18961 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
18964 (defun org-info (&optional node)
18965 "Read documentation for Org-mode in the info system.
18966 With optional NODE, go directly to that node."
18967 (interactive)
18968 (info (format "(org)%s" (or node ""))))
18970 ;;;###autoload
18971 (defun org-submit-bug-report ()
18972 "Submit a bug report on Org-mode via mail.
18974 Don't hesitate to report any problems or inaccurate documentation.
18976 If you don't have setup sending mail from (X)Emacs, please copy the
18977 output buffer into your mail program, as it gives us important
18978 information about your Org-mode version and configuration."
18979 (interactive)
18980 (require 'reporter)
18981 (org-load-modules-maybe)
18982 (org-require-autoloaded-modules)
18983 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
18984 (reporter-submit-bug-report
18985 "emacs-orgmode@gnu.org"
18986 (org-version)
18987 (let (list)
18988 (save-window-excursion
18989 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
18990 (delete-other-windows)
18991 (erase-buffer)
18992 (insert "You are about to submit a bug report to the Org-mode mailing list.
18994 We would like to add your full Org-mode and Outline configuration to the
18995 bug report. This greatly simplifies the work of the maintainer and
18996 other experts on the mailing list.
18998 HOWEVER, some variables you have customized may contain private
18999 information. The names of customers, colleagues, or friends, might
19000 appear in the form of file names, tags, todo states, or search strings.
19001 If you answer yes to the prompt, you might want to check and remove
19002 such private information before sending the email.")
19003 (add-text-properties (point-min) (point-max) '(face org-warning))
19004 (when (yes-or-no-p "Include your Org-mode configuration ")
19005 (mapatoms
19006 (lambda (v)
19007 (and (boundp v)
19008 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19009 (or (and (symbol-value v)
19010 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19011 (and
19012 (get v 'custom-type) (get v 'standard-value)
19013 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19014 (push v list)))))
19015 (kill-buffer (get-buffer "*Warn about privacy*"))
19016 list))
19017 nil nil
19018 "Remember to cover the basics, that is, what you expected to happen and
19019 what in fact did happen. You don't know how to make a good report? See
19021 http://orgmode.org/manual/Feedback.html#Feedback
19023 Your bug report will be posted to the Org-mode mailing list.
19024 ------------------------------------------------------------------------")
19025 (save-excursion
19026 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19027 (replace-match "\\1Bug: \\3 [\\2]")))))
19030 (defun org-install-agenda-files-menu ()
19031 (let ((bl (buffer-list)))
19032 (save-excursion
19033 (while bl
19034 (set-buffer (pop bl))
19035 (if (eq major-mode 'org-mode) (setq bl nil)))
19036 (when (eq major-mode 'org-mode)
19037 (easy-menu-change
19038 '("Org") "File List for Agenda"
19039 (append
19040 (list
19041 ["Edit File List" (org-edit-agenda-file-list) t]
19042 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19043 ["Remove Current File from List" org-remove-file t]
19044 ["Cycle through agenda files" org-cycle-agenda-files t]
19045 ["Occur in all agenda files" org-occur-in-agenda-files t]
19046 "--")
19047 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19049 ;;;; Documentation
19051 ;;;###autoload
19052 (defun org-require-autoloaded-modules ()
19053 (interactive)
19054 (mapc 'require
19055 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19056 org-docbook org-exp org-html org-icalendar
19057 org-id org-latex
19058 org-publish org-remember org-table
19059 org-timer org-xoxo)))
19061 ;;;###autoload
19062 (defun org-reload (&optional uncompiled)
19063 "Reload all org lisp files.
19064 With prefix arg UNCOMPILED, load the uncompiled versions."
19065 (interactive "P")
19066 (require 'find-func)
19067 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
19068 (dir-org (file-name-directory (org-find-library-name "org")))
19069 (dir-org-contrib (ignore-errors
19070 (file-name-directory
19071 (org-find-library-name "org-contribdir"))))
19072 (babel-files
19073 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19074 (append (list nil "comint" "eval" "exp" "keys"
19075 "lob" "ref" "table" "tangle")
19076 (delq nil
19077 (mapcar
19078 (lambda (lang)
19079 (when (cdr lang) (symbol-name (car lang))))
19080 org-babel-load-languages)))))
19081 (files
19082 (append (directory-files dir-org t file-re)
19083 babel-files
19084 (and dir-org-contrib
19085 (directory-files dir-org-contrib t file-re))))
19086 (remove-re (concat (if (featurep 'xemacs)
19087 "org-colview" "org-colview-xemacs")
19088 "\\'")))
19089 (setq files (mapcar 'file-name-sans-extension files))
19090 (setq files (mapcar
19091 (lambda (x) (if (string-match remove-re x) nil x))
19092 files))
19093 (setq files (delq nil files))
19094 (mapc
19095 (lambda (f)
19096 (when (featurep (intern (file-name-nondirectory f)))
19097 (if (and (not uncompiled)
19098 (file-exists-p (concat f ".elc")))
19099 (load (concat f ".elc") nil nil t)
19100 (load (concat f ".el") nil nil t))))
19101 files))
19102 (org-version))
19104 ;;;###autoload
19105 (defun org-customize ()
19106 "Call the customize function with org as argument."
19107 (interactive)
19108 (org-load-modules-maybe)
19109 (org-require-autoloaded-modules)
19110 (customize-browse 'org))
19112 (defun org-create-customize-menu ()
19113 "Create a full customization menu for Org-mode, insert it into the menu."
19114 (interactive)
19115 (org-load-modules-maybe)
19116 (org-require-autoloaded-modules)
19117 (if (fboundp 'customize-menu-create)
19118 (progn
19119 (easy-menu-change
19120 '("Org") "Customize"
19121 `(["Browse Org group" org-customize t]
19122 "--"
19123 ,(customize-menu-create 'org)
19124 ["Set" Custom-set t]
19125 ["Save" Custom-save t]
19126 ["Reset to Current" Custom-reset-current t]
19127 ["Reset to Saved" Custom-reset-saved t]
19128 ["Reset to Standard Settings" Custom-reset-standard t]))
19129 (message "\"Org\"-menu now contains full customization menu"))
19130 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19132 ;;;; Miscellaneous stuff
19134 ;;; Generally useful functions
19136 (defun org-get-at-bol (property)
19137 "Get text property PROPERTY at beginning of line."
19138 (get-text-property (point-at-bol) property))
19140 (defun org-find-text-property-in-string (prop s)
19141 "Return the first non-nil value of property PROP in string S."
19142 (or (get-text-property 0 prop s)
19143 (get-text-property (or (next-single-property-change 0 prop s) 0)
19144 prop s)))
19146 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19147 "Display the given MESSAGE as a warning."
19148 (if (fboundp 'display-warning)
19149 (display-warning 'org message
19150 (if (featurep 'xemacs) 'warning :warning))
19151 (let ((buf (get-buffer-create "*Org warnings*")))
19152 (with-current-buffer buf
19153 (goto-char (point-max))
19154 (insert "Warning (Org): " message)
19155 (unless (bolp)
19156 (newline)))
19157 (display-buffer buf)
19158 (sit-for 0))))
19160 (defun org-eval (form)
19161 "Eval FORM and return result."
19162 (condition-case error
19163 (eval form)
19164 (error (format "%%![Error: %s]" error))))
19166 (defun org-in-commented-line ()
19167 "Is point in a line starting with `#'?"
19168 (equal (char-after (point-at-bol)) ?#))
19170 (defun org-in-indented-comment-line ()
19171 "Is point in a line starting with `#' after some white space?"
19172 (save-excursion
19173 (save-match-data
19174 (goto-char (point-at-bol))
19175 (looking-at "[ \t]*#"))))
19177 (defun org-in-verbatim-emphasis ()
19178 (save-match-data
19179 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19181 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19182 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19183 (if (and marker (marker-buffer marker)
19184 (buffer-live-p (marker-buffer marker)))
19185 (progn
19186 (org-pop-to-buffer-same-window (marker-buffer marker))
19187 (if (or (> marker (point-max)) (< marker (point-min)))
19188 (widen))
19189 (goto-char marker)
19190 (org-show-context 'org-goto))
19191 (if bookmark
19192 (bookmark-jump bookmark)
19193 (error "Cannot find location"))))
19195 (defun org-quote-csv-field (s)
19196 "Quote field for inclusion in CSV material."
19197 (if (string-match "[\",]" s)
19198 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19201 (defun org-force-self-insert (N)
19202 "Needed to enforce self-insert under remapping."
19203 (interactive "p")
19204 (self-insert-command N))
19206 (defun org-string-width (s)
19207 "Compute width of string, ignoring invisible characters.
19208 This ignores character with invisibility property `org-link', and also
19209 characters with property `org-cwidth', because these will become invisible
19210 upon the next fontification round."
19211 (let (b l)
19212 (when (or (eq t buffer-invisibility-spec)
19213 (assq 'org-link buffer-invisibility-spec))
19214 (while (setq b (text-property-any 0 (length s)
19215 'invisible 'org-link s))
19216 (setq s (concat (substring s 0 b)
19217 (substring s (or (next-single-property-change
19218 b 'invisible s) (length s)))))))
19219 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19220 (setq s (concat (substring s 0 b)
19221 (substring s (or (next-single-property-change
19222 b 'org-cwidth s) (length s))))))
19223 (setq l (string-width s) b -1)
19224 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19225 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19228 (defun org-shorten-string (s maxlength)
19229 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19230 If the string is shorter or has length MAXLENGTH, just return the
19231 original string. If it is longer, the functions finds a space in the
19232 string, breaks this string off at that locations and adds three dots
19233 as ellipsis. Including the ellipsis, the string will not be longer
19234 than MAXLENGTH. If finding a good breaking point in the string does
19235 not work, the string is just chopped off in the middle of a word
19236 if necessary."
19237 (if (<= (length s) maxlength)
19239 (let* ((n (max (- maxlength 4) 1))
19240 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19241 (if (string-match re s)
19242 (concat (match-string 1 s) "...")
19243 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19245 (defun org-get-indentation (&optional line)
19246 "Get the indentation of the current line, interpreting tabs.
19247 When LINE is given, assume it represents a line and compute its indentation."
19248 (if line
19249 (if (string-match "^ *" (org-remove-tabs line))
19250 (match-end 0))
19251 (save-excursion
19252 (beginning-of-line 1)
19253 (skip-chars-forward " \t")
19254 (current-column))))
19256 (defun org-get-string-indentation (s)
19257 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19258 (let ((n -1) (i 0) (w tab-width) c)
19259 (catch 'exit
19260 (while (< (setq n (1+ n)) (length s))
19261 (setq c (aref s n))
19262 (cond ((= c ?\ ) (setq i (1+ i)))
19263 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19264 (t (throw 'exit t)))))
19267 (defun org-remove-tabs (s &optional width)
19268 "Replace tabulators in S with spaces.
19269 Assumes that s is a single line, starting in column 0."
19270 (setq width (or width tab-width))
19271 (while (string-match "\t" s)
19272 (setq s (replace-match
19273 (make-string
19274 (- (* width (/ (+ (match-beginning 0) width) width))
19275 (match-beginning 0)) ?\ )
19276 t t s)))
19279 (defun org-fix-indentation (line ind)
19280 "Fix indentation in LINE.
19281 IND is a cons cell with target and minimum indentation.
19282 If the current indentation in LINE is smaller than the minimum,
19283 leave it alone. If it is larger than ind, set it to the target."
19284 (let* ((l (org-remove-tabs line))
19285 (i (org-get-indentation l))
19286 (i1 (car ind)) (i2 (cdr ind)))
19287 (if (>= i i2) (setq l (substring line i2)))
19288 (if (> i1 0)
19289 (concat (make-string i1 ?\ ) l)
19290 l)))
19292 (defun org-remove-indentation (code &optional n)
19293 "Remove the maximum common indentation from the lines in CODE.
19294 N may optionally be the number of spaces to remove."
19295 (with-temp-buffer
19296 (insert code)
19297 (org-do-remove-indentation n)
19298 (buffer-string)))
19300 (defun org-do-remove-indentation (&optional n)
19301 "Remove the maximum common indentation from the buffer."
19302 (untabify (point-min) (point-max))
19303 (let ((min 10000) re)
19304 (if n
19305 (setq min n)
19306 (goto-char (point-min))
19307 (while (re-search-forward "^ *[^ \n]" nil t)
19308 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19309 (unless (or (= min 0) (= min 10000))
19310 (setq re (format "^ \\{%d\\}" min))
19311 (goto-char (point-min))
19312 (while (re-search-forward re nil t)
19313 (replace-match "")
19314 (end-of-line 1))
19315 min)))
19317 (defun org-fill-template (template alist)
19318 "Find each %key of ALIST in TEMPLATE and replace it."
19319 (let ((case-fold-search nil)
19320 entry key value)
19321 (setq alist (sort (copy-sequence alist)
19322 (lambda (a b) (< (length (car a)) (length (car b))))))
19323 (while (setq entry (pop alist))
19324 (setq template
19325 (replace-regexp-in-string
19326 (concat "%" (regexp-quote (car entry)))
19327 (cdr entry) template t t)))
19328 template))
19330 (defun org-base-buffer (buffer)
19331 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19332 (if (not buffer)
19333 buffer
19334 (or (buffer-base-buffer buffer)
19335 buffer)))
19337 (defun org-trim (s)
19338 "Remove whitespace at beginning and end of string."
19339 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19340 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19343 (defun org-wrap (string &optional width lines)
19344 "Wrap string to either a number of lines, or a width in characters.
19345 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19346 that costs. If there is a word longer than WIDTH, the text is actually
19347 wrapped to the length of that word.
19348 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19349 many lines, whatever width that takes.
19350 The return value is a list of lines, without newlines at the end."
19351 (let* ((words (org-split-string string "[ \t\n]+"))
19352 (maxword (apply 'max (mapcar 'org-string-width words)))
19353 w ll)
19354 (cond (width
19355 (org-do-wrap words (max maxword width)))
19356 (lines
19357 (setq w maxword)
19358 (setq ll (org-do-wrap words maxword))
19359 (if (<= (length ll) lines)
19361 (setq ll words)
19362 (while (> (length ll) lines)
19363 (setq w (1+ w))
19364 (setq ll (org-do-wrap words w)))
19365 ll))
19366 (t (error "Cannot wrap this")))))
19368 (defun org-do-wrap (words width)
19369 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19370 (let (lines line)
19371 (while words
19372 (setq line (pop words))
19373 (while (and words (< (+ (length line) (length (car words))) width))
19374 (setq line (concat line " " (pop words))))
19375 (setq lines (push line lines)))
19376 (nreverse lines)))
19378 (defun org-split-string (string &optional separators)
19379 "Splits STRING into substrings at SEPARATORS.
19380 No empty strings are returned if there are matches at the beginning
19381 and end of string."
19382 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19383 (start 0)
19384 notfirst
19385 (list nil))
19386 (while (and (string-match rexp string
19387 (if (and notfirst
19388 (= start (match-beginning 0))
19389 (< start (length string)))
19390 (1+ start) start))
19391 (< (match-beginning 0) (length string)))
19392 (setq notfirst t)
19393 (or (eq (match-beginning 0) 0)
19394 (and (eq (match-beginning 0) (match-end 0))
19395 (eq (match-beginning 0) start))
19396 (setq list
19397 (cons (substring string start (match-beginning 0))
19398 list)))
19399 (setq start (match-end 0)))
19400 (or (eq start (length string))
19401 (setq list
19402 (cons (substring string start)
19403 list)))
19404 (nreverse list)))
19406 (defun org-quote-vert (s)
19407 "Replace \"|\" with \"\\vert\"."
19408 (while (string-match "|" s)
19409 (setq s (replace-match "\\vert" t t s)))
19412 (defun org-uuidgen-p (s)
19413 "Is S an ID created by UUIDGEN?"
19414 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19416 (defun org-context ()
19417 "Return a list of contexts of the current cursor position.
19418 If several contexts apply, all are returned.
19419 Each context entry is a list with a symbol naming the context, and
19420 two positions indicating start and end of the context. Possible
19421 contexts are:
19423 :headline anywhere in a headline
19424 :headline-stars on the leading stars in a headline
19425 :todo-keyword on a TODO keyword (including DONE) in a headline
19426 :tags on the TAGS in a headline
19427 :priority on the priority cookie in a headline
19428 :item on the first line of a plain list item
19429 :item-bullet on the bullet/number of a plain list item
19430 :checkbox on the checkbox in a plain list item
19431 :table in an org-mode table
19432 :table-special on a special filed in a table
19433 :table-table in a table.el table
19434 :link on a hyperlink
19435 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
19436 :target on a <<target>>
19437 :radio-target on a <<<radio-target>>>
19438 :latex-fragment on a LaTeX fragment
19439 :latex-preview on a LaTeX fragment with overlaid preview image
19441 This function expects the position to be visible because it uses font-lock
19442 faces as a help to recognize the following contexts: :table-special, :link,
19443 and :keyword."
19444 (let* ((f (get-text-property (point) 'face))
19445 (faces (if (listp f) f (list f)))
19446 (p (point)) clist o)
19447 ;; First the large context
19448 (cond
19449 ((org-on-heading-p t)
19450 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19451 (when (progn
19452 (beginning-of-line 1)
19453 (looking-at org-todo-line-tags-regexp))
19454 (push (org-point-in-group p 1 :headline-stars) clist)
19455 (push (org-point-in-group p 2 :todo-keyword) clist)
19456 (push (org-point-in-group p 4 :tags) clist))
19457 (goto-char p)
19458 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19459 (if (looking-at "\\[#[A-Z0-9]\\]")
19460 (push (org-point-in-group p 0 :priority) clist)))
19462 ((org-at-item-p)
19463 (push (org-point-in-group p 2 :item-bullet) clist)
19464 (push (list :item (point-at-bol)
19465 (save-excursion (org-end-of-item) (point)))
19466 clist)
19467 (and (org-at-item-checkbox-p)
19468 (push (org-point-in-group p 0 :checkbox) clist)))
19470 ((org-at-table-p)
19471 (push (list :table (org-table-begin) (org-table-end)) clist)
19472 (if (memq 'org-formula faces)
19473 (push (list :table-special
19474 (previous-single-property-change p 'face)
19475 (next-single-property-change p 'face)) clist)))
19476 ((org-at-table-p 'any)
19477 (push (list :table-table) clist)))
19478 (goto-char p)
19480 ;; Now the small context
19481 (cond
19482 ((org-at-timestamp-p)
19483 (push (org-point-in-group p 0 :timestamp) clist))
19484 ((memq 'org-link faces)
19485 (push (list :link
19486 (previous-single-property-change p 'face)
19487 (next-single-property-change p 'face)) clist))
19488 ((memq 'org-special-keyword faces)
19489 (push (list :keyword
19490 (previous-single-property-change p 'face)
19491 (next-single-property-change p 'face)) clist))
19492 ((org-on-target-p)
19493 (push (org-point-in-group p 0 :target) clist)
19494 (goto-char (1- (match-beginning 0)))
19495 (if (looking-at org-radio-target-regexp)
19496 (push (org-point-in-group p 0 :radio-target) clist))
19497 (goto-char p))
19498 ((setq o (car (delq nil
19499 (mapcar
19500 (lambda (x)
19501 (if (memq x org-latex-fragment-image-overlays) x))
19502 (overlays-at (point))))))
19503 (push (list :latex-fragment
19504 (overlay-start o) (overlay-end o)) clist)
19505 (push (list :latex-preview
19506 (overlay-start o) (overlay-end o)) clist))
19507 ((org-inside-LaTeX-fragment-p)
19508 ;; FIXME: positions wrong.
19509 (push (list :latex-fragment (point) (point)) clist)))
19511 (setq clist (nreverse (delq nil clist)))
19512 clist))
19514 ;; FIXME: Compare with at-regexp-p Do we need both?
19515 (defun org-in-regexp (re &optional nlines visually)
19516 "Check if point is inside a match of regexp.
19517 Normally only the current line is checked, but you can include NLINES extra
19518 lines both before and after point into the search.
19519 If VISUALLY is set, require that the cursor is not after the match but
19520 really on, so that the block visually is on the match."
19521 (catch 'exit
19522 (let ((pos (point))
19523 (eol (point-at-eol (+ 1 (or nlines 0))))
19524 (inc (if visually 1 0)))
19525 (save-excursion
19526 (beginning-of-line (- 1 (or nlines 0)))
19527 (while (re-search-forward re eol t)
19528 (if (and (<= (match-beginning 0) pos)
19529 (>= (+ inc (match-end 0)) pos))
19530 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
19532 (defun org-at-regexp-p (regexp)
19533 "Is point inside a match of REGEXP in the current line?"
19534 (catch 'exit
19535 (save-excursion
19536 (let ((pos (point)) (end (point-at-eol)))
19537 (beginning-of-line 1)
19538 (while (re-search-forward regexp end t)
19539 (if (and (<= (match-beginning 0) pos)
19540 (>= (match-end 0) pos))
19541 (throw 'exit t)))
19542 nil))))
19544 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
19545 "Non-nil when point is between matches of START-RE and END-RE.
19547 Also return a non-nil value when point is on one of the matches.
19549 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
19550 buffer positions. Default values are the positions of headlines
19551 surrounding the point.
19553 The functions returns a cons cell whose car (resp. cdr) is the
19554 position before START-RE (resp. after END-RE)."
19555 (save-match-data
19556 (let ((pos (point))
19557 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
19558 (limit-down (or lim-down (save-excursion (outline-next-heading))))
19559 beg end)
19560 (save-excursion
19561 ;; Point is on a block when on START-RE or if START-RE can be
19562 ;; found before it...
19563 (and (or (org-at-regexp-p start-re)
19564 (re-search-backward start-re limit-up t))
19565 (setq beg (match-beginning 0))
19566 ;; ... and END-RE after it...
19567 (goto-char (match-end 0))
19568 (re-search-forward end-re limit-down t)
19569 (> (setq end (match-end 0)) pos)
19570 ;; ... without another START-RE in-between.
19571 (goto-char (match-beginning 0))
19572 (not (re-search-backward start-re (1+ beg) t))
19573 ;; Return value.
19574 (cons beg end))))))
19576 (defun org-in-block-p (names)
19577 "Non-nil when point belongs to a block whose name belongs to NAMES.
19579 NAMES is a list of strings containing names of blocks.
19581 Return first block name matched, or nil. Beware that in case of
19582 nested blocks, the returned name may not belong to the closest
19583 block from point."
19584 (save-match-data
19585 (catch 'exit
19586 (let ((case-fold-search t)
19587 (lim-up (save-excursion (outline-previous-heading)))
19588 (lim-down (save-excursion (outline-next-heading))))
19589 (mapc (lambda (name)
19590 (let ((n (regexp-quote name)))
19591 (when (org-between-regexps-p
19592 (concat "^[ \t]*#\\+begin_" n)
19593 (concat "^[ \t]*#\\+end_" n)
19594 lim-up lim-down)
19595 (throw 'exit n))))
19596 names))
19597 nil)))
19599 (defun org-occur-in-agenda-files (regexp &optional nlines)
19600 "Call `multi-occur' with buffers for all agenda files."
19601 (interactive "sOrg-files matching: \np")
19602 (let* ((files (org-agenda-files))
19603 (tnames (mapcar 'file-truename files))
19604 (extra org-agenda-text-search-extra-files)
19606 (when (eq (car extra) 'agenda-archives)
19607 (setq extra (cdr extra))
19608 (setq files (org-add-archive-files files)))
19609 (while (setq f (pop extra))
19610 (unless (member (file-truename f) tnames)
19611 (add-to-list 'files f 'append)
19612 (add-to-list 'tnames (file-truename f) 'append)))
19613 (multi-occur
19614 (mapcar (lambda (x)
19615 (with-current-buffer
19616 (or (get-file-buffer x) (find-file-noselect x))
19617 (widen)
19618 (current-buffer)))
19619 files)
19620 regexp)))
19622 (if (boundp 'occur-mode-find-occurrence-hook)
19623 ;; Emacs 23
19624 (add-hook 'occur-mode-find-occurrence-hook
19625 (lambda ()
19626 (when (eq major-mode 'org-mode)
19627 (org-reveal))))
19628 ;; Emacs 22
19629 (defadvice occur-mode-goto-occurrence
19630 (after org-occur-reveal activate)
19631 (and (eq major-mode 'org-mode) (org-reveal)))
19632 (defadvice occur-mode-goto-occurrence-other-window
19633 (after org-occur-reveal activate)
19634 (and (eq major-mode 'org-mode) (org-reveal)))
19635 (defadvice occur-mode-display-occurrence
19636 (after org-occur-reveal activate)
19637 (when (eq major-mode 'org-mode)
19638 (let ((pos (occur-mode-find-occurrence)))
19639 (with-current-buffer (marker-buffer pos)
19640 (save-excursion
19641 (goto-char pos)
19642 (org-reveal)))))))
19644 (defun org-occur-link-in-agenda-files ()
19645 "Create a link and search for it in the agendas.
19646 The link is not stored in `org-stored-links', it is just created
19647 for the search purpose."
19648 (interactive)
19649 (let ((link (condition-case nil
19650 (org-store-link nil)
19651 (error "Unable to create a link to here"))))
19652 (org-occur-in-agenda-files (regexp-quote link))))
19654 (defun org-uniquify (list)
19655 "Remove duplicate elements from LIST."
19656 (let (res)
19657 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
19658 res))
19660 (defun org-delete-all (elts list)
19661 "Remove all elements in ELTS from LIST."
19662 (while elts
19663 (setq list (delete (pop elts) list)))
19664 list)
19666 (defun org-count (cl-item cl-seq)
19667 "Count the number of occurrences of ITEM in SEQ.
19668 Taken from `count' in cl-seq.el with all keyword arguments removed."
19669 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
19670 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
19671 (while (< cl-start cl-end)
19672 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
19673 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
19674 (setq cl-start (1+ cl-start)))
19675 cl-count))
19677 (defun org-remove-if (predicate seq)
19678 "Remove everything from SEQ that fulfills PREDICATE."
19679 (let (res e)
19680 (while seq
19681 (setq e (pop seq))
19682 (if (not (funcall predicate e)) (push e res)))
19683 (nreverse res)))
19685 (defun org-remove-if-not (predicate seq)
19686 "Remove everything from SEQ that does not fulfill PREDICATE."
19687 (let (res e)
19688 (while seq
19689 (setq e (pop seq))
19690 (if (funcall predicate e) (push e res)))
19691 (nreverse res)))
19693 (defun org-reduce (cl-func cl-seq &rest cl-keys)
19694 "Reduce two-argument FUNCTION across SEQ.
19695 Taken from `reduce' in cl-seq.el with all keyword arguments but
19696 \":initial-value\" removed."
19697 (let ((cl-accum (cond ((memq :initial-value cl-keys)
19698 (cadr (memq :initial-value cl-keys)))
19699 (cl-seq (pop cl-seq))
19700 (t (funcall cl-func)))))
19701 (while cl-seq
19702 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
19703 cl-accum))
19705 (defun org-back-over-empty-lines ()
19706 "Move backwards over whitespace, to the beginning of the first empty line.
19707 Returns the number of empty lines passed."
19708 (let ((pos (point)))
19709 (if (cdr (assoc 'heading org-blank-before-new-entry))
19710 (skip-chars-backward " \t\n\r")
19711 (unless (eobp)
19712 (forward-line -1)))
19713 (beginning-of-line 2)
19714 (goto-char (min (point) pos))
19715 (count-lines (point) pos)))
19717 (defun org-skip-whitespace ()
19718 (skip-chars-forward " \t\n\r"))
19720 (defun org-point-in-group (point group &optional context)
19721 "Check if POINT is in match-group GROUP.
19722 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
19723 match. If the match group does not exist or point is not inside it,
19724 return nil."
19725 (and (match-beginning group)
19726 (>= point (match-beginning group))
19727 (<= point (match-end group))
19728 (if context
19729 (list context (match-beginning group) (match-end group))
19730 t)))
19732 (defun org-switch-to-buffer-other-window (&rest args)
19733 "Switch to buffer in a second window on the current frame.
19734 In particular, do not allow pop-up frames.
19735 Returns the newly created buffer."
19736 (let (pop-up-frames special-display-buffer-names special-display-regexps
19737 special-display-function)
19738 (apply 'switch-to-buffer-other-window args)))
19740 (defun org-combine-plists (&rest plists)
19741 "Create a single property list from all plists in PLISTS.
19742 The process starts by copying the first list, and then setting properties
19743 from the other lists. Settings in the last list are the most significant
19744 ones and overrule settings in the other lists."
19745 (let ((rtn (copy-sequence (pop plists)))
19746 p v ls)
19747 (while plists
19748 (setq ls (pop plists))
19749 (while ls
19750 (setq p (pop ls) v (pop ls))
19751 (setq rtn (plist-put rtn p v))))
19752 rtn))
19754 (defun org-move-line-down (arg)
19755 "Move the current line down. With prefix argument, move it past ARG lines."
19756 (interactive "p")
19757 (let ((col (current-column))
19758 beg end pos)
19759 (beginning-of-line 1) (setq beg (point))
19760 (beginning-of-line 2) (setq end (point))
19761 (beginning-of-line (+ 1 arg))
19762 (setq pos (move-marker (make-marker) (point)))
19763 (insert (delete-and-extract-region beg end))
19764 (goto-char pos)
19765 (org-move-to-column col)))
19767 (defun org-move-line-up (arg)
19768 "Move the current line up. With prefix argument, move it past ARG lines."
19769 (interactive "p")
19770 (let ((col (current-column))
19771 beg end pos)
19772 (beginning-of-line 1) (setq beg (point))
19773 (beginning-of-line 2) (setq end (point))
19774 (beginning-of-line (- arg))
19775 (setq pos (move-marker (make-marker) (point)))
19776 (insert (delete-and-extract-region beg end))
19777 (goto-char pos)
19778 (org-move-to-column col)))
19780 (defun org-replace-escapes (string table)
19781 "Replace %-escapes in STRING with values in TABLE.
19782 TABLE is an association list with keys like \"%a\" and string values.
19783 The sequences in STRING may contain normal field width and padding information,
19784 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
19785 so values can contain further %-escapes if they are define later in TABLE."
19786 (let ((tbl (copy-alist table))
19787 (case-fold-search nil)
19788 (pchg 0)
19789 e re rpl)
19790 (while (setq e (pop tbl))
19791 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
19792 (when (and (cdr e) (string-match re (cdr e)))
19793 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
19794 (safe "SREF"))
19795 (add-text-properties 0 3 (list 'sref sref) safe)
19796 (setcdr e (replace-match safe t t (cdr e)))))
19797 (while (string-match re string)
19798 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
19799 (cdr e)))
19800 (setq string (replace-match rpl t t string))))
19801 (while (setq pchg (next-property-change pchg string))
19802 (let ((sref (get-text-property pchg 'sref string)))
19803 (when (and sref (string-match "SREF" string pchg))
19804 (setq string (replace-match sref t t string)))))
19805 string))
19807 (defun org-sublist (list start end)
19808 "Return a section of LIST, from START to END.
19809 Counting starts at 1."
19810 (let (rtn (c start))
19811 (setq list (nthcdr (1- start) list))
19812 (while (and list (<= c end))
19813 (push (pop list) rtn)
19814 (setq c (1+ c)))
19815 (nreverse rtn)))
19817 (defun org-find-base-buffer-visiting (file)
19818 "Like `find-buffer-visiting' but always return the base buffer and
19819 not an indirect buffer."
19820 (let ((buf (or (get-file-buffer file)
19821 (find-buffer-visiting file))))
19822 (if buf
19823 (or (buffer-base-buffer buf) buf)
19824 nil)))
19826 (defun org-image-file-name-regexp (&optional extensions)
19827 "Return regexp matching the file names of images.
19828 If EXTENSIONS is given, only match these."
19829 (if (and (not extensions) (fboundp 'image-file-name-regexp))
19830 (image-file-name-regexp)
19831 (let ((image-file-name-extensions
19832 (or extensions
19833 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
19834 "xbm" "xpm" "pbm" "pgm" "ppm"))))
19835 (concat "\\."
19836 (regexp-opt (nconc (mapcar 'upcase
19837 image-file-name-extensions)
19838 image-file-name-extensions)
19840 "\\'"))))
19842 (defun org-file-image-p (file &optional extensions)
19843 "Return non-nil if FILE is an image."
19844 (save-match-data
19845 (string-match (org-image-file-name-regexp extensions) file)))
19847 (defun org-get-cursor-date ()
19848 "Return the date at cursor in as a time.
19849 This works in the calendar and in the agenda, anywhere else it just
19850 returns the current time."
19851 (let (date day defd)
19852 (cond
19853 ((eq major-mode 'calendar-mode)
19854 (setq date (calendar-cursor-to-date)
19855 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
19856 ((eq major-mode 'org-agenda-mode)
19857 (setq day (get-text-property (point) 'day))
19858 (if day
19859 (setq date (calendar-gregorian-from-absolute day)
19860 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
19861 (nth 2 date))))))
19862 (or defd (current-time))))
19864 (defvar org-agenda-action-marker (make-marker)
19865 "Marker pointing to the entry for the next agenda action.")
19867 (defun org-mark-entry-for-agenda-action ()
19868 "Mark the current entry as target of an agenda action.
19869 Agenda actions are actions executed from the agenda with the key `k',
19870 which make use of the date at the cursor."
19871 (interactive)
19872 (move-marker org-agenda-action-marker
19873 (save-excursion (org-back-to-heading t) (point))
19874 (current-buffer))
19875 (message
19876 "Entry marked for action; press `k' at desired date in agenda or calendar"))
19878 (defun org-mark-subtree ()
19879 "Mark the current subtree.
19880 This puts point at the start of the current subtree, and mark at the end.
19882 If point is in an inline task, mark that task instead."
19883 (interactive)
19884 (let ((inline-task-p
19885 (and (featurep 'org-inlinetask)
19886 (org-inlinetask-in-task-p)))
19887 (beg))
19888 ;; Get beginning of subtree
19889 (cond
19890 (inline-task-p (org-inlinetask-goto-beginning))
19891 ((org-at-heading-p) (beginning-of-line))
19892 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
19893 (setq beg (point))
19894 ;; Get end of it
19895 (if inline-task-p
19896 (org-inlinetask-goto-end)
19897 (org-end-of-subtree))
19898 ;; Mark zone
19899 (push-mark (point) nil t)
19900 (goto-char beg)))
19902 ;;; Paragraph filling stuff.
19903 ;; We want this to be just right, so use the full arsenal.
19905 (defun org-indent-line-function ()
19906 "Indent line depending on context."
19907 (interactive)
19908 (let* ((pos (point))
19909 (itemp (org-at-item-p))
19910 (case-fold-search t)
19911 (org-drawer-regexp (or org-drawer-regexp "\000"))
19912 (inline-task-p (and (featurep 'org-inlinetask)
19913 (org-inlinetask-in-task-p)))
19914 (inline-re (and inline-task-p
19915 (org-inlinetask-outline-regexp)))
19916 column)
19917 (beginning-of-line 1)
19918 (cond
19919 ;; Comments
19920 ((looking-at "# ") (setq column 0))
19921 ;; Headings
19922 ((looking-at org-outline-regexp) (setq column 0))
19923 ;; Included files
19924 ((looking-at "#\\+include:") (setq column 0))
19925 ;; Footnote definition
19926 ((looking-at org-footnote-definition-re) (setq column 0))
19927 ;; Literal examples
19928 ((looking-at "[ \t]*:\\( \\|$\\)")
19929 (setq column (org-get-indentation))) ; do nothing
19930 ;; Lists
19931 ((ignore-errors (goto-char (org-in-item-p)))
19932 (setq column (if itemp
19933 (org-get-indentation)
19934 (org-list-item-body-column (point))))
19935 (goto-char pos))
19936 ;; Drawers
19937 ((and (looking-at "[ \t]*:END:")
19938 (save-excursion (re-search-backward org-drawer-regexp nil t)))
19939 (save-excursion
19940 (goto-char (1- (match-beginning 1)))
19941 (setq column (current-column))))
19942 ;; Special blocks
19943 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
19944 (save-excursion
19945 (re-search-backward
19946 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
19947 (setq column (org-get-indentation (match-string 0))))
19948 ((and (not (looking-at "[ \t]*#\\+begin_"))
19949 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
19950 (save-excursion
19951 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
19952 (setq column
19953 (cond ((equal (downcase (match-string 1)) "src")
19954 ;; src blocks: let `org-edit-src-exit' handle them
19955 (org-get-indentation))
19956 ((equal (downcase (match-string 1)) "example")
19957 (max (org-get-indentation)
19958 (org-get-indentation (match-string 0))))
19960 (org-get-indentation (match-string 0))))))
19961 ;; This line has nothing special, look at the previous relevant
19962 ;; line to compute indentation
19964 (beginning-of-line 0)
19965 (while (and (not (bobp))
19966 (not (looking-at org-drawer-regexp))
19967 ;; When point started in an inline task, do not move
19968 ;; above task starting line.
19969 (not (and inline-task-p (looking-at inline-re)))
19970 ;; Skip drawers, blocks, empty lines, verbatim,
19971 ;; comments, tables, footnotes definitions, lists,
19972 ;; inline tasks.
19973 (or (and (looking-at "[ \t]*:END:")
19974 (re-search-backward org-drawer-regexp nil t))
19975 (and (looking-at "[ \t]*#\\+end_")
19976 (re-search-backward "[ \t]*#\\+begin_"nil t))
19977 (looking-at "[ \t]*[\n:#|]")
19978 (looking-at org-footnote-definition-re)
19979 (and (ignore-errors (goto-char (org-in-item-p)))
19980 (goto-char
19981 (org-list-get-top-point (org-list-struct))))
19982 (and (not inline-task-p)
19983 (featurep 'org-inlinetask)
19984 (org-inlinetask-in-task-p)
19985 (or (org-inlinetask-goto-beginning) t))))
19986 (beginning-of-line 0))
19987 (cond
19988 ;; There was an heading above.
19989 ((looking-at "\\*+[ \t]+")
19990 (if (not org-adapt-indentation)
19991 (setq column 0)
19992 (goto-char (match-end 0))
19993 (setq column (current-column))))
19994 ;; A drawer had started and is unfinished
19995 ((looking-at org-drawer-regexp)
19996 (goto-char (1- (match-beginning 1)))
19997 (setq column (current-column)))
19998 ;; Else, nothing noticeable found: get indentation and go on.
19999 (t (setq column (org-get-indentation))))))
20000 ;; Now apply indentation and move cursor accordingly
20001 (goto-char pos)
20002 (if (<= (current-column) (current-indentation))
20003 (org-indent-line-to column)
20004 (save-excursion (org-indent-line-to column)))
20005 ;; Special polishing for properties, see `org-property-format'
20006 (setq column (current-column))
20007 (beginning-of-line 1)
20008 (if (looking-at
20009 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20010 (replace-match (concat (match-string 1)
20011 (format org-property-format
20012 (match-string 2) (match-string 3)))
20013 t t))
20014 (org-move-to-column column)))
20016 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
20017 "Variable to store copy of `adaptive-fill-regexp'.
20018 Since `adaptive-fill-regexp' is set to never match, we need to
20019 store a backup of its value before entering `org-mode' so that
20020 the functionality can be provided as a fall-back.")
20022 (defun org-set-autofill-regexps ()
20023 (interactive)
20024 ;; In the paragraph separator we include headlines, because filling
20025 ;; text in a line directly attached to a headline would otherwise
20026 ;; fill the headline as well.
20027 (org-set-local 'comment-start-skip "^#+[ \t]*")
20028 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
20029 ;; The paragraph starter includes hand-formatted lists.
20030 (org-set-local
20031 'paragraph-start
20032 (concat
20033 "\f" "\\|"
20034 "[ ]*$" "\\|"
20035 org-outline-regexp "\\|"
20036 "[ \t]*#" "\\|"
20037 (org-item-re) "\\|"
20038 "[ \t]*[:|]" "\\|"
20039 "\\$\\$" "\\|"
20040 "\\\\\\(begin\\|end\\|[][]\\)"))
20041 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20042 ;; But only if the user has not turned off tables or fixed-width regions
20043 (org-set-local
20044 'auto-fill-inhibit-regexp
20045 (concat org-outline-regexp
20046 "\\|#\\+"
20047 "\\|[ \t]*" org-keyword-time-regexp
20048 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20049 (concat
20050 "\\|[ \t]*["
20051 (if org-enable-table-editor "|" "")
20052 (if org-enable-fixed-width-editor ":" "")
20053 "]"))))
20054 ;; We use our own fill-paragraph function, to make sure that tables
20055 ;; and fixed-width regions are not wrapped. That function will pass
20056 ;; through to `fill-paragraph' when appropriate.
20057 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20058 ;; Prevent auto-fill from inserting unwanted new items.
20059 (if (boundp 'fill-nobreak-predicate)
20060 (org-set-local 'fill-nobreak-predicate
20061 (if (memq 'org-fill-item-nobreak-p fill-nobreak-predicate)
20062 fill-nobreak-predicate
20063 (cons 'org-fill-item-nobreak-p fill-nobreak-predicate))))
20064 ;; Adaptive filling: To get full control, first make sure that
20065 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20066 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
20067 (org-set-local 'org-adaptive-fill-regexp-backup
20068 adaptive-fill-regexp))
20069 (org-set-local 'adaptive-fill-regexp "\000")
20070 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
20071 (org-set-local 'adaptive-fill-function
20072 'org-adaptive-fill-function)
20073 (org-set-local
20074 'align-mode-rules-list
20075 '((org-in-buffer-settings
20076 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
20077 (modes . '(org-mode))))))
20079 (defun org-fill-item-nobreak-p ()
20080 "Non-nil when a line break at point would insert a new item."
20081 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
20083 (defun org-fill-paragraph (&optional justify)
20084 "Re-align a table, pass through to fill-paragraph if no table."
20085 (let ((table-p (org-at-table-p))
20086 (table.el-p (org-at-table.el-p))
20087 (itemp (org-in-item-p)))
20088 (cond ((and (equal (char-after (point-at-bol)) ?*)
20089 (save-excursion (goto-char (point-at-bol))
20090 (looking-at org-outline-regexp)))
20091 t) ; skip headlines
20092 (table.el-p t) ; skip table.el tables
20093 (table-p (org-table-align) t) ; align Org tables
20094 (itemp ; align text in items
20095 (let* ((struct (save-excursion (goto-char itemp)
20096 (org-list-struct)))
20097 (parents (org-list-parents-alist struct))
20098 (children (org-list-get-children itemp struct parents))
20099 beg end prev next prefix)
20100 ;; Determine in which part of item point is: before
20101 ;; first child, after last child, between two
20102 ;; sub-lists, or simply in item if there's no child.
20103 (cond
20104 ((not children)
20105 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20106 beg itemp
20107 end (org-list-get-item-end itemp struct)))
20108 ((< (point) (setq next (car children)))
20109 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
20110 beg itemp
20111 end next))
20112 ((> (point) (setq prev (car (last children))))
20113 (setq beg (org-list-get-item-end prev struct)
20114 end (org-list-get-item-end itemp struct)
20115 prefix (save-excursion
20116 (goto-char beg)
20117 (skip-chars-forward " \t")
20118 (make-string (current-column) ?\ ))))
20119 (t (catch 'exit
20120 (while (setq next (pop children))
20121 (if (> (point) next)
20122 (setq prev next)
20123 (setq beg (org-list-get-item-end prev struct)
20124 end next
20125 prefix (save-excursion
20126 (goto-char beg)
20127 (skip-chars-forward " \t")
20128 (make-string (current-column) ?\ )))
20129 (throw 'exit nil))))))
20130 ;; Use `fill-paragraph' with buffer narrowed to item
20131 ;; without any child, and with our computed PREFIX.
20132 (flet ((fill-context-prefix (from to &optional flr) prefix))
20133 (save-restriction
20134 (narrow-to-region beg end)
20135 (save-excursion (fill-paragraph justify)))) t))
20136 ;; Special case where point is not in a list but is on
20137 ;; a paragraph adjacent to a list: make sure this paragraph
20138 ;; doesn't get merged with the end of the list by narrowing
20139 ;; buffer first.
20140 ((save-excursion (forward-paragraph -1)
20141 (setq itemp (org-in-item-p)))
20142 (let ((struct (save-excursion (goto-char itemp)
20143 (org-list-struct))))
20144 (save-restriction
20145 (narrow-to-region (org-list-get-bottom-point struct)
20146 (save-excursion (forward-paragraph 1)
20147 (point)))
20148 (fill-paragraph justify) t)))
20149 ;; Else simply call `fill-paragraph'.
20150 (t nil))))
20152 ;; For reference, this is the default value of adaptive-fill-regexp
20153 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20155 (defun org-adaptive-fill-function ()
20156 "Return a fill prefix for org-mode files."
20157 (let (itemp)
20158 (save-excursion
20159 (cond
20160 ;; Comment line
20161 ((looking-at "#[ \t]+")
20162 (match-string-no-properties 0))
20163 ;; Plain list item
20164 ((org-at-item-p)
20165 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20166 ;; Point is in a list after `backward-paragraph': original
20167 ;; point wasn't in the list, or filling would have been taken
20168 ;; care of by `org-auto-fill-function', but the list and the
20169 ;; real paragraph are not separated by a blank line. Thus, move
20170 ;; point after the list to go back to real paragraph and
20171 ;; determine fill-prefix.
20172 ((setq itemp (org-in-item-p))
20173 (goto-char itemp)
20174 (let* ((struct (org-list-struct))
20175 (bottom (org-list-get-bottom-point struct)))
20176 (goto-char bottom)
20177 (make-string (org-get-indentation) ?\ )))
20178 ;; Other text
20179 ((looking-at org-adaptive-fill-regexp-backup)
20180 (match-string-no-properties 0))))))
20182 (defun org-auto-fill-function ()
20183 "Auto-fill function."
20184 (let (itemp prefix)
20185 ;; When in a list, compute an appropriate fill-prefix and make
20186 ;; sure it will be used by `do-auto-fill'.
20187 (if (setq itemp (org-in-item-p))
20188 (progn
20189 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20190 (flet ((fill-context-prefix (from to &optional flr) prefix))
20191 (do-auto-fill)))
20192 ;; Else just use `do-auto-fill'.
20193 (do-auto-fill))))
20195 ;;; Other stuff.
20197 (defun org-toggle-fixed-width-section (arg)
20198 "Toggle the fixed-width export.
20199 If there is no active region, the QUOTE keyword at the current headline is
20200 inserted or removed. When present, it causes the text between this headline
20201 and the next to be exported as fixed-width text, and unmodified.
20202 If there is an active region, this command adds or removes a colon as the
20203 first character of this line. If the first character of a line is a colon,
20204 this line is also exported in fixed-width font."
20205 (interactive "P")
20206 (let* ((cc 0)
20207 (regionp (org-region-active-p))
20208 (beg (if regionp (region-beginning) (point)))
20209 (end (if regionp (region-end)))
20210 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20211 (case-fold-search nil)
20212 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20213 off)
20214 (if regionp
20215 (save-excursion
20216 (goto-char beg)
20217 (setq cc (current-column))
20218 (beginning-of-line 1)
20219 (setq off (looking-at re))
20220 (while (> nlines 0)
20221 (setq nlines (1- nlines))
20222 (beginning-of-line 1)
20223 (cond
20224 (arg
20225 (org-move-to-column cc t)
20226 (insert ": \n")
20227 (forward-line -1))
20228 ((and off (looking-at re))
20229 (replace-match "" t t nil 1))
20230 ((not off) (org-move-to-column cc t) (insert ": ")))
20231 (forward-line 1)))
20232 (save-excursion
20233 (org-back-to-heading)
20234 (cond
20235 ((looking-at (format org-heading-keyword-regexp-format
20236 org-quote-string))
20237 (goto-char (match-end 1))
20238 (looking-at (concat " +" org-quote-string))
20239 (replace-match "" t t)
20240 (when (eolp) (insert " ")))
20241 ((looking-at org-outline-regexp)
20242 (goto-char (match-end 0))
20243 (insert org-quote-string " ")))))))
20245 (defun org-reftex-citation ()
20246 "Use reftex-citation to insert a citation into the buffer.
20247 This looks for a line like
20249 #+BIBLIOGRAPHY: foo plain option:-d
20251 and derives from it that foo.bib is the bibliography file relevant
20252 for this document. It then installs the necessary environment for RefTeX
20253 to work in this buffer and calls `reftex-citation' to insert a citation
20254 into the buffer.
20256 Export of such citations to both LaTeX and HTML is handled by the contributed
20257 package org-exp-bibtex by Taru Karttunen."
20258 (interactive)
20259 (let ((reftex-docstruct-symbol 'rds)
20260 (reftex-cite-format "\\cite{%l}")
20261 rds bib)
20262 (save-excursion
20263 (save-restriction
20264 (widen)
20265 (let ((case-fold-search t)
20266 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20267 (if (not (save-excursion
20268 (or (re-search-forward re nil t)
20269 (re-search-backward re nil t))))
20270 (error "No bibliography defined in file")
20271 (setq bib (concat (match-string 1) ".bib")
20272 rds (list (list 'bib bib)))))))
20273 (call-interactively 'reftex-citation)))
20275 ;;;; Functions extending outline functionality
20277 (defun org-beginning-of-line (&optional arg)
20278 "Go to the beginning of the current line. If that is invisible, continue
20279 to a visible line beginning. This makes the function of C-a more intuitive.
20280 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20281 first attempt, and only move to after the tags when the cursor is already
20282 beyond the end of the headline."
20283 (interactive "P")
20284 (let ((pos (point))
20285 (special (if (consp org-special-ctrl-a/e)
20286 (car org-special-ctrl-a/e)
20287 org-special-ctrl-a/e))
20288 refpos)
20289 (if (org-bound-and-true-p line-move-visual)
20290 (beginning-of-visual-line 1)
20291 (beginning-of-line 1))
20292 (if (and arg (fboundp 'move-beginning-of-line))
20293 (call-interactively 'move-beginning-of-line)
20294 (if (bobp)
20296 (backward-char 1)
20297 (if (org-truely-invisible-p)
20298 (while (and (not (bobp)) (org-truely-invisible-p))
20299 (backward-char 1)
20300 (beginning-of-line 1))
20301 (forward-char 1))))
20302 (when special
20303 (cond
20304 ((and (looking-at org-complex-heading-regexp)
20305 (= (char-after (match-end 1)) ?\ ))
20306 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20307 (point-at-eol)))
20308 (goto-char
20309 (if (eq special t)
20310 (cond ((> pos refpos) refpos)
20311 ((= pos (point)) refpos)
20312 (t (point)))
20313 (cond ((> pos (point)) (point))
20314 ((not (eq last-command this-command)) (point))
20315 (t refpos)))))
20316 ((org-at-item-p)
20317 (goto-char
20318 (if (eq special t)
20319 (cond ((> pos (match-end 0)) (match-end 0))
20320 ((= pos (point)) (match-end 0))
20321 (t (point)))
20322 (cond ((> pos (point)) (point))
20323 ((not (eq last-command this-command)) (point))
20324 (t (match-end 0))))))))
20325 (org-no-warnings
20326 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20328 (defun org-end-of-line (&optional arg)
20329 "Go to the end of the line.
20330 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20331 first attempt, and only move to after the tags when the cursor is already
20332 beyond the end of the headline."
20333 (interactive "P")
20334 (let ((special (if (consp org-special-ctrl-a/e)
20335 (cdr org-special-ctrl-a/e)
20336 org-special-ctrl-a/e)))
20337 (cond
20338 ((or (not special) arg
20339 (not (or (org-on-heading-p) (org-at-item-p))))
20340 (call-interactively
20341 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20342 ((fboundp 'move-end-of-line) 'move-end-of-line)
20343 (t 'end-of-line))))
20344 ((org-on-heading-p)
20345 (let ((pos (point)))
20346 (beginning-of-line 1)
20347 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20348 (if (eq special t)
20349 (if (or (< pos (match-beginning 1))
20350 (= pos (match-end 0)))
20351 (goto-char (match-beginning 1))
20352 (goto-char (match-end 0)))
20353 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20354 (goto-char (match-end 0))
20355 (goto-char (match-beginning 1))))
20356 (call-interactively (if (fboundp 'move-end-of-line)
20357 'move-end-of-line
20358 'end-of-line)))))
20359 ;; At an item: Move before any hidden text.
20360 (t (call-interactively 'end-of-line)))
20361 (org-no-warnings
20362 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20364 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20365 (define-key org-mode-map "\C-e" 'org-end-of-line)
20367 (defun org-backward-sentence (&optional arg)
20368 "Go to beginning of sentence, or beginning of table field.
20369 This will call `backward-sentence' or `org-table-beginning-of-field',
20370 depending on context."
20371 (interactive "P")
20372 (cond
20373 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
20374 (t (call-interactively 'backward-sentence))))
20376 (defun org-forward-sentence (&optional arg)
20377 "Go to end of sentence, or end of table field.
20378 This will call `forward-sentence' or `org-table-end-of-field',
20379 depending on context."
20380 (interactive "P")
20381 (cond
20382 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
20383 (t (call-interactively 'forward-sentence))))
20385 (define-key org-mode-map "\M-a" 'org-backward-sentence)
20386 (define-key org-mode-map "\M-e" 'org-forward-sentence)
20388 (defun org-kill-line (&optional arg)
20389 "Kill line, to tags or end of line."
20390 (interactive "P")
20391 (cond
20392 ((or (not org-special-ctrl-k)
20393 (bolp)
20394 (not (org-on-heading-p)))
20395 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
20396 org-ctrl-k-protect-subtree)
20397 (if (or (eq org-ctrl-k-protect-subtree 'error)
20398 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
20399 (error "C-k aborted - would kill hidden subtree")))
20400 (call-interactively 'kill-line))
20401 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
20402 (kill-region (point) (match-beginning 1))
20403 (org-set-tags nil t))
20404 (t (kill-region (point) (point-at-eol)))))
20406 (define-key org-mode-map "\C-k" 'org-kill-line)
20408 (defun org-yank (&optional arg)
20409 "Yank. If the kill is a subtree, treat it specially.
20410 This command will look at the current kill and check if is a single
20411 subtree, or a series of subtrees[1]. If it passes the test, and if the
20412 cursor is at the beginning of a line or after the stars of a currently
20413 empty headline, then the yank is handled specially. How exactly depends
20414 on the value of the following variables, both set by default.
20416 org-yank-folded-subtrees
20417 When set, the subtree(s) will be folded after insertion, but only
20418 if doing so would now swallow text after the yanked text.
20420 org-yank-adjusted-subtrees
20421 When set, the subtree will be promoted or demoted in order to
20422 fit into the local outline tree structure, which means that the level
20423 will be adjusted so that it becomes the smaller one of the two
20424 *visible* surrounding headings.
20426 Any prefix to this command will cause `yank' to be called directly with
20427 no special treatment. In particular, a simple \\[universal-argument] prefix \
20428 will just
20429 plainly yank the text as it is.
20431 \[1] The test checks if the first non-white line is a heading
20432 and if there are no other headings with fewer stars."
20433 (interactive "P")
20434 (org-yank-generic 'yank arg))
20436 (defun org-yank-generic (command arg)
20437 "Perform some yank-like command.
20439 This function implements the behavior described in the `org-yank'
20440 documentation. However, it has been generalized to work for any
20441 interactive command with similar behavior."
20443 ;; pretend to be command COMMAND
20444 (setq this-command command)
20446 (if arg
20447 (call-interactively command)
20449 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
20450 (and (org-kill-is-subtree-p)
20451 (or (bolp)
20452 (and (looking-at "[ \t]*$")
20453 (string-match
20454 "\\`\\*+\\'"
20455 (buffer-substring (point-at-bol) (point)))))))
20456 swallowp)
20457 (cond
20458 ((and subtreep org-yank-folded-subtrees)
20459 (let ((beg (point))
20460 end)
20461 (if (and subtreep org-yank-adjusted-subtrees)
20462 (org-paste-subtree nil nil 'for-yank)
20463 (call-interactively command))
20465 (setq end (point))
20466 (goto-char beg)
20467 (when (and (bolp) subtreep
20468 (not (setq swallowp
20469 (org-yank-folding-would-swallow-text beg end))))
20470 (org-with-limited-levels
20471 (or (looking-at org-outline-regexp)
20472 (re-search-forward org-outline-regexp-bol end t))
20473 (while (and (< (point) end) (looking-at org-outline-regexp))
20474 (hide-subtree)
20475 (org-cycle-show-empty-lines 'folded)
20476 (condition-case nil
20477 (outline-forward-same-level 1)
20478 (error (goto-char end))))))
20479 (when swallowp
20480 (message
20481 "Inserted text not folded because that would swallow text"))
20483 (goto-char end)
20484 (skip-chars-forward " \t\n\r")
20485 (beginning-of-line 1)
20486 (push-mark beg 'nomsg)))
20487 ((and subtreep org-yank-adjusted-subtrees)
20488 (let ((beg (point-at-bol)))
20489 (org-paste-subtree nil nil 'for-yank)
20490 (push-mark beg 'nomsg)))
20492 (call-interactively command))))))
20494 (defun org-yank-folding-would-swallow-text (beg end)
20495 "Would hide-subtree at BEG swallow any text after END?"
20496 (let (level)
20497 (org-with-limited-levels
20498 (save-excursion
20499 (goto-char beg)
20500 (when (or (looking-at org-outline-regexp)
20501 (re-search-forward org-outline-regexp-bol end t))
20502 (setq level (org-outline-level)))
20503 (goto-char end)
20504 (skip-chars-forward " \t\r\n\v\f")
20505 (if (or (eobp)
20506 (and (bolp) (looking-at org-outline-regexp)
20507 (<= (org-outline-level) level)))
20508 nil ; Nothing would be swallowed
20509 t))))) ; something would swallow
20511 (define-key org-mode-map "\C-y" 'org-yank)
20513 (defun org-truely-invisible-p ()
20514 "Check if point is at a character currently not visible.
20515 This version does not only check the character property, but also
20516 `visible-mode'."
20517 ;; Early versions of noutline don't have `outline-invisible-p'.
20518 (if (org-bound-and-true-p visible-mode)
20520 (outline-invisible-p)))
20522 (defun org-invisible-p2 ()
20523 "Check if point is at a character currently not visible."
20524 (save-excursion
20525 (if (and (eolp) (not (bobp))) (backward-char 1))
20526 ;; Early versions of noutline don't have `outline-invisible-p'.
20527 (outline-invisible-p)))
20529 (defun org-back-to-heading (&optional invisible-ok)
20530 "Call `outline-back-to-heading', but provide a better error message."
20531 (condition-case nil
20532 (outline-back-to-heading invisible-ok)
20533 (error (error "Before first headline at position %d in buffer %s"
20534 (point) (current-buffer)))))
20536 (defun org-beginning-of-defun ()
20537 "Go to the beginning of the subtree, i.e. back to the heading."
20538 (org-back-to-heading))
20539 (defun org-end-of-defun ()
20540 "Go to the end of the subtree."
20541 (org-end-of-subtree nil t))
20543 (defun org-before-first-heading-p ()
20544 "Before first heading?"
20545 (save-excursion
20546 (end-of-line)
20547 (null (re-search-backward org-outline-regexp-bol nil t))))
20549 (defun org-on-heading-p (&optional ignored)
20550 (outline-on-heading-p t))
20551 (defun org-at-heading-p (&optional ignored)
20552 (outline-on-heading-p t))
20554 (defun org-point-at-end-of-empty-headline ()
20555 "If point is at the end of an empty headline, return t, else nil.
20556 If the heading only contains a TODO keyword, it is still still considered
20557 empty."
20558 (and (looking-at "[ \t]*$")
20559 (save-excursion
20560 (beginning-of-line 1)
20561 (let ((case-fold-search nil))
20562 (looking-at org-todo-line-regexp)))
20563 (string= (match-string 3) "")))
20565 (defun org-at-heading-or-item-p ()
20566 (or (org-on-heading-p) (org-at-item-p)))
20568 (defun org-on-target-p ()
20569 (or (org-in-regexp org-radio-target-regexp)
20570 (org-in-regexp org-target-regexp)))
20572 (defun org-up-heading-all (arg)
20573 "Move to the heading line of which the present line is a subheading.
20574 This function considers both visible and invisible heading lines.
20575 With argument, move up ARG levels."
20576 (if (fboundp 'outline-up-heading-all)
20577 (outline-up-heading-all arg) ; emacs 21 version of outline.el
20578 (outline-up-heading arg t))) ; emacs 22 version of outline.el
20580 (defun org-up-heading-safe ()
20581 "Move to the heading line of which the present line is a subheading.
20582 This version will not throw an error. It will return the level of the
20583 headline found, or nil if no higher level is found.
20585 Also, this function will be a lot faster than `outline-up-heading',
20586 because it relies on stars being the outline starters. This can really
20587 make a significant difference in outlines with very many siblings."
20588 (let (start-level re)
20589 (org-back-to-heading t)
20590 (setq start-level (funcall outline-level))
20591 (if (equal start-level 1)
20593 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
20594 (if (re-search-backward re nil t)
20595 (funcall outline-level)))))
20597 (defun org-first-sibling-p ()
20598 "Is this heading the first child of its parents?"
20599 (interactive)
20600 (let ((re org-outline-regexp-bol)
20601 level l)
20602 (unless (org-at-heading-p t)
20603 (error "Not at a heading"))
20604 (setq level (funcall outline-level))
20605 (save-excursion
20606 (if (not (re-search-backward re nil t))
20608 (setq l (funcall outline-level))
20609 (< l level)))))
20611 (defun org-goto-sibling (&optional previous)
20612 "Goto the next sibling, even if it is invisible.
20613 When PREVIOUS is set, go to the previous sibling instead. Returns t
20614 when a sibling was found. When none is found, return nil and don't
20615 move point."
20616 (let ((fun (if previous 're-search-backward 're-search-forward))
20617 (pos (point))
20618 (re org-outline-regexp-bol)
20619 level l)
20620 (when (condition-case nil (org-back-to-heading t) (error nil))
20621 (setq level (funcall outline-level))
20622 (catch 'exit
20623 (or previous (forward-char 1))
20624 (while (funcall fun re nil t)
20625 (setq l (funcall outline-level))
20626 (when (< l level) (goto-char pos) (throw 'exit nil))
20627 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
20628 (goto-char pos)
20629 nil))))
20631 (defun org-show-siblings ()
20632 "Show all siblings of the current headline."
20633 (save-excursion
20634 (while (org-goto-sibling) (org-flag-heading nil)))
20635 (save-excursion
20636 (while (org-goto-sibling 'previous)
20637 (org-flag-heading nil))))
20639 (defun org-goto-first-child ()
20640 "Goto the first child, even if it is invisible.
20641 Return t when a child was found. Otherwise don't move point and
20642 return nil."
20643 (let (level (pos (point)) (re org-outline-regexp-bol))
20644 (when (condition-case nil (org-back-to-heading t) (error nil))
20645 (setq level (outline-level))
20646 (forward-char 1)
20647 (if (and (re-search-forward re nil t) (> (outline-level) level))
20648 (progn (goto-char (match-beginning 0)) t)
20649 (goto-char pos) nil))))
20651 (defun org-show-hidden-entry ()
20652 "Show an entry where even the heading is hidden."
20653 (save-excursion
20654 (org-show-entry)))
20656 (defun org-flag-heading (flag &optional entry)
20657 "Flag the current heading. FLAG non-nil means make invisible.
20658 When ENTRY is non-nil, show the entire entry."
20659 (save-excursion
20660 (org-back-to-heading t)
20661 ;; Check if we should show the entire entry
20662 (if entry
20663 (progn
20664 (org-show-entry)
20665 (save-excursion
20666 (and (outline-next-heading)
20667 (org-flag-heading nil))))
20668 (outline-flag-region (max (point-min) (1- (point)))
20669 (save-excursion (outline-end-of-heading) (point))
20670 flag))))
20672 (defun org-get-next-sibling ()
20673 "Move to next heading of the same level, and return point.
20674 If there is no such heading, return nil.
20675 This is like outline-next-sibling, but invisible headings are ok."
20676 (let ((level (funcall outline-level)))
20677 (outline-next-heading)
20678 (while (and (not (eobp)) (> (funcall outline-level) level))
20679 (outline-next-heading))
20680 (if (or (eobp) (< (funcall outline-level) level))
20682 (point))))
20684 (defun org-get-last-sibling ()
20685 "Move to previous heading of the same level, and return point.
20686 If there is no such heading, return nil."
20687 (let ((opoint (point))
20688 (level (funcall outline-level)))
20689 (outline-previous-heading)
20690 (when (and (/= (point) opoint) (outline-on-heading-p t))
20691 (while (and (> (funcall outline-level) level)
20692 (not (bobp)))
20693 (outline-previous-heading))
20694 (if (< (funcall outline-level) level)
20696 (point)))))
20698 (defun org-end-of-subtree (&optional invisible-OK to-heading)
20699 ;; This contains an exact copy of the original function, but it uses
20700 ;; `org-back-to-heading', to make it work also in invisible
20701 ;; trees. And is uses an invisible-OK argument.
20702 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
20703 ;; Furthermore, when used inside Org, finding the end of a large subtree
20704 ;; with many children and grandchildren etc, this can be much faster
20705 ;; than the outline version.
20706 (org-back-to-heading invisible-OK)
20707 (let ((first t)
20708 (level (funcall outline-level)))
20709 (if (and (eq major-mode 'org-mode) (< level 1000))
20710 ;; A true heading (not a plain list item), in Org-mode
20711 ;; This means we can easily find the end by looking
20712 ;; only for the right number of stars. Using a regexp to do
20713 ;; this is so much faster than using a Lisp loop.
20714 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
20715 (forward-char 1)
20716 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
20717 ;; something else, do it the slow way
20718 (while (and (not (eobp))
20719 (or first (> (funcall outline-level) level)))
20720 (setq first nil)
20721 (outline-next-heading)))
20722 (unless to-heading
20723 (if (memq (preceding-char) '(?\n ?\^M))
20724 (progn
20725 ;; Go to end of line before heading
20726 (forward-char -1)
20727 (if (memq (preceding-char) '(?\n ?\^M))
20728 ;; leave blank line before heading
20729 (forward-char -1))))))
20730 (point))
20732 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
20733 "Use Org version in org-mode, for dramatic speed-up."
20734 (if (eq major-mode 'org-mode)
20735 (progn
20736 (org-end-of-subtree nil t)
20737 (unless (eobp) (backward-char 1)))
20738 ad-do-it))
20740 (defun org-end-of-meta-data-and-drawers ()
20741 "Jump to the first text after meta data and drawers in the current entry.
20742 This will move over empty lines, lines with planning time stamps,
20743 clocking lines, and drawers."
20744 (org-back-to-heading t)
20745 (let ((end (save-excursion (outline-next-heading) (point)))
20746 (re (concat "\\(" org-drawer-regexp "\\)"
20747 "\\|" "[ \t]*" org-keyword-time-regexp)))
20748 (forward-line 1)
20749 (while (re-search-forward re end t)
20750 (if (not (match-end 1))
20751 ;; empty or planning line
20752 (forward-line 1)
20753 ;; a drawer, find the end
20754 (re-search-forward "^[ \t]*:END:" end 'move)
20755 (forward-line 1)))
20756 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
20757 (point)))
20759 (defun org-forward-same-level (arg &optional invisible-ok)
20760 "Move forward to the arg'th subheading at same level as this one.
20761 Stop at the first and last subheadings of a superior heading.
20762 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
20763 it wil also look at invisible ones."
20764 (interactive "p")
20765 (org-back-to-heading invisible-ok)
20766 (org-on-heading-p)
20767 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20768 (re (format "^\\*\\{1,%d\\} " level))
20770 (forward-char 1)
20771 (while (> arg 0)
20772 (while (and (re-search-forward re nil 'move)
20773 (setq l (- (match-end 0) (match-beginning 0) 1))
20774 (= l level)
20775 (not invisible-ok)
20776 (progn (backward-char 1) (outline-invisible-p)))
20777 (if (< l level) (setq arg 1)))
20778 (setq arg (1- arg)))
20779 (beginning-of-line 1)))
20781 (defun org-backward-same-level (arg &optional invisible-ok)
20782 "Move backward to the arg'th subheading at same level as this one.
20783 Stop at the first and last subheadings of a superior heading."
20784 (interactive "p")
20785 (org-back-to-heading)
20786 (org-on-heading-p)
20787 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20788 (re (format "^\\*\\{1,%d\\} " level))
20790 (while (> arg 0)
20791 (while (and (re-search-backward re nil 'move)
20792 (setq l (- (match-end 0) (match-beginning 0) 1))
20793 (= l level)
20794 (not invisible-ok)
20795 (outline-invisible-p))
20796 (if (< l level) (setq arg 1)))
20797 (setq arg (1- arg)))))
20799 (defun org-show-subtree ()
20800 "Show everything after this heading at deeper levels."
20801 (outline-flag-region
20802 (point)
20803 (save-excursion
20804 (org-end-of-subtree t t))
20805 nil))
20807 (defun org-show-entry ()
20808 "Show the body directly following this heading.
20809 Show the heading too, if it is currently invisible."
20810 (interactive)
20811 (save-excursion
20812 (condition-case nil
20813 (progn
20814 (org-back-to-heading t)
20815 (outline-flag-region
20816 (max (point-min) (1- (point)))
20817 (save-excursion
20818 (if (re-search-forward
20819 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
20820 (match-beginning 1)
20821 (point-max)))
20822 nil)
20823 (org-cycle-hide-drawers 'children))
20824 (error nil))))
20826 (defun org-make-options-regexp (kwds &optional extra)
20827 "Make a regular expression for keyword lines."
20828 (concat
20830 "#?[ \t]*\\+\\("
20831 (mapconcat 'regexp-quote kwds "\\|")
20832 (if extra (concat "\\|" extra))
20833 "\\):[ \t]*"
20834 "\\(.*\\)"))
20836 ;; Make isearch reveal the necessary context
20837 (defun org-isearch-end ()
20838 "Reveal context after isearch exits."
20839 (when isearch-success ; only if search was successful
20840 (if (featurep 'xemacs)
20841 ;; Under XEmacs, the hook is run in the correct place,
20842 ;; we directly show the context.
20843 (org-show-context 'isearch)
20844 ;; In Emacs the hook runs *before* restoring the overlays.
20845 ;; So we have to use a one-time post-command-hook to do this.
20846 ;; (Emacs 22 has a special variable, see function `org-mode')
20847 (unless (and (boundp 'isearch-mode-end-hook-quit)
20848 isearch-mode-end-hook-quit)
20849 ;; Only when the isearch was not quitted.
20850 (org-add-hook 'post-command-hook 'org-isearch-post-command
20851 'append 'local)))))
20853 (defun org-isearch-post-command ()
20854 "Remove self from hook, and show context."
20855 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
20856 (org-show-context 'isearch))
20859 ;;;; Integration with and fixes for other packages
20861 ;;; Imenu support
20863 (defvar org-imenu-markers nil
20864 "All markers currently used by Imenu.")
20865 (make-variable-buffer-local 'org-imenu-markers)
20867 (defun org-imenu-new-marker (&optional pos)
20868 "Return a new marker for use by Imenu, and remember the marker."
20869 (let ((m (make-marker)))
20870 (move-marker m (or pos (point)))
20871 (push m org-imenu-markers)
20874 (defun org-imenu-get-tree ()
20875 "Produce the index for Imenu."
20876 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
20877 (setq org-imenu-markers nil)
20878 (let* ((n org-imenu-depth)
20879 (re (concat "^" (org-get-limited-outline-regexp)))
20880 (subs (make-vector (1+ n) nil))
20881 (last-level 0)
20882 m level head)
20883 (save-excursion
20884 (save-restriction
20885 (widen)
20886 (goto-char (point-max))
20887 (while (re-search-backward re nil t)
20888 (setq level (org-reduced-level (funcall outline-level)))
20889 (when (<= level n)
20890 (looking-at org-complex-heading-regexp)
20891 (setq head (org-link-display-format
20892 (org-match-string-no-properties 4))
20893 m (org-imenu-new-marker))
20894 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
20895 (if (>= level last-level)
20896 (push (cons head m) (aref subs level))
20897 (push (cons head (aref subs (1+ level))) (aref subs level))
20898 (loop for i from (1+ level) to n do (aset subs i nil)))
20899 (setq last-level level)))))
20900 (aref subs 1)))
20902 (eval-after-load "imenu"
20903 '(progn
20904 (add-hook 'imenu-after-jump-hook
20905 (lambda ()
20906 (if (eq major-mode 'org-mode)
20907 (org-show-context 'org-goto))))))
20909 (defun org-link-display-format (link)
20910 "Replace a link with either the description, or the link target
20911 if no description is present"
20912 (save-match-data
20913 (if (string-match org-bracket-link-analytic-regexp link)
20914 (replace-match (if (match-end 5)
20915 (match-string 5 link)
20916 (concat (match-string 1 link)
20917 (match-string 3 link)))
20918 nil t link)
20919 link)))
20921 (defun org-toggle-link-display ()
20922 "Toggle the literal or descriptive display of links."
20923 (interactive)
20924 (if org-descriptive-links
20925 (progn (org-remove-from-invisibility-spec '(org-link))
20926 (org-restart-font-lock)
20927 (setq org-descriptive-links nil))
20928 (progn (add-to-invisibility-spec '(org-link))
20929 (org-restart-font-lock)
20930 (setq org-descriptive-links t))))
20932 ;; Speedbar support
20934 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
20935 "Overlay marking the agenda restriction line in speedbar.")
20936 (overlay-put org-speedbar-restriction-lock-overlay
20937 'face 'org-agenda-restriction-lock)
20938 (overlay-put org-speedbar-restriction-lock-overlay
20939 'help-echo "Agendas are currently limited to this item.")
20940 (org-detach-overlay org-speedbar-restriction-lock-overlay)
20942 (defun org-speedbar-set-agenda-restriction ()
20943 "Restrict future agenda commands to the location at point in speedbar.
20944 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
20945 (interactive)
20946 (require 'org-agenda)
20947 (let (p m tp np dir txt)
20948 (cond
20949 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20950 'org-imenu t))
20951 (setq m (get-text-property p 'org-imenu-marker))
20952 (with-current-buffer (marker-buffer m)
20953 (goto-char m)
20954 (org-agenda-set-restriction-lock 'subtree)))
20955 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20956 'speedbar-function 'speedbar-find-file))
20957 (setq tp (previous-single-property-change
20958 (1+ p) 'speedbar-function)
20959 np (next-single-property-change
20960 tp 'speedbar-function)
20961 dir (speedbar-line-directory)
20962 txt (buffer-substring-no-properties (or tp (point-min))
20963 (or np (point-max))))
20964 (with-current-buffer (find-file-noselect
20965 (let ((default-directory dir))
20966 (expand-file-name txt)))
20967 (unless (eq major-mode 'org-mode)
20968 (error "Cannot restrict to non-Org-mode file"))
20969 (org-agenda-set-restriction-lock 'file)))
20970 (t (error "Don't know how to restrict Org-mode's agenda")))
20971 (move-overlay org-speedbar-restriction-lock-overlay
20972 (point-at-bol) (point-at-eol))
20973 (setq current-prefix-arg nil)
20974 (org-agenda-maybe-redo)))
20976 (eval-after-load "speedbar"
20977 '(progn
20978 (speedbar-add-supported-extension ".org")
20979 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
20980 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
20981 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
20982 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
20983 (add-hook 'speedbar-visiting-tag-hook
20984 (lambda () (and (eq major-mode 'org-mode) (org-show-context 'org-goto))))))
20986 ;;; Fixes and Hacks for problems with other packages
20988 ;; Make flyspell not check words in links, to not mess up our keymap
20989 (defun org-mode-flyspell-verify ()
20990 "Don't let flyspell put overlays at active buttons, or on
20991 {todo,all-time,additional-option-like}-keywords."
20992 (let ((pos (max (1- (point)) (point-min)))
20993 (word (thing-at-point 'word)))
20994 (and (not (get-text-property pos 'keymap))
20995 (not (get-text-property pos 'org-no-flyspell))
20996 (not (member word org-todo-keywords-1))
20997 (not (member word org-all-time-keywords))
20998 (not (member word org-additional-option-like-keywords)))))
21000 (defun org-remove-flyspell-overlays-in (beg end)
21001 "Remove flyspell overlays in region."
21002 (and (org-bound-and-true-p flyspell-mode)
21003 (fboundp 'flyspell-delete-region-overlays)
21004 (flyspell-delete-region-overlays beg end))
21005 (add-text-properties beg end '(org-no-flyspell t)))
21007 ;; Make `bookmark-jump' shows the jump location if it was hidden.
21008 (eval-after-load "bookmark"
21009 '(if (boundp 'bookmark-after-jump-hook)
21010 ;; We can use the hook
21011 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21012 ;; Hook not available, use advice
21013 (defadvice bookmark-jump (after org-make-visible activate)
21014 "Make the position visible."
21015 (org-bookmark-jump-unhide))))
21017 ;; Make sure saveplace shows the location if it was hidden
21018 (eval-after-load "saveplace"
21019 '(defadvice save-place-find-file-hook (after org-make-visible activate)
21020 "Make the position visible."
21021 (org-bookmark-jump-unhide)))
21023 ;; Make sure ecb shows the location if it was hidden
21024 (eval-after-load "ecb"
21025 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
21026 "Make hierarchy visible when jumping into location from ECB tree buffer."
21027 (if (eq major-mode 'org-mode)
21028 (org-show-context))))
21030 (defun org-bookmark-jump-unhide ()
21031 "Unhide the current position, to show the bookmark location."
21032 (and (eq major-mode 'org-mode)
21033 (or (outline-invisible-p)
21034 (save-excursion (goto-char (max (point-min) (1- (point))))
21035 (outline-invisible-p)))
21036 (org-show-context 'bookmark-jump)))
21038 ;; Make session.el ignore our circular variable
21039 (eval-after-load "session"
21040 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21042 ;;;; Experimental code
21044 (defun org-closed-in-range ()
21045 "Sparse tree of items closed in a certain time range.
21046 Still experimental, may disappear in the future."
21047 (interactive)
21048 ;; Get the time interval from the user.
21049 (let* ((time1 (org-float-time
21050 (org-read-date nil 'to-time nil "Starting date: ")))
21051 (time2 (org-float-time
21052 (org-read-date nil 'to-time nil "End date:")))
21053 ;; callback function
21054 (callback (lambda ()
21055 (let ((time
21056 (org-float-time
21057 (apply 'encode-time
21058 (org-parse-time-string
21059 (match-string 1))))))
21060 ;; check if time in interval
21061 (and (>= time time1) (<= time time2))))))
21062 ;; make tree, check each match with the callback
21063 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21065 ;;;; Finish up
21067 (provide 'org)
21069 (run-hooks 'org-load-hook)
21071 ;;; org.el ends here