Merge branch 'master' of orgmode.org:org-mode
[org-mode/org-mode-NeilSmithlineMods.git] / lisp / org.el
blob2599d41d4174d7ce487d7c59deccbb417c1eca51
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004-2011 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 7.7
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
79 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
80 (when (fboundp 'defvaralias)
81 (unless (boundp 'calendar-view-holidays-initially-flag)
82 (defvaralias 'calendar-view-holidays-initially-flag
83 'view-calendar-holidays-initially))
84 (unless (boundp 'calendar-view-diary-initially-flag)
85 (defvaralias 'calendar-view-diary-initially-flag
86 'view-diary-entries-initially))
87 (unless (boundp 'diary-fancy-buffer)
88 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
90 (require 'outline) (require 'noutline)
91 ;; Other stuff we need.
92 (require 'time-date)
93 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
94 (require 'easymenu)
95 (require 'overlay)
97 (require 'org-macs)
98 (require 'org-entities)
99 (require 'org-compat)
100 (require 'org-faces)
101 (require 'org-list)
102 (require 'org-pcomplete)
103 (require 'org-src)
104 (require 'org-footnote)
106 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
107 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
108 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
109 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
110 (declare-function org-at-clock-log-p "org-clock" ())
111 (declare-function org-clock-timestamps-up "org-clock" ())
112 (declare-function org-clock-timestamps-down "org-clock" ())
114 ;; babel
115 (require 'ob)
116 (require 'ob-table)
117 (require 'ob-lob)
118 (require 'ob-ref)
119 (require 'ob-tangle)
120 (require 'ob-comint)
121 (require 'ob-keys)
123 ;; load languages based on value of `org-babel-load-languages'
124 (defvar org-babel-load-languages)
125 ;;;###autoload
126 (defun org-babel-do-load-languages (sym value)
127 "Load the languages defined in `org-babel-load-languages'."
128 (set-default sym value)
129 (mapc (lambda (pair)
130 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
131 (if active
132 (progn
133 (require (intern (concat "ob-" lang))))
134 (progn
135 (funcall 'fmakunbound
136 (intern (concat "org-babel-execute:" lang)))
137 (funcall 'fmakunbound
138 (intern (concat "org-babel-expand-body:" lang)))))))
139 org-babel-load-languages))
141 (defcustom org-babel-load-languages '((emacs-lisp . t))
142 "Languages which can be evaluated in Org-mode buffers.
143 This list can be used to load support for any of the languages
144 below, note that each language will depend on a different set of
145 system executables and/or Emacs modes. When a language is
146 \"loaded\", then code blocks in that language can be evaluated
147 with `org-babel-execute-src-block' bound by default to C-c
148 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
149 be set to remove code block evaluation from the C-c C-c
150 keybinding. By default only Emacs Lisp (which has no
151 requirements) is loaded."
152 :group 'org-babel
153 :set 'org-babel-do-load-languages
154 :type '(alist :tag "Babel Languages"
155 :key-type
156 (choice
157 (const :tag "Awk" awk)
158 (const :tag "C" C)
159 (const :tag "R" R)
160 (const :tag "Asymptote" asymptote)
161 (const :tag "Calc" calc)
162 (const :tag "Clojure" clojure)
163 (const :tag "CSS" css)
164 (const :tag "Ditaa" ditaa)
165 (const :tag "Dot" dot)
166 (const :tag "Emacs Lisp" emacs-lisp)
167 (const :tag "Gnuplot" gnuplot)
168 (const :tag "Haskell" haskell)
169 (const :tag "Java" java)
170 (const :tag "Javascript" js)
171 (const :tag "Latex" latex)
172 (const :tag "Ledger" ledger)
173 (const :tag "Lilypond" lilypond)
174 (const :tag "Maxima" maxima)
175 (const :tag "Matlab" matlab)
176 (const :tag "Mscgen" mscgen)
177 (const :tag "Ocaml" ocaml)
178 (const :tag "Octave" octave)
179 (const :tag "Org" org)
180 (const :tag "Perl" perl)
181 (const :tag "PlantUML" plantuml)
182 (const :tag "Python" python)
183 (const :tag "Ruby" ruby)
184 (const :tag "Sass" sass)
185 (const :tag "Scheme" scheme)
186 (const :tag "Screen" screen)
187 (const :tag "Shell Script" sh)
188 (const :tag "Shen" shen)
189 (const :tag "Sql" sql)
190 (const :tag "Sqlite" sqlite))
191 :value-type (boolean :tag "Activate" :value t)))
193 ;;;; Customization variables
194 (defcustom org-clone-delete-id nil
195 "Remove ID property of clones of a subtree.
196 When non-nil, clones of a subtree don't inherit the ID property.
197 Otherwise they inherit the ID property with a new unique
198 identifier."
199 :type 'boolean
200 :group 'org-id)
202 ;;; Version
204 (defconst org-version "7.7"
205 "The version number of the file org.el.")
207 (defun org-version (&optional here)
208 "Show the org-mode version in the echo area.
209 With prefix arg HERE, insert it at point."
210 (interactive "P")
211 (let* ((origin default-directory)
212 (version org-version)
213 (git-version)
214 (dir (concat (file-name-directory (locate-library "org")) "../" )))
215 (when (and (file-exists-p (expand-file-name ".git" dir))
216 (executable-find "git"))
217 (unwind-protect
218 (progn
219 (cd dir)
220 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
221 (with-current-buffer "*Shell Command Output*"
222 (goto-char (point-min))
223 (setq git-version (buffer-substring (point) (point-at-eol))))
224 (subst-char-in-string ?- ?. git-version t)
225 (when (string-match "\\S-"
226 (shell-command-to-string
227 "git diff-index --name-only HEAD --"))
228 (setq git-version (concat git-version ".dirty")))
229 (setq version (concat version " (" git-version ")"))))
230 (cd origin)))
231 (setq version (format "Org-mode version %s" version))
232 (if here (insert version))
233 (message version)))
235 ;;; Compatibility constants
237 ;;; The custom variables
239 (defgroup org nil
240 "Outline-based notes management and organizer."
241 :tag "Org"
242 :group 'outlines
243 :group 'calendar)
245 (defcustom org-mode-hook nil
246 "Mode hook for Org-mode, run after the mode was turned on."
247 :group 'org
248 :type 'hook)
250 (defcustom org-load-hook nil
251 "Hook that is run after org.el has been loaded."
252 :group 'org
253 :type 'hook)
255 (defcustom org-log-buffer-setup-hook nil
256 "Hook that is run after an Org log buffer is created."
257 :group 'org
258 :type 'hook)
260 (defvar org-modules) ; defined below
261 (defvar org-modules-loaded nil
262 "Have the modules been loaded already?")
264 (defun org-load-modules-maybe (&optional force)
265 "Load all extensions listed in `org-modules'."
266 (when (or force (not org-modules-loaded))
267 (mapc (lambda (ext)
268 (condition-case nil (require ext)
269 (error (message "Problems while trying to load feature `%s'" ext))))
270 org-modules)
271 (setq org-modules-loaded t)))
273 (defun org-set-modules (var value)
274 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
275 (set var value)
276 (when (featurep 'org)
277 (org-load-modules-maybe 'force)))
279 (when (org-bound-and-true-p org-modules)
280 (let ((a (member 'org-infojs org-modules)))
281 (and a (setcar a 'org-jsinfo))))
283 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
284 "Modules that should always be loaded together with org.el.
285 If a description starts with <C>, the file is not part of Emacs
286 and loading it will require that you have downloaded and properly installed
287 the org-mode distribution.
289 You can also use this system to load external packages (i.e. neither Org
290 core modules, nor modules from the CONTRIB directory). Just add symbols
291 to the end of the list. If the package is called org-xyz.el, then you need
292 to add the symbol `xyz', and the package must have a call to
294 (provide 'org-xyz)"
295 :group 'org
296 :set 'org-set-modules
297 :type
298 '(set :greedy t
299 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
300 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
301 (const :tag " crypt: Encryption of subtrees" org-crypt)
302 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
303 (const :tag " docview: Links to doc-view buffers" org-docview)
304 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
305 (const :tag " id: Global IDs for identifying entries" org-id)
306 (const :tag " info: Links to Info nodes" org-info)
307 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
308 (const :tag " habit: Track your consistency with habits" org-habit)
309 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
310 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
311 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
312 (const :tag " mew Links to Mew folders/messages" org-mew)
313 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
314 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
315 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
316 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
317 (const :tag " vm: Links to VM folders/messages" org-vm)
318 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
319 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
320 (const :tag " mouse: Additional mouse support" org-mouse)
321 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
323 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
324 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
325 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
326 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
327 (const :tag "C collector: Collect properties into tables" org-collector)
328 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
329 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
330 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
331 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
332 (const :tag "C eval: Include command output as text" org-eval)
333 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
334 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
335 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
336 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
337 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
339 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
341 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
342 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
343 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
344 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
345 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
346 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
347 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
348 (const :tag "C mtags: Support for muse-like tags" org-mtags)
349 (const :tag "C odt: OpenDocumentText exporter for Org-mode" org-odt)
350 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
351 (const :tag "C registry: A registry for Org-mode links" org-registry)
352 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
353 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
354 (const :tag "C secretary: Team management with org-mode" org-secretary)
355 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
356 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
357 (const :tag "C track: Keep up with Org-mode development" org-track)
358 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
359 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
360 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
362 (defcustom org-support-shift-select nil
363 "Non-nil means make shift-cursor commands select text when possible.
365 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
366 start selecting a region, or enlarge regions started in this way.
367 In Org-mode, in special contexts, these same keys are used for
368 other purposes, important enough to compete with shift selection.
369 Org tries to balance these needs by supporting `shift-select-mode'
370 outside these special contexts, under control of this variable.
372 The default of this variable is nil, to avoid confusing behavior. Shifted
373 cursor keys will then execute Org commands in the following contexts:
374 - on a headline, changing TODO state (left/right) and priority (up/down)
375 - on a time stamp, changing the time
376 - in a plain list item, changing the bullet type
377 - in a property definition line, switching between allowed values
378 - in the BEGIN line of a clock table (changing the time block).
379 Outside these contexts, the commands will throw an error.
381 When this variable is t and the cursor is not in a special
382 context, Org-mode will support shift-selection for making and
383 enlarging regions. To make this more effective, the bullet
384 cycling will no longer happen anywhere in an item line, but only
385 if the cursor is exactly on the bullet.
387 If you set this variable to the symbol `always', then the keys
388 will not be special in headlines, property lines, and item lines,
389 to make shift selection work there as well. If this is what you
390 want, you can use the following alternative commands: `C-c C-t'
391 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
392 can be used to switch TODO sets, `C-c -' to cycle item bullet
393 types, and properties can be edited by hand or in column view.
395 However, when the cursor is on a timestamp, shift-cursor commands
396 will still edit the time stamp - this is just too good to give up.
398 XEmacs user should have this variable set to nil, because
399 `shift-select-mode' is in Emacs 23 or later only."
400 :group 'org
401 :type '(choice
402 (const :tag "Never" nil)
403 (const :tag "When outside special context" t)
404 (const :tag "Everywhere except timestamps" always)))
406 (defcustom org-loop-over-headlines-in-active-region nil
407 "Shall some commands act upon headlines in the active region?
409 When set to `t', some commands will be performed in all headlines
410 within the active region.
412 When set to a string, those commands will be performed on the
413 matching headlines within the active region. Such string must be
414 a tags/property/todo match as it is used in the agenda tags view.
416 The list of commands is:
417 - `org-schedule'
418 - `org-deadline'"
419 :type '(choice (const :tag "Don't loop" nil)
420 (const :tag "All headlines in active region" t)
421 (string :tag "Tags/Property/Todo matcher"))
422 :group 'org-todo
423 :group 'org-archive)
425 (defgroup org-startup nil
426 "Options concerning startup of Org-mode."
427 :tag "Org Startup"
428 :group 'org)
430 (defcustom org-startup-folded t
431 "Non-nil means entering Org-mode will switch to OVERVIEW.
432 This can also be configured on a per-file basis by adding one of
433 the following lines anywhere in the buffer:
435 #+STARTUP: fold (or `overview', this is equivalent)
436 #+STARTUP: nofold (or `showall', this is equivalent)
437 #+STARTUP: content
438 #+STARTUP: showeverything"
439 :group 'org-startup
440 :type '(choice
441 (const :tag "nofold: show all" nil)
442 (const :tag "fold: overview" t)
443 (const :tag "content: all headlines" content)
444 (const :tag "show everything, even drawers" showeverything)))
446 (defcustom org-startup-truncated t
447 "Non-nil means entering Org-mode will set `truncate-lines'.
448 This is useful since some lines containing links can be very long and
449 uninteresting. Also tables look terrible when wrapped."
450 :group 'org-startup
451 :type 'boolean)
453 (defcustom org-startup-indented nil
454 "Non-nil means turn on `org-indent-mode' on startup.
455 This can also be configured on a per-file basis by adding one of
456 the following lines anywhere in the buffer:
458 #+STARTUP: indent
459 #+STARTUP: noindent"
460 :group 'org-structure
461 :type '(choice
462 (const :tag "Not" nil)
463 (const :tag "Globally (slow on startup in large files)" t)))
465 (defcustom org-use-sub-superscripts t
466 "Non-nil means interpret \"_\" and \"^\" for export.
467 When this option is turned on, you can use TeX-like syntax for sub- and
468 superscripts. Several characters after \"_\" or \"^\" will be
469 considered as a single item - so grouping with {} is normally not
470 needed. For example, the following things will be parsed as single
471 sub- or superscripts.
473 10^24 or 10^tau several digits will be considered 1 item.
474 10^-12 or 10^-tau a leading sign with digits or a word
475 x^2-y^3 will be read as x^2 - y^3, because items are
476 terminated by almost any nonword/nondigit char.
477 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
479 Still, ambiguity is possible - so when in doubt use {} to enclose the
480 sub/superscript. If you set this variable to the symbol `{}',
481 the braces are *required* in order to trigger interpretations as
482 sub/superscript. This can be helpful in documents that need \"_\"
483 frequently in plain text.
485 Not all export backends support this, but HTML does.
487 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
488 :group 'org-startup
489 :group 'org-export-translation
490 :type '(choice
491 (const :tag "Always interpret" t)
492 (const :tag "Only with braces" {})
493 (const :tag "Never interpret" nil)))
495 (if (fboundp 'defvaralias)
496 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
499 (defcustom org-startup-with-beamer-mode nil
500 "Non-nil means turn on `org-beamer-mode' on startup.
501 This can also be configured on a per-file basis by adding one of
502 the following lines anywhere in the buffer:
504 #+STARTUP: beamer"
505 :group 'org-startup
506 :type 'boolean)
508 (defcustom org-startup-align-all-tables nil
509 "Non-nil means align all tables when visiting a file.
510 This is useful when the column width in tables is forced with <N> cookies
511 in table fields. Such tables will look correct only after the first re-align.
512 This can also be configured on a per-file basis by adding one of
513 the following lines anywhere in the buffer:
514 #+STARTUP: align
515 #+STARTUP: noalign"
516 :group 'org-startup
517 :type 'boolean)
519 (defcustom org-startup-with-inline-images nil
520 "Non-nil means show inline images when loading a new Org file.
521 This can also be configured on a per-file basis by adding one of
522 the following lines anywhere in the buffer:
523 #+STARTUP: inlineimages
524 #+STARTUP: noinlineimages"
525 :group 'org-startup
526 :type 'boolean)
528 (defcustom org-insert-mode-line-in-empty-file nil
529 "Non-nil means insert the first line setting Org-mode in empty files.
530 When the function `org-mode' is called interactively in an empty file, this
531 normally means that the file name does not automatically trigger Org-mode.
532 To ensure that the file will always be in Org-mode in the future, a
533 line enforcing Org-mode will be inserted into the buffer, if this option
534 has been set."
535 :group 'org-startup
536 :type 'boolean)
538 (defcustom org-replace-disputed-keys nil
539 "Non-nil means use alternative key bindings for some keys.
540 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
541 These keys are also used by other packages like shift-selection-mode'
542 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
543 If you want to use Org-mode together with one of these other modes,
544 or more generally if you would like to move some Org-mode commands to
545 other keys, set this variable and configure the keys with the variable
546 `org-disputed-keys'.
548 This option is only relevant at load-time of Org-mode, and must be set
549 *before* org.el is loaded. Changing it requires a restart of Emacs to
550 become effective."
551 :group 'org-startup
552 :type 'boolean)
554 (defcustom org-use-extra-keys nil
555 "Non-nil means use extra key sequence definitions for certain commands.
556 This happens automatically if you run XEmacs or if `window-system'
557 is nil. This variable lets you do the same manually. You must
558 set it before loading org.
560 Example: on Carbon Emacs 22 running graphically, with an external
561 keyboard on a Powerbook, the default way of setting M-left might
562 not work for either Alt or ESC. Setting this variable will make
563 it work for ESC."
564 :group 'org-startup
565 :type 'boolean)
567 (if (fboundp 'defvaralias)
568 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
570 (defcustom org-disputed-keys
571 '(([(shift up)] . [(meta p)])
572 ([(shift down)] . [(meta n)])
573 ([(shift left)] . [(meta -)])
574 ([(shift right)] . [(meta +)])
575 ([(control shift right)] . [(meta shift +)])
576 ([(control shift left)] . [(meta shift -)]))
577 "Keys for which Org-mode and other modes compete.
578 This is an alist, cars are the default keys, second element specifies
579 the alternative to use when `org-replace-disputed-keys' is t.
581 Keys can be specified in any syntax supported by `define-key'.
582 The value of this option takes effect only at Org-mode's startup,
583 therefore you'll have to restart Emacs to apply it after changing."
584 :group 'org-startup
585 :type 'alist)
587 (defun org-key (key)
588 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
589 Or return the original if not disputed.
590 Also apply the translations defined in `org-xemacs-key-equivalents'."
591 (when org-replace-disputed-keys
592 (let* ((nkey (key-description key))
593 (x (org-find-if (lambda (x)
594 (equal (key-description (car x)) nkey))
595 org-disputed-keys)))
596 (setq key (if x (cdr x) key))))
597 (when (featurep 'xemacs)
598 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
599 key)
601 (defun org-find-if (predicate seq)
602 (catch 'exit
603 (while seq
604 (if (funcall predicate (car seq))
605 (throw 'exit (car seq))
606 (pop seq)))))
608 (defun org-defkey (keymap key def)
609 "Define a key, possibly translated, as returned by `org-key'."
610 (define-key keymap (org-key key) def))
612 (defcustom org-ellipsis nil
613 "The ellipsis to use in the Org-mode outline.
614 When nil, just use the standard three dots. When a string, use that instead,
615 When a face, use the standard 3 dots, but with the specified face.
616 The change affects only Org-mode (which will then use its own display table).
617 Changing this requires executing `M-x org-mode' in a buffer to become
618 effective."
619 :group 'org-startup
620 :type '(choice (const :tag "Default" nil)
621 (face :tag "Face" :value org-warning)
622 (string :tag "String" :value "...#")))
624 (defvar org-display-table nil
625 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
627 (defgroup org-keywords nil
628 "Keywords in Org-mode."
629 :tag "Org Keywords"
630 :group 'org)
632 (defcustom org-deadline-string "DEADLINE:"
633 "String to mark deadline entries.
634 A deadline is this string, followed by a time stamp. Should be a word,
635 terminated by a colon. You can insert a schedule keyword and
636 a timestamp with \\[org-deadline].
637 Changes become only effective after restarting Emacs."
638 :group 'org-keywords
639 :type 'string)
641 (defcustom org-scheduled-string "SCHEDULED:"
642 "String to mark scheduled TODO entries.
643 A schedule is this string, followed by a time stamp. Should be a word,
644 terminated by a colon. You can insert a schedule keyword and
645 a timestamp with \\[org-schedule].
646 Changes become only effective after restarting Emacs."
647 :group 'org-keywords
648 :type 'string)
650 (defcustom org-closed-string "CLOSED:"
651 "String used as the prefix for timestamps logging closing a TODO entry."
652 :group 'org-keywords
653 :type 'string)
655 (defcustom org-clock-string "CLOCK:"
656 "String used as prefix for timestamps clocking work hours on an item."
657 :group 'org-keywords
658 :type 'string)
660 (defcustom org-comment-string "COMMENT"
661 "Entries starting with this keyword will never be exported.
662 An entry can be toggled between COMMENT and normal with
663 \\[org-toggle-comment].
664 Changes become only effective after restarting Emacs."
665 :group 'org-keywords
666 :type 'string)
668 (defcustom org-quote-string "QUOTE"
669 "Entries starting with this keyword will be exported in fixed-width font.
670 Quoting applies only to the text in the entry following the headline, and does
671 not extend beyond the next headline, even if that is lower level.
672 An entry can be toggled between QUOTE and normal with
673 \\[org-toggle-fixed-width-section]."
674 :group 'org-keywords
675 :type 'string)
677 (defconst org-repeat-re
678 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
679 "Regular expression for specifying repeated events.
680 After a match, group 1 contains the repeat expression.")
682 (defgroup org-structure nil
683 "Options concerning the general structure of Org-mode files."
684 :tag "Org Structure"
685 :group 'org)
687 (defgroup org-reveal-location nil
688 "Options about how to make context of a location visible."
689 :tag "Org Reveal Location"
690 :group 'org-structure)
692 (defconst org-context-choice
693 '(choice
694 (const :tag "Always" t)
695 (const :tag "Never" nil)
696 (repeat :greedy t :tag "Individual contexts"
697 (cons
698 (choice :tag "Context"
699 (const agenda)
700 (const org-goto)
701 (const occur-tree)
702 (const tags-tree)
703 (const link-search)
704 (const mark-goto)
705 (const bookmark-jump)
706 (const isearch)
707 (const default))
708 (boolean))))
709 "Contexts for the reveal options.")
711 (defcustom org-show-hierarchy-above '((default . t))
712 "Non-nil means show full hierarchy when revealing a location.
713 Org-mode often shows locations in an org-mode file which might have
714 been invisible before. When this is set, the hierarchy of headings
715 above the exposed location is shown.
716 Turning this off for example for sparse trees makes them very compact.
717 Instead of t, this can also be an alist specifying this option for different
718 contexts. Valid contexts are
719 agenda when exposing an entry from the agenda
720 org-goto when using the command `org-goto' on key C-c C-j
721 occur-tree when using the command `org-occur' on key C-c /
722 tags-tree when constructing a sparse tree based on tags matches
723 link-search when exposing search matches associated with a link
724 mark-goto when exposing the jump goal of a mark
725 bookmark-jump when exposing a bookmark location
726 isearch when exiting from an incremental search
727 default default for all contexts not set explicitly"
728 :group 'org-reveal-location
729 :type org-context-choice)
731 (defcustom org-show-following-heading '((default . nil))
732 "Non-nil means show following heading when revealing a location.
733 Org-mode often shows locations in an org-mode file which might have
734 been invisible before. When this is set, the heading following the
735 match is shown.
736 Turning this off for example for sparse trees makes them very compact,
737 but makes it harder to edit the location of the match. In such a case,
738 use the command \\[org-reveal] to show more context.
739 Instead of t, this can also be an alist specifying this option for different
740 contexts. See `org-show-hierarchy-above' for valid contexts."
741 :group 'org-reveal-location
742 :type org-context-choice)
744 (defcustom org-show-siblings '((default . nil) (isearch t))
745 "Non-nil means show all sibling heading when revealing a location.
746 Org-mode often shows locations in an org-mode file which might have
747 been invisible before. When this is set, the sibling of the current entry
748 heading are all made visible. If `org-show-hierarchy-above' is t,
749 the same happens on each level of the hierarchy above the current entry.
751 By default this is on for the isearch context, off for all other contexts.
752 Turning this off for example for sparse trees makes them very compact,
753 but makes it harder to edit the location of the match. In such a case,
754 use the command \\[org-reveal] to show more context.
755 Instead of t, this can also be an alist specifying this option for different
756 contexts. See `org-show-hierarchy-above' for valid contexts."
757 :group 'org-reveal-location
758 :type org-context-choice)
760 (defcustom org-show-entry-below '((default . nil))
761 "Non-nil means show the entry below a headline when revealing a location.
762 Org-mode often shows locations in an org-mode file which might have
763 been invisible before. When this is set, the text below the headline that is
764 exposed is also shown.
766 By default this is off for all contexts.
767 Instead of t, this can also be an alist specifying this option for different
768 contexts. See `org-show-hierarchy-above' for valid contexts."
769 :group 'org-reveal-location
770 :type org-context-choice)
772 (defcustom org-indirect-buffer-display 'other-window
773 "How should indirect tree buffers be displayed?
774 This applies to indirect buffers created with the commands
775 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
776 Valid values are:
777 current-window Display in the current window
778 other-window Just display in another window.
779 dedicated-frame Create one new frame, and re-use it each time.
780 new-frame Make a new frame each time. Note that in this case
781 previously-made indirect buffers are kept, and you need to
782 kill these buffers yourself."
783 :group 'org-structure
784 :group 'org-agenda-windows
785 :type '(choice
786 (const :tag "In current window" current-window)
787 (const :tag "In current frame, other window" other-window)
788 (const :tag "Each time a new frame" new-frame)
789 (const :tag "One dedicated frame" dedicated-frame)))
791 (defcustom org-use-speed-commands nil
792 "Non-nil means activate single letter commands at beginning of a headline.
793 This may also be a function to test for appropriate locations where speed
794 commands should be active."
795 :group 'org-structure
796 :type '(choice
797 (const :tag "Never" nil)
798 (const :tag "At beginning of headline stars" t)
799 (function)))
801 (defcustom org-speed-commands-user nil
802 "Alist of additional speed commands.
803 This list will be checked before `org-speed-commands-default'
804 when the variable `org-use-speed-commands' is non-nil
805 and when the cursor is at the beginning of a headline.
806 The car if each entry is a string with a single letter, which must
807 be assigned to `self-insert-command' in the global map.
808 The cdr is either a command to be called interactively, a function
809 to be called, or a form to be evaluated.
810 An entry that is just a list with a single string will be interpreted
811 as a descriptive headline that will be added when listing the speed
812 commands in the Help buffer using the `?' speed command."
813 :group 'org-structure
814 :type '(repeat :value ("k" . ignore)
815 (choice :value ("k" . ignore)
816 (list :tag "Descriptive Headline" (string :tag "Headline"))
817 (cons :tag "Letter and Command"
818 (string :tag "Command letter")
819 (choice
820 (function)
821 (sexp))))))
823 (defgroup org-cycle nil
824 "Options concerning visibility cycling in Org-mode."
825 :tag "Org Cycle"
826 :group 'org-structure)
828 (defcustom org-cycle-skip-children-state-if-no-children t
829 "Non-nil means skip CHILDREN state in entries that don't have any."
830 :group 'org-cycle
831 :type 'boolean)
833 (defcustom org-cycle-max-level nil
834 "Maximum level which should still be subject to visibility cycling.
835 Levels higher than this will, for cycling, be treated as text, not a headline.
836 When `org-odd-levels-only' is set, a value of N in this variable actually
837 means 2N-1 stars as the limiting headline.
838 When nil, cycle all levels.
839 Note that the limiting level of cycling is also influenced by
840 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
841 `org-inlinetask-min-level' is, cycling will be limited to levels one less
842 than its value."
843 :group 'org-cycle
844 :type '(choice
845 (const :tag "No limit" nil)
846 (integer :tag "Maximum level")))
848 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
849 "Names of drawers. Drawers are not opened by cycling on the headline above.
850 Drawers only open with a TAB on the drawer line itself. A drawer looks like
851 this:
852 :DRAWERNAME:
853 .....
854 :END:
855 The drawer \"PROPERTIES\" is special for capturing properties through
856 the property API.
858 Drawers can be defined on the per-file basis with a line like:
860 #+DRAWERS: HIDDEN STATE PROPERTIES"
861 :group 'org-structure
862 :group 'org-cycle
863 :type '(repeat (string :tag "Drawer Name")))
865 (defcustom org-hide-block-startup nil
866 "Non-nil means entering Org-mode will fold all blocks.
867 This can also be set in on a per-file basis with
869 #+STARTUP: hideblocks
870 #+STARTUP: showblocks"
871 :group 'org-startup
872 :group 'org-cycle
873 :type 'boolean)
875 (defcustom org-cycle-global-at-bob nil
876 "Cycle globally if cursor is at beginning of buffer and not at a headline.
877 This makes it possible to do global cycling without having to use S-TAB or
878 \\[universal-argument] TAB. For this special case to work, the first line \
879 of the buffer
880 must not be a headline - it may be empty or some other text. When used in
881 this way, `org-cycle-hook' is disables temporarily, to make sure the
882 cursor stays at the beginning of the buffer.
883 When this option is nil, don't do anything special at the beginning
884 of the buffer."
885 :group 'org-cycle
886 :type 'boolean)
888 (defcustom org-cycle-level-after-item/entry-creation t
889 "Non-nil means cycle entry level or item indentation in new empty entries.
891 When the cursor is at the end of an empty headline, i.e with only stars
892 and maybe a TODO keyword, TAB will then switch the entry to become a child,
893 and then all possible ancestor states, before returning to the original state.
894 This makes data entry extremely fast: M-RET to create a new headline,
895 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
897 When the cursor is at the end of an empty plain list item, one TAB will
898 make it a subitem, two or more tabs will back up to make this an item
899 higher up in the item hierarchy."
900 :group 'org-cycle
901 :type 'boolean)
903 (defcustom org-cycle-emulate-tab t
904 "Where should `org-cycle' emulate TAB.
905 nil Never
906 white Only in completely white lines
907 whitestart Only at the beginning of lines, before the first non-white char
908 t Everywhere except in headlines
909 exc-hl-bol Everywhere except at the start of a headline
910 If TAB is used in a place where it does not emulate TAB, the current subtree
911 visibility is cycled."
912 :group 'org-cycle
913 :type '(choice (const :tag "Never" nil)
914 (const :tag "Only in completely white lines" white)
915 (const :tag "Before first char in a line" whitestart)
916 (const :tag "Everywhere except in headlines" t)
917 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
920 (defcustom org-cycle-separator-lines 2
921 "Number of empty lines needed to keep an empty line between collapsed trees.
922 If you leave an empty line between the end of a subtree and the following
923 headline, this empty line is hidden when the subtree is folded.
924 Org-mode will leave (exactly) one empty line visible if the number of
925 empty lines is equal or larger to the number given in this variable.
926 So the default 2 means at least 2 empty lines after the end of a subtree
927 are needed to produce free space between a collapsed subtree and the
928 following headline.
930 If the number is negative, and the number of empty lines is at least -N,
931 all empty lines are shown.
933 Special case: when 0, never leave empty lines in collapsed view."
934 :group 'org-cycle
935 :type 'integer)
936 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
938 (defcustom org-pre-cycle-hook nil
939 "Hook that is run before visibility cycling is happening.
940 The function(s) in this hook must accept a single argument which indicates
941 the new state that will be set right after running this hook. The
942 argument is a symbol. Before a global state change, it can have the values
943 `overview', `content', or `all'. Before a local state change, it can have
944 the values `folded', `children', or `subtree'."
945 :group 'org-cycle
946 :type 'hook)
948 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
949 org-cycle-hide-drawers
950 org-cycle-show-empty-lines
951 org-optimize-window-after-visibility-change)
952 "Hook that is run after `org-cycle' has changed the buffer visibility.
953 The function(s) in this hook must accept a single argument which indicates
954 the new state that was set by the most recent `org-cycle' command. The
955 argument is a symbol. After a global state change, it can have the values
956 `overview', `content', or `all'. After a local state change, it can have
957 the values `folded', `children', or `subtree'."
958 :group 'org-cycle
959 :type 'hook)
961 (defgroup org-edit-structure nil
962 "Options concerning structure editing in Org-mode."
963 :tag "Org Edit Structure"
964 :group 'org-structure)
966 (defcustom org-odd-levels-only nil
967 "Non-nil means skip even levels and only use odd levels for the outline.
968 This has the effect that two stars are being added/taken away in
969 promotion/demotion commands. It also influences how levels are
970 handled by the exporters.
971 Changing it requires restart of `font-lock-mode' to become effective
972 for fontification also in regions already fontified.
973 You may also set this on a per-file basis by adding one of the following
974 lines to the buffer:
976 #+STARTUP: odd
977 #+STARTUP: oddeven"
978 :group 'org-edit-structure
979 :group 'org-appearance
980 :type 'boolean)
982 (defcustom org-adapt-indentation t
983 "Non-nil means adapt indentation to outline node level.
985 When this variable is set, Org assumes that you write outlines by
986 indenting text in each node to align with the headline (after the stars).
987 The following issues are influenced by this variable:
989 - When this is set and the *entire* text in an entry is indented, the
990 indentation is increased by one space in a demotion command, and
991 decreased by one in a promotion command. If any line in the entry
992 body starts with text at column 0, indentation is not changed at all.
994 - Property drawers and planning information is inserted indented when
995 this variable s set. When nil, they will not be indented.
997 - TAB indents a line relative to context. The lines below a headline
998 will be indented when this variable is set.
1000 Note that this is all about true indentation, by adding and removing
1001 space characters. See also `org-indent.el' which does level-dependent
1002 indentation in a virtual way, i.e. at display time in Emacs."
1003 :group 'org-edit-structure
1004 :type 'boolean)
1006 (defcustom org-special-ctrl-a/e nil
1007 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1009 When t, `C-a' will bring back the cursor to the beginning of the
1010 headline text, i.e. after the stars and after a possible TODO keyword.
1011 In an item, this will be the position after the bullet.
1012 When the cursor is already at that position, another `C-a' will bring
1013 it to the beginning of the line.
1015 `C-e' will jump to the end of the headline, ignoring the presence of tags
1016 in the headline. A second `C-e' will then jump to the true end of the
1017 line, after any tags. This also means that, when this variable is
1018 non-nil, `C-e' also will never jump beyond the end of the heading of a
1019 folded section, i.e. not after the ellipses.
1021 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
1022 going to the true line boundary first. Only a directly following, identical
1023 keypress will bring the cursor to the special positions.
1025 This may also be a cons cell where the behavior for `C-a' and `C-e' is
1026 set separately."
1027 :group 'org-edit-structure
1028 :type '(choice
1029 (const :tag "off" nil)
1030 (const :tag "on: after stars/bullet and before tags first" t)
1031 (const :tag "reversed: true line boundary first" reversed)
1032 (cons :tag "Set C-a and C-e separately"
1033 (choice :tag "Special C-a"
1034 (const :tag "off" nil)
1035 (const :tag "on: after stars/bullet first" t)
1036 (const :tag "reversed: before stars/bullet first" reversed))
1037 (choice :tag "Special C-e"
1038 (const :tag "off" nil)
1039 (const :tag "on: before tags first" t)
1040 (const :tag "reversed: after tags first" reversed)))))
1041 (if (fboundp 'defvaralias)
1042 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1044 (defcustom org-special-ctrl-k nil
1045 "Non-nil means `C-k' will behave specially in headlines.
1046 When nil, `C-k' will call the default `kill-line' command.
1047 When t, the following will happen while the cursor is in the headline:
1049 - When the cursor is at the beginning of a headline, kill the entire
1050 line and possible the folded subtree below the line.
1051 - When in the middle of the headline text, kill the headline up to the tags.
1052 - When after the headline text, kill the tags."
1053 :group 'org-edit-structure
1054 :type 'boolean)
1056 (defcustom org-ctrl-k-protect-subtree nil
1057 "Non-nil means, do not delete a hidden subtree with C-k.
1058 When set to the symbol `error', simply throw an error when C-k is
1059 used to kill (part-of) a headline that has hidden text behind it.
1060 Any other non-nil value will result in a query to the user, if it is
1061 OK to kill that hidden subtree. When nil, kill without remorse."
1062 :group 'org-edit-structure
1063 :type '(choice
1064 (const :tag "Do not protect hidden subtrees" nil)
1065 (const :tag "Protect hidden subtrees with a security query" t)
1066 (const :tag "Never kill a hidden subtree with C-k" error)))
1068 (defcustom org-yank-folded-subtrees t
1069 "Non-nil means when yanking subtrees, fold them.
1070 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1071 it starts with a heading and all other headings in it are either children
1072 or siblings, then fold all the subtrees. However, do this only if no
1073 text after the yank would be swallowed into a folded tree by this action."
1074 :group 'org-edit-structure
1075 :type 'boolean)
1077 (defcustom org-yank-adjusted-subtrees nil
1078 "Non-nil means when yanking subtrees, adjust the level.
1079 With this setting, `org-paste-subtree' is used to insert the subtree, see
1080 this function for details."
1081 :group 'org-edit-structure
1082 :type 'boolean)
1084 (defcustom org-M-RET-may-split-line '((default . t))
1085 "Non-nil means M-RET will split the line at the cursor position.
1086 When nil, it will go to the end of the line before making a
1087 new line.
1088 You may also set this option in a different way for different
1089 contexts. Valid contexts are:
1091 headline when creating a new headline
1092 item when creating a new item
1093 table in a table field
1094 default the value to be used for all contexts not explicitly
1095 customized"
1096 :group 'org-structure
1097 :group 'org-table
1098 :type '(choice
1099 (const :tag "Always" t)
1100 (const :tag "Never" nil)
1101 (repeat :greedy t :tag "Individual contexts"
1102 (cons
1103 (choice :tag "Context"
1104 (const headline)
1105 (const item)
1106 (const table)
1107 (const default))
1108 (boolean)))))
1111 (defcustom org-insert-heading-respect-content nil
1112 "Non-nil means insert new headings after the current subtree.
1113 When nil, the new heading is created directly after the current line.
1114 The commands \\[org-insert-heading-respect-content] and
1115 \\[org-insert-todo-heading-respect-content] turn this variable on
1116 for the duration of the command."
1117 :group 'org-structure
1118 :type 'boolean)
1120 (defcustom org-blank-before-new-entry '((heading . auto)
1121 (plain-list-item . auto))
1122 "Should `org-insert-heading' leave a blank line before new heading/item?
1123 The value is an alist, with `heading' and `plain-list-item' as CAR,
1124 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1125 which case Org will look at the surrounding headings/items and try to
1126 make an intelligent decision whether to insert a blank line or not.
1128 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1129 set, the setting here is ignored and no empty line is inserted, to avoid
1130 breaking the list structure."
1131 :group 'org-edit-structure
1132 :type '(list
1133 (cons (const heading)
1134 (choice (const :tag "Never" nil)
1135 (const :tag "Always" t)
1136 (const :tag "Auto" auto)))
1137 (cons (const plain-list-item)
1138 (choice (const :tag "Never" nil)
1139 (const :tag "Always" t)
1140 (const :tag "Auto" auto)))))
1142 (defcustom org-insert-heading-hook nil
1143 "Hook being run after inserting a new heading."
1144 :group 'org-edit-structure
1145 :type 'hook)
1147 (defcustom org-enable-fixed-width-editor t
1148 "Non-nil means lines starting with \":\" are treated as fixed-width.
1149 This currently only means they are never auto-wrapped.
1150 When nil, such lines will be treated like ordinary lines.
1151 See also the QUOTE keyword."
1152 :group 'org-edit-structure
1153 :type 'boolean)
1155 (defcustom org-goto-auto-isearch t
1156 "Non-nil means typing characters in `org-goto' starts incremental search."
1157 :group 'org-edit-structure
1158 :type 'boolean)
1160 (defgroup org-sparse-trees nil
1161 "Options concerning sparse trees in Org-mode."
1162 :tag "Org Sparse Trees"
1163 :group 'org-structure)
1165 (defcustom org-highlight-sparse-tree-matches t
1166 "Non-nil means highlight all matches that define a sparse tree.
1167 The highlights will automatically disappear the next time the buffer is
1168 changed by an edit command."
1169 :group 'org-sparse-trees
1170 :type 'boolean)
1172 (defcustom org-remove-highlights-with-change t
1173 "Non-nil means any change to the buffer will remove temporary highlights.
1174 Such highlights are created by `org-occur' and `org-clock-display'.
1175 When nil, `C-c C-c needs to be used to get rid of the highlights.
1176 The highlights created by `org-preview-latex-fragment' always need
1177 `C-c C-c' to be removed."
1178 :group 'org-sparse-trees
1179 :group 'org-time
1180 :type 'boolean)
1183 (defcustom org-occur-hook '(org-first-headline-recenter)
1184 "Hook that is run after `org-occur' has constructed a sparse tree.
1185 This can be used to recenter the window to show as much of the structure
1186 as possible."
1187 :group 'org-sparse-trees
1188 :type 'hook)
1190 (defgroup org-imenu-and-speedbar nil
1191 "Options concerning imenu and speedbar in Org-mode."
1192 :tag "Org Imenu and Speedbar"
1193 :group 'org-structure)
1195 (defcustom org-imenu-depth 2
1196 "The maximum level for Imenu access to Org-mode headlines.
1197 This also applied for speedbar access."
1198 :group 'org-imenu-and-speedbar
1199 :type 'integer)
1201 (defgroup org-table nil
1202 "Options concerning tables in Org-mode."
1203 :tag "Org Table"
1204 :group 'org)
1206 (defcustom org-enable-table-editor 'optimized
1207 "Non-nil means lines starting with \"|\" are handled by the table editor.
1208 When nil, such lines will be treated like ordinary lines.
1210 When equal to the symbol `optimized', the table editor will be optimized to
1211 do the following:
1212 - Automatic overwrite mode in front of whitespace in table fields.
1213 This makes the structure of the table stay in tact as long as the edited
1214 field does not exceed the column width.
1215 - Minimize the number of realigns. Normally, the table is aligned each time
1216 TAB or RET are pressed to move to another field. With optimization this
1217 happens only if changes to a field might have changed the column width.
1218 Optimization requires replacing the functions `self-insert-command',
1219 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1220 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1221 very good at guessing when a re-align will be necessary, but you can always
1222 force one with \\[org-ctrl-c-ctrl-c].
1224 If you would like to use the optimized version in Org-mode, but the
1225 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1227 This variable can be used to turn on and off the table editor during a session,
1228 but in order to toggle optimization, a restart is required.
1230 See also the variable `org-table-auto-blank-field'."
1231 :group 'org-table
1232 :type '(choice
1233 (const :tag "off" nil)
1234 (const :tag "on" t)
1235 (const :tag "on, optimized" optimized)))
1237 (defcustom org-self-insert-cluster-for-undo t
1238 "Non-nil means cluster self-insert commands for undo when possible.
1239 If this is set, then, like in the Emacs command loop, 20 consecutive
1240 characters will be undone together.
1241 This is configurable, because there is some impact on typing performance."
1242 :group 'org-table
1243 :type 'boolean)
1245 (defcustom org-table-tab-recognizes-table.el t
1246 "Non-nil means TAB will automatically notice a table.el table.
1247 When it sees such a table, it moves point into it and - if necessary -
1248 calls `table-recognize-table'."
1249 :group 'org-table-editing
1250 :type 'boolean)
1252 (defgroup org-link nil
1253 "Options concerning links in Org-mode."
1254 :tag "Org Link"
1255 :group 'org)
1257 (defvar org-link-abbrev-alist-local nil
1258 "Buffer-local version of `org-link-abbrev-alist', which see.
1259 The value of this is taken from the #+LINK lines.")
1260 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1262 (defcustom org-link-abbrev-alist nil
1263 "Alist of link abbreviations.
1264 The car of each element is a string, to be replaced at the start of a link.
1265 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1266 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1268 [[linkkey:tag][description]]
1270 The 'linkkey' must be a word word, starting with a letter, followed
1271 by letters, numbers, '-' or '_'.
1273 If REPLACE is a string, the tag will simply be appended to create the link.
1274 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1275 the placeholder \"%h\" will cause a url-encoded version of the tag to
1276 be inserted at that point (see the function `url-hexify-string').
1278 REPLACE may also be a function that will be called with the tag as the
1279 only argument to create the link, which should be returned as a string.
1281 See the manual for examples."
1282 :group 'org-link
1283 :type '(repeat
1284 (cons
1285 (string :tag "Protocol")
1286 (choice
1287 (string :tag "Format")
1288 (function)))))
1290 (defcustom org-descriptive-links t
1291 "Non-nil means Org will display descriptive links.
1292 E.g. [[http://orgmode.org][Org website]] will be displayed as
1293 \"Org Website\", hiding the link itself and just displaying its
1294 description. When set to `nil', Org will display the full links
1295 literally.
1297 You can interactively set the value of this variable by calling
1298 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1299 :group 'org-link
1300 :type 'boolean)
1302 (defcustom org-link-file-path-type 'adaptive
1303 "How the path name in file links should be stored.
1304 Valid values are:
1306 relative Relative to the current directory, i.e. the directory of the file
1307 into which the link is being inserted.
1308 absolute Absolute path, if possible with ~ for home directory.
1309 noabbrev Absolute path, no abbreviation of home directory.
1310 adaptive Use relative path for files in the current directory and sub-
1311 directories of it. For other files, use an absolute path."
1312 :group 'org-link
1313 :type '(choice
1314 (const relative)
1315 (const absolute)
1316 (const noabbrev)
1317 (const adaptive)))
1319 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1320 "Types of links that should be activated in Org-mode files.
1321 This is a list of symbols, each leading to the activation of a certain link
1322 type. In principle, it does not hurt to turn on most link types - there may
1323 be a small gain when turning off unused link types. The types are:
1325 bracket The recommended [[link][description]] or [[link]] links with hiding.
1326 angle Links in angular brackets that may contain whitespace like
1327 <bbdb:Carsten Dominik>.
1328 plain Plain links in normal text, no whitespace, like http://google.com.
1329 radio Text that is matched by a radio target, see manual for details.
1330 tag Tag settings in a headline (link to tag search).
1331 date Time stamps (link to calendar).
1332 footnote Footnote labels.
1334 Changing this variable requires a restart of Emacs to become effective."
1335 :group 'org-link
1336 :type '(set :greedy t
1337 (const :tag "Double bracket links" bracket)
1338 (const :tag "Angular bracket links" angle)
1339 (const :tag "Plain text links" plain)
1340 (const :tag "Radio target matches" radio)
1341 (const :tag "Tags" tag)
1342 (const :tag "Timestamps" date)
1343 (const :tag "Footnotes" footnote)))
1345 (defcustom org-make-link-description-function nil
1346 "Function to use to generate link descriptions from links.
1347 If nil the link location will be used. This function must take
1348 two parameters; the first is the link and the second the
1349 description `org-insert-link' has generated, and should return the
1350 description to use."
1351 :group 'org-link
1352 :type 'function)
1354 (defgroup org-link-store nil
1355 "Options concerning storing links in Org-mode."
1356 :tag "Org Store Link"
1357 :group 'org-link)
1359 (defcustom org-email-link-description-format "Email %c: %.30s"
1360 "Format of the description part of a link to an email or usenet message.
1361 The following %-escapes will be replaced by corresponding information:
1363 %F full \"From\" field
1364 %f name, taken from \"From\" field, address if no name
1365 %T full \"To\" field
1366 %t first name in \"To\" field, address if no name
1367 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1368 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1369 %s subject
1370 %d date
1371 %m message-id.
1373 You may use normal field width specification between the % and the letter.
1374 This is for example useful to limit the length of the subject.
1376 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1377 :group 'org-link-store
1378 :type 'string)
1380 (defcustom org-from-is-user-regexp
1381 (let (r1 r2)
1382 (when (and user-mail-address (not (string= user-mail-address "")))
1383 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1384 (when (and user-full-name (not (string= user-full-name "")))
1385 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1386 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1387 "Regexp matched against the \"From:\" header of an email or usenet message.
1388 It should match if the message is from the user him/herself."
1389 :group 'org-link-store
1390 :type 'regexp)
1392 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1393 "Non-nil means storing a link to an Org file will use entry IDs.
1395 Note that before this variable is even considered, org-id must be loaded,
1396 so please customize `org-modules' and turn it on.
1398 The variable can have the following values:
1400 t Create an ID if needed to make a link to the current entry.
1402 create-if-interactive
1403 If `org-store-link' is called directly (interactively, as a user
1404 command), do create an ID to support the link. But when doing the
1405 job for remember, only use the ID if it already exists. The
1406 purpose of this setting is to avoid proliferation of unwanted
1407 IDs, just because you happen to be in an Org file when you
1408 call `org-remember' that automatically and preemptively
1409 creates a link. If you do want to get an ID link in a remember
1410 template to an entry not having an ID, create it first by
1411 explicitly creating a link to it, using `C-c C-l' first.
1413 create-if-interactive-and-no-custom-id
1414 Like create-if-interactive, but do not create an ID if there is
1415 a CUSTOM_ID property defined in the entry. This is the default.
1417 use-existing
1418 Use existing ID, do not create one.
1420 nil Never use an ID to make a link, instead link using a text search for
1421 the headline text."
1422 :group 'org-link-store
1423 :type '(choice
1424 (const :tag "Create ID to make link" t)
1425 (const :tag "Create if storing link interactively"
1426 create-if-interactive)
1427 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1428 create-if-interactive-and-no-custom-id)
1429 (const :tag "Only use existing" use-existing)
1430 (const :tag "Do not use ID to create link" nil)))
1432 (defcustom org-context-in-file-links t
1433 "Non-nil means file links from `org-store-link' contain context.
1434 A search string will be added to the file name with :: as separator and
1435 used to find the context when the link is activated by the command
1436 `org-open-at-point'. When this option is t, the entire active region
1437 will be placed in the search string of the file link. If set to a
1438 positive integer, only the first n lines of context will be stored.
1440 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1441 negates this setting for the duration of the command."
1442 :group 'org-link-store
1443 :type '(choice boolean integer))
1445 (defcustom org-keep-stored-link-after-insertion nil
1446 "Non-nil means keep link in list for entire session.
1448 The command `org-store-link' adds a link pointing to the current
1449 location to an internal list. These links accumulate during a session.
1450 The command `org-insert-link' can be used to insert links into any
1451 Org-mode file (offering completion for all stored links). When this
1452 option is nil, every link which has been inserted once using \\[org-insert-link]
1453 will be removed from the list, to make completing the unused links
1454 more efficient."
1455 :group 'org-link-store
1456 :type 'boolean)
1458 (defgroup org-link-follow nil
1459 "Options concerning following links in Org-mode."
1460 :tag "Org Follow Link"
1461 :group 'org-link)
1463 (defcustom org-link-translation-function nil
1464 "Function to translate links with different syntax to Org syntax.
1465 This can be used to translate links created for example by the Planner
1466 or emacs-wiki packages to Org syntax.
1467 The function must accept two parameters, a TYPE containing the link
1468 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1469 which is everything after the link protocol. It should return a cons
1470 with possibly modified values of type and path.
1471 Org contains a function for this, so if you set this variable to
1472 `org-translate-link-from-planner', you should be able follow many
1473 links created by planner."
1474 :group 'org-link-follow
1475 :type 'function)
1477 (defcustom org-follow-link-hook nil
1478 "Hook that is run after a link has been followed."
1479 :group 'org-link-follow
1480 :type 'hook)
1482 (defcustom org-tab-follows-link nil
1483 "Non-nil means on links TAB will follow the link.
1484 Needs to be set before org.el is loaded.
1485 This really should not be used, it does not make sense, and the
1486 implementation is bad."
1487 :group 'org-link-follow
1488 :type 'boolean)
1490 (defcustom org-return-follows-link nil
1491 "Non-nil means on links RET will follow the link."
1492 :group 'org-link-follow
1493 :type 'boolean)
1495 (defcustom org-mouse-1-follows-link
1496 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1497 "Non-nil means mouse-1 on a link will follow the link.
1498 A longer mouse click will still set point. Does not work on XEmacs.
1499 Needs to be set before org.el is loaded."
1500 :group 'org-link-follow
1501 :type 'boolean)
1503 (defcustom org-mark-ring-length 4
1504 "Number of different positions to be recorded in the ring.
1505 Changing this requires a restart of Emacs to work correctly."
1506 :group 'org-link-follow
1507 :type 'integer)
1509 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1510 "Non-nil means internal links in Org files must exactly match a headline.
1511 When nil, the link search tries to match a phrase with all words
1512 in the search text."
1513 :group 'org-link-follow
1514 :type '(choice
1515 (const :tag "Use fuzzy text search" nil)
1516 (const :tag "Match only exact headline" t)
1517 (const :tag "Match exact headline or query to create it"
1518 query-to-create)))
1520 (defcustom org-link-frame-setup
1521 '((vm . vm-visit-folder-other-frame)
1522 (gnus . org-gnus-no-new-news)
1523 (file . find-file-other-window)
1524 (wl . wl-other-frame))
1525 "Setup the frame configuration for following links.
1526 When following a link with Emacs, it may often be useful to display
1527 this link in another window or frame. This variable can be used to
1528 set this up for the different types of links.
1529 For VM, use any of
1530 `vm-visit-folder'
1531 `vm-visit-folder-other-window'
1532 `vm-visit-folder-other-frame'
1533 For Gnus, use any of
1534 `gnus'
1535 `gnus-other-frame'
1536 `org-gnus-no-new-news'
1537 For FILE, use any of
1538 `find-file'
1539 `find-file-other-window'
1540 `find-file-other-frame'
1541 For Wanderlust use any of
1542 `wl'
1543 `wl-other-frame'
1544 For the calendar, use the variable `calendar-setup'.
1545 For BBDB, it is currently only possible to display the matches in
1546 another window."
1547 :group 'org-link-follow
1548 :type '(list
1549 (cons (const vm)
1550 (choice
1551 (const vm-visit-folder)
1552 (const vm-visit-folder-other-window)
1553 (const vm-visit-folder-other-frame)))
1554 (cons (const gnus)
1555 (choice
1556 (const gnus)
1557 (const gnus-other-frame)
1558 (const org-gnus-no-new-news)))
1559 (cons (const file)
1560 (choice
1561 (const find-file)
1562 (const find-file-other-window)
1563 (const find-file-other-frame)))
1564 (cons (const wl)
1565 (choice
1566 (const wl)
1567 (const wl-other-frame)))))
1569 (defcustom org-display-internal-link-with-indirect-buffer nil
1570 "Non-nil means use indirect buffer to display infile links.
1571 Activating internal links (from one location in a file to another location
1572 in the same file) normally just jumps to the location. When the link is
1573 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1574 is displayed in
1575 another window. When this option is set, the other window actually displays
1576 an indirect buffer clone of the current buffer, to avoid any visibility
1577 changes to the current buffer."
1578 :group 'org-link-follow
1579 :type 'boolean)
1581 (defcustom org-open-non-existing-files nil
1582 "Non-nil means `org-open-file' will open non-existing files.
1583 When nil, an error will be generated.
1584 This variable applies only to external applications because they
1585 might choke on non-existing files. If the link is to a file that
1586 will be opened in Emacs, the variable is ignored."
1587 :group 'org-link-follow
1588 :type 'boolean)
1590 (defcustom org-open-directory-means-index-dot-org nil
1591 "Non-nil means a link to a directory really means to index.org.
1592 When nil, following a directory link will run dired or open a finder/explorer
1593 window on that directory."
1594 :group 'org-link-follow
1595 :type 'boolean)
1597 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1598 "Function and arguments to call for following mailto links.
1599 This is a list with the first element being a Lisp function, and the
1600 remaining elements being arguments to the function. In string arguments,
1601 %a will be replaced by the address, and %s will be replaced by the subject
1602 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1603 :group 'org-link-follow
1604 :type '(choice
1605 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1606 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1607 (const :tag "message-mail" (message-mail "%a" "%s"))
1608 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1610 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1611 "Non-nil means ask for confirmation before executing shell links.
1612 Shell links can be dangerous: just think about a link
1614 [[shell:rm -rf ~/*][Google Search]]
1616 This link would show up in your Org-mode document as \"Google Search\",
1617 but really it would remove your entire home directory.
1618 Therefore we advise against setting this variable to nil.
1619 Just change it to `y-or-n-p' if you want to confirm with a
1620 single keystroke rather than having to type \"yes\"."
1621 :group 'org-link-follow
1622 :type '(choice
1623 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1624 (const :tag "with y-or-n (faster)" y-or-n-p)
1625 (const :tag "no confirmation (dangerous)" nil)))
1626 (put 'org-confirm-shell-link-function
1627 'safe-local-variable
1628 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1630 (defcustom org-confirm-shell-link-not-regexp ""
1631 "A regexp to skip confirmation for shell links."
1632 :group 'org-link-follow
1633 :type 'regexp)
1635 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1636 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1637 Elisp links can be dangerous: just think about a link
1639 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1641 This link would show up in your Org-mode document as \"Google Search\",
1642 but really it would remove your entire home directory.
1643 Therefore we advise against setting this variable to nil.
1644 Just change it to `y-or-n-p' if you want to confirm with a
1645 single keystroke rather than having to type \"yes\"."
1646 :group 'org-link-follow
1647 :type '(choice
1648 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1649 (const :tag "with y-or-n (faster)" y-or-n-p)
1650 (const :tag "no confirmation (dangerous)" nil)))
1651 (put 'org-confirm-shell-link-function
1652 'safe-local-variable
1653 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1655 (defcustom org-confirm-elisp-link-not-regexp ""
1656 "A regexp to skip confirmation for Elisp links."
1657 :group 'org-link-follow
1658 :type 'regexp)
1660 (defconst org-file-apps-defaults-gnu
1661 '((remote . emacs)
1662 (system . mailcap)
1663 (t . mailcap))
1664 "Default file applications on a UNIX or GNU/Linux system.
1665 See `org-file-apps'.")
1667 (defconst org-file-apps-defaults-macosx
1668 '((remote . emacs)
1669 (t . "open %s")
1670 (system . "open %s")
1671 ("ps.gz" . "gv %s")
1672 ("eps.gz" . "gv %s")
1673 ("dvi" . "xdvi %s")
1674 ("fig" . "xfig %s"))
1675 "Default file applications on a MacOS X system.
1676 The system \"open\" is known as a default, but we use X11 applications
1677 for some files for which the OS does not have a good default.
1678 See `org-file-apps'.")
1680 (defconst org-file-apps-defaults-windowsnt
1681 (list
1682 '(remote . emacs)
1683 (cons t
1684 (list (if (featurep 'xemacs)
1685 'mswindows-shell-execute
1686 'w32-shell-execute)
1687 "open" 'file))
1688 (cons 'system
1689 (list (if (featurep 'xemacs)
1690 'mswindows-shell-execute
1691 'w32-shell-execute)
1692 "open" 'file)))
1693 "Default file applications on a Windows NT system.
1694 The system \"open\" is used for most files.
1695 See `org-file-apps'.")
1697 (defcustom org-file-apps
1699 (auto-mode . emacs)
1700 ("\\.mm\\'" . default)
1701 ("\\.x?html?\\'" . default)
1702 ("\\.pdf\\'" . default)
1704 "External applications for opening `file:path' items in a document.
1705 Org-mode uses system defaults for different file types, but
1706 you can use this variable to set the application for a given file
1707 extension. The entries in this list are cons cells where the car identifies
1708 files and the cdr the corresponding command. Possible values for the
1709 file identifier are
1710 \"string\" A string as a file identifier can be interpreted in different
1711 ways, depending on its contents:
1713 - Alphanumeric characters only:
1714 Match links with this file extension.
1715 Example: (\"pdf\" . \"evince %s\")
1716 to open PDFs with evince.
1718 - Regular expression: Match links where the
1719 filename matches the regexp. If you want to
1720 use groups here, use shy groups.
1722 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1723 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1724 to open *.html and *.xhtml with firefox.
1726 - Regular expression which contains (non-shy) groups:
1727 Match links where the whole link, including \"::\", and
1728 anything after that, matches the regexp.
1729 In a custom command string, %1, %2, etc. are replaced with
1730 the parts of the link that were matched by the groups.
1731 For backwards compatibility, if a command string is given
1732 that does not use any of the group matches, this case is
1733 handled identically to the second one (i.e. match against
1734 file name only).
1735 In a custom lisp form, you can access the group matches with
1736 (match-string n link).
1738 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1739 to open [[file:document.pdf::5]] with evince at page 5.
1741 `directory' Matches a directory
1742 `remote' Matches a remote file, accessible through tramp or efs.
1743 Remote files most likely should be visited through Emacs
1744 because external applications cannot handle such paths.
1745 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1746 so all files Emacs knows how to handle. Using this with
1747 command `emacs' will open most files in Emacs. Beware that this
1748 will also open html files inside Emacs, unless you add
1749 (\"html\" . default) to the list as well.
1750 t Default for files not matched by any of the other options.
1751 `system' The system command to open files, like `open' on Windows
1752 and Mac OS X, and mailcap under GNU/Linux. This is the command
1753 that will be selected if you call `C-c C-o' with a double
1754 \\[universal-argument] \\[universal-argument] prefix.
1756 Possible values for the command are:
1757 `emacs' The file will be visited by the current Emacs process.
1758 `default' Use the default application for this file type, which is the
1759 association for t in the list, most likely in the system-specific
1760 part.
1761 This can be used to overrule an unwanted setting in the
1762 system-specific variable.
1763 `system' Use the system command for opening files, like \"open\".
1764 This command is specified by the entry whose car is `system'.
1765 Most likely, the system-specific version of this variable
1766 does define this command, but you can overrule/replace it
1767 here.
1768 string A command to be executed by a shell; %s will be replaced
1769 by the path to the file.
1770 sexp A Lisp form which will be evaluated. The file path will
1771 be available in the Lisp variable `file'.
1772 For more examples, see the system specific constants
1773 `org-file-apps-defaults-macosx'
1774 `org-file-apps-defaults-windowsnt'
1775 `org-file-apps-defaults-gnu'."
1776 :group 'org-link-follow
1777 :type '(repeat
1778 (cons (choice :value ""
1779 (string :tag "Extension")
1780 (const :tag "System command to open files" system)
1781 (const :tag "Default for unrecognized files" t)
1782 (const :tag "Remote file" remote)
1783 (const :tag "Links to a directory" directory)
1784 (const :tag "Any files that have Emacs modes"
1785 auto-mode))
1786 (choice :value ""
1787 (const :tag "Visit with Emacs" emacs)
1788 (const :tag "Use default" default)
1789 (const :tag "Use the system command" system)
1790 (string :tag "Command")
1791 (sexp :tag "Lisp form")))))
1795 (defgroup org-refile nil
1796 "Options concerning refiling entries in Org-mode."
1797 :tag "Org Refile"
1798 :group 'org)
1800 (defcustom org-directory "~/org"
1801 "Directory with org files.
1802 This is just a default location to look for Org files. There is no need
1803 at all to put your files into this directory. It is only used in the
1804 following situations:
1806 1. When a remember template specifies a target file that is not an
1807 absolute path. The path will then be interpreted relative to
1808 `org-directory'
1809 2. When a remember note is filed away in an interactive way (when exiting the
1810 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1811 with `org-directory' as the default path."
1812 :group 'org-refile
1813 :group 'org-remember
1814 :type 'directory)
1816 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1817 "Default target for storing notes.
1818 Used as a fall back file for org-remember.el and org-capture.el, for
1819 templates that do not specify a target file."
1820 :group 'org-refile
1821 :group 'org-remember
1822 :type '(choice
1823 (const :tag "Default from remember-data-file" nil)
1824 file))
1826 (defcustom org-goto-interface 'outline
1827 "The default interface to be used for `org-goto'.
1828 Allowed values are:
1829 outline The interface shows an outline of the relevant file
1830 and the correct heading is found by moving through
1831 the outline or by searching with incremental search.
1832 outline-path-completion Headlines in the current buffer are offered via
1833 completion. This is the interface also used by
1834 the refile command."
1835 :group 'org-refile
1836 :type '(choice
1837 (const :tag "Outline" outline)
1838 (const :tag "Outline-path-completion" outline-path-completion)))
1840 (defcustom org-goto-max-level 5
1841 "Maximum target level when running `org-goto' with refile interface."
1842 :group 'org-refile
1843 :type 'integer)
1845 (defcustom org-reverse-note-order nil
1846 "Non-nil means store new notes at the beginning of a file or entry.
1847 When nil, new notes will be filed to the end of a file or entry.
1848 This can also be a list with cons cells of regular expressions that
1849 are matched against file names, and values."
1850 :group 'org-remember
1851 :group 'org-refile
1852 :type '(choice
1853 (const :tag "Reverse always" t)
1854 (const :tag "Reverse never" nil)
1855 (repeat :tag "By file name regexp"
1856 (cons regexp boolean))))
1858 (defcustom org-log-refile nil
1859 "Information to record when a task is refiled.
1861 Possible values are:
1863 nil Don't add anything
1864 time Add a time stamp to the task
1865 note Prompt for a note and add it with template `org-log-note-headings'
1867 This option can also be set with on a per-file-basis with
1869 #+STARTUP: nologrefile
1870 #+STARTUP: logrefile
1871 #+STARTUP: lognoterefile
1873 You can have local logging settings for a subtree by setting the LOGGING
1874 property to one or more of these keywords.
1876 When bulk-refiling from the agenda, the value `note' is forbidden and
1877 will temporarily be changed to `time'."
1878 :group 'org-refile
1879 :group 'org-progress
1880 :type '(choice
1881 (const :tag "No logging" nil)
1882 (const :tag "Record timestamp" time)
1883 (const :tag "Record timestamp with note." note)))
1885 (defcustom org-refile-targets nil
1886 "Targets for refiling entries with \\[org-refile].
1887 This is a list of cons cells. Each cell contains:
1888 - a specification of the files to be considered, either a list of files,
1889 or a symbol whose function or variable value will be used to retrieve
1890 a file name or a list of file names. If you use `org-agenda-files' for
1891 that, all agenda files will be scanned for targets. Nil means consider
1892 headings in the current buffer.
1893 - A specification of how to find candidate refile targets. This may be
1894 any of:
1895 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1896 This tag has to be present in all target headlines, inheritance will
1897 not be considered.
1898 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1899 todo keyword.
1900 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1901 headlines that are refiling targets.
1902 - a cons cell (:level . N). Any headline of level N is considered a target.
1903 Note that, when `org-odd-levels-only' is set, level corresponds to
1904 order in hierarchy, not to the number of stars.
1905 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1906 Note that, when `org-odd-levels-only' is set, level corresponds to
1907 order in hierarchy, not to the number of stars.
1909 Each element of this list generates a set of possible targets.
1910 The union of these sets is presented (with completion) to
1911 the user by `org-refile'.
1913 You can set the variable `org-refile-target-verify-function' to a function
1914 to verify each headline found by the simple criteria above.
1916 When this variable is nil, all top-level headlines in the current buffer
1917 are used, equivalent to the value `((nil . (:level . 1))'."
1918 :group 'org-refile
1919 :type '(repeat
1920 (cons
1921 (choice :value org-agenda-files
1922 (const :tag "All agenda files" org-agenda-files)
1923 (const :tag "Current buffer" nil)
1924 (function) (variable) (file))
1925 (choice :tag "Identify target headline by"
1926 (cons :tag "Specific tag" (const :value :tag) (string))
1927 (cons :tag "TODO keyword" (const :value :todo) (string))
1928 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1929 (cons :tag "Level number" (const :value :level) (integer))
1930 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1932 (defcustom org-refile-target-verify-function nil
1933 "Function to verify if the headline at point should be a refile target.
1934 The function will be called without arguments, with point at the
1935 beginning of the headline. It should return t and leave point
1936 where it is if the headline is a valid target for refiling.
1938 If the target should not be selected, the function must return nil.
1939 In addition to this, it may move point to a place from where the search
1940 should be continued. For example, the function may decide that the entire
1941 subtree of the current entry should be excluded and move point to the end
1942 of the subtree."
1943 :group 'org-refile
1944 :type 'function)
1946 (defcustom org-refile-use-cache nil
1947 "Non-nil means cache refile targets to speed up the process.
1948 The cache for a particular file will be updated automatically when
1949 the buffer has been killed, or when any of the marker used for flagging
1950 refile targets no longer points at a live buffer.
1951 If you have added new entries to a buffer that might themselves be targets,
1952 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1953 find that easier, `C-u C-u C-u C-c C-w'."
1954 :group 'org-refile
1955 :type 'boolean)
1957 (defcustom org-refile-use-outline-path nil
1958 "Non-nil means provide refile targets as paths.
1959 So a level 3 headline will be available as level1/level2/level3.
1961 When the value is `file', also include the file name (without directory)
1962 into the path. In this case, you can also stop the completion after
1963 the file name, to get entries inserted as top level in the file.
1965 When `full-file-path', include the full file path."
1966 :group 'org-refile
1967 :type '(choice
1968 (const :tag "Not" nil)
1969 (const :tag "Yes" t)
1970 (const :tag "Start with file name" file)
1971 (const :tag "Start with full file path" full-file-path)))
1973 (defcustom org-outline-path-complete-in-steps t
1974 "Non-nil means complete the outline path in hierarchical steps.
1975 When Org-mode uses the refile interface to select an outline path
1976 \(see variable `org-refile-use-outline-path'), the completion of
1977 the path can be done is a single go, or if can be done in steps down
1978 the headline hierarchy. Going in steps is probably the best if you
1979 do not use a special completion package like `ido' or `icicles'.
1980 However, when using these packages, going in one step can be very
1981 fast, while still showing the whole path to the entry."
1982 :group 'org-refile
1983 :type 'boolean)
1985 (defcustom org-refile-allow-creating-parent-nodes nil
1986 "Non-nil means allow to create new nodes as refile targets.
1987 New nodes are then created by adding \"/new node name\" to the completion
1988 of an existing node. When the value of this variable is `confirm',
1989 new node creation must be confirmed by the user (recommended)
1990 When nil, the completion must match an existing entry.
1992 Note that, if the new heading is not seen by the criteria
1993 listed in `org-refile-targets', multiple instances of the same
1994 heading would be created by trying again to file under the new
1995 heading."
1996 :group 'org-refile
1997 :type '(choice
1998 (const :tag "Never" nil)
1999 (const :tag "Always" t)
2000 (const :tag "Prompt for confirmation" confirm)))
2002 (defcustom org-refile-active-region-within-subtree nil
2003 "Non-nil means also refile active region within a subtree.
2005 By default `org-refile' doesn't allow refiling regions if they
2006 don't contain a set of subtrees, but it might be convenient to
2007 do so sometimes: in that case, the first line of the region is
2008 converted to a headline before refiling."
2009 :group 'org-refile
2010 :type 'boolean)
2012 (defgroup org-todo nil
2013 "Options concerning TODO items in Org-mode."
2014 :tag "Org TODO"
2015 :group 'org)
2017 (defgroup org-progress nil
2018 "Options concerning Progress logging in Org-mode."
2019 :tag "Org Progress"
2020 :group 'org-time)
2022 (defvar org-todo-interpretation-widgets
2023 '((:tag "Sequence (cycling hits every state)" sequence)
2024 (:tag "Type (cycling directly to DONE)" type))
2025 "The available interpretation symbols for customizing `org-todo-keywords'.
2026 Interested libraries should add to this list.")
2028 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2029 "List of TODO entry keyword sequences and their interpretation.
2030 \\<org-mode-map>This is a list of sequences.
2032 Each sequence starts with a symbol, either `sequence' or `type',
2033 indicating if the keywords should be interpreted as a sequence of
2034 action steps, or as different types of TODO items. The first
2035 keywords are states requiring action - these states will select a headline
2036 for inclusion into the global TODO list Org-mode produces. If one of
2037 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2038 signify that no further action is necessary. If \"|\" is not found,
2039 the last keyword is treated as the only DONE state of the sequence.
2041 The command \\[org-todo] cycles an entry through these states, and one
2042 additional state where no keyword is present. For details about this
2043 cycling, see the manual.
2045 TODO keywords and interpretation can also be set on a per-file basis with
2046 the special #+SEQ_TODO and #+TYP_TODO lines.
2048 Each keyword can optionally specify a character for fast state selection
2049 \(in combination with the variable `org-use-fast-todo-selection')
2050 and specifiers for state change logging, using the same syntax
2051 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2052 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2053 indicates to record a time stamp each time this state is selected.
2055 Each keyword may also specify if a timestamp or a note should be
2056 recorded when entering or leaving the state, by adding additional
2057 characters in the parenthesis after the keyword. This looks like this:
2058 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2059 record only the time of the state change. With X and Y being either
2060 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2061 Y when leaving the state if and only if the *target* state does not
2062 define X. You may omit any of the fast-selection key or X or /Y,
2063 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2065 For backward compatibility, this variable may also be just a list
2066 of keywords - in this case the interpretation (sequence or type) will be
2067 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2068 :group 'org-todo
2069 :group 'org-keywords
2070 :type '(choice
2071 (repeat :tag "Old syntax, just keywords"
2072 (string :tag "Keyword"))
2073 (repeat :tag "New syntax"
2074 (cons
2075 (choice
2076 :tag "Interpretation"
2077 ;;Quick and dirty way to see
2078 ;;`org-todo-interpretations'. This takes the
2079 ;;place of item arguments
2080 :convert-widget
2081 (lambda (widget)
2082 (widget-put widget
2083 :args (mapcar
2084 #'(lambda (x)
2085 (widget-convert
2086 (cons 'const x)))
2087 org-todo-interpretation-widgets))
2088 widget))
2089 (repeat
2090 (string :tag "Keyword"))))))
2092 (defvar org-todo-keywords-1 nil
2093 "All TODO and DONE keywords active in a buffer.")
2094 (make-variable-buffer-local 'org-todo-keywords-1)
2095 (defvar org-todo-keywords-for-agenda nil)
2096 (defvar org-done-keywords-for-agenda nil)
2097 (defvar org-drawers-for-agenda nil)
2098 (defvar org-todo-keyword-alist-for-agenda nil)
2099 (defvar org-tag-alist-for-agenda nil)
2100 (defvar org-agenda-contributing-files nil)
2101 (defvar org-not-done-keywords nil)
2102 (make-variable-buffer-local 'org-not-done-keywords)
2103 (defvar org-done-keywords nil)
2104 (make-variable-buffer-local 'org-done-keywords)
2105 (defvar org-todo-heads nil)
2106 (make-variable-buffer-local 'org-todo-heads)
2107 (defvar org-todo-sets nil)
2108 (make-variable-buffer-local 'org-todo-sets)
2109 (defvar org-todo-log-states nil)
2110 (make-variable-buffer-local 'org-todo-log-states)
2111 (defvar org-todo-kwd-alist nil)
2112 (make-variable-buffer-local 'org-todo-kwd-alist)
2113 (defvar org-todo-key-alist nil)
2114 (make-variable-buffer-local 'org-todo-key-alist)
2115 (defvar org-todo-key-trigger nil)
2116 (make-variable-buffer-local 'org-todo-key-trigger)
2118 (defcustom org-todo-interpretation 'sequence
2119 "Controls how TODO keywords are interpreted.
2120 This variable is in principle obsolete and is only used for
2121 backward compatibility, if the interpretation of todo keywords is
2122 not given already in `org-todo-keywords'. See that variable for
2123 more information."
2124 :group 'org-todo
2125 :group 'org-keywords
2126 :type '(choice (const sequence)
2127 (const type)))
2129 (defcustom org-use-fast-todo-selection t
2130 "Non-nil means use the fast todo selection scheme with C-c C-t.
2131 This variable describes if and under what circumstances the cycling
2132 mechanism for TODO keywords will be replaced by a single-key, direct
2133 selection scheme.
2135 When nil, fast selection is never used.
2137 When the symbol `prefix', it will be used when `org-todo' is called with
2138 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2139 in an agenda buffer.
2141 When t, fast selection is used by default. In this case, the prefix
2142 argument forces cycling instead.
2144 In all cases, the special interface is only used if access keys have actually
2145 been assigned by the user, i.e. if keywords in the configuration are followed
2146 by a letter in parenthesis, like TODO(t)."
2147 :group 'org-todo
2148 :type '(choice
2149 (const :tag "Never" nil)
2150 (const :tag "By default" t)
2151 (const :tag "Only with C-u C-c C-t" prefix)))
2153 (defcustom org-provide-todo-statistics t
2154 "Non-nil means update todo statistics after insert and toggle.
2155 ALL-HEADLINES means update todo statistics by including headlines
2156 with no TODO keyword as well, counting them as not done.
2157 A list of TODO keywords means the same, but skip keywords that are
2158 not in this list.
2160 When this is set, todo statistics is updated in the parent of the
2161 current entry each time a todo state is changed."
2162 :group 'org-todo
2163 :type '(choice
2164 (const :tag "Yes, only for TODO entries" t)
2165 (const :tag "Yes, including all entries" 'all-headlines)
2166 (repeat :tag "Yes, for TODOs in this list"
2167 (string :tag "TODO keyword"))
2168 (other :tag "No TODO statistics" nil)))
2170 (defcustom org-hierarchical-todo-statistics t
2171 "Non-nil means TODO statistics covers just direct children.
2172 When nil, all entries in the subtree are considered.
2173 This has only an effect if `org-provide-todo-statistics' is set.
2174 To set this to nil for only a single subtree, use a COOKIE_DATA
2175 property and include the word \"recursive\" into the value."
2176 :group 'org-todo
2177 :type 'boolean)
2179 (defcustom org-after-todo-state-change-hook nil
2180 "Hook which is run after the state of a TODO item was changed.
2181 The new state (a string with a TODO keyword, or nil) is available in the
2182 Lisp variable `state'."
2183 :group 'org-todo
2184 :type 'hook)
2186 (defvar org-blocker-hook nil
2187 "Hook for functions that are allowed to block a state change.
2189 Each function gets as its single argument a property list, see
2190 `org-trigger-hook' for more information about this list.
2192 If any of the functions in this hook returns nil, the state change
2193 is blocked.")
2195 (defvar org-trigger-hook nil
2196 "Hook for functions that are triggered by a state change.
2198 Each function gets as its single argument a property list with at least
2199 the following elements:
2201 (:type type-of-change :position pos-at-entry-start
2202 :from old-state :to new-state)
2204 Depending on the type, more properties may be present.
2206 This mechanism is currently implemented for:
2208 TODO state changes
2209 ------------------
2210 :type todo-state-change
2211 :from previous state (keyword as a string), or nil, or a symbol
2212 'todo' or 'done', to indicate the general type of state.
2213 :to new state, like in :from")
2215 (defcustom org-enforce-todo-dependencies nil
2216 "Non-nil means undone TODO entries will block switching the parent to DONE.
2217 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2218 be blocked if any prior sibling is not yet done.
2219 Finally, if the parent is blocked because of ordered siblings of its own,
2220 the child will also be blocked.
2221 This variable needs to be set before org.el is loaded, and you need to
2222 restart Emacs after a change to make the change effective. The only way
2223 to change is while Emacs is running is through the customize interface."
2224 :set (lambda (var val)
2225 (set var val)
2226 (if val
2227 (add-hook 'org-blocker-hook
2228 'org-block-todo-from-children-or-siblings-or-parent)
2229 (remove-hook 'org-blocker-hook
2230 'org-block-todo-from-children-or-siblings-or-parent)))
2231 :group 'org-todo
2232 :type 'boolean)
2234 (defcustom org-enforce-todo-checkbox-dependencies nil
2235 "Non-nil means unchecked boxes will block switching the parent to DONE.
2236 When this is nil, checkboxes have no influence on switching TODO states.
2237 When non-nil, you first need to check off all check boxes before the TODO
2238 entry can be switched to DONE.
2239 This variable needs to be set before org.el is loaded, and you need to
2240 restart Emacs after a change to make the change effective. The only way
2241 to change is while Emacs is running is through the customize interface."
2242 :set (lambda (var val)
2243 (set var val)
2244 (if val
2245 (add-hook 'org-blocker-hook
2246 'org-block-todo-from-checkboxes)
2247 (remove-hook 'org-blocker-hook
2248 'org-block-todo-from-checkboxes)))
2249 :group 'org-todo
2250 :type 'boolean)
2252 (defcustom org-treat-insert-todo-heading-as-state-change nil
2253 "Non-nil means inserting a TODO heading is treated as state change.
2254 So when the command \\[org-insert-todo-heading] is used, state change
2255 logging will apply if appropriate. When nil, the new TODO item will
2256 be inserted directly, and no logging will take place."
2257 :group 'org-todo
2258 :type 'boolean)
2260 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2261 "Non-nil means switching TODO states with S-cursor counts as state change.
2262 This is the default behavior. However, setting this to nil allows a
2263 convenient way to select a TODO state and bypass any logging associated
2264 with that."
2265 :group 'org-todo
2266 :type 'boolean)
2268 (defcustom org-todo-state-tags-triggers nil
2269 "Tag changes that should be triggered by TODO state changes.
2270 This is a list. Each entry is
2272 (state-change (tag . flag) .......)
2274 State-change can be a string with a state, and empty string to indicate the
2275 state that has no TODO keyword, or it can be one of the symbols `todo'
2276 or `done', meaning any not-done or done state, respectively."
2277 :group 'org-todo
2278 :group 'org-tags
2279 :type '(repeat
2280 (cons (choice :tag "When changing to"
2281 (const :tag "Not-done state" todo)
2282 (const :tag "Done state" done)
2283 (string :tag "State"))
2284 (repeat
2285 (cons :tag "Tag action"
2286 (string :tag "Tag")
2287 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2289 (defcustom org-log-done nil
2290 "Information to record when a task moves to the DONE state.
2292 Possible values are:
2294 nil Don't add anything, just change the keyword
2295 time Add a time stamp to the task
2296 note Prompt for a note and add it with template `org-log-note-headings'
2298 This option can also be set with on a per-file-basis with
2300 #+STARTUP: nologdone
2301 #+STARTUP: logdone
2302 #+STARTUP: lognotedone
2304 You can have local logging settings for a subtree by setting the LOGGING
2305 property to one or more of these keywords."
2306 :group 'org-todo
2307 :group 'org-progress
2308 :type '(choice
2309 (const :tag "No logging" nil)
2310 (const :tag "Record CLOSED timestamp" time)
2311 (const :tag "Record CLOSED timestamp with note." note)))
2313 ;; Normalize old uses of org-log-done.
2314 (cond
2315 ((eq org-log-done t) (setq org-log-done 'time))
2316 ((and (listp org-log-done) (memq 'done org-log-done))
2317 (setq org-log-done 'note)))
2319 (defcustom org-log-reschedule nil
2320 "Information to record when the scheduling date of a tasks is modified.
2322 Possible values are:
2324 nil Don't add anything, just change the date
2325 time Add a time stamp to the task
2326 note Prompt for a note and add it with template `org-log-note-headings'
2328 This option can also be set with on a per-file-basis with
2330 #+STARTUP: nologreschedule
2331 #+STARTUP: logreschedule
2332 #+STARTUP: lognotereschedule"
2333 :group 'org-todo
2334 :group 'org-progress
2335 :type '(choice
2336 (const :tag "No logging" nil)
2337 (const :tag "Record timestamp" time)
2338 (const :tag "Record timestamp with note." note)))
2340 (defcustom org-log-redeadline nil
2341 "Information to record when the deadline date of a tasks is modified.
2343 Possible values are:
2345 nil Don't add anything, just change the date
2346 time Add a time stamp to the task
2347 note Prompt for a note and add it with template `org-log-note-headings'
2349 This option can also be set with on a per-file-basis with
2351 #+STARTUP: nologredeadline
2352 #+STARTUP: logredeadline
2353 #+STARTUP: lognoteredeadline
2355 You can have local logging settings for a subtree by setting the LOGGING
2356 property to one or more of these keywords."
2357 :group 'org-todo
2358 :group 'org-progress
2359 :type '(choice
2360 (const :tag "No logging" nil)
2361 (const :tag "Record timestamp" time)
2362 (const :tag "Record timestamp with note." note)))
2364 (defcustom org-log-note-clock-out nil
2365 "Non-nil means record a note when clocking out of an item.
2366 This can also be configured on a per-file basis by adding one of
2367 the following lines anywhere in the buffer:
2369 #+STARTUP: lognoteclock-out
2370 #+STARTUP: nolognoteclock-out"
2371 :group 'org-todo
2372 :group 'org-progress
2373 :type 'boolean)
2375 (defcustom org-log-done-with-time t
2376 "Non-nil means the CLOSED time stamp will contain date and time.
2377 When nil, only the date will be recorded."
2378 :group 'org-progress
2379 :type 'boolean)
2381 (defcustom org-log-note-headings
2382 '((done . "CLOSING NOTE %t")
2383 (state . "State %-12s from %-12S %t")
2384 (note . "Note taken on %t")
2385 (reschedule . "Rescheduled from %S on %t")
2386 (delschedule . "Not scheduled, was %S on %t")
2387 (redeadline . "New deadline from %S on %t")
2388 (deldeadline . "Removed deadline, was %S on %t")
2389 (refile . "Refiled on %t")
2390 (clock-out . ""))
2391 "Headings for notes added to entries.
2392 The value is an alist, with the car being a symbol indicating the note
2393 context, and the cdr is the heading to be used. The heading may also be the
2394 empty string.
2395 %t in the heading will be replaced by a time stamp.
2396 %T will be an active time stamp instead the default inactive one
2397 %d will be replaced by a short-format time stamp.
2398 %D will be replaced by an active short-format time stamp.
2399 %s will be replaced by the new TODO state, in double quotes.
2400 %S will be replaced by the old TODO state, in double quotes.
2401 %u will be replaced by the user name.
2402 %U will be replaced by the full user name.
2404 In fact, it is not a good idea to change the `state' entry, because
2405 agenda log mode depends on the format of these entries."
2406 :group 'org-todo
2407 :group 'org-progress
2408 :type '(list :greedy t
2409 (cons (const :tag "Heading when closing an item" done) string)
2410 (cons (const :tag
2411 "Heading when changing todo state (todo sequence only)"
2412 state) string)
2413 (cons (const :tag "Heading when just taking a note" note) string)
2414 (cons (const :tag "Heading when clocking out" clock-out) string)
2415 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2416 (cons (const :tag "Heading when rescheduling" reschedule) string)
2417 (cons (const :tag "Heading when changing deadline" redeadline) string)
2418 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2419 (cons (const :tag "Heading when refiling" refile) string)))
2421 (unless (assq 'note org-log-note-headings)
2422 (push '(note . "%t") org-log-note-headings))
2424 (defcustom org-log-into-drawer nil
2425 "Non-nil means insert state change notes and time stamps into a drawer.
2426 When nil, state changes notes will be inserted after the headline and
2427 any scheduling and clock lines, but not inside a drawer.
2429 The value of this variable should be the name of the drawer to use.
2430 LOGBOOK is proposed as the default drawer for this purpose, you can
2431 also set this to a string to define the drawer of your choice.
2433 A value of t is also allowed, representing \"LOGBOOK\".
2435 If this variable is set, `org-log-state-notes-insert-after-drawers'
2436 will be ignored.
2438 You can set the property LOG_INTO_DRAWER to overrule this setting for
2439 a subtree."
2440 :group 'org-todo
2441 :group 'org-progress
2442 :type '(choice
2443 (const :tag "Not into a drawer" nil)
2444 (const :tag "LOGBOOK" t)
2445 (string :tag "Other")))
2447 (if (fboundp 'defvaralias)
2448 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2450 (defun org-log-into-drawer ()
2451 "Return the value of `org-log-into-drawer', but let properties overrule.
2452 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2453 used instead of the default value."
2454 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2455 (cond
2456 ((or (not p) (equal p "nil")) org-log-into-drawer)
2457 ((equal p "t") "LOGBOOK")
2458 (t p))))
2460 (defcustom org-log-state-notes-insert-after-drawers nil
2461 "Non-nil means insert state change notes after any drawers in entry.
2462 Only the drawers that *immediately* follow the headline and the
2463 deadline/scheduled line are skipped.
2464 When nil, insert notes right after the heading and perhaps the line
2465 with deadline/scheduling if present.
2467 This variable will have no effect if `org-log-into-drawer' is
2468 set."
2469 :group 'org-todo
2470 :group 'org-progress
2471 :type 'boolean)
2473 (defcustom org-log-states-order-reversed t
2474 "Non-nil means the latest state note will be directly after heading.
2475 When nil, the state change notes will be ordered according to time."
2476 :group 'org-todo
2477 :group 'org-progress
2478 :type 'boolean)
2480 (defcustom org-todo-repeat-to-state nil
2481 "The TODO state to which a repeater should return the repeating task.
2482 By default this is the first task in a TODO sequence, or the previous state
2483 in a TODO_TYP set. But you can specify another task here.
2484 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2485 :group 'org-todo
2486 :type '(choice (const :tag "Head of sequence" nil)
2487 (string :tag "Specific state")))
2489 (defcustom org-log-repeat 'time
2490 "Non-nil means record moving through the DONE state when triggering repeat.
2491 An auto-repeating task is immediately switched back to TODO when
2492 marked DONE. If you are not logging state changes (by adding \"@\"
2493 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2494 record a closing note, there will be no record of the task moving
2495 through DONE. This variable forces taking a note anyway.
2497 nil Don't force a record
2498 time Record a time stamp
2499 note Record a note
2501 This option can also be set with on a per-file-basis with
2503 #+STARTUP: logrepeat
2504 #+STARTUP: lognoterepeat
2505 #+STARTUP: nologrepeat
2507 You can have local logging settings for a subtree by setting the LOGGING
2508 property to one or more of these keywords."
2509 :group 'org-todo
2510 :group 'org-progress
2511 :type '(choice
2512 (const :tag "Don't force a record" nil)
2513 (const :tag "Force recording the DONE state" time)
2514 (const :tag "Force recording a note with the DONE state" note)))
2517 (defgroup org-priorities nil
2518 "Priorities in Org-mode."
2519 :tag "Org Priorities"
2520 :group 'org-todo)
2522 (defcustom org-enable-priority-commands t
2523 "Non-nil means priority commands are active.
2524 When nil, these commands will be disabled, so that you never accidentally
2525 set a priority."
2526 :group 'org-priorities
2527 :type 'boolean)
2529 (defcustom org-highest-priority ?A
2530 "The highest priority of TODO items. A character like ?A, ?B etc.
2531 Must have a smaller ASCII number than `org-lowest-priority'."
2532 :group 'org-priorities
2533 :type 'character)
2535 (defcustom org-lowest-priority ?C
2536 "The lowest priority of TODO items. A character like ?A, ?B etc.
2537 Must have a larger ASCII number than `org-highest-priority'."
2538 :group 'org-priorities
2539 :type 'character)
2541 (defcustom org-default-priority ?B
2542 "The default priority of TODO items.
2543 This is the priority an item gets if no explicit priority is given.
2544 When starting to cycle on an empty priority the first step in the cycle
2545 depends on `org-priority-start-cycle-with-default'. The resulting first
2546 step priority must not exceed the range from `org-highest-priority' to
2547 `org-lowest-priority' which means that `org-default-priority' has to be
2548 in this range exclusive or inclusive the range boundaries. Else the
2549 first step refuses to set the default and the second will fall back
2550 to (depending on the command used) the highest or lowest priority."
2551 :group 'org-priorities
2552 :type 'character)
2554 (defcustom org-priority-start-cycle-with-default t
2555 "Non-nil means start with default priority when starting to cycle.
2556 When this is nil, the first step in the cycle will be (depending on the
2557 command used) one higher or lower than the default priority.
2558 See also `org-default-priority'."
2559 :group 'org-priorities
2560 :type 'boolean)
2562 (defcustom org-get-priority-function nil
2563 "Function to extract the priority from a string.
2564 The string is normally the headline. If this is nil Org computes the
2565 priority from the priority cookie like [#A] in the headline. It returns
2566 an integer, increasing by 1000 for each priority level.
2567 The user can set a different function here, which should take a string
2568 as an argument and return the numeric priority."
2569 :group 'org-priorities
2570 :type 'function)
2572 (defgroup org-time nil
2573 "Options concerning time stamps and deadlines in Org-mode."
2574 :tag "Org Time"
2575 :group 'org)
2577 (defcustom org-insert-labeled-timestamps-at-point nil
2578 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2579 When nil, these labeled time stamps are forces into the second line of an
2580 entry, just after the headline. When scheduling from the global TODO list,
2581 the time stamp will always be forced into the second line."
2582 :group 'org-time
2583 :type 'boolean)
2585 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2586 "Formats for `format-time-string' which are used for time stamps.
2587 It is not recommended to change this constant.")
2589 (defcustom org-time-stamp-rounding-minutes '(0 5)
2590 "Number of minutes to round time stamps to.
2591 These are two values, the first applies when first creating a time stamp.
2592 The second applies when changing it with the commands `S-up' and `S-down'.
2593 When changing the time stamp, this means that it will change in steps
2594 of N minutes, as given by the second value.
2596 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2597 numbers should be factors of 60, so for example 5, 10, 15.
2599 When this is larger than 1, you can still force an exact time stamp by using
2600 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2601 and by using a prefix arg to `S-up/down' to specify the exact number
2602 of minutes to shift."
2603 :group 'org-time
2604 :get #'(lambda (var) ; Make sure both elements are there
2605 (if (integerp (default-value var))
2606 (list (default-value var) 5)
2607 (default-value var)))
2608 :type '(list
2609 (integer :tag "when inserting times")
2610 (integer :tag "when modifying times")))
2612 ;; Normalize old customizations of this variable.
2613 (when (integerp org-time-stamp-rounding-minutes)
2614 (setq org-time-stamp-rounding-minutes
2615 (list org-time-stamp-rounding-minutes
2616 org-time-stamp-rounding-minutes)))
2618 (defcustom org-display-custom-times nil
2619 "Non-nil means overlay custom formats over all time stamps.
2620 The formats are defined through the variable `org-time-stamp-custom-formats'.
2621 To turn this on on a per-file basis, insert anywhere in the file:
2622 #+STARTUP: customtime"
2623 :group 'org-time
2624 :set 'set-default
2625 :type 'sexp)
2626 (make-variable-buffer-local 'org-display-custom-times)
2628 (defcustom org-time-stamp-custom-formats
2629 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2630 "Custom formats for time stamps. See `format-time-string' for the syntax.
2631 These are overlayed over the default ISO format if the variable
2632 `org-display-custom-times' is set. Time like %H:%M should be at the
2633 end of the second format. The custom formats are also honored by export
2634 commands, if custom time display is turned on at the time of export."
2635 :group 'org-time
2636 :type 'sexp)
2638 (defun org-time-stamp-format (&optional long inactive)
2639 "Get the right format for a time string."
2640 (let ((f (if long (cdr org-time-stamp-formats)
2641 (car org-time-stamp-formats))))
2642 (if inactive
2643 (concat "[" (substring f 1 -1) "]")
2644 f)))
2646 (defcustom org-time-clocksum-format "%d:%02d"
2647 "The format string used when creating CLOCKSUM lines.
2648 This is also used when org-mode generates a time duration."
2649 :group 'org-time
2650 :type 'string)
2652 (defcustom org-time-clocksum-use-fractional nil
2653 "If non-nil, \\[org-clock-display] uses fractional times.
2654 org-mode generates a time duration."
2655 :group 'org-time
2656 :type 'boolean)
2658 (defcustom org-time-clocksum-fractional-format "%.2f"
2659 "The format string used when creating CLOCKSUM lines, or when
2660 org-mode generates a time duration."
2661 :group 'org-time
2662 :type 'string)
2664 (defcustom org-deadline-warning-days 14
2665 "No. of days before expiration during which a deadline becomes active.
2666 This variable governs the display in sparse trees and in the agenda.
2667 When 0 or negative, it means use this number (the absolute value of it)
2668 even if a deadline has a different individual lead time specified.
2670 Custom commands can set this variable in the options section."
2671 :group 'org-time
2672 :group 'org-agenda-daily/weekly
2673 :type 'integer)
2675 (defcustom org-read-date-prefer-future t
2676 "Non-nil means assume future for incomplete date input from user.
2677 This affects the following situations:
2678 1. The user gives a month but not a year.
2679 For example, if it is April and you enter \"feb 2\", this will be read
2680 as Feb 2, *next* year. \"May 5\", however, will be this year.
2681 2. The user gives a day, but no month.
2682 For example, if today is the 15th, and you enter \"3\", Org-mode will
2683 read this as the third of *next* month. However, if you enter \"17\",
2684 it will be considered as *this* month.
2686 If you set this variable to the symbol `time', then also the following
2687 will work:
2689 3. If the user gives a time, but no day. If the time is before now,
2690 to will be interpreted as tomorrow.
2692 Currently none of this works for ISO week specifications.
2694 When this option is nil, the current day, month and year will always be
2695 used as defaults.
2697 See also `org-agenda-jump-prefer-future'."
2698 :group 'org-time
2699 :type '(choice
2700 (const :tag "Never" nil)
2701 (const :tag "Check month and day" t)
2702 (const :tag "Check month, day, and time" time)))
2704 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2705 "Should the agenda jump command prefer the future for incomplete dates?
2706 The default is to do the same as configured in `org-read-date-prefer-future'.
2707 But you can also set a deviating value here.
2708 This may t or nil, or the symbol `org-read-date-prefer-future'."
2709 :group 'org-agenda
2710 :group 'org-time
2711 :type '(choice
2712 (const :tag "Use org-read-date-prefer-future"
2713 org-read-date-prefer-future)
2714 (const :tag "Never" nil)
2715 (const :tag "Always" t)))
2717 (defcustom org-read-date-force-compatible-dates t
2718 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2720 Depending on the system Emacs is running on, certain dates cannot
2721 be represented with the type used internally to represent time.
2722 Dates between 1970-1-1 and 2038-1-1 can always be represented
2723 correctly. Some systems allow for earlier dates, some for later,
2724 some for both. One way to find out it to insert any date into an
2725 Org buffer, putting the cursor on the year and hitting S-up and
2726 S-down to test the range.
2728 When this variable is set to t, the date/time prompt will not let
2729 you specify dates outside the 1970-2037 range, so it is certain that
2730 these dates will work in whatever version of Emacs you are
2731 running, and also that you can move a file from one Emacs implementation
2732 to another. WHenever Org is forcing the year for you, it will display
2733 a message and beep.
2735 When this variable is nil, Org will check if the date is
2736 representable in the specific Emacs implementation you are using.
2737 If not, it will force a year, usually the current year, and beep
2738 to remind you. Currently this setting is not recommended because
2739 the likelihood that you will open your Org files in an Emacs that
2740 has limited date range is not negligible.
2742 A workaround for this problem is to use diary sexp dates for time
2743 stamps outside of this range."
2744 :group 'org-time
2745 :type 'boolean)
2747 (defcustom org-read-date-display-live t
2748 "Non-nil means display current interpretation of date prompt live.
2749 This display will be in an overlay, in the minibuffer."
2750 :group 'org-time
2751 :type 'boolean)
2753 (defcustom org-read-date-popup-calendar t
2754 "Non-nil means pop up a calendar when prompting for a date.
2755 In the calendar, the date can be selected with mouse-1. However, the
2756 minibuffer will also be active, and you can simply enter the date as well.
2757 When nil, only the minibuffer will be available."
2758 :group 'org-time
2759 :type 'boolean)
2760 (if (fboundp 'defvaralias)
2761 (defvaralias 'org-popup-calendar-for-date-prompt
2762 'org-read-date-popup-calendar))
2764 (defcustom org-read-date-minibuffer-setup-hook nil
2765 "Hook to be used to set up keys for the date/time interface.
2766 Add key definitions to `minibuffer-local-map', which will be a temporary
2767 copy."
2768 :group 'org-time
2769 :type 'hook)
2771 (defcustom org-extend-today-until 0
2772 "The hour when your day really ends. Must be an integer.
2773 This has influence for the following applications:
2774 - When switching the agenda to \"today\". It it is still earlier than
2775 the time given here, the day recognized as TODAY is actually yesterday.
2776 - When a date is read from the user and it is still before the time given
2777 here, the current date and time will be assumed to be yesterday, 23:59.
2778 Also, timestamps inserted in remember templates follow this rule.
2780 IMPORTANT: This is a feature whose implementation is and likely will
2781 remain incomplete. Really, it is only here because past midnight seems to
2782 be the favorite working time of John Wiegley :-)"
2783 :group 'org-time
2784 :type 'integer)
2786 (defcustom org-use-effective-time nil
2787 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2788 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2789 \"effective time\" of any timestamps between midnight and 8am will be
2790 23:59 of the previous day."
2791 :group 'boolean
2792 :type 'integer)
2794 (defcustom org-edit-timestamp-down-means-later nil
2795 "Non-nil means S-down will increase the time in a time stamp.
2796 When nil, S-up will increase."
2797 :group 'org-time
2798 :type 'boolean)
2800 (defcustom org-calendar-follow-timestamp-change t
2801 "Non-nil means make the calendar window follow timestamp changes.
2802 When a timestamp is modified and the calendar window is visible, it will be
2803 moved to the new date."
2804 :group 'org-time
2805 :type 'boolean)
2807 (defgroup org-tags nil
2808 "Options concerning tags in Org-mode."
2809 :tag "Org Tags"
2810 :group 'org)
2812 (defcustom org-tag-alist nil
2813 "List of tags allowed in Org-mode files.
2814 When this list is nil, Org-mode will base TAG input on what is already in the
2815 buffer.
2816 The value of this variable is an alist, the car of each entry must be a
2817 keyword as a string, the cdr may be a character that is used to select
2818 that tag through the fast-tag-selection interface.
2819 See the manual for details."
2820 :group 'org-tags
2821 :type '(repeat
2822 (choice
2823 (cons (string :tag "Tag name")
2824 (character :tag "Access char"))
2825 (list :tag "Start radio group"
2826 (const :startgroup)
2827 (option (string :tag "Group description")))
2828 (list :tag "End radio group"
2829 (const :endgroup)
2830 (option (string :tag "Group description")))
2831 (const :tag "New line" (:newline)))))
2833 (defcustom org-tag-persistent-alist nil
2834 "List of tags that will always appear in all Org-mode files.
2835 This is in addition to any in buffer settings or customizations
2836 of `org-tag-alist'.
2837 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2838 The value of this variable is an alist, the car of each entry must be a
2839 keyword as a string, the cdr may be a character that is used to select
2840 that tag through the fast-tag-selection interface.
2841 See the manual for details.
2842 To disable these tags on a per-file basis, insert anywhere in the file:
2843 #+STARTUP: noptag"
2844 :group 'org-tags
2845 :type '(repeat
2846 (choice
2847 (cons (string :tag "Tag name")
2848 (character :tag "Access char"))
2849 (const :tag "Start radio group" (:startgroup))
2850 (const :tag "End radio group" (:endgroup))
2851 (const :tag "New line" (:newline)))))
2853 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2854 "If non-nil, always offer completion for all tags of all agenda files.
2855 Instead of customizing this variable directly, you might want to
2856 set it locally for capture buffers, because there no list of
2857 tags in that file can be created dynamically (there are none).
2859 (add-hook 'org-capture-mode-hook
2860 (lambda ()
2861 (set (make-local-variable
2862 'org-complete-tags-always-offer-all-agenda-tags)
2863 t)))"
2864 :group 'org-tags
2865 :type 'boolean)
2867 (defvar org-file-tags nil
2868 "List of tags that can be inherited by all entries in the file.
2869 The tags will be inherited if the variable `org-use-tag-inheritance'
2870 says they should be.
2871 This variable is populated from #+FILETAGS lines.")
2873 (defcustom org-use-fast-tag-selection 'auto
2874 "Non-nil means use fast tag selection scheme.
2875 This is a special interface to select and deselect tags with single keys.
2876 When nil, fast selection is never used.
2877 When the symbol `auto', fast selection is used if and only if selection
2878 characters for tags have been configured, either through the variable
2879 `org-tag-alist' or through a #+TAGS line in the buffer.
2880 When t, fast selection is always used and selection keys are assigned
2881 automatically if necessary."
2882 :group 'org-tags
2883 :type '(choice
2884 (const :tag "Always" t)
2885 (const :tag "Never" nil)
2886 (const :tag "When selection characters are configured" 'auto)))
2888 (defcustom org-fast-tag-selection-single-key nil
2889 "Non-nil means fast tag selection exits after first change.
2890 When nil, you have to press RET to exit it.
2891 During fast tag selection, you can toggle this flag with `C-c'.
2892 This variable can also have the value `expert'. In this case, the window
2893 displaying the tags menu is not even shown, until you press C-c again."
2894 :group 'org-tags
2895 :type '(choice
2896 (const :tag "No" nil)
2897 (const :tag "Yes" t)
2898 (const :tag "Expert" expert)))
2900 (defvar org-fast-tag-selection-include-todo nil
2901 "Non-nil means fast tags selection interface will also offer TODO states.
2902 This is an undocumented feature, you should not rely on it.")
2904 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2905 "The column to which tags should be indented in a headline.
2906 If this number is positive, it specifies the column. If it is negative,
2907 it means that the tags should be flushright to that column. For example,
2908 -80 works well for a normal 80 character screen.
2909 When 0, place tags directly after headline text, with only one space in
2910 between."
2911 :group 'org-tags
2912 :type 'integer)
2914 (defcustom org-auto-align-tags t
2915 "Non-nil keeps tags aligned when modifying headlines.
2916 Some operations (i.e. demoting) change the length of a headline and
2917 therefore shift the tags around. With this option turned on, after
2918 each such operation the tags are again aligned to `org-tags-column'."
2919 :group 'org-tags
2920 :type 'boolean)
2922 (defcustom org-use-tag-inheritance t
2923 "Non-nil means tags in levels apply also for sublevels.
2924 When nil, only the tags directly given in a specific line apply there.
2925 This may also be a list of tags that should be inherited, or a regexp that
2926 matches tags that should be inherited. Additional control is possible
2927 with the variable `org-tags-exclude-from-inheritance' which gives an
2928 explicit list of tags to be excluded from inheritance., even if the value of
2929 `org-use-tag-inheritance' would select it for inheritance.
2931 If this option is t, a match early-on in a tree can lead to a large
2932 number of matches in the subtree when constructing the agenda or creating
2933 a sparse tree. If you only want to see the first match in a tree during
2934 a search, check out the variable `org-tags-match-list-sublevels'."
2935 :group 'org-tags
2936 :type '(choice
2937 (const :tag "Not" nil)
2938 (const :tag "Always" t)
2939 (repeat :tag "Specific tags" (string :tag "Tag"))
2940 (regexp :tag "Tags matched by regexp")))
2942 (defcustom org-tags-exclude-from-inheritance nil
2943 "List of tags that should never be inherited.
2944 This is a way to exclude a few tags from inheritance. For way to do
2945 the opposite, to actively allow inheritance for selected tags,
2946 see the variable `org-use-tag-inheritance'."
2947 :group 'org-tags
2948 :type '(repeat (string :tag "Tag")))
2950 (defun org-tag-inherit-p (tag)
2951 "Check if TAG is one that should be inherited."
2952 (cond
2953 ((member tag org-tags-exclude-from-inheritance) nil)
2954 ((eq org-use-tag-inheritance t) t)
2955 ((not org-use-tag-inheritance) nil)
2956 ((stringp org-use-tag-inheritance)
2957 (string-match org-use-tag-inheritance tag))
2958 ((listp org-use-tag-inheritance)
2959 (member tag org-use-tag-inheritance))
2960 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2962 (defcustom org-tags-match-list-sublevels t
2963 "Non-nil means list also sublevels of headlines matching a search.
2964 This variable applies to tags/property searches, and also to stuck
2965 projects because this search is based on a tags match as well.
2967 When set to the symbol `indented', sublevels are indented with
2968 leading dots.
2970 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2971 the sublevels of a headline matching a tag search often also match
2972 the same search. Listing all of them can create very long lists.
2973 Setting this variable to nil causes subtrees of a match to be skipped.
2975 This variable is semi-obsolete and probably should always be true. It
2976 is better to limit inheritance to certain tags using the variables
2977 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2978 :group 'org-tags
2979 :type '(choice
2980 (const :tag "No, don't list them" nil)
2981 (const :tag "Yes, do list them" t)
2982 (const :tag "List them, indented with leading dots" indented)))
2984 (defcustom org-tags-sort-function nil
2985 "When set, tags are sorted using this function as a comparator."
2986 :group 'org-tags
2987 :type '(choice
2988 (const :tag "No sorting" nil)
2989 (const :tag "Alphabetical" string<)
2990 (const :tag "Reverse alphabetical" string>)
2991 (function :tag "Custom function" nil)))
2993 (defvar org-tags-history nil
2994 "History of minibuffer reads for tags.")
2995 (defvar org-last-tags-completion-table nil
2996 "The last used completion table for tags.")
2997 (defvar org-after-tags-change-hook nil
2998 "Hook that is run after the tags in a line have changed.")
3000 (defgroup org-properties nil
3001 "Options concerning properties in Org-mode."
3002 :tag "Org Properties"
3003 :group 'org)
3005 (defcustom org-property-format "%-10s %s"
3006 "How property key/value pairs should be formatted by `indent-line'.
3007 When `indent-line' hits a property definition, it will format the line
3008 according to this format, mainly to make sure that the values are
3009 lined-up with respect to each other."
3010 :group 'org-properties
3011 :type 'string)
3013 (defcustom org-properties-postprocess-alist nil
3014 "Alist of properties and functions to adjust inserted values.
3015 Elements of this alist must be of the form
3017 ([string] [function])
3019 where [string] must be a property name and [function] must be a
3020 lambda expression: this lambda expression must take one argument,
3021 the value to adjust, and return the new value as a string.
3023 For example, this element will allow the property \"Remaining\"
3024 to be updated wrt the relation between the \"Effort\" property
3025 and the clock summary:
3027 ((\"Remaining\" (lambda(value)
3028 (let ((clocksum (org-clock-sum-current-item))
3029 (effort (org-duration-string-to-minutes
3030 (org-entry-get (point) \"Effort\"))))
3031 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3032 :group 'org-properties
3033 :type 'alist)
3035 (defcustom org-use-property-inheritance nil
3036 "Non-nil means properties apply also for sublevels.
3038 This setting is chiefly used during property searches. Turning it on can
3039 cause significant overhead when doing a search, which is why it is not
3040 on by default.
3042 When nil, only the properties directly given in the current entry count.
3043 When t, every property is inherited. The value may also be a list of
3044 properties that should have inheritance, or a regular expression matching
3045 properties that should be inherited.
3047 However, note that some special properties use inheritance under special
3048 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3049 and the properties ending in \"_ALL\" when they are used as descriptor
3050 for valid values of a property.
3052 Note for programmers:
3053 When querying an entry with `org-entry-get', you can control if inheritance
3054 should be used. By default, `org-entry-get' looks only at the local
3055 properties. You can request inheritance by setting the inherit argument
3056 to t (to force inheritance) or to `selective' (to respect the setting
3057 in this variable)."
3058 :group 'org-properties
3059 :type '(choice
3060 (const :tag "Not" nil)
3061 (const :tag "Always" t)
3062 (repeat :tag "Specific properties" (string :tag "Property"))
3063 (regexp :tag "Properties matched by regexp")))
3065 (defun org-property-inherit-p (property)
3066 "Check if PROPERTY is one that should be inherited."
3067 (cond
3068 ((eq org-use-property-inheritance t) t)
3069 ((not org-use-property-inheritance) nil)
3070 ((stringp org-use-property-inheritance)
3071 (string-match org-use-property-inheritance property))
3072 ((listp org-use-property-inheritance)
3073 (member property org-use-property-inheritance))
3074 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3076 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3077 "The default column format, if no other format has been defined.
3078 This variable can be set on the per-file basis by inserting a line
3080 #+COLUMNS: %25ITEM ....."
3081 :group 'org-properties
3082 :type 'string)
3084 (defcustom org-columns-ellipses ".."
3085 "The ellipses to be used when a field in column view is truncated.
3086 When this is the empty string, as many characters as possible are shown,
3087 but then there will be no visual indication that the field has been truncated.
3088 When this is a string of length N, the last N characters of a truncated
3089 field are replaced by this string. If the column is narrower than the
3090 ellipses string, only part of the ellipses string will be shown."
3091 :group 'org-properties
3092 :type 'string)
3094 (defcustom org-columns-modify-value-for-display-function nil
3095 "Function that modifies values for display in column view.
3096 For example, it can be used to cut out a certain part from a time stamp.
3097 The function must take 2 arguments:
3099 column-title The title of the column (*not* the property name)
3100 value The value that should be modified.
3102 The function should return the value that should be displayed,
3103 or nil if the normal value should be used."
3104 :group 'org-properties
3105 :type 'function)
3107 (defcustom org-effort-property "Effort"
3108 "The property that is being used to keep track of effort estimates.
3109 Effort estimates given in this property need to have the format H:MM."
3110 :group 'org-properties
3111 :group 'org-progress
3112 :type '(string :tag "Property"))
3114 (defconst org-global-properties-fixed
3115 '(("VISIBILITY_ALL" . "folded children content all")
3116 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3117 "List of property/value pairs that can be inherited by any entry.
3119 These are fixed values, for the preset properties. The user variable
3120 that can be used to add to this list is `org-global-properties'.
3122 The entries in this list are cons cells where the car is a property
3123 name and cdr is a string with the value. If the value represents
3124 multiple items like an \"_ALL\" property, separate the items by
3125 spaces.")
3127 (defcustom org-global-properties nil
3128 "List of property/value pairs that can be inherited by any entry.
3130 This list will be combined with the constant `org-global-properties-fixed'.
3132 The entries in this list are cons cells where the car is a property
3133 name and cdr is a string with the value.
3135 You can set buffer-local values for the same purpose in the variable
3136 `org-file-properties' this by adding lines like
3138 #+PROPERTY: NAME VALUE"
3139 :group 'org-properties
3140 :type '(repeat
3141 (cons (string :tag "Property")
3142 (string :tag "Value"))))
3144 (defvar org-file-properties nil
3145 "List of property/value pairs that can be inherited by any entry.
3146 Valid for the current buffer.
3147 This variable is populated from #+PROPERTY lines.")
3148 (make-variable-buffer-local 'org-file-properties)
3150 (defgroup org-agenda nil
3151 "Options concerning agenda views in Org-mode."
3152 :tag "Org Agenda"
3153 :group 'org)
3155 (defvar org-category nil
3156 "Variable used by org files to set a category for agenda display.
3157 Such files should use a file variable to set it, for example
3159 # -*- mode: org; org-category: \"ELisp\"
3161 or contain a special line
3163 #+CATEGORY: ELisp
3165 If the file does not specify a category, then file's base name
3166 is used instead.")
3167 (make-variable-buffer-local 'org-category)
3168 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3170 (defcustom org-agenda-files nil
3171 "The files to be used for agenda display.
3172 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3173 \\[org-remove-file]. You can also use customize to edit the list.
3175 If an entry is a directory, all files in that directory that are matched by
3176 `org-agenda-file-regexp' will be part of the file list.
3178 If the value of the variable is not a list but a single file name, then
3179 the list of agenda files is actually stored and maintained in that file, one
3180 agenda file per line. In this file paths can be given relative to
3181 `org-directory'. Tilde expansion and environment variable substitution
3182 are also made."
3183 :group 'org-agenda
3184 :type '(choice
3185 (repeat :tag "List of files and directories" file)
3186 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3188 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3189 "Regular expression to match files for `org-agenda-files'.
3190 If any element in the list in that variable contains a directory instead
3191 of a normal file, all files in that directory that are matched by this
3192 regular expression will be included."
3193 :group 'org-agenda
3194 :type 'regexp)
3196 (defcustom org-agenda-text-search-extra-files nil
3197 "List of extra files to be searched by text search commands.
3198 These files will be search in addition to the agenda files by the
3199 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3200 Note that these files will only be searched for text search commands,
3201 not for the other agenda views like todo lists, tag searches or the weekly
3202 agenda. This variable is intended to list notes and possibly archive files
3203 that should also be searched by these two commands.
3204 In fact, if the first element in the list is the symbol `agenda-archives',
3205 than all archive files of all agenda files will be added to the search
3206 scope."
3207 :group 'org-agenda
3208 :type '(set :greedy t
3209 (const :tag "Agenda Archives" agenda-archives)
3210 (repeat :inline t (file))))
3212 (if (fboundp 'defvaralias)
3213 (defvaralias 'org-agenda-multi-occur-extra-files
3214 'org-agenda-text-search-extra-files))
3216 (defcustom org-agenda-skip-unavailable-files nil
3217 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3218 A nil value means to remove them, after a query, from the list."
3219 :group 'org-agenda
3220 :type 'boolean)
3222 (defcustom org-calendar-to-agenda-key [?c]
3223 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3224 The command `org-calendar-goto-agenda' will be bound to this key. The
3225 default is the character `c' because then `c' can be used to switch back and
3226 forth between agenda and calendar."
3227 :group 'org-agenda
3228 :type 'sexp)
3230 (defcustom org-calendar-agenda-action-key [?k]
3231 "The key to be installed in `calendar-mode-map' for agenda-action.
3232 The command `org-agenda-action' will be bound to this key. The
3233 default is the character `k' because we use the same key in the agenda."
3234 :group 'org-agenda
3235 :type 'sexp)
3237 (defcustom org-calendar-insert-diary-entry-key [?i]
3238 "The key to be installed in `calendar-mode-map' for adding diary entries.
3239 This option is irrelevant until `org-agenda-diary-file' has been configured
3240 to point to an Org-mode file. When that is the case, the command
3241 `org-agenda-diary-entry' will be bound to the key given here, by default
3242 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3243 if you want to continue doing this, you need to change this to a different
3244 key."
3245 :group 'org-agenda
3246 :type 'sexp)
3248 (defcustom org-agenda-diary-file 'diary-file
3249 "File to which to add new entries with the `i' key in agenda and calendar.
3250 When this is the symbol `diary-file', the functionality in the Emacs
3251 calendar will be used to add entries to the `diary-file'. But when this
3252 points to a file, `org-agenda-diary-entry' will be used instead."
3253 :group 'org-agenda
3254 :type '(choice
3255 (const :tag "The standard Emacs diary file" diary-file)
3256 (file :tag "Special Org file diary entries")))
3258 (eval-after-load "calendar"
3259 '(progn
3260 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3261 'org-calendar-goto-agenda)
3262 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3263 'org-agenda-action)
3264 (add-hook 'calendar-mode-hook
3265 (lambda ()
3266 (unless (eq org-agenda-diary-file 'diary-file)
3267 (define-key calendar-mode-map
3268 org-calendar-insert-diary-entry-key
3269 'org-agenda-diary-entry))))))
3271 (defgroup org-latex nil
3272 "Options for embedding LaTeX code into Org-mode."
3273 :tag "Org LaTeX"
3274 :group 'org)
3276 (defcustom org-format-latex-options
3277 '(:foreground default :background default :scale 1.0
3278 :html-foreground "Black" :html-background "Transparent"
3279 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3280 "Options for creating images from LaTeX fragments.
3281 This is a property list with the following properties:
3282 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3283 `default' means use the foreground of the default face.
3284 :background the background color, or \"Transparent\".
3285 `default' means use the background of the default face.
3286 :scale a scaling factor for the size of the images, to get more pixels
3287 :html-foreground, :html-background, :html-scale
3288 the same numbers for HTML export.
3289 :matchers a list indicating which matchers should be used to
3290 find LaTeX fragments. Valid members of this list are:
3291 \"begin\" find environments
3292 \"$1\" find single characters surrounded by $.$
3293 \"$\" find math expressions surrounded by $...$
3294 \"$$\" find math expressions surrounded by $$....$$
3295 \"\\(\" find math expressions surrounded by \\(...\\)
3296 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3297 :group 'org-latex
3298 :type 'plist)
3300 (defcustom org-format-latex-signal-error t
3301 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3302 When nil, just push out a message."
3303 :group 'org-latex
3304 :type 'boolean)
3305 (defcustom org-latex-to-mathml-jar-file nil
3306 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3307 Use this to specify additional executable file say a jar file.
3309 When using MathToWeb as the converter, specify the full-path to
3310 your mathtoweb.jar file."
3311 :group 'org-latex
3312 :type '(choice
3313 (const :tag "None" nil)
3314 (file :tag "JAR file" :must-match t)))
3316 (defcustom org-latex-to-mathml-convert-command nil
3317 "Command to convert LaTeX fragments to MathML.
3318 Replace format-specifiers in the command as noted below and use
3319 `shell-command' to convert LaTeX to MathML.
3320 %j: Executable file in fully expanded form as specified by
3321 `org-latex-to-mathml-jar-file'.
3322 %I: Input LaTeX file in fully expanded form
3323 %o: Output MathML file
3324 This command is used by `org-create-math-formula'.
3326 When using MathToWeb as the converter, set this to
3327 \"java -jar %j -unicode -force -df %o %I\"."
3328 :group 'org-latex
3329 :type '(choice
3330 (const :tag "None" nil)
3331 (string :tag "\nShell command")))
3333 (defun org-format-latex-mathml-available-p ()
3334 "Return t if `org-latex-to-mathml-convert-command' is usable."
3335 (save-match-data
3336 (when (and (boundp 'org-latex-to-mathml-convert-command)
3337 org-latex-to-mathml-convert-command)
3338 (let ((executable (car (split-string
3339 org-latex-to-mathml-convert-command))))
3340 (when (executable-find executable)
3341 (if (string-match
3342 "%j" org-latex-to-mathml-convert-command)
3343 (file-readable-p org-latex-to-mathml-jar-file)
3344 t))))))
3346 (defcustom org-format-latex-header "\\documentclass{article}
3347 \\usepackage[usenames]{color}
3348 \\usepackage{amsmath}
3349 \\usepackage[mathscr]{eucal}
3350 \\pagestyle{empty} % do not remove
3351 \[PACKAGES]
3352 \[DEFAULT-PACKAGES]
3353 % The settings below are copied from fullpage.sty
3354 \\setlength{\\textwidth}{\\paperwidth}
3355 \\addtolength{\\textwidth}{-3cm}
3356 \\setlength{\\oddsidemargin}{1.5cm}
3357 \\addtolength{\\oddsidemargin}{-2.54cm}
3358 \\setlength{\\evensidemargin}{\\oddsidemargin}
3359 \\setlength{\\textheight}{\\paperheight}
3360 \\addtolength{\\textheight}{-\\headheight}
3361 \\addtolength{\\textheight}{-\\headsep}
3362 \\addtolength{\\textheight}{-\\footskip}
3363 \\addtolength{\\textheight}{-3cm}
3364 \\setlength{\\topmargin}{1.5cm}
3365 \\addtolength{\\topmargin}{-2.54cm}"
3366 "The document header used for processing LaTeX fragments.
3367 It is imperative that this header make sure that no page number
3368 appears on the page. The package defined in the variables
3369 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3370 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3371 will be appended."
3372 :group 'org-latex
3373 :type 'string)
3375 (defvar org-format-latex-header-extra nil)
3377 (defun org-set-packages-alist (var val)
3378 "Set the packages alist and make sure it has 3 elements per entry."
3379 (set var (mapcar (lambda (x)
3380 (if (and (consp x) (= (length x) 2))
3381 (list (car x) (nth 1 x) t)
3383 val)))
3385 (defun org-get-packages-alist (var)
3387 "Get the packages alist and make sure it has 3 elements per entry."
3388 (mapcar (lambda (x)
3389 (if (and (consp x) (= (length x) 2))
3390 (list (car x) (nth 1 x) t)
3392 (default-value var)))
3394 ;; The following variables are defined here because is it also used
3395 ;; when formatting latex fragments. Originally it was part of the
3396 ;; LaTeX exporter, which is why the name includes "export".
3397 (defcustom org-export-latex-default-packages-alist
3398 '(("AUTO" "inputenc" t)
3399 ("T1" "fontenc" t)
3400 ("" "fixltx2e" nil)
3401 ("" "graphicx" t)
3402 ("" "longtable" nil)
3403 ("" "float" nil)
3404 ("" "wrapfig" nil)
3405 ("" "soul" t)
3406 ("" "textcomp" t)
3407 ("" "marvosym" t)
3408 ("" "wasysym" t)
3409 ("" "latexsym" t)
3410 ("" "amssymb" t)
3411 ("" "hyperref" nil)
3412 "\\tolerance=1000"
3414 "Alist of default packages to be inserted in the header.
3415 Change this only if one of the packages here causes an incompatibility
3416 with another package you are using.
3417 The packages in this list are needed by one part or another of Org-mode
3418 to function properly.
3420 - inputenc, fontenc: for basic font and character selection
3421 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3422 for interpreting the entities in `org-entities'. You can skip some of these
3423 packages if you don't use any of the symbols in it.
3424 - graphicx: for including images
3425 - float, wrapfig: for figure placement
3426 - longtable: for long tables
3427 - hyperref: for cross references
3429 Therefore you should not modify this variable unless you know what you
3430 are doing. The one reason to change it anyway is that you might be loading
3431 some other package that conflicts with one of the default packages.
3432 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3433 If SNIPPET-FLAG is t, the package also needs to be included when
3434 compiling LaTeX snippets into images for inclusion into HTML."
3435 :group 'org-export-latex
3436 :set 'org-set-packages-alist
3437 :get 'org-get-packages-alist
3438 :type '(repeat
3439 (choice
3440 (list :tag "options/package pair"
3441 (string :tag "options")
3442 (string :tag "package")
3443 (boolean :tag "Snippet"))
3444 (string :tag "A line of LaTeX"))))
3446 (defcustom org-export-latex-packages-alist nil
3447 "Alist of packages to be inserted in every LaTeX header.
3448 These will be inserted after `org-export-latex-default-packages-alist'.
3449 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3450 SNIPPET-FLAG, when t, indicates that this package is also needed when
3451 turning LaTeX snippets into images for inclusion into HTML.
3452 Make sure that you only list packages here which:
3453 - you want in every file
3454 - do not conflict with the default packages in
3455 `org-export-latex-default-packages-alist'
3456 - do not conflict with the setup in `org-format-latex-header'."
3457 :group 'org-export-latex
3458 :set 'org-set-packages-alist
3459 :get 'org-get-packages-alist
3460 :type '(repeat
3461 (choice
3462 (list :tag "options/package pair"
3463 (string :tag "options")
3464 (string :tag "package")
3465 (boolean :tag "Snippet"))
3466 (string :tag "A line of LaTeX"))))
3469 (defgroup org-appearance nil
3470 "Settings for Org-mode appearance."
3471 :tag "Org Appearance"
3472 :group 'org)
3474 (defcustom org-level-color-stars-only nil
3475 "Non-nil means fontify only the stars in each headline.
3476 When nil, the entire headline is fontified.
3477 Changing it requires restart of `font-lock-mode' to become effective
3478 also in regions already fontified."
3479 :group 'org-appearance
3480 :type 'boolean)
3482 (defcustom org-hide-leading-stars nil
3483 "Non-nil means hide the first N-1 stars in a headline.
3484 This works by using the face `org-hide' for these stars. This
3485 face is white for a light background, and black for a dark
3486 background. You may have to customize the face `org-hide' to
3487 make this work.
3488 Changing it requires restart of `font-lock-mode' to become effective
3489 also in regions already fontified.
3490 You may also set this on a per-file basis by adding one of the following
3491 lines to the buffer:
3493 #+STARTUP: hidestars
3494 #+STARTUP: showstars"
3495 :group 'org-appearance
3496 :type 'boolean)
3498 (defcustom org-hidden-keywords nil
3499 "List of symbols corresponding to keywords to be hidden the org buffer.
3500 For example, a value '(title) for this list will make the document's title
3501 appear in the buffer without the initial #+TITLE: keyword."
3502 :group 'org-appearance
3503 :type '(set (const :tag "#+AUTHOR" author)
3504 (const :tag "#+DATE" date)
3505 (const :tag "#+EMAIL" email)
3506 (const :tag "#+TITLE" title)))
3508 (defcustom org-fontify-done-headline nil
3509 "Non-nil means change the face of a headline if it is marked DONE.
3510 Normally, only the TODO/DONE keyword indicates the state of a headline.
3511 When this is non-nil, the headline after the keyword is set to the
3512 `org-headline-done' as an additional indication."
3513 :group 'org-appearance
3514 :type 'boolean)
3516 (defcustom org-fontify-emphasized-text t
3517 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3518 Changing this variable requires a restart of Emacs to take effect."
3519 :group 'org-appearance
3520 :type 'boolean)
3522 (defcustom org-fontify-whole-heading-line nil
3523 "Non-nil means fontify the whole line for headings.
3524 This is useful when setting a background color for the
3525 org-level-* faces."
3526 :group 'org-appearance
3527 :type 'boolean)
3529 (defcustom org-highlight-latex-fragments-and-specials nil
3530 "Non-nil means fontify what is treated specially by the exporters."
3531 :group 'org-appearance
3532 :type 'boolean)
3534 (defcustom org-hide-emphasis-markers nil
3535 "Non-nil mean font-lock should hide the emphasis marker characters."
3536 :group 'org-appearance
3537 :type 'boolean)
3539 (defcustom org-pretty-entities nil
3540 "Non-nil means show entities as UTF8 characters.
3541 When nil, the \\name form remains in the buffer."
3542 :group 'org-appearance
3543 :type 'boolean)
3545 (defcustom org-pretty-entities-include-sub-superscripts t
3546 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3547 :group 'org-appearance
3548 :type 'boolean)
3550 (defvar org-emph-re nil
3551 "Regular expression for matching emphasis.
3552 After a match, the match groups contain these elements:
3553 0 The match of the full regular expression, including the characters
3554 before and after the proper match
3555 1 The character before the proper match, or empty at beginning of line
3556 2 The proper match, including the leading and trailing markers
3557 3 The leading marker like * or /, indicating the type of highlighting
3558 4 The text between the emphasis markers, not including the markers
3559 5 The character after the match, empty at the end of a line")
3560 (defvar org-verbatim-re nil
3561 "Regular expression for matching verbatim text.")
3562 (defvar org-emphasis-regexp-components) ; defined just below
3563 (defvar org-emphasis-alist) ; defined just below
3564 (defun org-set-emph-re (var val)
3565 "Set variable and compute the emphasis regular expression."
3566 (set var val)
3567 (when (and (boundp 'org-emphasis-alist)
3568 (boundp 'org-emphasis-regexp-components)
3569 org-emphasis-alist org-emphasis-regexp-components)
3570 (let* ((e org-emphasis-regexp-components)
3571 (pre (car e))
3572 (post (nth 1 e))
3573 (border (nth 2 e))
3574 (body (nth 3 e))
3575 (nl (nth 4 e))
3576 (body1 (concat body "*?"))
3577 (markers (mapconcat 'car org-emphasis-alist ""))
3578 (vmarkers (mapconcat
3579 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3580 org-emphasis-alist "")))
3581 ;; make sure special characters appear at the right position in the class
3582 (if (string-match "\\^" markers)
3583 (setq markers (concat (replace-match "" t t markers) "^")))
3584 (if (string-match "-" markers)
3585 (setq markers (concat (replace-match "" t t markers) "-")))
3586 (if (string-match "\\^" vmarkers)
3587 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3588 (if (string-match "-" vmarkers)
3589 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3590 (if (> nl 0)
3591 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3592 (int-to-string nl) "\\}")))
3593 ;; Make the regexp
3594 (setq org-emph-re
3595 (concat "\\([" pre "]\\|^\\)"
3596 "\\("
3597 "\\([" markers "]\\)"
3598 "\\("
3599 "[^" border "]\\|"
3600 "[^" border "]"
3601 body1
3602 "[^" border "]"
3603 "\\)"
3604 "\\3\\)"
3605 "\\([" post "]\\|$\\)"))
3606 (setq org-verbatim-re
3607 (concat "\\([" pre "]\\|^\\)"
3608 "\\("
3609 "\\([" vmarkers "]\\)"
3610 "\\("
3611 "[^" border "]\\|"
3612 "[^" border "]"
3613 body1
3614 "[^" border "]"
3615 "\\)"
3616 "\\3\\)"
3617 "\\([" post "]\\|$\\)")))))
3619 (defcustom org-emphasis-regexp-components
3620 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3621 "Components used to build the regular expression for emphasis.
3622 This is a list with five entries. Terminology: In an emphasis string
3623 like \" *strong word* \", we call the initial space PREMATCH, the final
3624 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3625 and \"trong wor\" is the body. The different components in this variable
3626 specify what is allowed/forbidden in each part:
3628 pre Chars allowed as prematch. Beginning of line will be allowed too.
3629 post Chars allowed as postmatch. End of line will be allowed too.
3630 border The chars *forbidden* as border characters.
3631 body-regexp A regexp like \".\" to match a body character. Don't use
3632 non-shy groups here, and don't allow newline here.
3633 newline The maximum number of newlines allowed in an emphasis exp.
3635 Use customize to modify this, or restart Emacs after changing it."
3636 :group 'org-appearance
3637 :set 'org-set-emph-re
3638 :type '(list
3639 (sexp :tag "Allowed chars in pre ")
3640 (sexp :tag "Allowed chars in post ")
3641 (sexp :tag "Forbidden chars in border ")
3642 (sexp :tag "Regexp for body ")
3643 (integer :tag "number of newlines allowed")
3644 (option (boolean :tag "Please ignore this button"))))
3646 (defcustom org-emphasis-alist
3647 `(("*" bold "<b>" "</b>")
3648 ("/" italic "<i>" "</i>")
3649 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3650 ("=" org-code "<code>" "</code>" verbatim)
3651 ("~" org-verbatim "<code>" "</code>" verbatim)
3652 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3653 "<del>" "</del>")
3655 "Special syntax for emphasized text.
3656 Text starting and ending with a special character will be emphasized, for
3657 example *bold*, _underlined_ and /italic/. This variable sets the marker
3658 characters, the face to be used by font-lock for highlighting in Org-mode
3659 Emacs buffers, and the HTML tags to be used for this.
3660 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3661 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3662 Use customize to modify this, or restart Emacs after changing it."
3663 :group 'org-appearance
3664 :set 'org-set-emph-re
3665 :type '(repeat
3666 (list
3667 (string :tag "Marker character")
3668 (choice
3669 (face :tag "Font-lock-face")
3670 (plist :tag "Face property list"))
3671 (string :tag "HTML start tag")
3672 (string :tag "HTML end tag")
3673 (option (const verbatim)))))
3675 (defvar org-protecting-blocks
3676 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3677 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3678 This is needed for font-lock setup.")
3680 ;;; Miscellaneous options
3682 (defgroup org-completion nil
3683 "Completion in Org-mode."
3684 :tag "Org Completion"
3685 :group 'org)
3687 (defcustom org-completion-use-ido nil
3688 "Non-nil means use ido completion wherever possible.
3689 Note that `ido-mode' must be active for this variable to be relevant.
3690 If you decide to turn this variable on, you might well want to turn off
3691 `org-outline-path-complete-in-steps'.
3692 See also `org-completion-use-iswitchb'."
3693 :group 'org-completion
3694 :type 'boolean)
3696 (defcustom org-completion-use-iswitchb nil
3697 "Non-nil means use iswitchb completion wherever possible.
3698 Note that `iswitchb-mode' must be active for this variable to be relevant.
3699 If you decide to turn this variable on, you might well want to turn off
3700 `org-outline-path-complete-in-steps'.
3701 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3702 :group 'org-completion
3703 :type 'boolean)
3705 (defcustom org-completion-fallback-command 'hippie-expand
3706 "The expansion command called by \\[pcomplete] in normal context.
3707 Normal means, no org-mode-specific context."
3708 :group 'org-completion
3709 :type 'function)
3711 ;;; Functions and variables from their packages
3712 ;; Declared here to avoid compiler warnings
3714 ;; XEmacs only
3715 (defvar outline-mode-menu-heading)
3716 (defvar outline-mode-menu-show)
3717 (defvar outline-mode-menu-hide)
3718 (defvar zmacs-regions) ; XEmacs regions
3720 ;; Emacs only
3721 (defvar mark-active)
3723 ;; Various packages
3724 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3725 (declare-function calendar-forward-day "cal-move" (arg))
3726 (declare-function calendar-goto-date "cal-move" (date))
3727 (declare-function calendar-goto-today "cal-move" ())
3728 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3729 (defvar calc-embedded-close-formula)
3730 (defvar calc-embedded-open-formula)
3731 (declare-function cdlatex-tab "ext:cdlatex" ())
3732 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3733 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3734 (defvar font-lock-unfontify-region-function)
3735 (declare-function iswitchb-read-buffer "iswitchb"
3736 (prompt &optional default require-match start matches-set))
3737 (defvar iswitchb-temp-buflist)
3738 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3739 (defvar org-agenda-tags-todo-honor-ignore-options)
3740 (declare-function org-agenda-skip "org-agenda" ())
3741 (declare-function
3742 org-agenda-format-item "org-agenda"
3743 (extra txt &optional category tags dotime noprefix remove-re habitp))
3744 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3745 (declare-function org-agenda-change-all-lines "org-agenda"
3746 (newhead hdmarker &optional fixface just-this))
3747 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3748 (declare-function org-agenda-maybe-redo "org-agenda" ())
3749 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3750 (beg end))
3751 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3752 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3753 "org-agenda" (&optional end))
3754 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3755 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3756 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3757 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3758 (declare-function org-indent-mode "org-indent" (&optional arg))
3759 (declare-function parse-time-string "parse-time" (string))
3760 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3761 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3762 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3763 (defvar remember-data-file)
3764 (defvar texmathp-why)
3765 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3766 (declare-function table--at-cell-p "table" (position &optional object at-column))
3768 (defvar w3m-current-url)
3769 (defvar w3m-current-title)
3771 (defvar org-latex-regexps)
3773 ;;; Autoload and prepare some org modules
3775 ;; Some table stuff that needs to be defined here, because it is used
3776 ;; by the functions setting up org-mode or checking for table context.
3778 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3779 "Detect an org-type or table-type table.")
3780 (defconst org-table-line-regexp "^[ \t]*|"
3781 "Detect an org-type table line.")
3782 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3783 "Detect an org-type table line.")
3784 (defconst org-table-hline-regexp "^[ \t]*|-"
3785 "Detect an org-type table hline.")
3786 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3787 "Detect a table-type table hline.")
3788 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3789 "Detect the first line outside a table when searching from within it.
3790 This works for both table types.")
3792 ;; Autoload the functions in org-table.el that are needed by functions here.
3794 (eval-and-compile
3795 (org-autoload "org-table"
3796 '(org-table-align org-table-begin org-table-blank-field
3797 org-table-convert org-table-convert-region org-table-copy-down
3798 org-table-copy-region org-table-create
3799 org-table-create-or-convert-from-region
3800 org-table-create-with-table.el org-table-current-dline
3801 org-table-cut-region org-table-delete-column org-table-edit-field
3802 org-table-edit-formulas org-table-end org-table-eval-formula
3803 org-table-export org-table-field-info
3804 org-table-get-stored-formulas org-table-goto-column
3805 org-table-hline-and-move org-table-import org-table-insert-column
3806 org-table-insert-hline org-table-insert-row org-table-iterate
3807 org-table-justify-field-maybe org-table-kill-row
3808 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3809 org-table-move-column org-table-move-column-left
3810 org-table-move-column-right org-table-move-row
3811 org-table-move-row-down org-table-move-row-up
3812 org-table-next-field org-table-next-row org-table-paste-rectangle
3813 org-table-previous-field org-table-recalculate
3814 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3815 org-table-toggle-coordinate-overlays
3816 org-table-toggle-formula-debugger org-table-wrap-region
3817 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3818 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3819 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3821 (defun org-at-table-p (&optional table-type)
3822 "Return t if the cursor is inside an org-type table.
3823 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3824 (if org-enable-table-editor
3825 (save-excursion
3826 (beginning-of-line 1)
3827 (looking-at (if table-type org-table-any-line-regexp
3828 org-table-line-regexp)))
3829 nil))
3830 (defsubst org-table-p () (org-at-table-p))
3832 (defun org-at-table.el-p ()
3833 "Return t if and only if we are at a table.el table."
3834 (and (org-at-table-p 'any)
3835 (save-excursion
3836 (goto-char (org-table-begin 'any))
3837 (looking-at org-table1-hline-regexp))))
3838 (defun org-table-recognize-table.el ()
3839 "If there is a table.el table nearby, recognize it and move into it."
3840 (if org-table-tab-recognizes-table.el
3841 (if (org-at-table.el-p)
3842 (progn
3843 (beginning-of-line 1)
3844 (if (looking-at org-table-dataline-regexp)
3846 (if (looking-at org-table1-hline-regexp)
3847 (progn
3848 (beginning-of-line 2)
3849 (if (looking-at org-table-any-border-regexp)
3850 (beginning-of-line -1)))))
3851 (if (re-search-forward "|" (org-table-end t) t)
3852 (progn
3853 (require 'table)
3854 (if (table--at-cell-p (point))
3856 (message "recognizing table.el table...")
3857 (table-recognize-table)
3858 (message "recognizing table.el table...done")))
3859 (error "This should not happen"))
3861 nil)
3862 nil))
3864 (defun org-at-table-hline-p ()
3865 "Return t if the cursor is inside a hline in a table."
3866 (if org-enable-table-editor
3867 (save-excursion
3868 (beginning-of-line 1)
3869 (looking-at org-table-hline-regexp))
3870 nil))
3872 (defvar org-table-clean-did-remove-column nil)
3874 (defun org-table-map-tables (function &optional quietly)
3875 "Apply FUNCTION to the start of all tables in the buffer."
3876 (save-excursion
3877 (save-restriction
3878 (widen)
3879 (goto-char (point-min))
3880 (while (re-search-forward org-table-any-line-regexp nil t)
3881 (unless quietly
3882 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3883 (beginning-of-line 1)
3884 (when (looking-at org-table-line-regexp)
3885 (save-excursion (funcall function))
3886 (or (looking-at org-table-line-regexp)
3887 (forward-char 1)))
3888 (re-search-forward org-table-any-border-regexp nil 1))))
3889 (unless quietly (message "Mapping tables: done")))
3891 ;; Declare and autoload functions from org-exp.el & Co
3893 (declare-function org-default-export-plist "org-exp")
3894 (declare-function org-infile-export-plist "org-exp")
3895 (declare-function org-get-current-options "org-exp")
3896 (eval-and-compile
3897 (org-autoload "org-exp"
3898 '(org-export org-export-visible
3899 org-insert-export-options-template
3900 org-table-clean-before-export))
3901 (org-autoload "org-ascii"
3902 '(org-export-as-ascii org-export-ascii-preprocess
3903 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3904 org-export-region-as-ascii))
3905 (org-autoload "org-latex"
3906 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3907 org-replace-region-by-latex org-export-region-as-latex
3908 org-export-as-latex org-export-as-pdf
3909 org-export-as-pdf-and-open))
3910 (org-autoload "org-html"
3911 '(org-export-as-html-and-open
3912 org-export-as-html-batch org-export-as-html-to-buffer
3913 org-replace-region-by-html org-export-region-as-html
3914 org-export-as-html))
3915 (org-autoload "org-docbook"
3916 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3917 org-replace-region-by-docbook org-export-region-as-docbook
3918 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3919 org-export-as-docbook))
3920 (org-autoload "org-icalendar"
3921 '(org-export-icalendar-this-file
3922 org-export-icalendar-all-agenda-files
3923 org-export-icalendar-combine-agenda-files))
3924 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3925 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3927 ;; Declare and autoload functions from org-agenda.el
3929 (eval-and-compile
3930 (org-autoload "org-agenda"
3931 '(org-agenda org-agenda-list org-search-view
3932 org-todo-list org-tags-view org-agenda-list-stuck-projects
3933 org-diary org-agenda-to-appt
3934 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3936 ;; Autoload org-remember
3938 (eval-and-compile
3939 (org-autoload "org-remember"
3940 '(org-remember-insinuate org-remember-annotation
3941 org-remember-apply-template org-remember org-remember-handler)))
3943 (eval-and-compile
3944 (org-autoload "org-capture"
3945 '(org-capture org-capture-insert-template-here
3946 org-capture-import-remember-templates)))
3948 ;; Autoload org-clock.el
3950 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3951 (beg end))
3952 (declare-function org-clock-update-mode-line "org-clock" ())
3953 (declare-function org-resolve-clocks "org-clock"
3954 (&optional also-non-dangling-p prompt last-valid))
3955 (defvar org-clock-start-time)
3956 (defvar org-clock-marker (make-marker)
3957 "Marker recording the last clock-in.")
3958 (defvar org-clock-hd-marker (make-marker)
3959 "Marker recording the last clock-in, but the headline position.")
3960 (defvar org-clock-heading ""
3961 "The heading of the current clock entry.")
3962 (defun org-clock-is-active ()
3963 "Return non-nil if clock is currently running.
3964 The return value is actually the clock marker."
3965 (marker-buffer org-clock-marker))
3967 (eval-and-compile
3968 (org-autoload
3969 "org-clock"
3970 '(org-clock-in org-clock-out org-clock-cancel
3971 org-clock-goto org-clock-sum org-clock-display
3972 org-clock-remove-overlays org-clock-report
3973 org-clocktable-shift org-dblock-write:clocktable
3974 org-get-clocktable org-resolve-clocks)))
3976 (defun org-clock-update-time-maybe ()
3977 "If this is a CLOCK line, update it and return t.
3978 Otherwise, return nil."
3979 (interactive)
3980 (save-excursion
3981 (beginning-of-line 1)
3982 (skip-chars-forward " \t")
3983 (when (looking-at org-clock-string)
3984 (let ((re (concat "[ \t]*" org-clock-string
3985 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3986 "\\([ \t]*=>.*\\)?\\)?"))
3987 ts te h m s neg)
3988 (cond
3989 ((not (looking-at re))
3990 nil)
3991 ((not (match-end 2))
3992 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3993 (> org-clock-marker (point))
3994 (<= org-clock-marker (point-at-eol)))
3995 ;; The clock is running here
3996 (setq org-clock-start-time
3997 (apply 'encode-time
3998 (org-parse-time-string (match-string 1))))
3999 (org-clock-update-mode-line)))
4001 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4002 (end-of-line 1)
4003 (setq ts (match-string 1)
4004 te (match-string 3))
4005 (setq s (- (org-float-time
4006 (apply 'encode-time (org-parse-time-string te)))
4007 (org-float-time
4008 (apply 'encode-time (org-parse-time-string ts))))
4009 neg (< s 0)
4010 s (abs s)
4011 h (floor (/ s 3600))
4012 s (- s (* 3600 h))
4013 m (floor (/ s 60))
4014 s (- s (* 60 s)))
4015 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4016 t))))))
4018 (defun org-check-running-clock ()
4019 "Check if the current buffer contains the running clock.
4020 If yes, offer to stop it and to save the buffer with the changes."
4021 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4022 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4023 (buffer-name))))
4024 (org-clock-out)
4025 (when (y-or-n-p "Save changed buffer?")
4026 (save-buffer))))
4028 (defun org-clocktable-try-shift (dir n)
4029 "Check if this line starts a clock table, if yes, shift the time block."
4030 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4031 (org-clocktable-shift dir n)))
4033 ;; Autoload org-timer.el
4035 (eval-and-compile
4036 (org-autoload
4037 "org-timer"
4038 '(org-timer-start org-timer org-timer-item
4039 org-timer-change-times-in-region
4040 org-timer-set-timer
4041 org-timer-reset-timers
4042 org-timer-show-remaining-time)))
4044 ;; Autoload org-feed.el
4046 (eval-and-compile
4047 (org-autoload
4048 "org-feed"
4049 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4052 ;; Autoload org-indent.el
4054 ;; Define the variable already here, to make sure we have it.
4055 (defvar org-indent-mode nil
4056 "Non-nil if Org-Indent mode is enabled.
4057 Use the command `org-indent-mode' to change this variable.")
4059 (eval-and-compile
4060 (org-autoload
4061 "org-indent"
4062 '(org-indent-mode)))
4064 ;; Autoload org-mobile.el
4066 (eval-and-compile
4067 (org-autoload
4068 "org-mobile"
4069 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4071 ;; Autoload archiving code
4072 ;; The stuff that is needed for cycling and tags has to be defined here.
4074 (defgroup org-archive nil
4075 "Options concerning archiving in Org-mode."
4076 :tag "Org Archive"
4077 :group 'org-structure)
4079 (defcustom org-archive-location "%s_archive::"
4080 "The location where subtrees should be archived.
4082 The value of this variable is a string, consisting of two parts,
4083 separated by a double-colon. The first part is a filename and
4084 the second part is a headline.
4086 When the filename is omitted, archiving happens in the same file.
4087 %s in the filename will be replaced by the current file
4088 name (without the directory part). Archiving to a different file
4089 is useful to keep archived entries from contributing to the
4090 Org-mode Agenda.
4092 The archived entries will be filed as subtrees of the specified
4093 headline. When the headline is omitted, the subtrees are simply
4094 filed away at the end of the file, as top-level entries. Also in
4095 the heading you can use %s to represent the file name, this can be
4096 useful when using the same archive for a number of different files.
4098 Here are a few examples:
4099 \"%s_archive::\"
4100 If the current file is Projects.org, archive in file
4101 Projects.org_archive, as top-level trees. This is the default.
4103 \"::* Archived Tasks\"
4104 Archive in the current file, under the top-level headline
4105 \"* Archived Tasks\".
4107 \"~/org/archive.org::\"
4108 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4110 \"~/org/archive.org::* From %s\"
4111 Archive in file ~/org/archive.org (absolute path), under headlines
4112 \"From FILENAME\" where file name is the current file name.
4114 \"basement::** Finished Tasks\"
4115 Archive in file ./basement (relative path), as level 3 trees
4116 below the level 2 heading \"** Finished Tasks\".
4118 You may set this option on a per-file basis by adding to the buffer a
4119 line like
4121 #+ARCHIVE: basement::** Finished Tasks
4123 You may also define it locally for a subtree by setting an ARCHIVE property
4124 in the entry. If such a property is found in an entry, or anywhere up
4125 the hierarchy, it will be used."
4126 :group 'org-archive
4127 :type 'string)
4129 (defcustom org-archive-tag "ARCHIVE"
4130 "The tag that marks a subtree as archived.
4131 An archived subtree does not open during visibility cycling, and does
4132 not contribute to the agenda listings.
4133 After changing this, font-lock must be restarted in the relevant buffers to
4134 get the proper fontification."
4135 :group 'org-archive
4136 :group 'org-keywords
4137 :type 'string)
4139 (defcustom org-agenda-skip-archived-trees t
4140 "Non-nil means the agenda will skip any items located in archived trees.
4141 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4142 variable is no longer recommended, you should leave it at the value t.
4143 Instead, use the key `v' to cycle the archives-mode in the agenda."
4144 :group 'org-archive
4145 :group 'org-agenda-skip
4146 :type 'boolean)
4148 (defcustom org-columns-skip-archived-trees t
4149 "Non-nil means ignore archived trees when creating column view."
4150 :group 'org-archive
4151 :group 'org-properties
4152 :type 'boolean)
4154 (defcustom org-cycle-open-archived-trees nil
4155 "Non-nil means `org-cycle' will open archived trees.
4156 An archived tree is a tree marked with the tag ARCHIVE.
4157 When nil, archived trees will stay folded. You can still open them with
4158 normal outline commands like `show-all', but not with the cycling commands."
4159 :group 'org-archive
4160 :group 'org-cycle
4161 :type 'boolean)
4163 (defcustom org-sparse-tree-open-archived-trees nil
4164 "Non-nil means sparse tree construction shows matches in archived trees.
4165 When nil, matches in these trees are highlighted, but the trees are kept in
4166 collapsed state."
4167 :group 'org-archive
4168 :group 'org-sparse-trees
4169 :type 'boolean)
4171 (defun org-cycle-hide-archived-subtrees (state)
4172 "Re-hide all archived subtrees after a visibility state change."
4173 (when (and (not org-cycle-open-archived-trees)
4174 (not (memq state '(overview folded))))
4175 (save-excursion
4176 (let* ((globalp (memq state '(contents all)))
4177 (beg (if globalp (point-min) (point)))
4178 (end (if globalp (point-max) (org-end-of-subtree t))))
4179 (org-hide-archived-subtrees beg end)
4180 (goto-char beg)
4181 (if (looking-at (concat ".*:" org-archive-tag ":"))
4182 (message "%s" (substitute-command-keys
4183 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4185 (defun org-force-cycle-archived ()
4186 "Cycle subtree even if it is archived."
4187 (interactive)
4188 (setq this-command 'org-cycle)
4189 (let ((org-cycle-open-archived-trees t))
4190 (call-interactively 'org-cycle)))
4192 (defun org-hide-archived-subtrees (beg end)
4193 "Re-hide all archived subtrees after a visibility state change."
4194 (save-excursion
4195 (let* ((re (concat ":" org-archive-tag ":")))
4196 (goto-char beg)
4197 (while (re-search-forward re end t)
4198 (when (org-on-heading-p)
4199 (org-flag-subtree t)
4200 (org-end-of-subtree t))))))
4202 (defun org-flag-subtree (flag)
4203 (save-excursion
4204 (org-back-to-heading t)
4205 (outline-end-of-heading)
4206 (outline-flag-region (point)
4207 (progn (org-end-of-subtree t) (point))
4208 flag)))
4210 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4212 (eval-and-compile
4213 (org-autoload "org-archive"
4214 '(org-add-archive-files org-archive-subtree
4215 org-archive-to-archive-sibling org-toggle-archive-tag
4216 org-archive-subtree-default
4217 org-archive-subtree-default-with-confirmation)))
4219 ;; Autoload Column View Code
4221 (declare-function org-columns-number-to-string "org-colview")
4222 (declare-function org-columns-get-format-and-top-level "org-colview")
4223 (declare-function org-columns-compute "org-colview")
4225 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4226 '(org-columns-number-to-string org-columns-get-format-and-top-level
4227 org-columns-compute org-agenda-columns org-columns-remove-overlays
4228 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4230 ;; Autoload ID code
4232 (declare-function org-id-store-link "org-id")
4233 (declare-function org-id-locations-load "org-id")
4234 (declare-function org-id-locations-save "org-id")
4235 (defvar org-id-track-globally)
4236 (org-autoload "org-id"
4237 '(org-id-get-create org-id-new org-id-copy org-id-get
4238 org-id-get-with-outline-path-completion
4239 org-id-get-with-outline-drilling org-id-store-link
4240 org-id-goto org-id-find org-id-store-link))
4242 ;; Autoload Plotting Code
4244 (org-autoload "org-plot"
4245 '(org-plot/gnuplot))
4247 ;;; Variables for pre-computed regular expressions, all buffer local
4249 (defvar org-heading-regexp nil
4250 "Matches an headline.
4251 Stars are put in group 1 and the trimmed body in group 2.")
4252 (make-variable-buffer-local 'org-heading-regexp)
4253 (defvar org-drawer-regexp nil
4254 "Matches first line of a hidden block.")
4255 (make-variable-buffer-local 'org-drawer-regexp)
4256 (defvar org-todo-regexp nil
4257 "Matches any of the TODO state keywords.")
4258 (make-variable-buffer-local 'org-todo-regexp)
4259 (defvar org-not-done-regexp nil
4260 "Matches any of the TODO state keywords except the last one.")
4261 (make-variable-buffer-local 'org-not-done-regexp)
4262 (defvar org-not-done-heading-regexp nil
4263 "Matches a TODO headline that is not done.")
4264 (make-variable-buffer-local 'org-not-done-regexp)
4265 (defvar org-todo-line-regexp nil
4266 "Matches a headline and puts TODO state into group 2 if present.")
4267 (make-variable-buffer-local 'org-todo-line-regexp)
4268 (defvar org-complex-heading-regexp nil
4269 "Matches a headline and puts everything into groups:
4270 group 1: the stars
4271 group 2: The todo keyword, maybe
4272 group 3: Priority cookie
4273 group 4: True headline
4274 group 5: Tags")
4275 (make-variable-buffer-local 'org-complex-heading-regexp)
4276 (defvar org-heading-keyword-regexp-format nil
4277 "Printf format to make regexp to match an headline with some keyword.
4278 This regexp will match the headline of any node which has the
4279 exact keyword that is put into the format. The keyword isn't in
4280 any group by default, but the stars and the body are.")
4281 (make-variable-buffer-local 'org-heading-keyword-regexp-format)
4282 (defvar org-heading-keyword-maybe-regexp-format nil
4283 "Printf format to make regexp to match an headline with some keyword.
4284 This regexp can match any headline with the specified keyword, or
4285 a without a keyword. The keyword isn't in any group by default,
4286 but the stars and the body are.")
4287 (make-variable-buffer-local 'org-heading-keyword-maybe-regexp-format)
4288 (defvar org-complex-heading-regexp-format nil
4289 "Printf format to make regexp to match an exact headline.
4290 This regexp will match the headline of any node which has the
4291 exact headline text that is put into the format, but may have any
4292 TODO state, priority and tags.")
4293 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4294 (defvar org-todo-line-tags-regexp nil
4295 "Matches a headline and puts TODO state into group 2 if present.
4296 Also put tags into group 4 if tags are present.")
4297 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4298 (defvar org-ds-keyword-length 12
4299 "Maximum length of the Deadline and SCHEDULED keywords.")
4300 (make-variable-buffer-local 'org-ds-keyword-length)
4301 (defvar org-deadline-regexp nil
4302 "Matches the DEADLINE keyword.")
4303 (make-variable-buffer-local 'org-deadline-regexp)
4304 (defvar org-deadline-time-regexp nil
4305 "Matches the DEADLINE keyword together with a time stamp.")
4306 (make-variable-buffer-local 'org-deadline-time-regexp)
4307 (defvar org-deadline-line-regexp nil
4308 "Matches the DEADLINE keyword and the rest of the line.")
4309 (make-variable-buffer-local 'org-deadline-line-regexp)
4310 (defvar org-scheduled-regexp nil
4311 "Matches the SCHEDULED keyword.")
4312 (make-variable-buffer-local 'org-scheduled-regexp)
4313 (defvar org-scheduled-time-regexp nil
4314 "Matches the SCHEDULED keyword together with a time stamp.")
4315 (make-variable-buffer-local 'org-scheduled-time-regexp)
4316 (defvar org-closed-time-regexp nil
4317 "Matches the CLOSED keyword together with a time stamp.")
4318 (make-variable-buffer-local 'org-closed-time-regexp)
4320 (defvar org-keyword-time-regexp nil
4321 "Matches any of the 4 keywords, together with the time stamp.")
4322 (make-variable-buffer-local 'org-keyword-time-regexp)
4323 (defvar org-keyword-time-not-clock-regexp nil
4324 "Matches any of the 3 keywords, together with the time stamp.")
4325 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4326 (defvar org-maybe-keyword-time-regexp nil
4327 "Matches a timestamp, possibly preceded by a keyword.")
4328 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4329 (defvar org-planning-or-clock-line-re nil
4330 "Matches a line with planning or clock info.")
4331 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4332 (defvar org-all-time-keywords nil
4333 "List of time keywords.")
4334 (make-variable-buffer-local 'org-all-time-keywords)
4336 (defconst org-plain-time-of-day-regexp
4337 (concat
4338 "\\(\\<[012]?[0-9]"
4339 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4340 "\\(--?"
4341 "\\(\\<[012]?[0-9]"
4342 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4343 "\\)?")
4344 "Regular expression to match a plain time or time range.
4345 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4346 groups carry important information:
4347 0 the full match
4348 1 the first time, range or not
4349 8 the second time, if it is a range.")
4351 (defconst org-plain-time-extension-regexp
4352 (concat
4353 "\\(\\<[012]?[0-9]"
4354 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4355 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4356 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4357 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4358 groups carry important information:
4359 0 the full match
4360 7 hours of duration
4361 9 minutes of duration")
4363 (defconst org-stamp-time-of-day-regexp
4364 (concat
4365 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4366 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4367 "\\(--?"
4368 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4369 "Regular expression to match a timestamp time or time range.
4370 After a match, the following groups carry important information:
4371 0 the full match
4372 1 date plus weekday, for back referencing to make sure both times are on the same day
4373 2 the first time, range or not
4374 4 the second time, if it is a range.")
4376 (defconst org-startup-options
4377 '(("fold" org-startup-folded t)
4378 ("overview" org-startup-folded t)
4379 ("nofold" org-startup-folded nil)
4380 ("showall" org-startup-folded nil)
4381 ("showeverything" org-startup-folded showeverything)
4382 ("content" org-startup-folded content)
4383 ("indent" org-startup-indented t)
4384 ("noindent" org-startup-indented nil)
4385 ("hidestars" org-hide-leading-stars t)
4386 ("showstars" org-hide-leading-stars nil)
4387 ("odd" org-odd-levels-only t)
4388 ("oddeven" org-odd-levels-only nil)
4389 ("align" org-startup-align-all-tables t)
4390 ("noalign" org-startup-align-all-tables nil)
4391 ("inlineimages" org-startup-with-inline-images t)
4392 ("noinlineimages" org-startup-with-inline-images nil)
4393 ("customtime" org-display-custom-times t)
4394 ("logdone" org-log-done time)
4395 ("lognotedone" org-log-done note)
4396 ("nologdone" org-log-done nil)
4397 ("lognoteclock-out" org-log-note-clock-out t)
4398 ("nolognoteclock-out" org-log-note-clock-out nil)
4399 ("logrepeat" org-log-repeat state)
4400 ("lognoterepeat" org-log-repeat note)
4401 ("nologrepeat" org-log-repeat nil)
4402 ("logreschedule" org-log-reschedule time)
4403 ("lognotereschedule" org-log-reschedule note)
4404 ("nologreschedule" org-log-reschedule nil)
4405 ("logredeadline" org-log-redeadline time)
4406 ("lognoteredeadline" org-log-redeadline note)
4407 ("nologredeadline" org-log-redeadline nil)
4408 ("logrefile" org-log-refile time)
4409 ("lognoterefile" org-log-refile note)
4410 ("nologrefile" org-log-refile nil)
4411 ("fninline" org-footnote-define-inline t)
4412 ("nofninline" org-footnote-define-inline nil)
4413 ("fnlocal" org-footnote-section nil)
4414 ("fnauto" org-footnote-auto-label t)
4415 ("fnprompt" org-footnote-auto-label nil)
4416 ("fnconfirm" org-footnote-auto-label confirm)
4417 ("fnplain" org-footnote-auto-label plain)
4418 ("fnadjust" org-footnote-auto-adjust t)
4419 ("nofnadjust" org-footnote-auto-adjust nil)
4420 ("constcgs" constants-unit-system cgs)
4421 ("constSI" constants-unit-system SI)
4422 ("noptag" org-tag-persistent-alist nil)
4423 ("hideblocks" org-hide-block-startup t)
4424 ("nohideblocks" org-hide-block-startup nil)
4425 ("beamer" org-startup-with-beamer-mode t)
4426 ("entitiespretty" org-pretty-entities t)
4427 ("entitiesplain" org-pretty-entities nil))
4428 "Variable associated with STARTUP options for org-mode.
4429 Each element is a list of three items: The startup options as written
4430 in the #+STARTUP line, the corresponding variable, and the value to
4431 set this variable to if the option is found. An optional forth element PUSH
4432 means to push this value onto the list in the variable.")
4434 (defun org-set-regexps-and-options ()
4435 "Precompute regular expressions for current buffer."
4436 (when (eq major-mode 'org-mode)
4437 (org-set-local 'org-todo-kwd-alist nil)
4438 (org-set-local 'org-todo-key-alist nil)
4439 (org-set-local 'org-todo-key-trigger nil)
4440 (org-set-local 'org-todo-keywords-1 nil)
4441 (org-set-local 'org-done-keywords nil)
4442 (org-set-local 'org-todo-heads nil)
4443 (org-set-local 'org-todo-sets nil)
4444 (org-set-local 'org-todo-log-states nil)
4445 (org-set-local 'org-file-properties nil)
4446 (org-set-local 'org-file-tags nil)
4447 (let ((re (org-make-options-regexp
4448 '("CATEGORY" "TODO" "COLUMNS"
4449 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4450 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4451 "OPTIONS")
4452 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4453 (splitre "[ \t]+")
4454 (scripts org-use-sub-superscripts)
4455 kwds kws0 kwsa key log value cat arch tags const links hw dws
4456 tail sep kws1 prio props ftags drawers beamer-p
4457 ext-setup-or-nil setup-contents (start 0))
4458 (save-excursion
4459 (save-restriction
4460 (widen)
4461 (goto-char (point-min))
4462 (while (or (and ext-setup-or-nil
4463 (string-match re ext-setup-or-nil start)
4464 (setq start (match-end 0)))
4465 (and (setq ext-setup-or-nil nil start 0)
4466 (re-search-forward re nil t)))
4467 (setq key (upcase (match-string 1 ext-setup-or-nil))
4468 value (org-match-string-no-properties 2 ext-setup-or-nil))
4469 (if (stringp value) (setq value (org-trim value)))
4470 (cond
4471 ((equal key "CATEGORY")
4472 (setq cat value))
4473 ((member key '("SEQ_TODO" "TODO"))
4474 (push (cons 'sequence (org-split-string value splitre)) kwds))
4475 ((equal key "TYP_TODO")
4476 (push (cons 'type (org-split-string value splitre)) kwds))
4477 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4478 ;; general TODO-like setup
4479 (push (cons (intern (downcase (match-string 1 key)))
4480 (org-split-string value splitre)) kwds))
4481 ((equal key "TAGS")
4482 (setq tags (append tags (if tags '("\\n") nil)
4483 (org-split-string value splitre))))
4484 ((equal key "COLUMNS")
4485 (org-set-local 'org-columns-default-format value))
4486 ((equal key "LINK")
4487 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4488 (push (cons (match-string 1 value)
4489 (org-trim (match-string 2 value)))
4490 links)))
4491 ((equal key "PRIORITIES")
4492 (setq prio (org-split-string value " +")))
4493 ((equal key "PROPERTY")
4494 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4495 (push (cons (match-string 1 value) (match-string 2 value))
4496 props)))
4497 ((equal key "FILETAGS")
4498 (when (string-match "\\S-" value)
4499 (setq ftags
4500 (append
4501 ftags
4502 (apply 'append
4503 (mapcar (lambda (x) (org-split-string x ":"))
4504 (org-split-string value)))))))
4505 ((equal key "DRAWERS")
4506 (setq drawers (org-split-string value splitre)))
4507 ((equal key "CONSTANTS")
4508 (setq const (append const (org-split-string value splitre))))
4509 ((equal key "STARTUP")
4510 (let ((opts (org-split-string value splitre))
4511 l var val)
4512 (while (setq l (pop opts))
4513 (when (setq l (assoc l org-startup-options))
4514 (setq var (nth 1 l) val (nth 2 l))
4515 (if (not (nth 3 l))
4516 (set (make-local-variable var) val)
4517 (if (not (listp (symbol-value var)))
4518 (set (make-local-variable var) nil))
4519 (set (make-local-variable var) (symbol-value var))
4520 (add-to-list var val))))))
4521 ((equal key "ARCHIVE")
4522 (setq arch value)
4523 (remove-text-properties 0 (length arch)
4524 '(face t fontified t) arch))
4525 ((equal key "LATEX_CLASS")
4526 (setq beamer-p (equal value "beamer")))
4527 ((equal key "OPTIONS")
4528 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4529 (setq scripts (read (match-string 2 value)))))
4530 ((equal key "SETUPFILE")
4531 (setq setup-contents (org-file-contents
4532 (expand-file-name
4533 (org-remove-double-quotes value))
4534 'noerror))
4535 (if (not ext-setup-or-nil)
4536 (setq ext-setup-or-nil setup-contents start 0)
4537 (setq ext-setup-or-nil
4538 (concat (substring ext-setup-or-nil 0 start)
4539 "\n" setup-contents "\n"
4540 (substring ext-setup-or-nil start)))))
4541 ))))
4542 (org-set-local 'org-use-sub-superscripts scripts)
4543 (when cat
4544 (org-set-local 'org-category (intern cat))
4545 (push (cons "CATEGORY" cat) props))
4546 (when prio
4547 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4548 (setq prio (mapcar 'string-to-char prio))
4549 (org-set-local 'org-highest-priority (nth 0 prio))
4550 (org-set-local 'org-lowest-priority (nth 1 prio))
4551 (org-set-local 'org-default-priority (nth 2 prio)))
4552 (and props (org-set-local 'org-file-properties (nreverse props)))
4553 (and ftags (org-set-local 'org-file-tags
4554 (mapcar 'org-add-prop-inherited ftags)))
4555 (and drawers (org-set-local 'org-drawers drawers))
4556 (and arch (org-set-local 'org-archive-location arch))
4557 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4558 ;; Process the TODO keywords
4559 (unless kwds
4560 ;; Use the global values as if they had been given locally.
4561 (setq kwds (default-value 'org-todo-keywords))
4562 (if (stringp (car kwds))
4563 (setq kwds (list (cons org-todo-interpretation
4564 (default-value 'org-todo-keywords)))))
4565 (setq kwds (reverse kwds)))
4566 (setq kwds (nreverse kwds))
4567 (let (inter kws kw)
4568 (while (setq kws (pop kwds))
4569 (let ((kws (or
4570 (run-hook-with-args-until-success
4571 'org-todo-setup-filter-hook kws)
4572 kws)))
4573 (setq inter (pop kws) sep (member "|" kws)
4574 kws0 (delete "|" (copy-sequence kws))
4575 kwsa nil
4576 kws1 (mapcar
4577 (lambda (x)
4578 ;; 1 2
4579 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4580 (progn
4581 (setq kw (match-string 1 x)
4582 key (and (match-end 2) (match-string 2 x))
4583 log (org-extract-log-state-settings x))
4584 (push (cons kw (and key (string-to-char key))) kwsa)
4585 (and log (push log org-todo-log-states))
4587 (error "Invalid TODO keyword %s" x)))
4588 kws0)
4589 kwsa (if kwsa (append '((:startgroup))
4590 (nreverse kwsa)
4591 '((:endgroup))))
4592 hw (car kws1)
4593 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4594 tail (list inter hw (car dws) (org-last dws))))
4595 (add-to-list 'org-todo-heads hw 'append)
4596 (push kws1 org-todo-sets)
4597 (setq org-done-keywords (append org-done-keywords dws nil))
4598 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4599 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4600 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4601 (setq org-todo-sets (nreverse org-todo-sets)
4602 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4603 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4604 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4605 ;; Process the constants
4606 (when const
4607 (let (e cst)
4608 (while (setq e (pop const))
4609 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4610 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4611 (setq org-table-formula-constants-local cst)))
4613 ;; Process the tags.
4614 (when tags
4615 (let (e tgs)
4616 (while (setq e (pop tags))
4617 (cond
4618 ((equal e "{") (push '(:startgroup) tgs))
4619 ((equal e "}") (push '(:endgroup) tgs))
4620 ((equal e "\\n") (push '(:newline) tgs))
4621 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4622 (push (cons (match-string 1 e)
4623 (string-to-char (match-string 2 e)))
4624 tgs))
4625 (t (push (list e) tgs))))
4626 (org-set-local 'org-tag-alist nil)
4627 (while (setq e (pop tgs))
4628 (or (and (stringp (car e))
4629 (assoc (car e) org-tag-alist))
4630 (push e org-tag-alist)))))
4632 ;; Compute the regular expressions and other local variables.
4633 ;; Using `org-outline-regexp-bol' would complicate them much,
4634 ;; because of the fixed white space at the end of that string.
4635 (if (not org-done-keywords)
4636 (setq org-done-keywords (and org-todo-keywords-1
4637 (list (org-last org-todo-keywords-1)))))
4638 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4639 (length org-scheduled-string)
4640 (length org-clock-string)
4641 (length org-closed-string)))
4642 org-drawer-regexp
4643 (concat "^[ \t]*:\\("
4644 (mapconcat 'regexp-quote org-drawers "\\|")
4645 "\\):[ \t]*$")
4646 org-not-done-keywords
4647 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4648 org-todo-regexp
4649 (concat "\\("
4650 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4651 "\\)")
4652 org-not-done-regexp
4653 (concat "\\("
4654 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4655 "\\)")
4656 org-heading-regexp
4657 "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4658 org-heading-keyword-regexp-format
4659 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4660 org-heading-keyword-maybe-regexp-format
4661 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4662 org-not-done-heading-regexp
4663 (format org-heading-keyword-regexp-format org-not-done-regexp)
4664 org-todo-line-regexp
4665 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4666 org-complex-heading-regexp
4667 (concat "^\\(\\*+\\)"
4668 "\\(?: +" org-todo-regexp "\\)?"
4669 "\\(?: +\\(\\[#.\\]\\)\\)?"
4670 "\\(?: +\\(.*?\\)\\)?"
4671 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4672 "[ \t]*$")
4673 org-complex-heading-regexp-format
4674 (concat "^\\(\\*+\\)"
4675 "\\(?: +" org-todo-regexp "\\)?"
4676 "\\(?: +\\(\\[#.\\]\\)\\)?"
4677 "\\(?: +"
4678 ;; Stats cookies can be sticked to body.
4679 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4680 "\\(%s\\)"
4681 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4682 "\\)"
4683 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4684 "[ \t]*$")
4685 org-todo-line-tags-regexp
4686 (concat "^\\(\\*+\\)"
4687 "\\(?: +" org-todo-regexp "\\)?"
4688 "\\(?: +\\(.*?\\)\\)?"
4689 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4690 "[ \t]*$")
4691 org-deadline-regexp (concat "\\<" org-deadline-string)
4692 org-deadline-time-regexp
4693 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4694 org-deadline-line-regexp
4695 (concat "\\<\\(" org-deadline-string "\\).*")
4696 org-scheduled-regexp
4697 (concat "\\<" org-scheduled-string)
4698 org-scheduled-time-regexp
4699 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4700 org-closed-time-regexp
4701 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4702 org-keyword-time-regexp
4703 (concat "\\<\\(" org-scheduled-string
4704 "\\|" org-deadline-string
4705 "\\|" org-closed-string
4706 "\\|" org-clock-string "\\)"
4707 " *[[<]\\([^]>]+\\)[]>]")
4708 org-keyword-time-not-clock-regexp
4709 (concat "\\<\\(" org-scheduled-string
4710 "\\|" org-deadline-string
4711 "\\|" org-closed-string
4712 "\\)"
4713 " *[[<]\\([^]>]+\\)[]>]")
4714 org-maybe-keyword-time-regexp
4715 (concat "\\(\\<\\(" org-scheduled-string
4716 "\\|" org-deadline-string
4717 "\\|" org-closed-string
4718 "\\|" org-clock-string "\\)\\)?"
4719 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4720 org-planning-or-clock-line-re
4721 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4722 "\\|" org-deadline-string
4723 "\\|" org-closed-string "\\|" org-clock-string
4724 "\\)\\>\\)")
4725 org-all-time-keywords
4726 (mapcar (lambda (w) (substring w 0 -1))
4727 (list org-scheduled-string org-deadline-string
4728 org-clock-string org-closed-string))
4730 (org-compute-latex-and-specials-regexp)
4731 (org-set-font-lock-defaults))))
4733 (defun org-file-contents (file &optional noerror)
4734 "Return the contents of FILE, as a string."
4735 (if (or (not file)
4736 (not (file-readable-p file)))
4737 (if noerror
4738 (progn
4739 (message "Cannot read file \"%s\"" file)
4740 (ding) (sit-for 2)
4742 (error "Cannot read file \"%s\"" file))
4743 (with-temp-buffer
4744 (insert-file-contents file)
4745 (buffer-string))))
4747 (defun org-extract-log-state-settings (x)
4748 "Extract the log state setting from a TODO keyword string.
4749 This will extract info from a string like \"WAIT(w@/!)\"."
4750 (let (kw key log1 log2)
4751 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4752 (setq kw (match-string 1 x)
4753 key (and (match-end 2) (match-string 2 x))
4754 log1 (and (match-end 3) (match-string 3 x))
4755 log2 (and (match-end 4) (match-string 4 x)))
4756 (and (or log1 log2)
4757 (list kw
4758 (and log1 (if (equal log1 "!") 'time 'note))
4759 (and log2 (if (equal log2 "!") 'time 'note)))))))
4761 (defun org-remove-keyword-keys (list)
4762 "Remove a pair of parenthesis at the end of each string in LIST."
4763 (mapcar (lambda (x)
4764 (if (string-match "(.*)$" x)
4765 (substring x 0 (match-beginning 0))
4767 list))
4769 (defun org-assign-fast-keys (alist)
4770 "Assign fast keys to a keyword-key alist.
4771 Respect keys that are already there."
4772 (let (new e (alt ?0))
4773 (while (setq e (pop alist))
4774 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4775 (cdr e)) ;; Key already assigned.
4776 (push e new)
4777 (let ((clist (string-to-list (downcase (car e))))
4778 (used (append new alist)))
4779 (when (= (car clist) ?@)
4780 (pop clist))
4781 (while (and clist (rassoc (car clist) used))
4782 (pop clist))
4783 (unless clist
4784 (while (rassoc alt used)
4785 (incf alt)))
4786 (push (cons (car e) (or (car clist) alt)) new))))
4787 (nreverse new)))
4789 ;;; Some variables used in various places
4791 (defvar org-window-configuration nil
4792 "Used in various places to store a window configuration.")
4793 (defvar org-selected-window nil
4794 "Used in various places to store a window configuration.")
4795 (defvar org-finish-function nil
4796 "Function to be called when `C-c C-c' is used.
4797 This is for getting out of special buffers like remember.")
4800 ;; FIXME: Occasionally check by commenting these, to make sure
4801 ;; no other functions uses these, forgetting to let-bind them.
4802 (defvar entry)
4803 (defvar last-state)
4804 (defvar date)
4806 ;; Defined somewhere in this file, but used before definition.
4807 (defvar org-entities) ;; defined in org-entities.el
4808 (defvar org-struct-menu)
4809 (defvar org-org-menu)
4810 (defvar org-tbl-menu)
4812 ;;;; Define the Org-mode
4814 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4815 (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"))
4818 ;; We use a before-change function to check if a table might need
4819 ;; an update.
4820 (defvar org-table-may-need-update t
4821 "Indicates that a table might need an update.
4822 This variable is set by `org-before-change-function'.
4823 `org-table-align' sets it back to nil.")
4824 (defun org-before-change-function (beg end)
4825 "Every change indicates that a table might need an update."
4826 (setq org-table-may-need-update t))
4827 (defvar org-mode-map)
4828 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4829 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4830 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4831 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4832 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4833 (defvar org-table-buffer-is-an nil)
4835 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
4836 ;; some places -- e.g. see the macro org-with-limited-levels.
4838 ;; In Org buffers, the value of `outline-regexp' is that of
4839 ;; `org-outline-regexp'. The only function still directly relying on
4840 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
4841 ;; job when `orgstruct-mode' is active.
4842 (defvar org-outline-regexp "\\*+ "
4843 "Regexp to match Org headlines.")
4844 (defconst org-outline-regexp-bol "^\\*+ "
4845 "Regexp to match Org headlines.
4846 This is similar to `org-outline-regexp' but additionally makes
4847 sure that we are at the beginning of the line.")
4849 ;;;###autoload
4850 (define-derived-mode org-mode outline-mode "Org"
4851 "Outline-based notes management and organizer, alias
4852 \"Carsten's outline-mode for keeping track of everything.\"
4854 Org-mode develops organizational tasks around a NOTES file which
4855 contains information about projects as plain text. Org-mode is
4856 implemented on top of outline-mode, which is ideal to keep the content
4857 of large files well structured. It supports ToDo items, deadlines and
4858 time stamps, which magically appear in the diary listing of the Emacs
4859 calendar. Tables are easily created with a built-in table editor.
4860 Plain text URL-like links connect to websites, emails (VM), Usenet
4861 messages (Gnus), BBDB entries, and any files related to the project.
4862 For printing and sharing of notes, an Org-mode file (or a part of it)
4863 can be exported as a structured ASCII or HTML file.
4865 The following commands are available:
4867 \\{org-mode-map}"
4869 ;; Get rid of Outline menus, they are not needed
4870 ;; Need to do this here because define-derived-mode sets up
4871 ;; the keymap so late. Still, it is a waste to call this each time
4872 ;; we switch another buffer into org-mode.
4873 (if (featurep 'xemacs)
4874 (when (boundp 'outline-mode-menu-heading)
4875 ;; Assume this is Greg's port, it uses easymenu
4876 (easy-menu-remove outline-mode-menu-heading)
4877 (easy-menu-remove outline-mode-menu-show)
4878 (easy-menu-remove outline-mode-menu-hide))
4879 (define-key org-mode-map [menu-bar headings] 'undefined)
4880 (define-key org-mode-map [menu-bar hide] 'undefined)
4881 (define-key org-mode-map [menu-bar show] 'undefined))
4883 (org-load-modules-maybe)
4884 (easy-menu-add org-org-menu)
4885 (easy-menu-add org-tbl-menu)
4886 (org-install-agenda-files-menu)
4887 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4888 (add-to-invisibility-spec '(org-cwidth))
4889 (add-to-invisibility-spec '(org-hide-block . t))
4890 (when (featurep 'xemacs)
4891 (org-set-local 'line-move-ignore-invisible t))
4892 (org-set-local 'outline-regexp org-outline-regexp)
4893 (org-set-local 'outline-level 'org-outline-level)
4894 (setq bidi-paragraph-direction 'left-to-right)
4895 (when (and org-ellipsis
4896 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4897 (fboundp 'make-glyph-code))
4898 (unless org-display-table
4899 (setq org-display-table (make-display-table)))
4900 (set-display-table-slot
4901 org-display-table 4
4902 (vconcat (mapcar
4903 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4904 org-ellipsis)))
4905 (if (stringp org-ellipsis) org-ellipsis "..."))))
4906 (setq buffer-display-table org-display-table))
4907 (org-set-regexps-and-options)
4908 (when (and org-tag-faces (not org-tags-special-faces-re))
4909 ;; tag faces set outside customize.... force initialization.
4910 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4911 ;; Calc embedded
4912 (org-set-local 'calc-embedded-open-mode "# ")
4913 (modify-syntax-entry ?@ "w")
4914 (if org-startup-truncated (setq truncate-lines t))
4915 (org-set-local 'font-lock-unfontify-region-function
4916 'org-unfontify-region)
4917 ;; Activate before-change-function
4918 (org-set-local 'org-table-may-need-update t)
4919 (org-add-hook 'before-change-functions 'org-before-change-function nil
4920 'local)
4921 ;; Check for running clock before killing a buffer
4922 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4923 ;; Paragraphs and auto-filling
4924 (org-set-autofill-regexps)
4925 (setq indent-line-function 'org-indent-line-function)
4926 (org-update-radio-target-regexp)
4927 ;; Beginning/end of defun
4928 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
4929 (org-set-local 'end-of-defun-function 'org-end-of-defun)
4930 ;; Next error for sparse trees
4931 (org-set-local 'next-error-function 'org-occur-next-match)
4932 ;; Make sure dependence stuff works reliably, even for users who set it
4933 ;; too late :-(
4934 (if org-enforce-todo-dependencies
4935 (add-hook 'org-blocker-hook
4936 'org-block-todo-from-children-or-siblings-or-parent)
4937 (remove-hook 'org-blocker-hook
4938 'org-block-todo-from-children-or-siblings-or-parent))
4939 (if org-enforce-todo-checkbox-dependencies
4940 (add-hook 'org-blocker-hook
4941 'org-block-todo-from-checkboxes)
4942 (remove-hook 'org-blocker-hook
4943 'org-block-todo-from-checkboxes))
4945 ;; Comment characters
4946 (org-set-local 'comment-start "#")
4947 (org-set-local 'comment-padding " ")
4949 ;; Align options lines
4950 (org-set-local
4951 'align-mode-rules-list
4952 '((org-in-buffer-settings
4953 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4954 (modes . '(org-mode)))))
4956 ;; Imenu
4957 (org-set-local 'imenu-create-index-function
4958 'org-imenu-get-tree)
4960 ;; Make isearch reveal context
4961 (if (or (featurep 'xemacs)
4962 (not (boundp 'outline-isearch-open-invisible-function)))
4963 ;; Emacs 21 and XEmacs make use of the hook
4964 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4965 ;; Emacs 22 deals with this through a special variable
4966 (org-set-local 'outline-isearch-open-invisible-function
4967 (lambda (&rest ignore) (org-show-context 'isearch))))
4969 ;; Turn on org-beamer-mode?
4970 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4972 ;; Setup the pcomplete hooks
4973 (set (make-local-variable 'pcomplete-command-completion-function)
4974 'org-pcomplete-initial)
4975 (set (make-local-variable 'pcomplete-command-name-function)
4976 'org-command-at-point)
4977 (set (make-local-variable 'pcomplete-default-completion-function)
4978 'ignore)
4979 (set (make-local-variable 'pcomplete-parse-arguments-function)
4980 'org-parse-arguments)
4981 (set (make-local-variable 'pcomplete-termination-string) "")
4982 (set (make-local-variable 'face-remapping-alist)
4983 '((default org-default)))
4985 ;; If empty file that did not turn on org-mode automatically, make it to.
4986 (if (and org-insert-mode-line-in-empty-file
4987 (org-called-interactively-p 'any)
4988 (= (point-min) (point-max)))
4989 (insert "# -*- mode: org -*-\n\n"))
4990 (unless org-inhibit-startup
4991 (when org-startup-align-all-tables
4992 (let ((bmp (buffer-modified-p)))
4993 (org-table-map-tables 'org-table-align 'quietly)
4994 (set-buffer-modified-p bmp)))
4995 (when org-startup-with-inline-images
4996 (org-display-inline-images))
4997 (when org-startup-indented
4998 (require 'org-indent)
4999 (org-indent-mode 1))
5000 (unless org-inhibit-startup-visibility-stuff
5001 (org-set-startup-visibility))))
5003 (when (fboundp 'abbrev-table-put)
5004 (abbrev-table-put org-mode-abbrev-table
5005 :parents (list text-mode-abbrev-table)))
5007 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5009 (defun org-current-time ()
5010 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5011 (if (> (car org-time-stamp-rounding-minutes) 1)
5012 (let ((r (car org-time-stamp-rounding-minutes))
5013 (time (decode-time)))
5014 (apply 'encode-time
5015 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5016 (nthcdr 2 time))))
5017 (current-time)))
5019 (defun org-today ()
5020 "Return today date, considering `org-extend-today-until'."
5021 (time-to-days
5022 (time-subtract (current-time)
5023 (list 0 (* 3600 org-extend-today-until) 0))))
5025 ;;;; Font-Lock stuff, including the activators
5027 (defvar org-mouse-map (make-sparse-keymap))
5028 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5029 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5030 (when org-mouse-1-follows-link
5031 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5032 (when org-tab-follows-link
5033 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5034 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5036 (require 'font-lock)
5038 (defconst org-non-link-chars "]\t\n\r<>")
5039 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5040 "shell" "elisp" "doi" "message"))
5041 (defvar org-link-types-re nil
5042 "Matches a link that has a url-like prefix like \"http:\"")
5043 (defvar org-link-re-with-space nil
5044 "Matches a link with spaces, optional angular brackets around it.")
5045 (defvar org-link-re-with-space2 nil
5046 "Matches a link with spaces, optional angular brackets around it.")
5047 (defvar org-link-re-with-space3 nil
5048 "Matches a link with spaces, only for internal part in bracket links.")
5049 (defvar org-angle-link-re nil
5050 "Matches link with angular brackets, spaces are allowed.")
5051 (defvar org-plain-link-re nil
5052 "Matches plain link, without spaces.")
5053 (defvar org-bracket-link-regexp nil
5054 "Matches a link in double brackets.")
5055 (defvar org-bracket-link-analytic-regexp nil
5056 "Regular expression used to analyze links.
5057 Here is what the match groups contain after a match:
5058 1: http:
5059 2: http
5060 3: path
5061 4: [desc]
5062 5: desc")
5063 (defvar org-bracket-link-analytic-regexp++ nil
5064 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5065 (defvar org-any-link-re nil
5066 "Regular expression matching any link.")
5068 (defcustom org-match-sexp-depth 3
5069 "Number of stacked braces for sub/superscript matching.
5070 This has to be set before loading org.el to be effective."
5071 :group 'org-export-translation ; ??????????????????????????/
5072 :type 'integer)
5074 (defun org-create-multibrace-regexp (left right n)
5075 "Create a regular expression which will match a balanced sexp.
5076 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5077 as single character strings.
5078 The regexp returned will match the entire expression including the
5079 delimiters. It will also define a single group which contains the
5080 match except for the outermost delimiters. The maximum depth of
5081 stacked delimiters is N. Escaping delimiters is not possible."
5082 (let* ((nothing (concat "[^" left right "]*?"))
5083 (or "\\|")
5084 (re nothing)
5085 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5086 (while (> n 1)
5087 (setq n (1- n)
5088 re (concat re or next)
5089 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5090 (concat left "\\(" re "\\)" right)))
5092 (defvar org-match-substring-regexp
5093 (concat
5094 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5095 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5096 "\\|"
5097 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5098 "\\|"
5099 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5100 "The regular expression matching a sub- or superscript.")
5102 (defvar org-match-substring-with-braces-regexp
5103 (concat
5104 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5105 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5106 "\\)")
5107 "The regular expression matching a sub- or superscript, forcing braces.")
5109 (defun org-make-link-regexps ()
5110 "Update the link regular expressions.
5111 This should be called after the variable `org-link-types' has changed."
5112 (setq org-link-types-re
5113 (concat
5114 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5115 org-link-re-with-space
5116 (concat
5117 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5118 "\\([^" org-non-link-chars " ]"
5119 "[^" org-non-link-chars "]*"
5120 "[^" org-non-link-chars " ]\\)>?")
5121 org-link-re-with-space2
5122 (concat
5123 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5124 "\\([^" org-non-link-chars " ]"
5125 "[^\t\n\r]*"
5126 "[^" org-non-link-chars " ]\\)>?")
5127 org-link-re-with-space3
5128 (concat
5129 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5130 "\\([^" org-non-link-chars " ]"
5131 "[^\t\n\r]*\\)")
5132 org-angle-link-re
5133 (concat
5134 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5135 "\\([^" org-non-link-chars " ]"
5136 "[^" org-non-link-chars "]*"
5137 "\\)>")
5138 org-plain-link-re
5139 (concat
5140 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5141 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5142 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5143 org-bracket-link-regexp
5144 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5145 org-bracket-link-analytic-regexp
5146 (concat
5147 "\\[\\["
5148 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5149 "\\([^]]+\\)"
5150 "\\]"
5151 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5152 "\\]")
5153 org-bracket-link-analytic-regexp++
5154 (concat
5155 "\\[\\["
5156 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5157 "\\([^]]+\\)"
5158 "\\]"
5159 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5160 "\\]")
5161 org-any-link-re
5162 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5163 org-angle-link-re "\\)\\|\\("
5164 org-plain-link-re "\\)")))
5166 (org-make-link-regexps)
5168 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5169 "Regular expression for fast time stamp matching.")
5170 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?\\)[]>]"
5171 "Regular expression for fast time stamp matching.")
5172 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5173 "Regular expression matching time strings for analysis.
5174 This one does not require the space after the date, so it can be used
5175 on a string that terminates immediately after the date.")
5176 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5177 "Regular expression matching time strings for analysis.")
5178 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5179 "Regular expression matching time stamps, with groups.")
5180 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5181 "Regular expression matching time stamps (also [..]), with groups.")
5182 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5183 "Regular expression matching a time stamp range.")
5184 (defconst org-tr-regexp-both
5185 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5186 "Regular expression matching a time stamp range.")
5187 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5188 org-ts-regexp "\\)?")
5189 "Regular expression matching a time stamp or time stamp range.")
5190 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5191 org-ts-regexp-both "\\)?")
5192 "Regular expression matching a time stamp or time stamp range.
5193 The time stamps may be either active or inactive.")
5195 (defvar org-emph-face nil)
5197 (defun org-do-emphasis-faces (limit)
5198 "Run through the buffer and add overlays to emphasised strings."
5199 (let (rtn a)
5200 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5201 (if (not (= (char-after (match-beginning 3))
5202 (char-after (match-beginning 4))))
5203 (progn
5204 (setq rtn t)
5205 (setq a (assoc (match-string 3) org-emphasis-alist))
5206 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5207 'face
5208 (nth 1 a))
5209 (and (nth 4 a)
5210 (org-remove-flyspell-overlays-in
5211 (match-beginning 0) (match-end 0)))
5212 (add-text-properties (match-beginning 2) (match-end 2)
5213 '(font-lock-multiline t org-emphasis t))
5214 (when org-hide-emphasis-markers
5215 (add-text-properties (match-end 4) (match-beginning 5)
5216 '(invisible org-link))
5217 (add-text-properties (match-beginning 3) (match-end 3)
5218 '(invisible org-link)))))
5219 (backward-char 1))
5220 rtn))
5222 (defun org-emphasize (&optional char)
5223 "Insert or change an emphasis, i.e. a font like bold or italic.
5224 If there is an active region, change that region to a new emphasis.
5225 If there is no region, just insert the marker characters and position
5226 the cursor between them.
5227 CHAR should be either the marker character, or the first character of the
5228 HTML tag associated with that emphasis. If CHAR is a space, the means
5229 to remove the emphasis of the selected region.
5230 If char is not given (for example in an interactive call) it
5231 will be prompted for."
5232 (interactive)
5233 (let ((eal org-emphasis-alist) e det
5234 (erc org-emphasis-regexp-components)
5235 (prompt "")
5236 (string "") beg end move tag c s)
5237 (if (org-region-active-p)
5238 (setq beg (region-beginning) end (region-end)
5239 string (buffer-substring beg end))
5240 (setq move t))
5242 (while (setq e (pop eal))
5243 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5244 c (aref tag 0))
5245 (push (cons c (string-to-char (car e))) det)
5246 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5247 (substring tag 1)))))
5248 (setq det (nreverse det))
5249 (unless char
5250 (message "%s" (concat "Emphasis marker or tag:" prompt))
5251 (setq char (read-char-exclusive)))
5252 (setq char (or (cdr (assoc char det)) char))
5253 (if (equal char ?\ )
5254 (setq s "" move nil)
5255 (unless (assoc (char-to-string char) org-emphasis-alist)
5256 (error "No such emphasis marker: \"%c\"" char))
5257 (setq s (char-to-string char)))
5258 (while (and (> (length string) 1)
5259 (equal (substring string 0 1) (substring string -1))
5260 (assoc (substring string 0 1) org-emphasis-alist))
5261 (setq string (substring string 1 -1)))
5262 (setq string (concat s string s))
5263 (if beg (delete-region beg end))
5264 (unless (or (bolp)
5265 (string-match (concat "[" (nth 0 erc) "\n]")
5266 (char-to-string (char-before (point)))))
5267 (insert " "))
5268 (unless (or (eobp)
5269 (string-match (concat "[" (nth 1 erc) "\n]")
5270 (char-to-string (char-after (point)))))
5271 (insert " ") (backward-char 1))
5272 (insert string)
5273 (and move (backward-char 1))))
5275 (defconst org-nonsticky-props
5276 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5278 (defsubst org-rear-nonsticky-at (pos)
5279 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5281 (defun org-activate-plain-links (limit)
5282 "Run through the buffer and add overlays to links."
5283 (catch 'exit
5284 (let (f)
5285 (if (re-search-forward org-plain-link-re limit t)
5286 (progn
5287 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5288 (setq f (get-text-property (match-beginning 0) 'face))
5289 (if (or (eq f 'org-tag)
5290 (and (listp f) (memq 'org-tag f)))
5292 (add-text-properties (match-beginning 0) (match-end 0)
5293 (list 'mouse-face 'highlight
5294 'face 'org-link
5295 'keymap org-mouse-map))
5296 (org-rear-nonsticky-at (match-end 0)))
5297 t)))))
5299 (defun org-activate-code (limit)
5300 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5301 (progn
5302 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5303 (remove-text-properties (match-beginning 0) (match-end 0)
5304 '(display t invisible t intangible t))
5305 t)))
5307 (defcustom org-src-fontify-natively nil
5308 "When non-nil, fontify code in code blocks."
5309 :type 'boolean
5310 :group 'org-appearance
5311 :group 'org-babel)
5313 (defun org-fontify-meta-lines-and-blocks (limit)
5314 (condition-case nil
5315 (org-fontify-meta-lines-and-blocks-1 limit)
5316 (error (message "org-mode fontification error"))))
5318 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5319 "Fontify #+ lines and blocks, in the correct ways."
5320 (let ((case-fold-search t))
5321 (if (re-search-forward
5322 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5323 limit t)
5324 (let ((beg (match-beginning 0))
5325 (block-start (match-end 0))
5326 (block-end nil)
5327 (lang (match-string 7))
5328 (beg1 (line-beginning-position 2))
5329 (dc1 (downcase (match-string 2)))
5330 (dc3 (downcase (match-string 3)))
5331 end end1 quoting block-type ovl)
5332 (cond
5333 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5334 ;; a single line of backend-specific content
5335 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5336 (remove-text-properties (match-beginning 0) (match-end 0)
5337 '(display t invisible t intangible t))
5338 (add-text-properties (match-beginning 1) (match-end 3)
5339 '(font-lock-fontified t face org-meta-line))
5340 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5341 '(font-lock-fontified t face org-block))
5342 ; for backend-specific code
5344 ((and (match-end 4) (equal dc3 "begin"))
5345 ;; Truly a block
5346 (setq block-type (downcase (match-string 5))
5347 quoting (member block-type org-protecting-blocks))
5348 (when (re-search-forward
5349 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5350 nil t) ;; on purpose, we look further than LIMIT
5351 (setq end (match-end 0) end1 (1- (match-beginning 0)))
5352 (setq block-end (match-beginning 0))
5353 (when quoting
5354 (remove-text-properties beg end
5355 '(display t invisible t intangible t)))
5356 (add-text-properties
5357 beg end
5358 '(font-lock-fontified t font-lock-multiline t))
5359 (add-text-properties beg beg1 '(face org-meta-line))
5360 (add-text-properties end1 (min (point-max) (1+ end))
5361 '(face org-meta-line)) ; for end_src
5362 (cond
5363 ((and lang (not (string= lang "")) org-src-fontify-natively)
5364 (org-src-font-lock-fontify-block lang block-start block-end)
5365 ;; remove old background overlays
5366 (mapc (lambda (ov)
5367 (if (eq (overlay-get ov 'face) 'org-block-background)
5368 (delete-overlay ov)))
5369 (overlays-at (/ (+ beg1 block-end) 2)))
5370 ;; add a background overlay
5371 (setq ovl (make-overlay beg1 block-end))
5372 (overlay-put ovl 'face 'org-block-background)
5373 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5374 (quoting
5375 (add-text-properties beg1 (min (point-max) (1+ end1))
5376 '(face org-block))) ; end of source block
5377 ((not org-fontify-quote-and-verse-blocks))
5378 ((string= block-type "quote")
5379 (add-text-properties beg1 (1+ end1) '(face org-quote)))
5380 ((string= block-type "verse")
5381 (add-text-properties beg1 (1+ end1) '(face org-verse))))
5382 (add-text-properties beg beg1 '(face org-block-begin-line))
5383 (add-text-properties (1+ end) (1+ end1) '(face org-block-end-line))
5385 ((member dc1 '("title:" "author:" "email:" "date:"))
5386 (add-text-properties
5387 beg (match-end 3)
5388 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5389 '(font-lock-fontified t invisible t)
5390 '(font-lock-fontified t face org-document-info-keyword)))
5391 (add-text-properties
5392 (match-beginning 6) (match-end 6)
5393 (if (string-equal dc1 "title:")
5394 '(font-lock-fontified t face org-document-title)
5395 '(font-lock-fontified t face org-document-info))))
5396 ((not (member (char-after beg) '(?\ ?\t)))
5397 ;; just any other in-buffer setting, but not indented
5398 (add-text-properties
5399 beg (1+ (match-end 0))
5400 '(font-lock-fontified t face org-meta-line))
5402 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5403 "orgtbl:" "tblfm:" "tblname:" "result:"
5404 "results:" "source:" "srcname:" "call:"
5405 "data:" "header:" "headers:"))
5406 (and (match-end 4) (equal dc3 "attr")))
5407 (add-text-properties
5408 beg (match-end 0)
5409 '(font-lock-fontified t face org-meta-line))
5411 ((member dc3 '(" " ""))
5412 (add-text-properties
5413 beg (match-end 0)
5414 '(font-lock-fontified t face font-lock-comment-face)))
5415 (t nil))))))
5417 (defun org-activate-angle-links (limit)
5418 "Run through the buffer and add overlays to links."
5419 (if (re-search-forward org-angle-link-re limit t)
5420 (progn
5421 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5422 (add-text-properties (match-beginning 0) (match-end 0)
5423 (list 'mouse-face 'highlight
5424 'keymap org-mouse-map))
5425 (org-rear-nonsticky-at (match-end 0))
5426 t)))
5428 (defun org-activate-footnote-links (limit)
5429 "Run through the buffer and add overlays to footnotes."
5430 (let ((fn (org-footnote-next-reference-or-definition limit)))
5431 (when fn
5432 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5433 (org-remove-flyspell-overlays-in beg end)
5434 (add-text-properties beg end
5435 (list 'mouse-face 'highlight
5436 'keymap org-mouse-map
5437 'help-echo
5438 (if (= (point-at-bol) beg)
5439 "Footnote definition"
5440 "Footnote reference")
5441 'font-lock-fontified t
5442 'font-lock-multiline t
5443 'face 'org-footnote))))))
5445 (defun org-activate-bracket-links (limit)
5446 "Run through the buffer and add overlays to bracketed links."
5447 (if (re-search-forward org-bracket-link-regexp limit t)
5448 (let* ((help (concat "LINK: "
5449 (org-match-string-no-properties 1)))
5450 ;; FIXME: above we should remove the escapes.
5451 ;; but that requires another match, protecting match data,
5452 ;; a lot of overhead for font-lock.
5453 (ip (org-maybe-intangible
5454 (list 'invisible 'org-link
5455 'keymap org-mouse-map 'mouse-face 'highlight
5456 'font-lock-multiline t 'help-echo help)))
5457 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5458 'font-lock-multiline t 'help-echo help)))
5459 ;; We need to remove the invisible property here. Table narrowing
5460 ;; may have made some of this invisible.
5461 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5462 (remove-text-properties (match-beginning 0) (match-end 0)
5463 '(invisible nil))
5464 (if (match-end 3)
5465 (progn
5466 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5467 (org-rear-nonsticky-at (match-beginning 3))
5468 (add-text-properties (match-beginning 3) (match-end 3) vp)
5469 (org-rear-nonsticky-at (match-end 3))
5470 (add-text-properties (match-end 3) (match-end 0) ip)
5471 (org-rear-nonsticky-at (match-end 0)))
5472 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5473 (org-rear-nonsticky-at (match-beginning 1))
5474 (add-text-properties (match-beginning 1) (match-end 1) vp)
5475 (org-rear-nonsticky-at (match-end 1))
5476 (add-text-properties (match-end 1) (match-end 0) ip)
5477 (org-rear-nonsticky-at (match-end 0)))
5478 t)))
5480 (defun org-activate-dates (limit)
5481 "Run through the buffer and add overlays to dates."
5482 (if (re-search-forward org-tsr-regexp-both limit t)
5483 (progn
5484 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5485 (add-text-properties (match-beginning 0) (match-end 0)
5486 (list 'mouse-face 'highlight
5487 'keymap org-mouse-map))
5488 (org-rear-nonsticky-at (match-end 0))
5489 (when org-display-custom-times
5490 (if (match-end 3)
5491 (org-display-custom-time (match-beginning 3) (match-end 3)))
5492 (org-display-custom-time (match-beginning 1) (match-end 1)))
5493 t)))
5495 (defvar org-target-link-regexp nil
5496 "Regular expression matching radio targets in plain text.")
5497 (make-variable-buffer-local 'org-target-link-regexp)
5498 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5499 "Regular expression matching a link target.")
5500 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5501 "Regular expression matching a radio target.")
5502 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5503 "Regular expression matching any target.")
5505 (defun org-activate-target-links (limit)
5506 "Run through the buffer and add overlays to target matches."
5507 (when org-target-link-regexp
5508 (let ((case-fold-search t))
5509 (if (re-search-forward org-target-link-regexp limit t)
5510 (progn
5511 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5512 (add-text-properties (match-beginning 0) (match-end 0)
5513 (list 'mouse-face 'highlight
5514 'keymap org-mouse-map
5515 'help-echo "Radio target link"
5516 'org-linked-text t))
5517 (org-rear-nonsticky-at (match-end 0))
5518 t)))))
5520 (defun org-update-radio-target-regexp ()
5521 "Find all radio targets in this file and update the regular expression."
5522 (interactive)
5523 (when (memq 'radio org-activate-links)
5524 (setq org-target-link-regexp
5525 (org-make-target-link-regexp (org-all-targets 'radio)))
5526 (org-restart-font-lock)))
5528 (defun org-hide-wide-columns (limit)
5529 (let (s e)
5530 (setq s (text-property-any (point) (or limit (point-max))
5531 'org-cwidth t))
5532 (when s
5533 (setq e (next-single-property-change s 'org-cwidth))
5534 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5535 (goto-char e)
5536 t)))
5538 (defvar org-latex-and-specials-regexp nil
5539 "Regular expression for highlighting export special stuff.")
5540 (defvar org-match-substring-regexp)
5541 (defvar org-match-substring-with-braces-regexp)
5543 ;; This should be with the exporter code, but we also use if for font-locking
5544 (defconst org-export-html-special-string-regexps
5545 '(("\\\\-" . "&shy;")
5546 ("---\\([^-]\\)" . "&mdash;\\1")
5547 ("--\\([^-]\\)" . "&ndash;\\1")
5548 ("\\.\\.\\." . "&hellip;"))
5549 "Regular expressions for special string conversion.")
5552 (defun org-compute-latex-and-specials-regexp ()
5553 "Compute regular expression for stuff treated specially by exporters."
5554 (if (not org-highlight-latex-fragments-and-specials)
5555 (org-set-local 'org-latex-and-specials-regexp nil)
5556 (require 'org-exp)
5557 (let*
5558 ((matchers (plist-get org-format-latex-options :matchers))
5559 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5560 org-latex-regexps)))
5561 (org-export-allow-BIND nil)
5562 (options (org-combine-plists (org-default-export-plist)
5563 (org-infile-export-plist)))
5564 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5565 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5566 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5567 (org-export-html-expand (plist-get options :expand-quoted-html))
5568 (org-export-with-special-strings (plist-get options :special-strings))
5569 (re-sub
5570 (cond
5571 ((equal org-export-with-sub-superscripts '{})
5572 (list org-match-substring-with-braces-regexp))
5573 (org-export-with-sub-superscripts
5574 (list org-match-substring-regexp))
5575 (t nil)))
5576 (re-latex
5577 (if org-export-with-LaTeX-fragments
5578 (mapcar (lambda (x) (nth 1 x)) latexs)))
5579 (re-macros
5580 (if org-export-with-TeX-macros
5581 (list (concat "\\\\"
5582 (regexp-opt
5583 (append
5585 (delq nil
5586 (mapcar 'car-safe
5587 (append org-entities-user
5588 org-entities)))
5589 (if (boundp 'org-latex-entities)
5590 (mapcar (lambda (x)
5591 (or (car-safe x) x))
5592 org-latex-entities)
5593 nil))
5594 'words))) ; FIXME
5596 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5597 (re-special (if org-export-with-special-strings
5598 (mapcar (lambda (x) (car x))
5599 org-export-html-special-string-regexps)))
5600 (re-rest
5601 (delq nil
5602 (list
5603 (if org-export-html-expand "@<[^>\n]+>")
5604 ))))
5605 (org-set-local
5606 'org-latex-and-specials-regexp
5607 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5608 re-rest) "\\|")))))
5610 (defun org-do-latex-and-special-faces (limit)
5611 "Run through the buffer and add overlays to links."
5612 (when org-latex-and-specials-regexp
5613 (let (rtn d)
5614 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5615 limit t))
5616 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5617 'face))
5618 '(org-code org-verbatim underline)))
5619 (progn
5620 (setq rtn t
5621 d (cond ((member (char-after (1+ (match-beginning 0)))
5622 '(?_ ?^)) 1)
5623 (t 0)))
5624 (font-lock-prepend-text-property
5625 (+ d (match-beginning 0)) (match-end 0)
5626 'face 'org-latex-and-export-specials)
5627 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5628 '(font-lock-multiline t)))))
5629 rtn)))
5631 (defun org-restart-font-lock ()
5632 "Restart `font-lock-mode', to force refontification."
5633 (when (and (boundp 'font-lock-mode) font-lock-mode)
5634 (font-lock-mode -1)
5635 (font-lock-mode 1)))
5637 (defun org-all-targets (&optional radio)
5638 "Return a list of all targets in this file.
5639 With optional argument RADIO, only find radio targets."
5640 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5641 rtn)
5642 (save-excursion
5643 (goto-char (point-min))
5644 (while (re-search-forward re nil t)
5645 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5646 rtn)))
5648 (defun org-make-target-link-regexp (targets)
5649 "Make regular expression matching all strings in TARGETS.
5650 The regular expression finds the targets also if there is a line break
5651 between words."
5652 (and targets
5653 (concat
5654 "\\<\\("
5655 (mapconcat
5656 (lambda (x)
5657 (setq x (regexp-quote x))
5658 (while (string-match " +" x)
5659 (setq x (replace-match "\\s-+" t t x)))
5661 targets
5662 "\\|")
5663 "\\)\\>")))
5665 (defun org-activate-tags (limit)
5666 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5667 (progn
5668 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5669 (add-text-properties (match-beginning 1) (match-end 1)
5670 (list 'mouse-face 'highlight
5671 'keymap org-mouse-map))
5672 (org-rear-nonsticky-at (match-end 1))
5673 t)))
5675 (defun org-outline-level ()
5676 "Compute the outline level of the heading at point.
5677 This function assumes that the cursor is at the beginning of a line matched
5678 by `outline-regexp'. Otherwise it returns garbage.
5679 If this is called at a normal headline, the level is the number of stars.
5680 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5681 (save-excursion
5682 (looking-at org-outline-regexp)
5683 (1- (- (match-end 0) (match-beginning 0)))))
5685 (defvar org-font-lock-keywords nil)
5687 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5688 "Regular expression matching a property line.")
5690 (defvar org-font-lock-hook nil
5691 "Functions to be called for special font lock stuff.")
5693 (defvar org-font-lock-set-keywords-hook nil
5694 "Functions that can manipulate `org-font-lock-extra-keywords'.
5695 This is calles after `org-font-lock-extra-keywords' is defined, but before
5696 it is installed to be used by font lock. This can be useful if something
5697 needs to be inserted at a specific position in the font-lock sequence.")
5699 (defun org-font-lock-hook (limit)
5700 (run-hook-with-args 'org-font-lock-hook limit))
5702 (defun org-set-font-lock-defaults ()
5703 (let* ((em org-fontify-emphasized-text)
5704 (lk org-activate-links)
5705 (org-font-lock-extra-keywords
5706 (list
5707 ;; Call the hook
5708 '(org-font-lock-hook)
5709 ;; Headlines
5710 `(,(if org-fontify-whole-heading-line
5711 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5712 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5713 (1 (org-get-level-face 1))
5714 (2 (org-get-level-face 2))
5715 (3 (org-get-level-face 3)))
5716 ;; Table lines
5717 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5718 (1 'org-table t))
5719 ;; Table internals
5720 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5721 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5722 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5723 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5724 ;; Drawers
5725 (list org-drawer-regexp '(0 'org-special-keyword t))
5726 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5727 ;; Properties
5728 (list org-property-re
5729 '(1 'org-special-keyword t)
5730 '(3 'org-property-value t))
5731 ;; Links
5732 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5733 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5734 (if (memq 'plain lk) '(org-activate-plain-links))
5735 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5736 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5737 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5738 (if (memq 'footnote lk) '(org-activate-footnote-links))
5739 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5740 '(org-hide-wide-columns (0 nil append))
5741 ;; TODO keyword
5742 (list (format org-heading-keyword-regexp-format
5743 org-todo-regexp)
5744 '(2 (org-get-todo-face 2) t))
5745 ;; DONE
5746 (if org-fontify-done-headline
5747 (list (format org-heading-keyword-regexp-format
5748 (concat
5749 "\\("
5750 (mapconcat 'regexp-quote org-done-keywords "\\|")
5751 "\\)"))
5752 '(2 'org-headline-done t))
5753 nil)
5754 ;; Priorities
5755 '(org-font-lock-add-priority-faces)
5756 ;; Tags
5757 '(org-font-lock-add-tag-faces)
5758 ;; Special keywords
5759 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5760 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5761 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5762 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5763 ;; Emphasis
5764 (if em
5765 (if (featurep 'xemacs)
5766 '(org-do-emphasis-faces (0 nil append))
5767 '(org-do-emphasis-faces)))
5768 ;; Checkboxes
5769 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5770 1 'org-checkbox prepend)
5771 (if (cdr (assq 'checkbox org-list-automatic-rules))
5772 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5773 (0 (org-get-checkbox-statistics-face) t)))
5774 ;; Description list items
5775 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5776 1 'bold prepend)
5777 ;; ARCHIVEd headings
5778 (list (concat
5779 org-outline-regexp-bol
5780 "\\(.*:" org-archive-tag ":.*\\)")
5781 '(1 'org-archived prepend))
5782 ;; Specials
5783 '(org-do-latex-and-special-faces)
5784 '(org-fontify-entities)
5785 '(org-raise-scripts)
5786 ;; Code
5787 '(org-activate-code (1 'org-code t))
5788 ;; COMMENT
5789 (list (format org-heading-keyword-regexp-format
5790 (concat "\\("
5791 org-comment-string "\\|" org-quote-string
5792 "\\)"))
5793 '(1 'org-special-keyword t))
5794 '("^#.*" (0 'font-lock-comment-face t))
5795 ;; Blocks and meta lines
5796 '(org-fontify-meta-lines-and-blocks)
5798 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5799 (run-hooks 'org-font-lock-set-keywords-hook)
5800 ;; Now set the full font-lock-keywords
5801 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5802 (org-set-local 'font-lock-defaults
5803 '(org-font-lock-keywords t nil nil backward-paragraph))
5804 (kill-local-variable 'font-lock-keywords) nil))
5806 (defun org-toggle-pretty-entities ()
5807 "Toggle the composition display of entities as UTF8 characters."
5808 (interactive)
5809 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5810 (org-restart-font-lock)
5811 (if org-pretty-entities
5812 (message "Entities are displayed as UTF8 characers")
5813 (save-restriction
5814 (widen)
5815 (org-decompose-region (point-min) (point-max))
5816 (message "Entities are displayed plain"))))
5818 (defun org-fontify-entities (limit)
5819 "Find an entity to fontify."
5820 (let (ee)
5821 (when org-pretty-entities
5822 (catch 'match
5823 (while (re-search-forward
5824 "\\\\\\(frac[13][24]\\|[a-zA-Z]+\\)\\($\\|[^[:alpha:]\n]\\)"
5825 limit t)
5826 (if (and (not (org-in-indented-comment-line))
5827 (setq ee (org-entity-get (match-string 1)))
5828 (= (length (nth 6 ee)) 1))
5829 (progn
5830 (add-text-properties
5831 (match-beginning 0) (match-end 1)
5832 (list 'font-lock-fontified t))
5833 (compose-region (match-beginning 0) (match-end 1)
5834 (nth 6 ee) nil)
5835 (backward-char 1)
5836 (throw 'match t))))
5837 nil))))
5839 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5840 "Fontify string S like in Org-mode."
5841 (with-temp-buffer
5842 (insert s)
5843 (let ((org-odd-levels-only odd-levels))
5844 (org-mode)
5845 (font-lock-fontify-buffer)
5846 (buffer-string))))
5848 (defvar org-m nil)
5849 (defvar org-l nil)
5850 (defvar org-f nil)
5851 (defun org-get-level-face (n)
5852 "Get the right face for match N in font-lock matching of headlines."
5853 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5854 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5855 (if org-cycle-level-faces
5856 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5857 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5858 (cond
5859 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5860 ((eq n 2) org-f)
5861 (t (if org-level-color-stars-only nil org-f))))
5864 (defun org-get-todo-face (kwd)
5865 "Get the right face for a TODO keyword KWD.
5866 If KWD is a number, get the corresponding match group."
5867 (if (numberp kwd) (setq kwd (match-string kwd)))
5868 (or (org-face-from-face-or-color
5869 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5870 (and (member kwd org-done-keywords) 'org-done)
5871 'org-todo))
5873 (defun org-face-from-face-or-color (context inherit face-or-color)
5874 "Create a face list that inherits INHERIT, but sets the foreground color.
5875 When FACE-OR-COLOR is not a string, just return it."
5876 (if (stringp face-or-color)
5877 (list :inherit inherit
5878 (cdr (assoc context org-faces-easy-properties))
5879 face-or-color)
5880 face-or-color))
5882 (defun org-font-lock-add-tag-faces (limit)
5883 "Add the special tag faces."
5884 (when (and org-tag-faces org-tags-special-faces-re)
5885 (while (re-search-forward org-tags-special-faces-re limit t)
5886 (add-text-properties (match-beginning 1) (match-end 1)
5887 (list 'face (org-get-tag-face 1)
5888 'font-lock-fontified t))
5889 (backward-char 1))))
5891 (defun org-font-lock-add-priority-faces (limit)
5892 "Add the special priority faces."
5893 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5894 (add-text-properties
5895 (match-beginning 0) (match-end 0)
5896 (list 'face (or (org-face-from-face-or-color
5897 'priority 'org-special-keyword
5898 (cdr (assoc (char-after (match-beginning 1))
5899 org-priority-faces)))
5900 'org-special-keyword)
5901 'font-lock-fontified t))))
5903 (defun org-get-tag-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 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5909 'org-tag))
5911 (defun org-unfontify-region (beg end &optional maybe_loudly)
5912 "Remove fontification and activation overlays from links."
5913 (font-lock-default-unfontify-region beg end)
5914 (let* ((buffer-undo-list t)
5915 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5916 (inhibit-modification-hooks t)
5917 deactivate-mark buffer-file-name buffer-file-truename)
5918 (org-decompose-region beg end)
5919 (remove-text-properties beg end
5920 '(mouse-face t keymap t org-linked-text t
5921 invisible t intangible t
5922 org-no-flyspell t org-emphasis t))
5923 (org-remove-font-lock-display-properties beg end)))
5925 (defconst org-script-display '(((raise -0.3) (height 0.7))
5926 ((raise 0.3) (height 0.7))
5927 ((raise -0.5))
5928 ((raise 0.5)))
5929 "Display properties for showing superscripts and subscripts.")
5931 (defun org-remove-font-lock-display-properties (beg end)
5932 "Remove specific display properties that have been added by font lock.
5933 The will remove the raise properties that are used to show superscripts
5934 and subscripts."
5935 (let (next prop)
5936 (while (< beg end)
5937 (setq next (next-single-property-change beg 'display nil end)
5938 prop (get-text-property beg 'display))
5939 (if (member prop org-script-display)
5940 (put-text-property beg next 'display nil))
5941 (setq beg next))))
5943 (defun org-raise-scripts (limit)
5944 "Add raise properties to sub/superscripts."
5945 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
5946 (if (re-search-forward
5947 (if (eq org-use-sub-superscripts t)
5948 org-match-substring-regexp
5949 org-match-substring-with-braces-regexp)
5950 limit t)
5951 (let* ((pos (point)) table-p comment-p
5952 (mpos (match-beginning 3))
5953 (emph-p (get-text-property mpos 'org-emphasis))
5954 (link-p (get-text-property mpos 'mouse-face))
5955 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
5956 (goto-char (point-at-bol))
5957 (setq table-p (org-looking-at-p org-table-dataline-regexp)
5958 comment-p (org-looking-at-p "[ \t]*#"))
5959 (goto-char pos)
5960 ;; FIXME: Should we go back one character here, for a_b^c
5961 ;; (goto-char (1- pos)) ;????????????????????
5962 (if (or comment-p emph-p link-p keyw-p)
5964 (put-text-property (match-beginning 3) (match-end 0)
5965 'display
5966 (if (equal (char-after (match-beginning 2)) ?^)
5967 (nth (if table-p 3 1) org-script-display)
5968 (nth (if table-p 2 0) org-script-display)))
5969 (add-text-properties (match-beginning 2) (match-end 2)
5970 (list 'invisible t
5971 'org-dwidth t 'org-dwidth-n 1))
5972 (if (and (eq (char-after (match-beginning 3)) ?{)
5973 (eq (char-before (match-end 3)) ?}))
5974 (progn
5975 (add-text-properties
5976 (match-beginning 3) (1+ (match-beginning 3))
5977 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
5978 (add-text-properties
5979 (1- (match-end 3)) (match-end 3)
5980 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
5981 t)))))
5983 ;;;; Visibility cycling, including org-goto and indirect buffer
5985 ;;; Cycling
5987 (defvar org-cycle-global-status nil)
5988 (make-variable-buffer-local 'org-cycle-global-status)
5989 (defvar org-cycle-subtree-status nil)
5990 (make-variable-buffer-local 'org-cycle-subtree-status)
5992 ;;;###autoload
5994 (defvar org-inlinetask-min-level)
5996 (defun org-cycle (&optional arg)
5997 "TAB-action and visibility cycling for Org-mode.
5999 This is the command invoked in Org-mode by the TAB key. Its main purpose
6000 is outline visibility cycling, but it also invokes other actions
6001 in special contexts.
6003 - When this function is called with a prefix argument, rotate the entire
6004 buffer through 3 states (global cycling)
6005 1. OVERVIEW: Show only top-level headlines.
6006 2. CONTENTS: Show all headlines of all levels, but no body text.
6007 3. SHOW ALL: Show everything.
6008 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6009 determined by the variable `org-startup-folded', and by any VISIBILITY
6010 properties in the buffer.
6011 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6012 including any drawers.
6014 - When inside a table, re-align the table and move to the next field.
6016 - When point is at the beginning of a headline, rotate the subtree started
6017 by this line through 3 different states (local cycling)
6018 1. FOLDED: Only the main headline is shown.
6019 2. CHILDREN: The main headline and the direct children are shown.
6020 From this state, you can move to one of the children
6021 and zoom in further.
6022 3. SUBTREE: Show the entire subtree, including body text.
6023 If there is no subtree, switch directly from CHILDREN to FOLDED.
6025 - When point is at the beginning of an empty headline and the variable
6026 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6027 of the headline by demoting and promoting it to likely levels. This
6028 speeds up creation document structure by pressing TAB once or several
6029 times right after creating a new headline.
6031 - When there is a numeric prefix, go up to a heading with level ARG, do
6032 a `show-subtree' and return to the previous cursor position. If ARG
6033 is negative, go up that many levels.
6035 - When point is not at the beginning of a headline, execute the global
6036 binding for TAB, which is re-indenting the line. See the option
6037 `org-cycle-emulate-tab' for details.
6039 - Special case: if point is at the beginning of the buffer and there is
6040 no headline in line 1, this function will act as if called with prefix arg
6041 (C-u TAB, same as S-TAB) also when called without prefix arg.
6042 But only if also the variable `org-cycle-global-at-bob' is t."
6043 (interactive "P")
6044 (org-load-modules-maybe)
6045 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6046 (and org-cycle-level-after-item/entry-creation
6047 (or (org-cycle-level)
6048 (org-cycle-item-indentation))))
6049 (let* ((limit-level
6050 (or org-cycle-max-level
6051 (and (boundp 'org-inlinetask-min-level)
6052 org-inlinetask-min-level
6053 (1- org-inlinetask-min-level))))
6054 (nstars (and limit-level
6055 (if org-odd-levels-only
6056 (and limit-level (1- (* limit-level 2)))
6057 limit-level)))
6058 (org-outline-regexp
6059 (if (not (eq major-mode 'org-mode))
6060 outline-regexp
6061 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6062 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6063 (not (looking-at org-outline-regexp))))
6064 (org-cycle-hook
6065 (if bob-special
6066 (delq 'org-optimize-window-after-visibility-change
6067 (copy-sequence org-cycle-hook))
6068 org-cycle-hook))
6069 (pos (point)))
6071 (if (or bob-special (equal arg '(4)))
6072 ;; special case: use global cycling
6073 (setq arg t))
6075 (cond
6077 ((equal arg '(16))
6078 (setq last-command 'dummy)
6079 (org-set-startup-visibility)
6080 (message "Startup visibility, plus VISIBILITY properties"))
6082 ((equal arg '(64))
6083 (show-all)
6084 (message "Entire buffer visible, including drawers"))
6086 ;; Table: enter it or move to the next field.
6087 ((org-at-table-p 'any)
6088 (if (org-at-table.el-p)
6089 (message "Use C-c ' to edit table.el tables")
6090 (if arg (org-table-edit-field t)
6091 (org-table-justify-field-maybe)
6092 (call-interactively 'org-table-next-field))))
6094 ((run-hook-with-args-until-success
6095 'org-tab-after-check-for-table-hook))
6097 ;; Global cycling: delegate to `org-cycle-internal-global'.
6098 ((eq arg t) (org-cycle-internal-global))
6100 ;; Drawers: delegate to `org-flag-drawer'.
6101 ((and org-drawers org-drawer-regexp
6102 (save-excursion
6103 (beginning-of-line 1)
6104 (looking-at org-drawer-regexp)))
6105 (org-flag-drawer ; toggle block visibility
6106 (not (get-char-property (match-end 0) 'invisible))))
6108 ;; Show-subtree, ARG levels up from here.
6109 ((integerp arg)
6110 (save-excursion
6111 (org-back-to-heading)
6112 (outline-up-heading (if (< arg 0) (- arg)
6113 (- (funcall outline-level) arg)))
6114 (org-show-subtree)))
6116 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6117 ((and (featurep 'org-inlinetask)
6118 (org-inlinetask-at-task-p)
6119 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6120 (org-inlinetask-toggle-visibility))
6122 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6123 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6124 (save-excursion (beginning-of-line 1)
6125 (looking-at org-outline-regexp)))
6126 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6127 (org-cycle-internal-local))
6129 ;; From there: TAB emulation and template completion.
6130 (buffer-read-only (org-back-to-heading))
6132 ((run-hook-with-args-until-success
6133 'org-tab-after-check-for-cycling-hook))
6135 ((org-try-structure-completion))
6137 ((org-try-cdlatex-tab))
6139 ((run-hook-with-args-until-success
6140 'org-tab-before-tab-emulation-hook))
6142 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6143 (or (not (bolp))
6144 (not (looking-at org-outline-regexp))))
6145 (call-interactively (global-key-binding "\t")))
6147 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6148 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6149 (or (and (eq org-cycle-emulate-tab 'white)
6150 (= (match-end 0) (point-at-eol)))
6151 (and (eq org-cycle-emulate-tab 'whitestart)
6152 (>= (match-end 0) pos))))
6154 (eq org-cycle-emulate-tab t))
6155 (call-interactively (global-key-binding "\t")))
6157 (t (save-excursion
6158 (org-back-to-heading)
6159 (org-cycle)))))))
6161 (defun org-cycle-internal-global ()
6162 "Do the global cycling action."
6163 (cond
6164 ((and (eq last-command this-command)
6165 (eq org-cycle-global-status 'overview))
6166 ;; We just created the overview - now do table of contents
6167 ;; This can be slow in very large buffers, so indicate action
6168 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6169 (message "CONTENTS...")
6170 (org-content)
6171 (message "CONTENTS...done")
6172 (setq org-cycle-global-status 'contents)
6173 (run-hook-with-args 'org-cycle-hook 'contents))
6175 ((and (eq last-command this-command)
6176 (eq org-cycle-global-status 'contents))
6177 ;; We just showed the table of contents - now show everything
6178 (run-hook-with-args 'org-pre-cycle-hook 'all)
6179 (show-all)
6180 (message "SHOW ALL")
6181 (setq org-cycle-global-status 'all)
6182 (run-hook-with-args 'org-cycle-hook 'all))
6185 ;; Default action: go to overview
6186 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6187 (org-overview)
6188 (message "OVERVIEW")
6189 (setq org-cycle-global-status 'overview)
6190 (run-hook-with-args 'org-cycle-hook 'overview))))
6192 (defun org-cycle-internal-local ()
6193 "Do the local cycling action."
6194 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6195 ;; First, determine end of headline (EOH), end of subtree or item
6196 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6197 (save-excursion
6198 (if (org-at-item-p)
6199 (progn
6200 (beginning-of-line)
6201 (setq struct (org-list-struct))
6202 (setq eoh (point-at-eol))
6203 (setq eos (org-list-get-item-end-before-blank (point) struct))
6204 (setq has-children (org-list-has-child-p (point) struct)))
6205 (org-back-to-heading)
6206 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6207 (setq eos (save-excursion
6208 (org-end-of-subtree t)
6209 (unless (eobp)
6210 (skip-chars-forward " \t\n"))
6211 (if (eobp) (point) (1- (point)))))
6212 (setq has-children
6213 (or (save-excursion
6214 (let ((level (funcall outline-level)))
6215 (outline-next-heading)
6216 (and (org-at-heading-p t)
6217 (> (funcall outline-level) level))))
6218 (save-excursion
6219 (org-list-search-forward (org-item-beginning-re) eos t)))))
6220 ;; Determine end invisible part of buffer (EOL)
6221 (beginning-of-line 2)
6222 ;; XEmacs doesn't have `next-single-char-property-change'
6223 (if (featurep 'xemacs)
6224 (while (and (not (eobp)) ;; this is like `next-line'
6225 (get-char-property (1- (point)) 'invisible))
6226 (beginning-of-line 2))
6227 (while (and (not (eobp)) ;; this is like `next-line'
6228 (get-char-property (1- (point)) 'invisible))
6229 (goto-char (next-single-char-property-change (point) 'invisible))
6230 (and (eolp) (beginning-of-line 2))))
6231 (setq eol (point)))
6232 ;; Find out what to do next and set `this-command'
6233 (cond
6234 ((= eos eoh)
6235 ;; Nothing is hidden behind this heading
6236 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6237 (message "EMPTY ENTRY")
6238 (setq org-cycle-subtree-status nil)
6239 (save-excursion
6240 (goto-char eos)
6241 (outline-next-heading)
6242 (if (outline-invisible-p) (org-flag-heading nil))))
6243 ((and (or (>= eol eos)
6244 (not (string-match "\\S-" (buffer-substring eol eos))))
6245 (or has-children
6246 (not (setq children-skipped
6247 org-cycle-skip-children-state-if-no-children))))
6248 ;; Entire subtree is hidden in one line: children view
6249 (run-hook-with-args 'org-pre-cycle-hook 'children)
6250 (if (org-at-item-p)
6251 (org-list-set-item-visibility (point-at-bol) struct 'children)
6252 (org-show-entry)
6253 (show-children)
6254 ;; Fold every list in subtree to top-level items.
6255 (when (eq org-cycle-include-plain-lists 'integrate)
6256 (save-excursion
6257 (org-back-to-heading)
6258 (while (org-list-search-forward (org-item-beginning-re) eos t)
6259 (beginning-of-line 1)
6260 (let* ((struct (org-list-struct))
6261 (prevs (org-list-prevs-alist struct))
6262 (end (org-list-get-bottom-point struct)))
6263 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6264 (org-list-get-all-items (point) struct prevs))
6265 (goto-char end))))))
6266 (message "CHILDREN")
6267 (save-excursion
6268 (goto-char eos)
6269 (outline-next-heading)
6270 (if (outline-invisible-p) (org-flag-heading nil)))
6271 (setq org-cycle-subtree-status 'children)
6272 (run-hook-with-args 'org-cycle-hook 'children))
6273 ((or children-skipped
6274 (and (eq last-command this-command)
6275 (eq org-cycle-subtree-status 'children)))
6276 ;; We just showed the children, or no children are there,
6277 ;; now show everything.
6278 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6279 (outline-flag-region eoh eos nil)
6280 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6281 (setq org-cycle-subtree-status 'subtree)
6282 (run-hook-with-args 'org-cycle-hook 'subtree))
6284 ;; Default action: hide the subtree.
6285 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6286 (outline-flag-region eoh eos t)
6287 (message "FOLDED")
6288 (setq org-cycle-subtree-status 'folded)
6289 (run-hook-with-args 'org-cycle-hook 'folded)))))
6291 ;;;###autoload
6292 (defun org-global-cycle (&optional arg)
6293 "Cycle the global visibility. For details see `org-cycle'.
6294 With \\[universal-argument] prefix arg, switch to startup visibility.
6295 With a numeric prefix, show all headlines up to that level."
6296 (interactive "P")
6297 (let ((org-cycle-include-plain-lists
6298 (if (eq major-mode 'org-mode) org-cycle-include-plain-lists nil)))
6299 (cond
6300 ((integerp arg)
6301 (show-all)
6302 (hide-sublevels arg)
6303 (setq org-cycle-global-status 'contents))
6304 ((equal arg '(4))
6305 (org-set-startup-visibility)
6306 (message "Startup visibility, plus VISIBILITY properties."))
6308 (org-cycle '(4))))))
6310 (defun org-set-startup-visibility ()
6311 "Set the visibility required by startup options and properties."
6312 (cond
6313 ((eq org-startup-folded t)
6314 (org-cycle '(4)))
6315 ((eq org-startup-folded 'content)
6316 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6317 (org-cycle '(4)) (org-cycle '(4)))))
6318 (unless (eq org-startup-folded 'showeverything)
6319 (if org-hide-block-startup (org-hide-block-all))
6320 (org-set-visibility-according-to-property 'no-cleanup)
6321 (org-cycle-hide-archived-subtrees 'all)
6322 (org-cycle-hide-drawers 'all)
6323 (org-cycle-show-empty-lines t)))
6325 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6326 "Switch subtree visibilities according to :VISIBILITY: property."
6327 (interactive)
6328 (let (org-show-entry-below state)
6329 (save-excursion
6330 (goto-char (point-min))
6331 (while (re-search-forward
6332 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6333 nil t)
6334 (setq state (match-string 1))
6335 (save-excursion
6336 (org-back-to-heading t)
6337 (hide-subtree)
6338 (org-reveal)
6339 (cond
6340 ((equal state '("fold" "folded"))
6341 (hide-subtree))
6342 ((equal state "children")
6343 (org-show-hidden-entry)
6344 (show-children))
6345 ((equal state "content")
6346 (save-excursion
6347 (save-restriction
6348 (org-narrow-to-subtree)
6349 (org-content))))
6350 ((member state '("all" "showall"))
6351 (show-subtree)))))
6352 (unless no-cleanup
6353 (org-cycle-hide-archived-subtrees 'all)
6354 (org-cycle-hide-drawers 'all)
6355 (org-cycle-show-empty-lines 'all)))))
6357 ;; This function uses outline-regexp instead of the more fundamental
6358 ;; org-outline-regexp so that org-cycle-global works outside of Org
6359 ;; buffers, where outline-regexp is needed.
6360 (defun org-overview ()
6361 "Switch to overview mode, showing only top-level headlines.
6362 Really, this shows all headlines with level equal or greater than the level
6363 of the first headline in the buffer. This is important, because if the
6364 first headline is not level one, then (hide-sublevels 1) gives confusing
6365 results."
6366 (interactive)
6367 (let ((level (save-excursion
6368 (goto-char (point-min))
6369 (if (re-search-forward (concat "^" outline-regexp) nil t)
6370 (progn
6371 (goto-char (match-beginning 0))
6372 (funcall outline-level))))))
6373 (and level (hide-sublevels level))))
6375 (defun org-content (&optional arg)
6376 "Show all headlines in the buffer, like a table of contents.
6377 With numerical argument N, show content up to level N."
6378 (interactive "P")
6379 (save-excursion
6380 ;; Visit all headings and show their offspring
6381 (and (integerp arg) (org-overview))
6382 (goto-char (point-max))
6383 (catch 'exit
6384 (while (and (progn (condition-case nil
6385 (outline-previous-visible-heading 1)
6386 (error (goto-char (point-min))))
6388 (looking-at org-outline-regexp))
6389 (if (integerp arg)
6390 (show-children (1- arg))
6391 (show-branches))
6392 (if (bobp) (throw 'exit nil))))))
6395 (defun org-optimize-window-after-visibility-change (state)
6396 "Adjust the window after a change in outline visibility.
6397 This function is the default value of the hook `org-cycle-hook'."
6398 (when (get-buffer-window (current-buffer))
6399 (cond
6400 ((eq state 'content) nil)
6401 ((eq state 'all) nil)
6402 ((eq state 'folded) nil)
6403 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6404 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6406 (defun org-remove-empty-overlays-at (pos)
6407 "Remove outline overlays that do not contain non-white stuff."
6408 (mapc
6409 (lambda (o)
6410 (and (eq 'outline (overlay-get o 'invisible))
6411 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6412 (overlay-end o))))
6413 (delete-overlay o)))
6414 (overlays-at pos)))
6416 (defun org-clean-visibility-after-subtree-move ()
6417 "Fix visibility issues after moving a subtree."
6418 ;; First, find a reasonable region to look at:
6419 ;; Start two siblings above, end three below
6420 (let* ((beg (save-excursion
6421 (and (org-get-last-sibling)
6422 (org-get-last-sibling))
6423 (point)))
6424 (end (save-excursion
6425 (and (org-get-next-sibling)
6426 (org-get-next-sibling)
6427 (org-get-next-sibling))
6428 (if (org-at-heading-p)
6429 (point-at-eol)
6430 (point))))
6431 (level (looking-at "\\*+"))
6432 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6433 (save-excursion
6434 (save-restriction
6435 (narrow-to-region beg end)
6436 (when re
6437 ;; Properly fold already folded siblings
6438 (goto-char (point-min))
6439 (while (re-search-forward re nil t)
6440 (if (and (not (outline-invisible-p))
6441 (save-excursion
6442 (goto-char (point-at-eol)) (outline-invisible-p)))
6443 (hide-entry))))
6444 (org-cycle-show-empty-lines 'overview)
6445 (org-cycle-hide-drawers 'overview)))))
6447 (defun org-cycle-show-empty-lines (state)
6448 "Show empty lines above all visible headlines.
6449 The region to be covered depends on STATE when called through
6450 `org-cycle-hook'. Lisp program can use t for STATE to get the
6451 entire buffer covered. Note that an empty line is only shown if there
6452 are at least `org-cycle-separator-lines' empty lines before the headline."
6453 (when (not (= org-cycle-separator-lines 0))
6454 (save-excursion
6455 (let* ((n (abs org-cycle-separator-lines))
6456 (re (cond
6457 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6458 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6459 (t (let ((ns (number-to-string (- n 2))))
6460 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6461 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6462 beg end b e)
6463 (cond
6464 ((memq state '(overview contents t))
6465 (setq beg (point-min) end (point-max)))
6466 ((memq state '(children folded))
6467 (setq beg (point) end (progn (org-end-of-subtree t t)
6468 (beginning-of-line 2)
6469 (point)))))
6470 (when beg
6471 (goto-char beg)
6472 (while (re-search-forward re end t)
6473 (unless (get-char-property (match-end 1) 'invisible)
6474 (setq e (match-end 1))
6475 (if (< org-cycle-separator-lines 0)
6476 (setq b (save-excursion
6477 (goto-char (match-beginning 0))
6478 (org-back-over-empty-lines)
6479 (if (save-excursion
6480 (goto-char (max (point-min) (1- (point))))
6481 (org-on-heading-p))
6482 (1- (point))
6483 (point))))
6484 (setq b (match-beginning 1)))
6485 (outline-flag-region b e nil)))))))
6486 ;; Never hide empty lines at the end of the file.
6487 (save-excursion
6488 (goto-char (point-max))
6489 (outline-previous-heading)
6490 (outline-end-of-heading)
6491 (if (and (looking-at "[ \t\n]+")
6492 (= (match-end 0) (point-max)))
6493 (outline-flag-region (point) (match-end 0) nil))))
6495 (defun org-show-empty-lines-in-parent ()
6496 "Move to the parent and re-show empty lines before visible headlines."
6497 (save-excursion
6498 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6499 (org-cycle-show-empty-lines context))))
6501 (defun org-files-list ()
6502 "Return `org-agenda-files' list, plus all open org-mode files.
6503 This is useful for operations that need to scan all of a user's
6504 open and agenda-wise Org files."
6505 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6506 (dolist (buf (buffer-list))
6507 (with-current-buffer buf
6508 (if (and (eq major-mode 'org-mode) (buffer-file-name))
6509 (let ((file (expand-file-name (buffer-file-name))))
6510 (unless (member file files)
6511 (push file files))))))
6512 files))
6514 (defsubst org-entry-beginning-position ()
6515 "Return the beginning position of the current entry."
6516 (save-excursion (outline-back-to-heading t) (point)))
6518 (defsubst org-entry-end-position ()
6519 "Return the end position of the current entry."
6520 (save-excursion (outline-next-heading) (point)))
6522 (defun org-cycle-hide-drawers (state)
6523 "Re-hide all drawers after a visibility state change."
6524 (when (and (eq major-mode 'org-mode)
6525 (not (memq state '(overview folded contents))))
6526 (save-excursion
6527 (let* ((globalp (memq state '(contents all)))
6528 (beg (if globalp (point-min) (point)))
6529 (end (if globalp (point-max)
6530 (if (eq state 'children)
6531 (save-excursion (outline-next-heading) (point))
6532 (org-end-of-subtree t)))))
6533 (goto-char beg)
6534 (while (re-search-forward org-drawer-regexp end t)
6535 (org-flag-drawer t))))))
6537 (defun org-flag-drawer (flag)
6538 (save-excursion
6539 (beginning-of-line 1)
6540 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6541 (let ((b (match-end 0)))
6542 (if (re-search-forward
6543 "^[ \t]*:END:"
6544 (save-excursion (outline-next-heading) (point)) t)
6545 (outline-flag-region b (point-at-eol) flag)
6546 (error ":END: line missing at position %s" b))))))
6548 (defun org-subtree-end-visible-p ()
6549 "Is the end of the current subtree visible?"
6550 (pos-visible-in-window-p
6551 (save-excursion (org-end-of-subtree t) (point))))
6553 (defun org-first-headline-recenter (&optional N)
6554 "Move cursor to the first headline and recenter the headline.
6555 Optional argument N means put the headline into the Nth line of the window."
6556 (goto-char (point-min))
6557 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6558 (beginning-of-line)
6559 (recenter (prefix-numeric-value N))))
6561 ;;; Saving and restoring visibility
6563 (defun org-outline-overlay-data (&optional use-markers)
6564 "Return a list of the locations of all outline overlays.
6565 These are overlays with the `invisible' property value `outline'.
6566 The return value is a list of cons cells, with start and stop
6567 positions for each overlay.
6568 If USE-MARKERS is set, return the positions as markers."
6569 (let (beg end)
6570 (save-excursion
6571 (save-restriction
6572 (widen)
6573 (delq nil
6574 (mapcar (lambda (o)
6575 (when (eq (overlay-get o 'invisible) 'outline)
6576 (setq beg (overlay-start o)
6577 end (overlay-end o))
6578 (and beg end (> end beg)
6579 (if use-markers
6580 (cons (move-marker (make-marker) beg)
6581 (move-marker (make-marker) end))
6582 (cons beg end)))))
6583 (overlays-in (point-min) (point-max))))))))
6585 (defun org-set-outline-overlay-data (data)
6586 "Create visibility overlays for all positions in DATA.
6587 DATA should have been made by `org-outline-overlay-data'."
6588 (let (o)
6589 (save-excursion
6590 (save-restriction
6591 (widen)
6592 (show-all)
6593 (mapc (lambda (c)
6594 (setq o (make-overlay (car c) (cdr c)))
6595 (overlay-put o 'invisible 'outline))
6596 data)))))
6598 ;;; Folding of blocks
6600 (defconst org-block-regexp
6601 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
6602 "Regular expression for hiding blocks.")
6604 (defvar org-hide-block-overlays nil
6605 "Overlays hiding blocks.")
6606 (make-variable-buffer-local 'org-hide-block-overlays)
6608 (defun org-block-map (function &optional start end)
6609 "Call FUNCTION at the head of all source blocks in the current buffer.
6610 Optional arguments START and END can be used to limit the range."
6611 (let ((start (or start (point-min)))
6612 (end (or end (point-max))))
6613 (save-excursion
6614 (goto-char start)
6615 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6616 (save-excursion
6617 (save-match-data
6618 (goto-char (match-beginning 0))
6619 (funcall function)))))))
6621 (defun org-hide-block-toggle-all ()
6622 "Toggle the visibility of all blocks in the current buffer."
6623 (org-block-map #'org-hide-block-toggle))
6625 (defun org-hide-block-all ()
6626 "Fold all blocks in the current buffer."
6627 (interactive)
6628 (org-show-block-all)
6629 (org-block-map #'org-hide-block-toggle-maybe))
6631 (defun org-show-block-all ()
6632 "Unfold all blocks in the current buffer."
6633 (interactive)
6634 (mapc 'delete-overlay org-hide-block-overlays)
6635 (setq org-hide-block-overlays nil))
6637 (defun org-hide-block-toggle-maybe ()
6638 "Toggle visibility of block at point."
6639 (interactive)
6640 (let ((case-fold-search t))
6641 (if (save-excursion
6642 (beginning-of-line 1)
6643 (looking-at org-block-regexp))
6644 (progn (org-hide-block-toggle)
6645 t) ;; to signal that we took action
6646 nil))) ;; to signal that we did not
6648 (defun org-hide-block-toggle (&optional force)
6649 "Toggle the visibility of the current block."
6650 (interactive)
6651 (save-excursion
6652 (beginning-of-line)
6653 (if (re-search-forward org-block-regexp nil t)
6654 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6655 (end (match-end 0)) ;; end of entire body
6657 (if (memq t (mapcar (lambda (overlay)
6658 (eq (overlay-get overlay 'invisible)
6659 'org-hide-block))
6660 (overlays-at start)))
6661 (if (or (not force) (eq force 'off))
6662 (mapc (lambda (ov)
6663 (when (member ov org-hide-block-overlays)
6664 (setq org-hide-block-overlays
6665 (delq ov org-hide-block-overlays)))
6666 (when (eq (overlay-get ov 'invisible)
6667 'org-hide-block)
6668 (delete-overlay ov)))
6669 (overlays-at start)))
6670 (setq ov (make-overlay start end))
6671 (overlay-put ov 'invisible 'org-hide-block)
6672 ;; make the block accessible to isearch
6673 (overlay-put
6674 ov 'isearch-open-invisible
6675 (lambda (ov)
6676 (when (member ov org-hide-block-overlays)
6677 (setq org-hide-block-overlays
6678 (delq ov org-hide-block-overlays)))
6679 (when (eq (overlay-get ov 'invisible)
6680 'org-hide-block)
6681 (delete-overlay ov))))
6682 (push ov org-hide-block-overlays)))
6683 (error "Not looking at a source block"))))
6685 ;; org-tab-after-check-for-cycling-hook
6686 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6687 ;; Remove overlays when changing major mode
6688 (add-hook 'org-mode-hook
6689 (lambda () (org-add-hook 'change-major-mode-hook
6690 'org-show-block-all 'append 'local)))
6692 ;;; Org-goto
6694 (defvar org-goto-window-configuration nil)
6695 (defvar org-goto-marker nil)
6696 (defvar org-goto-map
6697 (let ((map (make-sparse-keymap)))
6698 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6699 (while (setq cmd (pop cmds))
6700 (substitute-key-definition cmd cmd map global-map)))
6701 (suppress-keymap map)
6702 (org-defkey map "\C-m" 'org-goto-ret)
6703 (org-defkey map [(return)] 'org-goto-ret)
6704 (org-defkey map [(left)] 'org-goto-left)
6705 (org-defkey map [(right)] 'org-goto-right)
6706 (org-defkey map [(control ?g)] 'org-goto-quit)
6707 (org-defkey map "\C-i" 'org-cycle)
6708 (org-defkey map [(tab)] 'org-cycle)
6709 (org-defkey map [(down)] 'outline-next-visible-heading)
6710 (org-defkey map [(up)] 'outline-previous-visible-heading)
6711 (if org-goto-auto-isearch
6712 (if (fboundp 'define-key-after)
6713 (define-key-after map [t] 'org-goto-local-auto-isearch)
6714 nil)
6715 (org-defkey map "q" 'org-goto-quit)
6716 (org-defkey map "n" 'outline-next-visible-heading)
6717 (org-defkey map "p" 'outline-previous-visible-heading)
6718 (org-defkey map "f" 'outline-forward-same-level)
6719 (org-defkey map "b" 'outline-backward-same-level)
6720 (org-defkey map "u" 'outline-up-heading))
6721 (org-defkey map "/" 'org-occur)
6722 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6723 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6724 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6725 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6726 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6727 map))
6729 (defconst org-goto-help
6730 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6731 RET=jump to location [Q]uit and return to previous location
6732 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6734 (defvar org-goto-start-pos) ; dynamically scoped parameter
6736 ;; FIXME: Docstring does not mention both interfaces
6737 (defun org-goto (&optional alternative-interface)
6738 "Look up a different location in the current file, keeping current visibility.
6740 When you want look-up or go to a different location in a document, the
6741 fastest way is often to fold the entire buffer and then dive into the tree.
6742 This method has the disadvantage, that the previous location will be folded,
6743 which may not be what you want.
6745 This command works around this by showing a copy of the current buffer
6746 in an indirect buffer, in overview mode. You can dive into the tree in
6747 that copy, use org-occur and incremental search to find a location.
6748 When pressing RET or `Q', the command returns to the original buffer in
6749 which the visibility is still unchanged. After RET is will also jump to
6750 the location selected in the indirect buffer and expose the headline
6751 hierarchy above."
6752 (interactive "P")
6753 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6754 (org-refile-use-outline-path t)
6755 (org-refile-target-verify-function nil)
6756 (interface
6757 (if (not alternative-interface)
6758 org-goto-interface
6759 (if (eq org-goto-interface 'outline)
6760 'outline-path-completion
6761 'outline)))
6762 (org-goto-start-pos (point))
6763 (selected-point
6764 (if (eq interface 'outline)
6765 (car (org-get-location (current-buffer) org-goto-help))
6766 (let ((pa (org-refile-get-location "Goto")))
6767 (org-refile-check-position pa)
6768 (nth 3 pa)))))
6769 (if selected-point
6770 (progn
6771 (org-mark-ring-push org-goto-start-pos)
6772 (goto-char selected-point)
6773 (if (or (outline-invisible-p) (org-invisible-p2))
6774 (org-show-context 'org-goto)))
6775 (message "Quit"))))
6777 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6778 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6779 (defvar org-goto-local-auto-isearch-map) ; defined below
6781 (defun org-get-location (buf help)
6782 "Let the user select a location in the Org-mode buffer BUF.
6783 This function uses a recursive edit. It returns the selected position
6784 or nil."
6785 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6786 (isearch-hide-immediately nil)
6787 (isearch-search-fun-function
6788 (lambda () 'org-goto-local-search-headings))
6789 (org-goto-selected-point org-goto-exit-command)
6790 (pop-up-frames nil)
6791 (special-display-buffer-names nil)
6792 (special-display-regexps nil)
6793 (special-display-function nil))
6794 (save-excursion
6795 (save-window-excursion
6796 (delete-other-windows)
6797 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6798 (org-pop-to-buffer-same-window
6799 (condition-case nil
6800 (make-indirect-buffer (current-buffer) "*org-goto*")
6801 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6802 (with-output-to-temp-buffer "*Help*"
6803 (princ help))
6804 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6805 (setq buffer-read-only nil)
6806 (let ((org-startup-truncated t)
6807 (org-startup-folded nil)
6808 (org-startup-align-all-tables nil))
6809 (org-mode)
6810 (org-overview))
6811 (setq buffer-read-only t)
6812 (if (and (boundp 'org-goto-start-pos)
6813 (integer-or-marker-p org-goto-start-pos))
6814 (let ((org-show-hierarchy-above t)
6815 (org-show-siblings t)
6816 (org-show-following-heading t))
6817 (goto-char org-goto-start-pos)
6818 (and (outline-invisible-p) (org-show-context)))
6819 (goto-char (point-min)))
6820 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6821 (message "Select location and press RET")
6822 (use-local-map org-goto-map)
6823 (recursive-edit)
6825 (kill-buffer "*org-goto*")
6826 (cons org-goto-selected-point org-goto-exit-command)))
6828 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6829 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6830 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6831 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6833 (defun org-goto-local-search-headings (string bound noerror)
6834 "Search and make sure that any matches are in headlines."
6835 (catch 'return
6836 (while (if isearch-forward
6837 (search-forward string bound noerror)
6838 (search-backward string bound noerror))
6839 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6840 (and (member :headline context)
6841 (not (member :tags context))))
6842 (throw 'return (point))))))
6844 (defun org-goto-local-auto-isearch ()
6845 "Start isearch."
6846 (interactive)
6847 (goto-char (point-min))
6848 (let ((keys (this-command-keys)))
6849 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6850 (isearch-mode t)
6851 (isearch-process-search-char (string-to-char keys)))))
6853 (defun org-goto-ret (&optional arg)
6854 "Finish `org-goto' by going to the new location."
6855 (interactive "P")
6856 (setq org-goto-selected-point (point)
6857 org-goto-exit-command 'return)
6858 (throw 'exit nil))
6860 (defun org-goto-left ()
6861 "Finish `org-goto' by going to the new location."
6862 (interactive)
6863 (if (org-on-heading-p)
6864 (progn
6865 (beginning-of-line 1)
6866 (setq org-goto-selected-point (point)
6867 org-goto-exit-command 'left)
6868 (throw 'exit nil))
6869 (error "Not on a heading")))
6871 (defun org-goto-right ()
6872 "Finish `org-goto' by going to the new location."
6873 (interactive)
6874 (if (org-on-heading-p)
6875 (progn
6876 (setq org-goto-selected-point (point)
6877 org-goto-exit-command 'right)
6878 (throw 'exit nil))
6879 (error "Not on a heading")))
6881 (defun org-goto-quit ()
6882 "Finish `org-goto' without cursor motion."
6883 (interactive)
6884 (setq org-goto-selected-point nil)
6885 (setq org-goto-exit-command 'quit)
6886 (throw 'exit nil))
6888 ;;; Indirect buffer display of subtrees
6890 (defvar org-indirect-dedicated-frame nil
6891 "This is the frame being used for indirect tree display.")
6892 (defvar org-last-indirect-buffer nil)
6894 (defun org-tree-to-indirect-buffer (&optional arg)
6895 "Create indirect buffer and narrow it to current subtree.
6896 With numerical prefix ARG, go up to this level and then take that tree.
6897 If ARG is negative, go up that many levels.
6898 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6899 indirect buffer previously made with this command, to avoid proliferation of
6900 indirect buffers. However, when you call the command with a \
6901 \\[universal-argument] prefix, or
6902 when `org-indirect-buffer-display' is `new-frame', the last buffer
6903 is kept so that you can work with several indirect buffers at the same time.
6904 If `org-indirect-buffer-display' is `dedicated-frame', the \
6905 \\[universal-argument] prefix also
6906 requests that a new frame be made for the new buffer, so that the dedicated
6907 frame is not changed."
6908 (interactive "P")
6909 (let ((cbuf (current-buffer))
6910 (cwin (selected-window))
6911 (pos (point))
6912 beg end level heading ibuf)
6913 (save-excursion
6914 (org-back-to-heading t)
6915 (when (numberp arg)
6916 (setq level (org-outline-level))
6917 (if (< arg 0) (setq arg (+ level arg)))
6918 (while (> (setq level (org-outline-level)) arg)
6919 (outline-up-heading 1 t)))
6920 (setq beg (point)
6921 heading (org-get-heading))
6922 (org-end-of-subtree t t)
6923 (if (org-on-heading-p) (backward-char 1))
6924 (setq end (point)))
6925 (if (and (buffer-live-p org-last-indirect-buffer)
6926 (not (eq org-indirect-buffer-display 'new-frame))
6927 (not arg))
6928 (kill-buffer org-last-indirect-buffer))
6929 (setq ibuf (org-get-indirect-buffer cbuf)
6930 org-last-indirect-buffer ibuf)
6931 (cond
6932 ((or (eq org-indirect-buffer-display 'new-frame)
6933 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6934 (select-frame (make-frame))
6935 (delete-other-windows)
6936 (org-pop-to-buffer-same-window ibuf)
6937 (org-set-frame-title heading))
6938 ((eq org-indirect-buffer-display 'dedicated-frame)
6939 (raise-frame
6940 (select-frame (or (and org-indirect-dedicated-frame
6941 (frame-live-p org-indirect-dedicated-frame)
6942 org-indirect-dedicated-frame)
6943 (setq org-indirect-dedicated-frame (make-frame)))))
6944 (delete-other-windows)
6945 (org-pop-to-buffer-same-window ibuf)
6946 (org-set-frame-title (concat "Indirect: " heading)))
6947 ((eq org-indirect-buffer-display 'current-window)
6948 (org-pop-to-buffer-same-window ibuf))
6949 ((eq org-indirect-buffer-display 'other-window)
6950 (pop-to-buffer ibuf))
6951 (t (error "Invalid value")))
6952 (if (featurep 'xemacs)
6953 (save-excursion (org-mode) (turn-on-font-lock)))
6954 (narrow-to-region beg end)
6955 (show-all)
6956 (goto-char pos)
6957 (run-hook-with-args 'org-cycle-hook 'all)
6958 (and (window-live-p cwin) (select-window cwin))))
6960 (defun org-get-indirect-buffer (&optional buffer)
6961 (setq buffer (or buffer (current-buffer)))
6962 (let ((n 1) (base (buffer-name buffer)) bname)
6963 (while (buffer-live-p
6964 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6965 (setq n (1+ n)))
6966 (condition-case nil
6967 (make-indirect-buffer buffer bname 'clone)
6968 (error (make-indirect-buffer buffer bname)))))
6970 (defun org-set-frame-title (title)
6971 "Set the title of the current frame to the string TITLE."
6972 ;; FIXME: how to name a single frame in XEmacs???
6973 (unless (featurep 'xemacs)
6974 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6976 ;;;; Structure editing
6978 ;;; Inserting headlines
6980 (defun org-previous-line-empty-p ()
6981 (save-excursion
6982 (and (not (bobp))
6983 (or (beginning-of-line 0) t)
6984 (save-match-data
6985 (looking-at "[ \t]*$")))))
6987 (defun org-insert-heading (&optional force-heading invisible-ok)
6988 "Insert a new heading or item with same depth at point.
6989 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6990 If point is at the beginning of a headline, insert a sibling before the
6991 current headline. If point is not at the beginning, split the line,
6992 create the new headline with the text in the current line after point
6993 \(but see also the variable `org-M-RET-may-split-line').
6995 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6996 This is important for non-interactive uses of the command."
6997 (interactive "P")
6998 (if (or (= (buffer-size) 0)
6999 (and (not (save-excursion
7000 (and (ignore-errors (org-back-to-heading invisible-ok))
7001 (org-on-heading-p))))
7002 (or force-heading (not (org-in-item-p)))))
7003 (progn
7004 (insert "\n* ")
7005 (run-hooks 'org-insert-heading-hook))
7006 (when (or force-heading (not (org-insert-item)))
7007 (let* ((empty-line-p nil)
7008 (level nil)
7009 (on-heading (org-on-heading-p))
7010 (head (save-excursion
7011 (condition-case nil
7012 (progn
7013 (org-back-to-heading invisible-ok)
7014 (when (and (not on-heading)
7015 (featurep 'org-inlinetask)
7016 (integerp org-inlinetask-min-level)
7017 (>= (length (match-string 0))
7018 org-inlinetask-min-level))
7019 ;; Find a heading level before the inline task
7020 (while (and (setq level (org-up-heading-safe))
7021 (>= level org-inlinetask-min-level)))
7022 (if (org-on-heading-p)
7023 (org-back-to-heading invisible-ok)
7024 (error "This should not happen")))
7025 (setq empty-line-p (org-previous-line-empty-p))
7026 (match-string 0))
7027 (error "*"))))
7028 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7029 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7030 pos hide-previous previous-pos)
7031 (cond
7032 ((and (org-on-heading-p) (bolp)
7033 (or (bobp)
7034 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7035 ;; insert before the current line
7036 (open-line (if blank 2 1)))
7037 ((and (bolp)
7038 (not org-insert-heading-respect-content)
7039 (or (bobp)
7040 (save-excursion
7041 (backward-char 1) (not (outline-invisible-p)))))
7042 ;; insert right here
7043 nil)
7045 ;; somewhere in the line
7046 (save-excursion
7047 (setq previous-pos (point-at-bol))
7048 (end-of-line)
7049 (setq hide-previous (outline-invisible-p)))
7050 (and org-insert-heading-respect-content (org-show-subtree))
7051 (let ((split
7052 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7053 (save-excursion
7054 (let ((p (point)))
7055 (goto-char (point-at-bol))
7056 (and (looking-at org-complex-heading-regexp)
7057 (match-beginning 4)
7058 (> p (match-beginning 4)))))))
7059 tags pos)
7060 (cond
7061 (org-insert-heading-respect-content
7062 (org-end-of-subtree nil t)
7063 (when (featurep 'org-inlinetask)
7064 (while (and (not (eobp))
7065 (looking-at "\\(\\*+\\)[ \t]+")
7066 (>= (length (match-string 1))
7067 org-inlinetask-min-level))
7068 (org-end-of-subtree nil t)))
7069 (or (bolp) (newline))
7070 (or (org-previous-line-empty-p)
7071 (and blank (newline)))
7072 (open-line 1))
7073 ((org-on-heading-p)
7074 (when hide-previous
7075 (show-children)
7076 (org-show-entry))
7077 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7078 (setq tags (and (match-end 2) (match-string 2)))
7079 (and (match-end 1)
7080 (delete-region (match-beginning 1) (match-end 1)))
7081 (setq pos (point-at-bol))
7082 (or split (end-of-line 1))
7083 (delete-horizontal-space)
7084 (if (string-match "\\`\\*+\\'"
7085 (buffer-substring (point-at-bol) (point)))
7086 (insert " "))
7087 (newline (if blank 2 1))
7088 (when tags
7089 (save-excursion
7090 (goto-char pos)
7091 (end-of-line 1)
7092 (insert " " tags)
7093 (org-set-tags nil 'align))))
7095 (or split (end-of-line 1))
7096 (newline (if blank 2 1)))))))
7097 (insert head) (just-one-space)
7098 (setq pos (point))
7099 (end-of-line 1)
7100 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7101 (when (and org-insert-heading-respect-content hide-previous)
7102 (save-excursion
7103 (goto-char previous-pos)
7104 (hide-subtree)))
7105 (run-hooks 'org-insert-heading-hook)))))
7107 (defun org-get-heading (&optional no-tags no-todo)
7108 "Return the heading of the current entry, without the stars.
7109 When NO-TAGS is non-nil, don't include tags.
7110 When NO-TODO is non-nil, don't include TODO keywords."
7111 (save-excursion
7112 (org-back-to-heading t)
7113 (cond
7114 ((and no-tags no-todo)
7115 (looking-at org-complex-heading-regexp)
7116 (match-string 4))
7117 (no-tags
7118 (looking-at (concat org-outline-regexp
7119 "\\(.*?\\)"
7120 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7121 (match-string 1))
7122 (no-todo
7123 (looking-at org-todo-line-regexp)
7124 (match-string 3))
7125 (t (looking-at org-heading-regexp)
7126 (match-string 2)))))
7128 (defun org-heading-components ()
7129 "Return the components of the current heading.
7130 This is a list with the following elements:
7131 - the level as an integer
7132 - the reduced level, different if `org-odd-levels-only' is set.
7133 - the TODO keyword, or nil
7134 - the priority character, like ?A, or nil if no priority is given
7135 - the headline text itself, or the tags string if no headline text
7136 - the tags string, or nil."
7137 (save-excursion
7138 (org-back-to-heading t)
7139 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7140 (list (length (match-string 1))
7141 (org-reduced-level (length (match-string 1)))
7142 (org-match-string-no-properties 2)
7143 (and (match-end 3) (aref (match-string 3) 2))
7144 (org-match-string-no-properties 4)
7145 (org-match-string-no-properties 5)))))
7147 (defun org-get-entry ()
7148 "Get the entry text, after heading, entire subtree."
7149 (save-excursion
7150 (org-back-to-heading t)
7151 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7153 (defun org-insert-heading-after-current ()
7154 "Insert a new heading with same level as current, after current subtree."
7155 (interactive)
7156 (org-back-to-heading)
7157 (org-insert-heading)
7158 (org-move-subtree-down)
7159 (end-of-line 1))
7161 (defun org-insert-heading-respect-content ()
7162 (interactive)
7163 (let ((org-insert-heading-respect-content t))
7164 (org-insert-heading t)))
7166 (defun org-insert-todo-heading-respect-content (&optional force-state)
7167 (interactive "P")
7168 (let ((org-insert-heading-respect-content t))
7169 (org-insert-todo-heading force-state t)))
7171 (defun org-insert-todo-heading (arg &optional force-heading)
7172 "Insert a new heading with the same level and TODO state as current heading.
7173 If the heading has no TODO state, or if the state is DONE, use the first
7174 state (TODO by default). Also with prefix arg, force first state."
7175 (interactive "P")
7176 (when (or force-heading (not (org-insert-item 'checkbox)))
7177 (org-insert-heading force-heading)
7178 (save-excursion
7179 (org-back-to-heading)
7180 (outline-previous-heading)
7181 (looking-at org-todo-line-regexp))
7182 (let*
7183 ((new-mark-x
7184 (if (or arg
7185 (not (match-beginning 2))
7186 (member (match-string 2) org-done-keywords))
7187 (car org-todo-keywords-1)
7188 (match-string 2)))
7189 (new-mark
7191 (run-hook-with-args-until-success
7192 'org-todo-get-default-hook new-mark-x nil)
7193 new-mark-x)))
7194 (beginning-of-line 1)
7195 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7196 (if org-treat-insert-todo-heading-as-state-change
7197 (org-todo new-mark)
7198 (insert new-mark " "))))
7199 (when org-provide-todo-statistics
7200 (org-update-parent-todo-statistics))))
7202 (defun org-insert-subheading (arg)
7203 "Insert a new subheading and demote it.
7204 Works for outline headings and for plain lists alike."
7205 (interactive "P")
7206 (org-insert-heading arg)
7207 (cond
7208 ((org-on-heading-p) (org-do-demote))
7209 ((org-at-item-p) (org-indent-item))))
7211 (defun org-insert-todo-subheading (arg)
7212 "Insert a new subheading with TODO keyword or checkbox and demote it.
7213 Works for outline headings and for plain lists alike."
7214 (interactive "P")
7215 (org-insert-todo-heading arg)
7216 (cond
7217 ((org-on-heading-p) (org-do-demote))
7218 ((org-at-item-p) (org-indent-item))))
7220 ;;; Promotion and Demotion
7222 (defvar org-after-demote-entry-hook nil
7223 "Hook run after an entry has been demoted.
7224 The cursor will be at the beginning of the entry.
7225 When a subtree is being demoted, the hook will be called for each node.")
7227 (defvar org-after-promote-entry-hook nil
7228 "Hook run after an entry has been promoted.
7229 The cursor will be at the beginning of the entry.
7230 When a subtree is being promoted, the hook will be called for each node.")
7232 (defun org-promote-subtree ()
7233 "Promote the entire subtree.
7234 See also `org-promote'."
7235 (interactive)
7236 (save-excursion
7237 (org-with-limited-levels (org-map-tree 'org-promote)))
7238 (org-fix-position-after-promote))
7240 (defun org-demote-subtree ()
7241 "Demote the entire subtree. See `org-demote'.
7242 See also `org-promote'."
7243 (interactive)
7244 (save-excursion
7245 (org-with-limited-levels (org-map-tree 'org-demote)))
7246 (org-fix-position-after-promote))
7249 (defun org-do-promote ()
7250 "Promote the current heading higher up the tree.
7251 If the region is active in `transient-mark-mode', promote all headings
7252 in the region."
7253 (interactive)
7254 (save-excursion
7255 (if (org-region-active-p)
7256 (org-map-region 'org-promote (region-beginning) (region-end))
7257 (org-promote)))
7258 (org-fix-position-after-promote))
7260 (defun org-do-demote ()
7261 "Demote the current heading lower down the tree.
7262 If the region is active in `transient-mark-mode', demote all headings
7263 in the region."
7264 (interactive)
7265 (save-excursion
7266 (if (org-region-active-p)
7267 (org-map-region 'org-demote (region-beginning) (region-end))
7268 (org-demote)))
7269 (org-fix-position-after-promote))
7271 (defun org-fix-position-after-promote ()
7272 "Make sure that after pro/demotion cursor position is right."
7273 (let ((pos (point)))
7274 (when (save-excursion
7275 (beginning-of-line 1)
7276 (looking-at org-todo-line-regexp)
7277 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7278 (cond ((eobp) (insert " "))
7279 ((eolp) (insert " "))
7280 ((equal (char-after) ?\ ) (forward-char 1))))))
7282 (defun org-current-level ()
7283 "Return the level of the current entry, or nil if before the first headline.
7284 The level is the number of stars at the beginning of the headline."
7285 (save-excursion
7286 (org-with-limited-levels
7287 (if (ignore-errors (org-back-to-heading t))
7288 (funcall outline-level)))))
7290 (defun org-get-previous-line-level ()
7291 "Return the outline depth of the last headline before the current line.
7292 Returns 0 for the first headline in the buffer, and nil if before the
7293 first headline."
7294 (let ((current-level (org-current-level))
7295 (prev-level (when (> (line-number-at-pos) 1)
7296 (save-excursion
7297 (beginning-of-line 0)
7298 (org-current-level)))))
7299 (cond ((null current-level) nil) ; Before first headline
7300 ((null prev-level) 0) ; At first headline
7301 (prev-level))))
7303 (defun org-reduced-level (l)
7304 "Compute the effective level of a heading.
7305 This takes into account the setting of `org-odd-levels-only'."
7306 (cond
7307 ((zerop l) 0)
7308 (org-odd-levels-only (1+ (floor (/ l 2))))
7309 (t l)))
7311 (defun org-level-increment ()
7312 "Return the number of stars that will be added or removed at a
7313 time to headlines when structure editing, based on the value of
7314 `org-odd-levels-only'."
7315 (if org-odd-levels-only 2 1))
7317 (defun org-get-valid-level (level &optional change)
7318 "Rectify a level change under the influence of `org-odd-levels-only'
7319 LEVEL is a current level, CHANGE is by how much the level should be
7320 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7321 even level numbers will become the next higher odd number."
7322 (if org-odd-levels-only
7323 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7324 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7325 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7326 (max 1 (+ level (or change 0)))))
7328 (if (boundp 'define-obsolete-function-alias)
7329 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7330 (define-obsolete-function-alias 'org-get-legal-level
7331 'org-get-valid-level)
7332 (define-obsolete-function-alias 'org-get-legal-level
7333 'org-get-valid-level "23.1")))
7335 (defun org-promote ()
7336 "Promote the current heading higher up the tree.
7337 If the region is active in `transient-mark-mode', promote all headings
7338 in the region."
7339 (org-back-to-heading t)
7340 (let* ((level (save-match-data (funcall outline-level)))
7341 (after-change-functions (remove 'flyspell-after-change-function
7342 after-change-functions))
7343 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7344 (diff (abs (- level (length up-head) -1))))
7345 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7346 (replace-match up-head nil t)
7347 ;; Fixup tag positioning
7348 (and org-auto-align-tags (org-set-tags nil t))
7349 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7350 (run-hooks 'org-after-promote-entry-hook)))
7352 (defun org-demote ()
7353 "Demote the current heading lower down the tree.
7354 If the region is active in `transient-mark-mode', demote all headings
7355 in the region."
7356 (org-back-to-heading t)
7357 (let* ((level (save-match-data (funcall outline-level)))
7358 (after-change-functions (remove 'flyspell-after-change-function
7359 after-change-functions))
7360 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7361 (diff (abs (- level (length down-head) -1))))
7362 (replace-match down-head nil t)
7363 ;; Fixup tag positioning
7364 (and org-auto-align-tags (org-set-tags nil t))
7365 (if org-adapt-indentation (org-fixup-indentation diff))
7366 (run-hooks 'org-after-demote-entry-hook)))
7368 (defun org-cycle-level ()
7369 "Cycle the level of an empty headline through possible states.
7370 This goes first to child, then to parent, level, then up the hierarchy.
7371 After top level, it switches back to sibling level."
7372 (interactive)
7373 (let ((org-adapt-indentation nil))
7374 (when (org-point-at-end-of-empty-headline)
7375 (setq this-command 'org-cycle-level) ; Only needed for caching
7376 (let ((cur-level (org-current-level))
7377 (prev-level (org-get-previous-line-level)))
7378 (cond
7379 ;; If first headline in file, promote to top-level.
7380 ((= prev-level 0)
7381 (loop repeat (/ (- cur-level 1) (org-level-increment))
7382 do (org-do-promote)))
7383 ;; If same level as prev, demote one.
7384 ((= prev-level cur-level)
7385 (org-do-demote))
7386 ;; If parent is top-level, promote to top level if not already.
7387 ((= prev-level 1)
7388 (loop repeat (/ (- cur-level 1) (org-level-increment))
7389 do (org-do-promote)))
7390 ;; If top-level, return to prev-level.
7391 ((= cur-level 1)
7392 (loop repeat (/ (- prev-level 1) (org-level-increment))
7393 do (org-do-demote)))
7394 ;; If less than prev-level, promote one.
7395 ((< cur-level prev-level)
7396 (org-do-promote))
7397 ;; If deeper than prev-level, promote until higher than
7398 ;; prev-level.
7399 ((> cur-level prev-level)
7400 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7401 do (org-do-promote))))
7402 t))))
7404 (defun org-map-tree (fun)
7405 "Call FUN for every heading underneath the current one."
7406 (org-back-to-heading)
7407 (let ((level (funcall outline-level)))
7408 (save-excursion
7409 (funcall fun)
7410 (while (and (progn
7411 (outline-next-heading)
7412 (> (funcall outline-level) level))
7413 (not (eobp)))
7414 (funcall fun)))))
7416 (defun org-map-region (fun beg end)
7417 "Call FUN for every heading between BEG and END."
7418 (let ((org-ignore-region t))
7419 (save-excursion
7420 (setq end (copy-marker end))
7421 (goto-char beg)
7422 (if (and (re-search-forward org-outline-regexp-bol nil t)
7423 (< (point) end))
7424 (funcall fun))
7425 (while (and (progn
7426 (outline-next-heading)
7427 (< (point) end))
7428 (not (eobp)))
7429 (funcall fun)))))
7431 (defvar org-property-end-re) ; silence byte-compiler
7432 (defun org-fixup-indentation (diff)
7433 "Change the indentation in the current entry by DIFF.
7434 However, if any line in the current entry has no indentation, or if it
7435 would end up with no indentation after the change, nothing at all is done."
7436 (save-excursion
7437 (let ((end (save-excursion (outline-next-heading)
7438 (point-marker)))
7439 (prohibit (if (> diff 0)
7440 "^\\S-"
7441 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7442 col)
7443 (unless (save-excursion (end-of-line 1)
7444 (re-search-forward prohibit end t))
7445 (while (and (< (point) end)
7446 (re-search-forward "^[ \t]+" end t))
7447 (goto-char (match-end 0))
7448 (setq col (current-column))
7449 (if (< diff 0) (replace-match ""))
7450 (org-indent-to-column (+ diff col))))
7451 (move-marker end nil))))
7453 (defun org-convert-to-odd-levels ()
7454 "Convert an org-mode file with all levels allowed to one with odd levels.
7455 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7456 level 5 etc."
7457 (interactive)
7458 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7459 (let ((outline-level 'org-outline-level)
7460 (org-odd-levels-only nil) n)
7461 (save-excursion
7462 (goto-char (point-min))
7463 (while (re-search-forward "^\\*\\*+ " nil t)
7464 (setq n (- (length (match-string 0)) 2))
7465 (while (>= (setq n (1- n)) 0)
7466 (org-demote))
7467 (end-of-line 1))))))
7469 (defun org-convert-to-oddeven-levels ()
7470 "Convert an org-mode file with only odd levels to one with odd/even levels.
7471 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7472 file contains a section with an even level, conversion would
7473 destroy the structure of the file. An error is signaled in this
7474 case."
7475 (interactive)
7476 (goto-char (point-min))
7477 ;; First check if there are no even levels
7478 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7479 (org-show-context t)
7480 (error "Not all levels are odd in this file. Conversion not possible"))
7481 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7482 (let ((outline-regexp org-outline-regexp)
7483 (outline-level 'org-outline-level)
7484 (org-odd-levels-only nil) n)
7485 (save-excursion
7486 (goto-char (point-min))
7487 (while (re-search-forward "^\\*\\*+ " nil t)
7488 (setq n (/ (1- (length (match-string 0))) 2))
7489 (while (>= (setq n (1- n)) 0)
7490 (org-promote))
7491 (end-of-line 1))))))
7493 (defun org-tr-level (n)
7494 "Make N odd if required."
7495 (if org-odd-levels-only (1+ (/ n 2)) n))
7497 ;;; Vertical tree motion, cutting and pasting of subtrees
7499 (defun org-move-subtree-up (&optional arg)
7500 "Move the current subtree up past ARG headlines of the same level."
7501 (interactive "p")
7502 (org-move-subtree-down (- (prefix-numeric-value arg))))
7504 (defun org-move-subtree-down (&optional arg)
7505 "Move the current subtree down past ARG headlines of the same level."
7506 (interactive "p")
7507 (setq arg (prefix-numeric-value arg))
7508 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7509 'org-get-last-sibling))
7510 (ins-point (make-marker))
7511 (cnt (abs arg))
7512 (col (current-column))
7513 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7514 ;; Select the tree
7515 (org-back-to-heading)
7516 (setq beg0 (point))
7517 (save-excursion
7518 (setq ne-beg (org-back-over-empty-lines))
7519 (setq beg (point)))
7520 (save-match-data
7521 (save-excursion (outline-end-of-heading)
7522 (setq folded (outline-invisible-p)))
7523 (outline-end-of-subtree))
7524 (outline-next-heading)
7525 (setq ne-end (org-back-over-empty-lines))
7526 (setq end (point))
7527 (goto-char beg0)
7528 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7529 ;; include less whitespace
7530 (save-excursion
7531 (goto-char beg)
7532 (forward-line (- ne-beg ne-end))
7533 (setq beg (point))))
7534 ;; Find insertion point, with error handling
7535 (while (> cnt 0)
7536 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7537 (progn (goto-char beg0)
7538 (error "Cannot move past superior level or buffer limit")))
7539 (setq cnt (1- cnt)))
7540 (if (> arg 0)
7541 ;; Moving forward - still need to move over subtree
7542 (progn (org-end-of-subtree t t)
7543 (save-excursion
7544 (org-back-over-empty-lines)
7545 (or (bolp) (newline)))))
7546 (setq ne-ins (org-back-over-empty-lines))
7547 (move-marker ins-point (point))
7548 (setq txt (buffer-substring beg end))
7549 (org-save-markers-in-region beg end)
7550 (delete-region beg end)
7551 (org-remove-empty-overlays-at beg)
7552 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7553 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7554 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7555 (let ((bbb (point)))
7556 (insert-before-markers txt)
7557 (org-reinstall-markers-in-region bbb)
7558 (move-marker ins-point bbb))
7559 (or (bolp) (insert "\n"))
7560 (setq ins-end (point))
7561 (goto-char ins-point)
7562 (org-skip-whitespace)
7563 (when (and (< arg 0)
7564 (org-first-sibling-p)
7565 (> ne-ins ne-beg))
7566 ;; Move whitespace back to beginning
7567 (save-excursion
7568 (goto-char ins-end)
7569 (let ((kill-whole-line t))
7570 (kill-line (- ne-ins ne-beg)) (point)))
7571 (insert (make-string (- ne-ins ne-beg) ?\n)))
7572 (move-marker ins-point nil)
7573 (if folded
7574 (hide-subtree)
7575 (org-show-entry)
7576 (show-children)
7577 (org-cycle-hide-drawers 'children))
7578 (org-clean-visibility-after-subtree-move)
7579 ;; move back to the initial column we were at
7580 (move-to-column col)))
7582 (defvar org-subtree-clip ""
7583 "Clipboard for cut and paste of subtrees.
7584 This is actually only a copy of the kill, because we use the normal kill
7585 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7587 (defvar org-subtree-clip-folded nil
7588 "Was the last copied subtree folded?
7589 This is used to fold the tree back after pasting.")
7591 (defun org-cut-subtree (&optional n)
7592 "Cut the current subtree into the clipboard.
7593 With prefix arg N, cut this many sequential subtrees.
7594 This is a short-hand for marking the subtree and then cutting it."
7595 (interactive "p")
7596 (org-copy-subtree n 'cut))
7598 (defun org-copy-subtree (&optional n cut force-store-markers)
7599 "Cut the current subtree into the clipboard.
7600 With prefix arg N, cut this many sequential subtrees.
7601 This is a short-hand for marking the subtree and then copying it.
7602 If CUT is non-nil, actually cut the subtree.
7603 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7604 of some markers in the region, even if CUT is non-nil. This is
7605 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7606 (interactive "p")
7607 (let (beg end folded (beg0 (point)))
7608 (if (org-called-interactively-p 'any)
7609 (org-back-to-heading nil) ; take what looks like a subtree
7610 (org-back-to-heading t)) ; take what is really there
7611 (org-back-over-empty-lines)
7612 (setq beg (point))
7613 (skip-chars-forward " \t\r\n")
7614 (save-match-data
7615 (save-excursion (outline-end-of-heading)
7616 (setq folded (outline-invisible-p)))
7617 (condition-case nil
7618 (org-forward-same-level (1- n) t)
7619 (error nil))
7620 (org-end-of-subtree t t))
7621 (org-back-over-empty-lines)
7622 (setq end (point))
7623 (goto-char beg0)
7624 (when (> end beg)
7625 (setq org-subtree-clip-folded folded)
7626 (when (or cut force-store-markers)
7627 (org-save-markers-in-region beg end))
7628 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7629 (setq org-subtree-clip (current-kill 0))
7630 (message "%s: Subtree(s) with %d characters"
7631 (if cut "Cut" "Copied")
7632 (length org-subtree-clip)))))
7634 (defun org-paste-subtree (&optional level tree for-yank)
7635 "Paste the clipboard as a subtree, with modification of headline level.
7636 The entire subtree is promoted or demoted in order to match a new headline
7637 level.
7639 If the cursor is at the beginning of a headline, the same level as
7640 that headline is used to paste the tree
7642 If not, the new level is derived from the *visible* headings
7643 before and after the insertion point, and taken to be the inferior headline
7644 level of the two. So if the previous visible heading is level 3 and the
7645 next is level 4 (or vice versa), level 4 will be used for insertion.
7646 This makes sure that the subtree remains an independent subtree and does
7647 not swallow low level entries.
7649 You can also force a different level, either by using a numeric prefix
7650 argument, or by inserting the heading marker by hand. For example, if the
7651 cursor is after \"*****\", then the tree will be shifted to level 5.
7653 If optional TREE is given, use this text instead of the kill ring.
7655 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7656 move back over whitespace before inserting, and move point to the end of
7657 the inserted text when done."
7658 (interactive "P")
7659 (setq tree (or tree (and kill-ring (current-kill 0))))
7660 (unless (org-kill-is-subtree-p tree)
7661 (error "%s"
7662 (substitute-command-keys
7663 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7664 (org-with-limited-levels
7665 (let* ((visp (not (outline-invisible-p)))
7666 (txt tree)
7667 (^re_ "\\(\\*+\\)[ \t]*")
7668 (old-level (if (string-match org-outline-regexp-bol txt)
7669 (- (match-end 0) (match-beginning 0) 1)
7670 -1))
7671 (force-level (cond (level (prefix-numeric-value level))
7672 ((and (looking-at "[ \t]*$")
7673 (string-match
7674 "^\\*+$" (buffer-substring
7675 (point-at-bol) (point))))
7676 (- (match-end 1) (match-beginning 1)))
7677 ((and (bolp)
7678 (looking-at org-outline-regexp))
7679 (- (match-end 0) (point) 1))
7680 (t nil)))
7681 (previous-level (save-excursion
7682 (condition-case nil
7683 (progn
7684 (outline-previous-visible-heading 1)
7685 (if (looking-at ^re_)
7686 (- (match-end 0) (match-beginning 0) 1)
7688 (error 1))))
7689 (next-level (save-excursion
7690 (condition-case nil
7691 (progn
7692 (or (looking-at org-outline-regexp)
7693 (outline-next-visible-heading 1))
7694 (if (looking-at ^re_)
7695 (- (match-end 0) (match-beginning 0) 1)
7697 (error 1))))
7698 (new-level (or force-level (max previous-level next-level)))
7699 (shift (if (or (= old-level -1)
7700 (= new-level -1)
7701 (= old-level new-level))
7703 (- new-level old-level)))
7704 (delta (if (> shift 0) -1 1))
7705 (func (if (> shift 0) 'org-demote 'org-promote))
7706 (org-odd-levels-only nil)
7707 beg end newend)
7708 ;; Remove the forced level indicator
7709 (if force-level
7710 (delete-region (point-at-bol) (point)))
7711 ;; Paste
7712 (beginning-of-line (if (bolp) 1 2))
7713 (unless for-yank (org-back-over-empty-lines))
7714 (setq beg (point))
7715 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7716 (insert-before-markers txt)
7717 (unless (string-match "\n\\'" txt) (insert "\n"))
7718 (setq newend (point))
7719 (org-reinstall-markers-in-region beg)
7720 (setq end (point))
7721 (goto-char beg)
7722 (skip-chars-forward " \t\n\r")
7723 (setq beg (point))
7724 (if (and (outline-invisible-p) visp)
7725 (save-excursion (outline-show-heading)))
7726 ;; Shift if necessary
7727 (unless (= shift 0)
7728 (save-restriction
7729 (narrow-to-region beg end)
7730 (while (not (= shift 0))
7731 (org-map-region func (point-min) (point-max))
7732 (setq shift (+ delta shift)))
7733 (goto-char (point-min))
7734 (setq newend (point-max))))
7735 (when (or (org-called-interactively-p 'interactive) for-yank)
7736 (message "Clipboard pasted as level %d subtree" new-level))
7737 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7738 kill-ring
7739 (eq org-subtree-clip (current-kill 0))
7740 org-subtree-clip-folded)
7741 ;; The tree was folded before it was killed/copied
7742 (hide-subtree))
7743 (and for-yank (goto-char newend)))))
7745 (defun org-kill-is-subtree-p (&optional txt)
7746 "Check if the current kill is an outline subtree, or a set of trees.
7747 Returns nil if kill does not start with a headline, or if the first
7748 headline level is not the largest headline level in the tree.
7749 So this will actually accept several entries of equal levels as well,
7750 which is OK for `org-paste-subtree'.
7751 If optional TXT is given, check this string instead of the current kill."
7752 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7753 (re (org-get-limited-outline-regexp))
7754 (^re (concat "^" re))
7755 (start-level (and kill
7756 (string-match
7757 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7758 kill)
7759 (- (match-end 2) (match-beginning 2) 1)))
7760 (start (1+ (or (match-beginning 2) -1))))
7761 (if (not start-level)
7762 (progn
7763 nil) ;; does not even start with a heading
7764 (catch 'exit
7765 (while (setq start (string-match ^re kill (1+ start)))
7766 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7767 (throw 'exit nil)))
7768 t))))
7770 (defvar org-markers-to-move nil
7771 "Markers that should be moved with a cut-and-paste operation.
7772 Those markers are stored together with their positions relative to
7773 the start of the region.")
7775 (defun org-save-markers-in-region (beg end)
7776 "Check markers in region.
7777 If these markers are between BEG and END, record their position relative
7778 to BEG, so that after moving the block of text, we can put the markers back
7779 into place.
7780 This function gets called just before an entry or tree gets cut from the
7781 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7782 called immediately, to move the markers with the entries."
7783 (setq org-markers-to-move nil)
7784 (when (featurep 'org-clock)
7785 (org-clock-save-markers-for-cut-and-paste beg end))
7786 (when (featurep 'org-agenda)
7787 (org-agenda-save-markers-for-cut-and-paste beg end)))
7789 (defun org-check-and-save-marker (marker beg end)
7790 "Check if MARKER is between BEG and END.
7791 If yes, remember the marker and the distance to BEG."
7792 (when (and (marker-buffer marker)
7793 (equal (marker-buffer marker) (current-buffer)))
7794 (if (and (>= marker beg) (< marker end))
7795 (push (cons marker (- marker beg)) org-markers-to-move))))
7797 (defun org-reinstall-markers-in-region (beg)
7798 "Move all remembered markers to their position relative to BEG."
7799 (mapc (lambda (x)
7800 (move-marker (car x) (+ beg (cdr x))))
7801 org-markers-to-move)
7802 (setq org-markers-to-move nil))
7804 (defun org-narrow-to-subtree ()
7805 "Narrow buffer to the current subtree."
7806 (interactive)
7807 (save-excursion
7808 (save-match-data
7809 (org-with-limited-levels
7810 (narrow-to-region
7811 (progn (org-back-to-heading t) (point))
7812 (progn (org-end-of-subtree t t)
7813 (if (and (org-on-heading-p) (not (eobp))) (backward-char 1))
7814 (point)))))))
7816 (defun org-narrow-to-block ()
7817 "Narrow buffer to the current block."
7818 (interactive)
7819 (let* ((case-fold-search t)
7820 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7821 "^[ \t]*#\\+end_.*")))
7822 (if blockp
7823 (narrow-to-region (car blockp) (cdr blockp))
7824 (error "Not in a block"))))
7826 (eval-when-compile
7827 (defvar org-property-drawer-re))
7829 (defvar org-property-start-re) ;; defined below
7830 (defun org-clone-subtree-with-time-shift (n &optional shift)
7831 "Clone the task (subtree) at point N times.
7832 The clones will be inserted as siblings.
7834 In interactive use, the user will be prompted for the number of
7835 clones to be produced, and for a time SHIFT, which may be a
7836 repeater as used in time stamps, for example `+3d'.
7838 When a valid repeater is given and the entry contains any time
7839 stamps, the clones will become a sequence in time, with time
7840 stamps in the subtree shifted for each clone produced. If SHIFT
7841 is nil or the empty string, time stamps will be left alone. The
7842 ID property of the original subtree is removed.
7844 If the original subtree did contain time stamps with a repeater,
7845 the following will happen:
7846 - the repeater will be removed in each clone
7847 - an additional clone will be produced, with the current, unshifted
7848 date(s) in the entry.
7849 - the original entry will be placed *after* all the clones, with
7850 repeater intact.
7851 - the start days in the repeater in the original entry will be shifted
7852 to past the last clone.
7853 I this way you can spell out a number of instances of a repeating task,
7854 and still retain the repeater to cover future instances of the task."
7855 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7856 (let (beg end template task idprop
7857 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7858 (if (not (and (integerp n) (> n 0)))
7859 (error "Invalid number of replications %s" n))
7860 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7861 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7862 shift)))
7863 (error "Invalid shift specification %s" shift))
7864 (when doshift
7865 (setq shift-n (string-to-number (match-string 1 shift))
7866 shift-what (cdr (assoc (match-string 2 shift)
7867 '(("d" . day) ("w" . week)
7868 ("m" . month) ("y" . year))))))
7869 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7870 (setq nmin 1 nmax n)
7871 (org-back-to-heading t)
7872 (setq beg (point))
7873 (setq idprop (org-entry-get nil "ID"))
7874 (org-end-of-subtree t t)
7875 (or (bolp) (insert "\n"))
7876 (setq end (point))
7877 (setq template (buffer-substring beg end))
7878 ;; Remove clocks and empty drawers
7879 (with-temp-buffer
7880 (insert template)
7881 (goto-char (point-min))
7882 (while (re-search-forward
7883 "^[ \t]*CLOCK:.*$" (save-excursion (org-end-of-subtree t t)) t)
7884 (replace-match "")
7885 (kill-whole-line))
7886 (goto-char (point-min))
7887 (while (re-search-forward
7888 (concat "^[ \t]*:" (regexp-opt org-drawers) ":[ \t]*$") nil t)
7889 (mapc (lambda(d) (org-remove-empty-drawer-at d (point))) org-drawers))
7890 (setq template (buffer-substring (point-min) (point-max))))
7891 (when (and doshift
7892 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7893 (delete-region beg end)
7894 (setq end beg)
7895 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7896 (goto-char end)
7897 (loop for n from nmin to nmax do
7898 ;; prepare clone
7899 (with-temp-buffer
7900 (insert template)
7901 (org-mode)
7902 (goto-char (point-min))
7903 (and idprop (if org-clone-delete-id
7904 (org-entry-delete nil "ID")
7905 (org-id-get-create t)))
7906 (while (re-search-forward org-property-start-re nil t)
7907 (org-remove-empty-drawer-at "PROPERTIES" (point)))
7908 (goto-char (point-min))
7909 (when doshift
7910 (while (re-search-forward org-ts-regexp-both nil t)
7911 (org-timestamp-change (* n shift-n) shift-what))
7912 (unless (= n n-no-remove)
7913 (goto-char (point-min))
7914 (while (re-search-forward org-ts-regexp nil t)
7915 (save-excursion
7916 (goto-char (match-beginning 0))
7917 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7918 (delete-region (match-beginning 1) (match-end 1)))))))
7919 (setq task (buffer-string)))
7920 (insert task))
7921 (goto-char beg)))
7923 ;;; Outline Sorting
7925 (defun org-sort (with-case)
7926 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
7927 Optional argument WITH-CASE means sort case-sensitively.
7928 With a double prefix argument, also remove duplicate entries."
7929 (interactive "P")
7930 (cond
7931 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
7932 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
7934 (org-call-with-arg 'org-sort-entries with-case))))
7936 (defun org-sort-remove-invisible (s)
7937 (remove-text-properties 0 (length s) org-rm-props s)
7938 (while (string-match org-bracket-link-regexp s)
7939 (setq s (replace-match (if (match-end 2)
7940 (match-string 3 s)
7941 (match-string 1 s)) t t s)))
7944 (defvar org-priority-regexp) ; defined later in the file
7946 (defvar org-after-sorting-entries-or-items-hook nil
7947 "Hook that is run after a bunch of entries or items have been sorted.
7948 When children are sorted, the cursor is in the parent line when this
7949 hook gets called. When a region or a plain list is sorted, the cursor
7950 will be in the first entry of the sorted region/list.")
7952 (defun org-sort-entries
7953 (&optional with-case sorting-type getkey-func compare-func property)
7954 "Sort entries on a certain level of an outline tree.
7955 If there is an active region, the entries in the region are sorted.
7956 Else, if the cursor is before the first entry, sort the top-level items.
7957 Else, the children of the entry at point are sorted.
7959 Sorting can be alphabetically, numerically, by date/time as given by
7960 a time stamp, by a property or by priority.
7962 The command prompts for the sorting type unless it has been given to the
7963 function through the SORTING-TYPE argument, which needs to be a character,
7964 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7965 precise meaning of each character:
7967 n Numerically, by converting the beginning of the entry/item to a number.
7968 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7969 t By date/time, either the first active time stamp in the entry, or, if
7970 none exist, by the first inactive one.
7971 s By the scheduled date/time.
7972 d By deadline date/time.
7973 c By creation time, which is assumed to be the first inactive time stamp
7974 at the beginning of a line.
7975 p By priority according to the cookie.
7976 r By the value of a property.
7978 Capital letters will reverse the sort order.
7980 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7981 called with point at the beginning of the record. It must return either
7982 a string or a number that should serve as the sorting key for that record.
7984 Comparing entries ignores case by default. However, with an optional argument
7985 WITH-CASE, the sorting considers case as well."
7986 (interactive "P")
7987 (let ((case-func (if with-case 'identity 'downcase))
7988 start beg end stars re re2
7989 txt what tmp)
7990 ;; Find beginning and end of region to sort
7991 (cond
7992 ((org-region-active-p)
7993 ;; we will sort the region
7994 (setq end (region-end)
7995 what "region")
7996 (goto-char (region-beginning))
7997 (if (not (org-on-heading-p)) (outline-next-heading))
7998 (setq start (point)))
7999 ((or (org-on-heading-p)
8000 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8001 ;; we will sort the children of the current headline
8002 (org-back-to-heading)
8003 (setq start (point)
8004 end (progn (org-end-of-subtree t t)
8005 (or (bolp) (insert "\n"))
8006 (org-back-over-empty-lines)
8007 (point))
8008 what "children")
8009 (goto-char start)
8010 (show-subtree)
8011 (outline-next-heading))
8013 ;; we will sort the top-level entries in this file
8014 (goto-char (point-min))
8015 (or (org-on-heading-p) (outline-next-heading))
8016 (setq start (point))
8017 (goto-char (point-max))
8018 (beginning-of-line 1)
8019 (when (looking-at ".*?\\S-")
8020 ;; File ends in a non-white line
8021 (end-of-line 1)
8022 (insert "\n"))
8023 (setq end (point-max))
8024 (setq what "top-level")
8025 (goto-char start)
8026 (show-all)))
8028 (setq beg (point))
8029 (if (>= beg end) (error "Nothing to sort"))
8031 (looking-at "\\(\\*+\\)")
8032 (setq stars (match-string 1)
8033 re (concat "^" (regexp-quote stars) " +")
8034 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8035 txt (buffer-substring beg end))
8036 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8037 (if (and (not (equal stars "*")) (string-match re2 txt))
8038 (error "Region to sort contains a level above the first entry"))
8040 (unless sorting-type
8041 (message
8042 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8043 [t]ime [s]cheduled [d]eadline [c]reated
8044 A/N/T/S/D/C/P/O/F means reversed:"
8045 what)
8046 (setq sorting-type (read-char-exclusive))
8048 (and (= (downcase sorting-type) ?f)
8049 (setq getkey-func
8050 (org-icompleting-read "Sort using function: "
8051 obarray 'fboundp t nil nil))
8052 (setq getkey-func (intern getkey-func)))
8054 (and (= (downcase sorting-type) ?r)
8055 (setq property
8056 (org-icompleting-read "Property: "
8057 (mapcar 'list (org-buffer-property-keys t))
8058 nil t))))
8060 (message "Sorting entries...")
8062 (save-restriction
8063 (narrow-to-region start end)
8064 (let ((dcst (downcase sorting-type))
8065 (case-fold-search nil)
8066 (now (current-time)))
8067 (sort-subr
8068 (/= dcst sorting-type)
8069 ;; This function moves to the beginning character of the "record" to
8070 ;; be sorted.
8071 (lambda nil
8072 (if (re-search-forward re nil t)
8073 (goto-char (match-beginning 0))
8074 (goto-char (point-max))))
8075 ;; This function moves to the last character of the "record" being
8076 ;; sorted.
8077 (lambda nil
8078 (save-match-data
8079 (condition-case nil
8080 (outline-forward-same-level 1)
8081 (error
8082 (goto-char (point-max))))))
8083 ;; This function returns the value that gets sorted against.
8084 (lambda nil
8085 (cond
8086 ((= dcst ?n)
8087 (if (looking-at org-complex-heading-regexp)
8088 (string-to-number (match-string 4))
8089 nil))
8090 ((= dcst ?a)
8091 (if (looking-at org-complex-heading-regexp)
8092 (funcall case-func (match-string 4))
8093 nil))
8094 ((= dcst ?t)
8095 (let ((end (save-excursion (outline-next-heading) (point))))
8096 (if (or (re-search-forward org-ts-regexp end t)
8097 (re-search-forward org-ts-regexp-both end t))
8098 (org-time-string-to-seconds (match-string 0))
8099 (org-float-time now))))
8100 ((= dcst ?c)
8101 (let ((end (save-excursion (outline-next-heading) (point))))
8102 (if (re-search-forward
8103 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8104 end t)
8105 (org-time-string-to-seconds (match-string 0))
8106 (org-float-time now))))
8107 ((= dcst ?s)
8108 (let ((end (save-excursion (outline-next-heading) (point))))
8109 (if (re-search-forward org-scheduled-time-regexp end t)
8110 (org-time-string-to-seconds (match-string 1))
8111 (org-float-time now))))
8112 ((= dcst ?d)
8113 (let ((end (save-excursion (outline-next-heading) (point))))
8114 (if (re-search-forward org-deadline-time-regexp end t)
8115 (org-time-string-to-seconds (match-string 1))
8116 (org-float-time now))))
8117 ((= dcst ?p)
8118 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8119 (string-to-char (match-string 2))
8120 org-default-priority))
8121 ((= dcst ?r)
8122 (or (org-entry-get nil property) ""))
8123 ((= dcst ?o)
8124 (if (looking-at org-complex-heading-regexp)
8125 (- 9999 (length (member (match-string 2)
8126 org-todo-keywords-1)))))
8127 ((= dcst ?f)
8128 (if getkey-func
8129 (progn
8130 (setq tmp (funcall getkey-func))
8131 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8132 tmp)
8133 (error "Invalid key function `%s'" getkey-func)))
8134 (t (error "Invalid sorting type `%c'" sorting-type))))
8136 (cond
8137 ((= dcst ?a) 'string<)
8138 ((= dcst ?f) compare-func)
8139 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8140 (t nil)))))
8141 (run-hooks 'org-after-sorting-entries-or-items-hook)
8142 (message "Sorting entries...done")))
8144 (defun org-do-sort (table what &optional with-case sorting-type)
8145 "Sort TABLE of WHAT according to SORTING-TYPE.
8146 The user will be prompted for the SORTING-TYPE if the call to this
8147 function does not specify it. WHAT is only for the prompt, to indicate
8148 what is being sorted. The sorting key will be extracted from
8149 the car of the elements of the table.
8150 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8151 (unless sorting-type
8152 (message
8153 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8154 what)
8155 (setq sorting-type (read-char-exclusive)))
8156 (let ((dcst (downcase sorting-type))
8157 extractfun comparefun)
8158 ;; Define the appropriate functions
8159 (cond
8160 ((= dcst ?n)
8161 (setq extractfun 'string-to-number
8162 comparefun (if (= dcst sorting-type) '< '>)))
8163 ((= dcst ?a)
8164 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8165 (lambda(x) (downcase (org-sort-remove-invisible x))))
8166 comparefun (if (= dcst sorting-type)
8167 'string<
8168 (lambda (a b) (and (not (string< a b))
8169 (not (string= a b)))))))
8170 ((= dcst ?t)
8171 (setq extractfun
8172 (lambda (x)
8173 (if (or (string-match org-ts-regexp x)
8174 (string-match org-ts-regexp-both x))
8175 (org-float-time
8176 (org-time-string-to-time (match-string 0 x)))
8178 comparefun (if (= dcst sorting-type) '< '>)))
8179 (t (error "Invalid sorting type `%c'" sorting-type)))
8181 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8182 table)
8183 (lambda (a b) (funcall comparefun (car a) (car b))))))
8186 ;;; The orgstruct minor mode
8188 ;; Define a minor mode which can be used in other modes in order to
8189 ;; integrate the org-mode structure editing commands.
8191 ;; This is really a hack, because the org-mode structure commands use
8192 ;; keys which normally belong to the major mode. Here is how it
8193 ;; works: The minor mode defines all the keys necessary to operate the
8194 ;; structure commands, but wraps the commands into a function which
8195 ;; tests if the cursor is currently at a headline or a plain list
8196 ;; item. If that is the case, the structure command is used,
8197 ;; temporarily setting many Org-mode variables like regular
8198 ;; expressions for filling etc. However, when any of those keys is
8199 ;; used at a different location, function uses `key-binding' to look
8200 ;; up if the key has an associated command in another currently active
8201 ;; keymap (minor modes, major mode, global), and executes that
8202 ;; command. There might be problems if any of the keys is otherwise
8203 ;; used as a prefix key.
8205 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8206 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8207 ;; addresses this by checking explicitly for both bindings.
8209 (defvar orgstruct-mode-map (make-sparse-keymap)
8210 "Keymap for the minor `orgstruct-mode'.")
8212 (defvar org-local-vars nil
8213 "List of local variables, for use by `orgstruct-mode'.")
8215 ;;;###autoload
8216 (define-minor-mode orgstruct-mode
8217 "Toggle the minor mode `orgstruct-mode'.
8218 This mode is for using Org-mode structure commands in other
8219 modes. The following keys behave as if Org-mode were active, if
8220 the cursor is on a headline, or on a plain list item (both as
8221 defined by Org-mode).
8223 M-up Move entry/item up
8224 M-down Move entry/item down
8225 M-left Promote
8226 M-right Demote
8227 M-S-up Move entry/item up
8228 M-S-down Move entry/item down
8229 M-S-left Promote subtree
8230 M-S-right Demote subtree
8231 M-q Fill paragraph and items like in Org-mode
8232 C-c ^ Sort entries
8233 C-c - Cycle list bullet
8234 TAB Cycle item visibility
8235 M-RET Insert new heading/item
8236 S-M-RET Insert new TODO heading / Checkbox item
8237 C-c C-c Set tags / toggle checkbox"
8238 nil " OrgStruct" nil
8239 (org-load-modules-maybe)
8240 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8242 ;;;###autoload
8243 (defun turn-on-orgstruct ()
8244 "Unconditionally turn on `orgstruct-mode'."
8245 (orgstruct-mode 1))
8247 (defun orgstruct++-mode (&optional arg)
8248 "Toggle `orgstruct-mode', the enhanced version of it.
8249 In addition to setting orgstruct-mode, this also exports all indentation
8250 and autofilling variables from org-mode into the buffer. It will also
8251 recognize item context in multiline items.
8252 Note that turning off orgstruct-mode will *not* remove the
8253 indentation/paragraph settings. This can only be done by refreshing the
8254 major mode, for example with \\[normal-mode]."
8255 (interactive "P")
8256 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8257 (if (< arg 1)
8258 (orgstruct-mode -1)
8259 (orgstruct-mode 1)
8260 (let (var val)
8261 (mapc
8262 (lambda (x)
8263 (when (string-match
8264 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8265 (symbol-name (car x)))
8266 (setq var (car x) val (nth 1 x))
8267 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8268 org-local-vars)
8269 (org-set-local 'orgstruct-is-++ t))))
8271 (defvar orgstruct-is-++ nil
8272 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8273 (make-variable-buffer-local 'orgstruct-is-++)
8275 ;;;###autoload
8276 (defun turn-on-orgstruct++ ()
8277 "Unconditionally turn on `orgstruct++-mode'."
8278 (orgstruct++-mode 1))
8280 (defun orgstruct-error ()
8281 "Error when there is no default binding for a structure key."
8282 (interactive)
8283 (error "This key has no function outside structure elements"))
8285 (defun orgstruct-setup ()
8286 "Setup orgstruct keymaps."
8287 (let ((nfunc 0)
8288 (bindings
8289 (list
8290 '([(meta up)] org-metaup)
8291 '([(meta down)] org-metadown)
8292 '([(meta left)] org-metaleft)
8293 '([(meta right)] org-metaright)
8294 '([(meta shift up)] org-shiftmetaup)
8295 '([(meta shift down)] org-shiftmetadown)
8296 '([(meta shift left)] org-shiftmetaleft)
8297 '([(meta shift right)] org-shiftmetaright)
8298 '([?\e (up)] org-metaup)
8299 '([?\e (down)] org-metadown)
8300 '([?\e (left)] org-metaleft)
8301 '([?\e (right)] org-metaright)
8302 '([?\e (shift up)] org-shiftmetaup)
8303 '([?\e (shift down)] org-shiftmetadown)
8304 '([?\e (shift left)] org-shiftmetaleft)
8305 '([?\e (shift right)] org-shiftmetaright)
8306 '([(shift up)] org-shiftup)
8307 '([(shift down)] org-shiftdown)
8308 '([(shift left)] org-shiftleft)
8309 '([(shift right)] org-shiftright)
8310 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8311 '("\M-q" fill-paragraph)
8312 '("\C-c^" org-sort)
8313 '("\C-c-" org-cycle-list-bullet)))
8314 elt key fun cmd)
8315 (while (setq elt (pop bindings))
8316 (setq nfunc (1+ nfunc))
8317 (setq key (org-key (car elt))
8318 fun (nth 1 elt)
8319 cmd (orgstruct-make-binding fun nfunc key))
8320 (org-defkey orgstruct-mode-map key cmd))
8322 ;; Special treatment needed for TAB and RET
8323 (org-defkey orgstruct-mode-map [(tab)]
8324 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8325 (org-defkey orgstruct-mode-map "\C-i"
8326 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8328 (org-defkey orgstruct-mode-map "\M-\C-m"
8329 (orgstruct-make-binding 'org-insert-heading 105
8330 "\M-\C-m" [(meta return)]))
8331 (org-defkey orgstruct-mode-map [(meta return)]
8332 (orgstruct-make-binding 'org-insert-heading 106
8333 [(meta return)] "\M-\C-m"))
8335 (org-defkey orgstruct-mode-map [(shift meta return)]
8336 (orgstruct-make-binding 'org-insert-todo-heading 107
8337 [(meta return)] "\M-\C-m"))
8339 (org-defkey orgstruct-mode-map "\e\C-m"
8340 (orgstruct-make-binding 'org-insert-heading 108
8341 "\e\C-m" [?\e (return)]))
8342 (org-defkey orgstruct-mode-map [?\e (return)]
8343 (orgstruct-make-binding 'org-insert-heading 109
8344 [?\e (return)] "\e\C-m"))
8345 (org-defkey orgstruct-mode-map [?\e (shift return)]
8346 (orgstruct-make-binding 'org-insert-todo-heading 110
8347 [?\e (return)] "\e\C-m"))
8349 (unless org-local-vars
8350 (setq org-local-vars (org-get-local-variables)))
8354 (defun orgstruct-make-binding (fun n &rest keys)
8355 "Create a function for binding in the structure minor mode.
8356 FUN is the command to call inside a table. N is used to create a unique
8357 command name. KEYS are keys that should be checked in for a command
8358 to execute outside of tables."
8359 (eval
8360 (list 'defun
8361 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8362 '(arg)
8363 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8364 "Outside of structure, run the binding of `"
8365 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8366 "'.")
8367 '(interactive "p")
8368 (list 'if
8369 `(org-context-p 'headline 'item
8370 (and orgstruct-is-++
8371 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8372 'item-body))
8373 (list 'org-run-like-in-org-mode (list 'quote fun))
8374 (list 'let '(orgstruct-mode)
8375 (list 'call-interactively
8376 (append '(or)
8377 (mapcar (lambda (k)
8378 (list 'key-binding k))
8379 keys)
8380 '('orgstruct-error))))))))
8382 (defun org-context-p (&rest contexts)
8383 "Check if local context is any of CONTEXTS.
8384 Possible values in the list of contexts are `table', `headline', and `item'."
8385 (let ((pos (point)))
8386 (goto-char (point-at-bol))
8387 (prog1 (or (and (memq 'table contexts)
8388 (looking-at "[ \t]*|"))
8389 (and (memq 'headline contexts)
8390 (looking-at org-outline-regexp))
8391 (and (memq 'item contexts)
8392 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8393 (and (memq 'item-body contexts)
8394 (org-in-item-p)))
8395 (goto-char pos))))
8397 (defun org-get-local-variables ()
8398 "Return a list of all local variables in an org-mode buffer."
8399 (let (varlist)
8400 (with-current-buffer (get-buffer-create "*Org tmp*")
8401 (erase-buffer)
8402 (org-mode)
8403 (setq varlist (buffer-local-variables)))
8404 (kill-buffer "*Org tmp*")
8405 (delq nil
8406 (mapcar
8407 (lambda (x)
8408 (setq x
8409 (if (symbolp x)
8410 (list x)
8411 (list (car x) (list 'quote (cdr x)))))
8412 (if (string-match
8413 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8414 (symbol-name (car x)))
8415 x nil))
8416 varlist))))
8418 (defun org-clone-local-variables (from-buffer &optional regexp)
8419 "Clone local variables from FROM-BUFFER.
8420 Optional argument REGEXP selects variables to clone."
8421 (mapc
8422 (lambda (pair)
8423 (and (symbolp (car pair))
8424 (or (null regexp)
8425 (string-match regexp (symbol-name (car pair))))
8426 (set (make-local-variable (car pair))
8427 (cdr pair))))
8428 (buffer-local-variables from-buffer)))
8430 ;;;###autoload
8431 (defun org-run-like-in-org-mode (cmd)
8432 "Run a command, pretending that the current buffer is in Org-mode.
8433 This will temporarily bind local variables that are typically bound in
8434 Org-mode to the values they have in Org-mode, and then interactively
8435 call CMD."
8436 (org-load-modules-maybe)
8437 (unless org-local-vars
8438 (setq org-local-vars (org-get-local-variables)))
8439 (eval (list 'let org-local-vars
8440 (list 'call-interactively (list 'quote cmd)))))
8442 ;;;; Archiving
8444 (defun org-get-category (&optional pos force-refresh)
8445 "Get the category applying to position POS."
8446 (if force-refresh (org-refresh-category-properties))
8447 (let ((pos (or pos (point))))
8448 (or (get-text-property pos 'org-category)
8449 (progn (org-refresh-category-properties)
8450 (get-text-property pos 'org-category)))))
8452 (defun org-refresh-category-properties ()
8453 "Refresh category text properties in the buffer."
8454 (let ((def-cat (cond
8455 ((null org-category)
8456 (if buffer-file-name
8457 (file-name-sans-extension
8458 (file-name-nondirectory buffer-file-name))
8459 "???"))
8460 ((symbolp org-category) (symbol-name org-category))
8461 (t org-category)))
8462 beg end cat pos optionp)
8463 (org-unmodified
8464 (save-excursion
8465 (save-restriction
8466 (widen)
8467 (goto-char (point-min))
8468 (put-text-property (point) (point-max) 'org-category def-cat)
8469 (while (re-search-forward
8470 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8471 (setq pos (match-end 0)
8472 optionp (equal (char-after (match-beginning 0)) ?#)
8473 cat (org-trim (match-string 2)))
8474 (if optionp
8475 (setq beg (point-at-bol) end (point-max))
8476 (org-back-to-heading t)
8477 (setq beg (point) end (org-end-of-subtree t t)))
8478 (put-text-property beg end 'org-category cat)
8479 (put-text-property beg end 'org-category-position beg)
8480 (goto-char pos)))))))
8483 ;;;; Link Stuff
8485 ;;; Link abbreviations
8487 (defun org-link-expand-abbrev (link)
8488 "Apply replacements as defined in `org-link-abbrev-alist."
8489 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8490 (let* ((key (match-string 1 link))
8491 (as (or (assoc key org-link-abbrev-alist-local)
8492 (assoc key org-link-abbrev-alist)))
8493 (tag (and (match-end 2) (match-string 3 link)))
8494 rpl)
8495 (if (not as)
8496 link
8497 (setq rpl (cdr as))
8498 (cond
8499 ((symbolp rpl) (funcall rpl tag))
8500 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8501 ((string-match "%h" rpl)
8502 (replace-match (url-hexify-string (or tag "")) t t rpl))
8503 (t (concat rpl tag)))))
8504 link))
8506 ;;; Storing and inserting links
8508 (defvar org-insert-link-history nil
8509 "Minibuffer history for links inserted with `org-insert-link'.")
8511 (defvar org-stored-links nil
8512 "Contains the links stored with `org-store-link'.")
8514 (defvar org-store-link-plist nil
8515 "Plist with info about the most recently link created with `org-store-link'.")
8517 (defvar org-link-protocols nil
8518 "Link protocols added to Org-mode using `org-add-link-type'.")
8520 (defvar org-store-link-functions nil
8521 "List of functions that are called to create and store a link.
8522 Each function will be called in turn until one returns a non-nil
8523 value. Each function should check if it is responsible for creating
8524 this link (for example by looking at the major mode).
8525 If not, it must exit and return nil.
8526 If yes, it should return a non-nil value after a calling
8527 `org-store-link-props' with a list of properties and values.
8528 Special properties are:
8530 :type The link prefix, like \"http\". This must be given.
8531 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8532 This is obligatory as well.
8533 :description Optional default description for the second pair
8534 of brackets in an Org-mode link. The user can still change
8535 this when inserting this link into an Org-mode buffer.
8537 In addition to these, any additional properties can be specified
8538 and then used in remember templates.")
8540 (defun org-add-link-type (type &optional follow export)
8541 "Add TYPE to the list of `org-link-types'.
8542 Re-compute all regular expressions depending on `org-link-types'
8544 FOLLOW and EXPORT are two functions.
8546 FOLLOW should take the link path as the single argument and do whatever
8547 is necessary to follow the link, for example find a file or display
8548 a mail message.
8550 EXPORT should format the link path for export to one of the export formats.
8551 It should be a function accepting three arguments:
8553 path the path of the link, the text after the prefix (like \"http:\")
8554 desc the description of the link, if any, or a description added by
8555 org-export-normalize-links if there is none
8556 format the export format, a symbol like `html' or `latex' or `ascii'..
8558 The function may use the FORMAT information to return different values
8559 depending on the format. The return value will be put literally into
8560 the exported file. If the return value is nil, this means Org should
8561 do what it normally does with links which do not have EXPORT defined.
8563 Org-mode has a built-in default for exporting links. If you are happy with
8564 this default, there is no need to define an export function for the link
8565 type. For a simple example of an export function, see `org-bbdb.el'."
8566 (add-to-list 'org-link-types type t)
8567 (org-make-link-regexps)
8568 (if (assoc type org-link-protocols)
8569 (setcdr (assoc type org-link-protocols) (list follow export))
8570 (push (list type follow export) org-link-protocols)))
8572 (defvar org-agenda-buffer-name)
8574 ;;;###autoload
8575 (defun org-store-link (arg)
8576 "\\<org-mode-map>Store an org-link to the current location.
8577 This link is added to `org-stored-links' and can later be inserted
8578 into an org-buffer with \\[org-insert-link].
8580 For some link types, a prefix arg is interpreted:
8581 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8582 For file links, arg negates `org-context-in-file-links'."
8583 (interactive "P")
8584 (org-load-modules-maybe)
8585 (setq org-store-link-plist nil) ; reset
8586 (org-with-limited-levels
8587 (let (link cpltxt desc description search txt custom-id agenda-link)
8588 (cond
8590 ((run-hook-with-args-until-success 'org-store-link-functions)
8591 (setq link (plist-get org-store-link-plist :link)
8592 desc (or (plist-get org-store-link-plist :description) link)))
8594 ((equal (buffer-name) "*Org Edit Src Example*")
8595 (let (label gc)
8596 (while (or (not label)
8597 (save-excursion
8598 (save-restriction
8599 (widen)
8600 (goto-char (point-min))
8601 (re-search-forward
8602 (regexp-quote (format org-coderef-label-format label))
8603 nil t))))
8604 (when label (message "Label exists already") (sit-for 2))
8605 (setq label (read-string "Code line label: " label)))
8606 (end-of-line 1)
8607 (setq link (format org-coderef-label-format label))
8608 (setq gc (- 79 (length link)))
8609 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8610 (insert link)
8611 (setq link (concat "(" label ")") desc nil)))
8613 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8614 ;; We are in the agenda, link to referenced location
8615 (let ((m (or (get-text-property (point) 'org-hd-marker)
8616 (get-text-property (point) 'org-marker))))
8617 (when m
8618 (org-with-point-at m
8619 (setq agenda-link
8620 (if (org-called-interactively-p 'any)
8621 (call-interactively 'org-store-link)
8622 (org-store-link nil)))))))
8624 ((eq major-mode 'calendar-mode)
8625 (let ((cd (calendar-cursor-to-date)))
8626 (setq link
8627 (format-time-string
8628 (car org-time-stamp-formats)
8629 (apply 'encode-time
8630 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8631 nil nil nil))))
8632 (org-store-link-props :type "calendar" :date cd)))
8634 ((eq major-mode 'w3-mode)
8635 (setq cpltxt (if (and (buffer-name)
8636 (not (string-match "Untitled" (buffer-name))))
8637 (buffer-name)
8638 (url-view-url t))
8639 link (org-make-link (url-view-url t)))
8640 (org-store-link-props :type "w3" :url (url-view-url t)))
8642 ((eq major-mode 'w3m-mode)
8643 (setq cpltxt (or w3m-current-title w3m-current-url)
8644 link (org-make-link w3m-current-url))
8645 (org-store-link-props :type "w3m" :url (url-view-url t)))
8647 ((setq search (run-hook-with-args-until-success
8648 'org-create-file-search-functions))
8649 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8650 "::" search))
8651 (setq cpltxt (or description link)))
8653 ((eq major-mode 'image-mode)
8654 (setq cpltxt (concat "file:"
8655 (abbreviate-file-name buffer-file-name))
8656 link (org-make-link cpltxt))
8657 (org-store-link-props :type "image" :file buffer-file-name))
8659 ((eq major-mode 'dired-mode)
8660 ;; link to the file in the current line
8661 (let ((file (dired-get-filename nil t)))
8662 (setq file (if file
8663 (abbreviate-file-name
8664 (expand-file-name (dired-get-filename nil t)))
8665 ;; otherwise, no file so use current directory.
8666 default-directory))
8667 (setq cpltxt (concat "file:" file)
8668 link (org-make-link cpltxt))))
8670 ((and (buffer-file-name (buffer-base-buffer)) (eq major-mode 'org-mode))
8671 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8672 (cond
8673 ((org-in-regexp "<<\\(.*?\\)>>")
8674 (setq cpltxt
8675 (concat "file:"
8676 (abbreviate-file-name
8677 (buffer-file-name (buffer-base-buffer)))
8678 "::" (match-string 1))
8679 link (org-make-link cpltxt)))
8680 ((and (featurep 'org-id)
8681 (or (eq org-link-to-org-use-id t)
8682 (and (eq org-link-to-org-use-id 'create-if-interactive)
8683 (org-called-interactively-p 'any))
8684 (and (eq org-link-to-org-use-id
8685 'create-if-interactive-and-no-custom-id)
8686 (org-called-interactively-p 'any)
8687 (not custom-id))
8688 (and org-link-to-org-use-id
8689 (org-entry-get nil "ID"))))
8690 ;; We can make a link using the ID.
8691 (setq link (condition-case nil
8692 (prog1 (org-id-store-link)
8693 (setq desc (plist-get org-store-link-plist
8694 :description)))
8695 (error
8696 ;; probably before first headline, link to file only
8697 (concat "file:"
8698 (abbreviate-file-name
8699 (buffer-file-name (buffer-base-buffer))))))))
8701 ;; Just link to current headline
8702 (setq cpltxt (concat "file:"
8703 (abbreviate-file-name
8704 (buffer-file-name (buffer-base-buffer)))))
8705 ;; Add a context search string
8706 (when (org-xor org-context-in-file-links arg)
8707 (setq txt (cond
8708 ((org-on-heading-p) nil)
8709 ((org-region-active-p)
8710 (buffer-substring (region-beginning) (region-end)))
8711 (t nil)))
8712 (when (or (null txt) (string-match "\\S-" txt))
8713 (setq cpltxt
8714 (concat cpltxt "::"
8715 (condition-case nil
8716 (org-make-org-heading-search-string txt)
8717 (error "")))
8718 desc (or (nth 4 (ignore-errors
8719 (org-heading-components))) "NONE"))))
8720 (if (string-match "::\\'" cpltxt)
8721 (setq cpltxt (substring cpltxt 0 -2)))
8722 (setq link (org-make-link cpltxt)))))
8724 ((buffer-file-name (buffer-base-buffer))
8725 ;; Just link to this file here.
8726 (setq cpltxt (concat "file:"
8727 (abbreviate-file-name
8728 (buffer-file-name (buffer-base-buffer)))))
8729 ;; Add a context string
8730 (when (org-xor org-context-in-file-links arg)
8731 (setq txt (if (org-region-active-p)
8732 (buffer-substring (region-beginning) (region-end))
8733 (buffer-substring (point-at-bol) (point-at-eol))))
8734 ;; Only use search option if there is some text.
8735 (when (string-match "\\S-" txt)
8736 (setq cpltxt
8737 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8738 desc "NONE")))
8739 (setq link (org-make-link cpltxt)))
8741 ((org-called-interactively-p 'interactive)
8742 (error "Cannot link to a buffer which is not visiting a file"))
8744 (t (setq link nil)))
8746 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8747 (setq link (or link cpltxt)
8748 desc (or desc cpltxt))
8749 (if (equal desc "NONE") (setq desc nil))
8751 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8752 (progn
8753 (setq org-stored-links
8754 (cons (list link desc) org-stored-links))
8755 (message "Stored: %s" (or desc link))
8756 (when custom-id
8757 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8758 "::#" custom-id))
8759 (setq org-stored-links
8760 (cons (list link desc) org-stored-links))))
8761 (or agenda-link (and link (org-make-link-string link desc)))))))
8763 (defun org-store-link-props (&rest plist)
8764 "Store link properties, extract names and addresses."
8765 (let (x adr)
8766 (when (setq x (plist-get plist :from))
8767 (setq adr (mail-extract-address-components x))
8768 (setq plist (plist-put plist :fromname (car adr)))
8769 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8770 (when (setq x (plist-get plist :to))
8771 (setq adr (mail-extract-address-components x))
8772 (setq plist (plist-put plist :toname (car adr)))
8773 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8774 (let ((from (plist-get plist :from))
8775 (to (plist-get plist :to)))
8776 (when (and from to org-from-is-user-regexp)
8777 (setq plist
8778 (plist-put plist :fromto
8779 (if (string-match org-from-is-user-regexp from)
8780 (concat "to %t")
8781 (concat "from %f"))))))
8782 (setq org-store-link-plist plist))
8784 (defun org-add-link-props (&rest plist)
8785 "Add these properties to the link property list."
8786 (let (key value)
8787 (while plist
8788 (setq key (pop plist) value (pop plist))
8789 (setq org-store-link-plist
8790 (plist-put org-store-link-plist key value)))))
8792 (defun org-email-link-description (&optional fmt)
8793 "Return the description part of an email link.
8794 This takes information from `org-store-link-plist' and formats it
8795 according to FMT (default from `org-email-link-description-format')."
8796 (setq fmt (or fmt org-email-link-description-format))
8797 (let* ((p org-store-link-plist)
8798 (to (plist-get p :toaddress))
8799 (from (plist-get p :fromaddress))
8800 (table
8801 (list
8802 (cons "%c" (plist-get p :fromto))
8803 (cons "%F" (plist-get p :from))
8804 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8805 (cons "%T" (plist-get p :to))
8806 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8807 (cons "%s" (plist-get p :subject))
8808 (cons "%d" (plist-get p :date))
8809 (cons "%m" (plist-get p :message-id)))))
8810 (when (string-match "%c" fmt)
8811 ;; Check if the user wrote this message
8812 (if (and org-from-is-user-regexp from to
8813 (save-match-data (string-match org-from-is-user-regexp from)))
8814 (setq fmt (replace-match "to %t" t t fmt))
8815 (setq fmt (replace-match "from %f" t t fmt))))
8816 (org-replace-escapes fmt table)))
8818 (defun org-make-org-heading-search-string (&optional string heading)
8819 "Make search string for STRING or current headline."
8820 (interactive)
8821 (let ((s (or string (org-get-heading)))
8822 (lines org-context-in-file-links))
8823 (unless (and string (not heading))
8824 ;; We are using a headline, clean up garbage in there.
8825 (if (string-match org-todo-regexp s)
8826 (setq s (replace-match "" t t s)))
8827 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8828 (setq s (replace-match "" t t s)))
8829 (setq s (org-trim s))
8830 (if (string-match (concat "^\\(" org-quote-string "\\|"
8831 org-comment-string "\\)") s)
8832 (setq s (replace-match "" t t s)))
8833 (while (string-match org-ts-regexp s)
8834 (setq s (replace-match "" t t s))))
8835 (or string (setq s (concat "*" s))) ; Add * for headlines
8836 (when (and string (integerp lines) (> lines 0))
8837 (let ((slines (org-split-string s "\n")))
8838 (when (< lines (length slines))
8839 (setq s (mapconcat
8840 'identity
8841 (reverse (nthcdr (- (length slines) lines)
8842 (reverse slines))) "\n")))))
8843 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8845 (defun org-make-link (&rest strings)
8846 "Concatenate STRINGS."
8847 (apply 'concat strings))
8849 (defun org-make-link-string (link &optional description)
8850 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8851 (unless (string-match "\\S-" link)
8852 (error "Empty link"))
8853 (when (and description
8854 (stringp description)
8855 (not (string-match "\\S-" description)))
8856 (setq description nil))
8857 (when (stringp description)
8858 ;; Remove brackets from the description, they are fatal.
8859 (while (string-match "\\[" description)
8860 (setq description (replace-match "{" t t description)))
8861 (while (string-match "\\]" description)
8862 (setq description (replace-match "}" t t description))))
8863 (when (equal link description)
8864 ;; No description needed, it is identical
8865 (setq description nil))
8866 (when (and (not description)
8867 (not (string-match (org-image-file-name-regexp) link))
8868 (not (equal link (org-link-escape link))))
8869 (setq description (org-extract-attributes link)))
8870 (setq link
8871 (cond ((string-match (org-image-file-name-regexp) link) link)
8872 ((string-match org-link-types-re link)
8873 (concat (match-string 1 link)
8874 (org-link-escape (substring link (match-end 1)))))
8875 (t (org-link-escape link))))
8876 (concat "[[" link "]"
8877 (if description (concat "[" description "]") "")
8878 "]"))
8880 (defconst org-link-escape-chars
8881 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8882 "List of characters that should be escaped in link.
8883 This is the list that is used for internal purposes.")
8885 (defvar org-url-encoding-use-url-hexify nil)
8887 (defconst org-link-escape-chars-browser
8888 '(?\ )
8889 "List of escapes for characters that are problematic in links.
8890 This is the list that is used before handing over to the browser.")
8892 (defun org-link-escape (text &optional table merge)
8893 "Return percent escaped representation of TEXT.
8894 TEXT is a string with the text to escape.
8895 Optional argument TABLE is a list with characters that should be
8896 escaped. When nil, `org-link-escape-chars' is used.
8897 If optional argument MERGE is set, merge TABLE into
8898 `org-link-escape-chars'."
8899 (if (and org-url-encoding-use-url-hexify (not table))
8900 (url-hexify-string text)
8901 (cond
8902 ((and table merge)
8903 (mapc (lambda (defchr)
8904 (unless (member defchr table)
8905 (setq table (cons defchr table)))) org-link-escape-chars))
8906 ((null table)
8907 (setq table org-link-escape-chars)))
8908 (mapconcat
8909 (lambda (char)
8910 (if (or (member char table)
8911 (< char 32) (= char 37) (> char 126))
8912 (mapconcat (lambda (sequence-element)
8913 (format "%%%.2X" sequence-element))
8914 (or (encode-coding-char char 'utf-8)
8915 (error "Unable to percent escape character: %s"
8916 (char-to-string char))) "")
8917 (char-to-string char))) text "")))
8919 (defun org-link-unescape (str)
8920 "Unhex hexified unicode strings as returned from the JavaScript function
8921 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
8922 (unless (and (null str) (string= "" str))
8923 (let ((pos 0) (case-fold-search t) unhexed)
8924 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
8925 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
8926 (setq str (replace-match unhexed t t str))
8927 (setq pos (+ pos (length unhexed))))))
8928 str)
8930 (defun org-link-unescape-compound (hex)
8931 "Unhexify unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
8932 Note: this function also decodes single byte encodings like
8933 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
8934 (save-match-data
8935 (let* ((bytes (cdr (split-string hex "%")))
8936 (ret "")
8937 (eat 0)
8938 (sum 0))
8939 (while bytes
8940 (let* ((val (string-to-number (pop bytes) 16))
8941 (shift-xor
8942 (if (= 0 eat)
8943 (cond
8944 ((>= val 252) (cons 6 252))
8945 ((>= val 248) (cons 5 248))
8946 ((>= val 240) (cons 4 240))
8947 ((>= val 224) (cons 3 224))
8948 ((>= val 192) (cons 2 192))
8949 (t (cons 0 0)))
8950 (cons 6 128))))
8951 (if (>= val 192) (setq eat (car shift-xor)))
8952 (setq val (logxor val (cdr shift-xor)))
8953 (setq sum (+ (lsh sum (car shift-xor)) val))
8954 (if (> eat 0) (setq eat (- eat 1)))
8955 (cond
8956 ((= 0 eat) ;multi byte
8957 (setq ret (concat ret (org-char-to-string sum)))
8958 (setq sum 0))
8959 ((not bytes) ; single byte(s)
8960 (setq ret (org-link-unescape-single-byte-sequence hex))))
8961 )) ;; end (while bytes
8962 ret )))
8964 (defun org-link-unescape-single-byte-sequence (hex)
8965 "Unhexify hex-encoded single byte character sequences."
8966 (mapconcat (lambda (byte)
8967 (char-to-string (string-to-number byte 16)))
8968 (cdr (split-string hex "%")) ""))
8970 (defun org-xor (a b)
8971 "Exclusive or."
8972 (if a (not b) b))
8974 (defun org-fixup-message-id-for-http (s)
8975 "Replace special characters in a message id, so it can be used in an http query."
8976 (when (string-match "%" s)
8977 (setq s (mapconcat (lambda (c)
8978 (if (eq c ?%)
8979 "%25"
8980 (char-to-string c)))
8981 s "")))
8982 (while (string-match "<" s)
8983 (setq s (replace-match "%3C" t t s)))
8984 (while (string-match ">" s)
8985 (setq s (replace-match "%3E" t t s)))
8986 (while (string-match "@" s)
8987 (setq s (replace-match "%40" t t s)))
8990 ;;;###autoload
8991 (defun org-insert-link-global ()
8992 "Insert a link like Org-mode does.
8993 This command can be called in any mode to insert a link in Org-mode syntax."
8994 (interactive)
8995 (org-load-modules-maybe)
8996 (org-run-like-in-org-mode 'org-insert-link))
8998 (defun org-insert-link (&optional complete-file link-location default-description)
8999 "Insert a link. At the prompt, enter the link.
9001 Completion can be used to insert any of the link protocol prefixes like
9002 http or ftp in use.
9004 The history can be used to select a link previously stored with
9005 `org-store-link'. When the empty string is entered (i.e. if you just
9006 press RET at the prompt), the link defaults to the most recently
9007 stored link. As SPC triggers completion in the minibuffer, you need to
9008 use M-SPC or C-q SPC to force the insertion of a space character.
9010 You will also be prompted for a description, and if one is given, it will
9011 be displayed in the buffer instead of the link.
9013 If there is already a link at point, this command will allow you to edit link
9014 and description parts.
9016 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9017 be selected using completion. The path to the file will be relative to the
9018 current directory if the file is in the current directory or a subdirectory.
9019 Otherwise, the link will be the absolute path as completed in the minibuffer
9020 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9021 option `org-link-file-path-type'.
9023 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9024 the current directory or below.
9026 With three \\[universal-argument] prefixes, negate the meaning of
9027 `org-keep-stored-link-after-insertion'.
9029 If `org-make-link-description-function' is non-nil, this function will be
9030 called with the link target, and the result will be the default
9031 link description.
9033 If the LINK-LOCATION parameter is non-nil, this value will be
9034 used as the link location instead of reading one interactively.
9036 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9037 be used as the default description."
9038 (interactive "P")
9039 (let* ((wcf (current-window-configuration))
9040 (region (if (org-region-active-p)
9041 (buffer-substring (region-beginning) (region-end))))
9042 (remove (and region (list (region-beginning) (region-end))))
9043 (desc region)
9044 tmphist ; byte-compile incorrectly complains about this
9045 (link link-location)
9046 entry file all-prefixes)
9047 (cond
9048 (link-location) ; specified by arg, just use it.
9049 ((org-in-regexp org-bracket-link-regexp 1)
9050 ;; We do have a link at point, and we are going to edit it.
9051 (setq remove (list (match-beginning 0) (match-end 0)))
9052 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9053 (setq link (read-string "Link: "
9054 (org-link-unescape
9055 (org-match-string-no-properties 1)))))
9056 ((or (org-in-regexp org-angle-link-re)
9057 (org-in-regexp org-plain-link-re))
9058 ;; Convert to bracket link
9059 (setq remove (list (match-beginning 0) (match-end 0))
9060 link (read-string "Link: "
9061 (org-remove-angle-brackets (match-string 0)))))
9062 ((member complete-file '((4) (16)))
9063 ;; Completing read for file names.
9064 (setq link (org-file-complete-link complete-file)))
9066 ;; Read link, with completion for stored links.
9067 (with-output-to-temp-buffer "*Org Links*"
9068 (princ "Insert a link.
9069 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9070 (when org-stored-links
9071 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9072 (princ (mapconcat
9073 (lambda (x)
9074 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
9075 (reverse org-stored-links) "\n"))))
9076 (let ((cw (selected-window)))
9077 (select-window (get-buffer-window "*Org Links*" 'visible))
9078 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9079 (unless (pos-visible-in-window-p (point-max))
9080 (org-fit-window-to-buffer))
9081 (and (window-live-p cw) (select-window cw)))
9082 ;; Fake a link history, containing the stored links.
9083 (setq tmphist (append (mapcar 'car org-stored-links)
9084 org-insert-link-history))
9085 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9086 (mapcar 'car org-link-abbrev-alist)
9087 org-link-types))
9088 (unwind-protect
9089 (progn
9090 (setq link
9091 (let ((org-completion-use-ido nil)
9092 (org-completion-use-iswitchb nil))
9093 (org-completing-read
9094 "Link: "
9095 (append
9096 (mapcar (lambda (x) (list (concat x ":")))
9097 all-prefixes)
9098 (mapcar 'car org-stored-links))
9099 nil nil nil
9100 'tmphist
9101 (car (car org-stored-links)))))
9102 (if (not (string-match "\\S-" link))
9103 (error "No link selected"))
9104 (if (or (member link all-prefixes)
9105 (and (equal ":" (substring link -1))
9106 (member (substring link 0 -1) all-prefixes)
9107 (setq link (substring link 0 -1))))
9108 (setq link (org-link-try-special-completion link))))
9109 (set-window-configuration wcf)
9110 (kill-buffer "*Org Links*"))
9111 (setq entry (assoc link org-stored-links))
9112 (or entry (push link org-insert-link-history))
9113 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9114 (not org-keep-stored-link-after-insertion))
9115 (setq org-stored-links (delq (assoc link org-stored-links)
9116 org-stored-links)))
9117 (setq desc (or desc (nth 1 entry)))))
9119 (if (string-match org-plain-link-re link)
9120 ;; URL-like link, normalize the use of angular brackets.
9121 (setq link (org-make-link (org-remove-angle-brackets link))))
9123 ;; Check if we are linking to the current file with a search option
9124 ;; If yes, simplify the link by using only the search option.
9125 (when (and buffer-file-name
9126 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9127 (let* ((path (match-string 1 link))
9128 (case-fold-search nil)
9129 (search (match-string 2 link)))
9130 (save-match-data
9131 (if (equal (file-truename buffer-file-name) (file-truename path))
9132 ;; We are linking to this same file, with a search option
9133 (setq link search)))))
9135 ;; Check if we can/should use a relative path. If yes, simplify the link
9136 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9137 (let* ((type (match-string 1 link))
9138 (path (match-string 2 link))
9139 (origpath path)
9140 (case-fold-search nil))
9141 (cond
9142 ((or (eq org-link-file-path-type 'absolute)
9143 (equal complete-file '(16)))
9144 (setq path (abbreviate-file-name (expand-file-name path))))
9145 ((eq org-link-file-path-type 'noabbrev)
9146 (setq path (expand-file-name path)))
9147 ((eq org-link-file-path-type 'relative)
9148 (setq path (file-relative-name path)))
9150 (save-match-data
9151 (if (string-match (concat "^" (regexp-quote
9152 (expand-file-name
9153 (file-name-as-directory
9154 default-directory))))
9155 (expand-file-name path))
9156 ;; We are linking a file with relative path name.
9157 (setq path (substring (expand-file-name path)
9158 (match-end 0)))
9159 (setq path (abbreviate-file-name (expand-file-name path)))))))
9160 (setq link (concat type path))
9161 (if (equal desc origpath)
9162 (setq desc path))))
9164 (if org-make-link-description-function
9165 (setq desc (funcall org-make-link-description-function link desc)))
9167 (if default-description (setq desc default-description))
9168 (setq desc (read-string "Description: " desc))
9169 (unless (string-match "\\S-" desc) (setq desc nil))
9170 (if remove (apply 'delete-region remove))
9171 (insert (org-make-link-string link desc))))
9173 (defun org-link-try-special-completion (type)
9174 "If there is completion support for link type TYPE, offer it."
9175 (let ((fun (intern (concat "org-" type "-complete-link"))))
9176 (if (functionp fun)
9177 (funcall fun)
9178 (read-string "Link (no completion support): " (concat type ":")))))
9180 (defun org-file-complete-link (&optional arg)
9181 "Create a file link using completion."
9182 (let (file link)
9183 (setq file (read-file-name "File: "))
9184 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9185 (pwd1 (file-name-as-directory (abbreviate-file-name
9186 (expand-file-name ".")))))
9187 (cond
9188 ((equal arg '(16))
9189 (setq link (org-make-link
9190 "file:"
9191 (abbreviate-file-name (expand-file-name file)))))
9192 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9193 (setq link (org-make-link "file:" (match-string 1 file))))
9194 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9195 (expand-file-name file))
9196 (setq link (org-make-link
9197 "file:" (match-string 1 (expand-file-name file)))))
9198 (t (setq link (org-make-link "file:" file)))))
9199 link))
9201 (defun org-completing-read (&rest args)
9202 "Completing-read with SPACE being a normal character."
9203 (let ((enable-recursive-minibuffers t)
9204 (minibuffer-local-completion-map
9205 (copy-keymap minibuffer-local-completion-map)))
9206 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9207 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9208 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9209 (apply 'org-icompleting-read args)))
9211 (defun org-completing-read-no-i (&rest args)
9212 (let (org-completion-use-ido org-completion-use-iswitchb)
9213 (apply 'org-completing-read args)))
9215 (defun org-iswitchb-completing-read (prompt choices &rest args)
9216 "Use iswitch as a completing-read replacement to choose from choices.
9217 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9218 from."
9219 (let* ((iswitchb-use-virtual-buffers nil)
9220 (iswitchb-make-buflist-hook
9221 (lambda ()
9222 (setq iswitchb-temp-buflist choices))))
9223 (iswitchb-read-buffer prompt)))
9225 (defun org-icompleting-read (&rest args)
9226 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9227 (org-without-partial-completion
9228 (if (and org-completion-use-ido
9229 (fboundp 'ido-completing-read)
9230 (boundp 'ido-mode) ido-mode
9231 (listp (second args)))
9232 (let ((ido-enter-matching-directory nil))
9233 (apply 'ido-completing-read (concat (car args))
9234 (if (consp (car (nth 1 args)))
9235 (mapcar 'car (nth 1 args))
9236 (nth 1 args))
9237 (cddr args)))
9238 (if (and org-completion-use-iswitchb
9239 (boundp 'iswitchb-mode) iswitchb-mode
9240 (listp (second args)))
9241 (apply 'org-iswitchb-completing-read (concat (car args))
9242 (if (consp (car (nth 1 args)))
9243 (mapcar 'car (nth 1 args))
9244 (nth 1 args))
9245 (cddr args))
9246 (apply 'completing-read args)))))
9248 (defun org-extract-attributes (s)
9249 "Extract the attributes cookie from a string and set as text property."
9250 (let (a attr (start 0) key value)
9251 (save-match-data
9252 (when (string-match "{{\\([^}]+\\)}}$" s)
9253 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9254 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9255 (setq key (match-string 1 a) value (match-string 2 a)
9256 start (match-end 0)
9257 attr (plist-put attr (intern key) value))))
9258 (org-add-props s nil 'org-attr attr))
9261 (defun org-extract-attributes-from-string (tag)
9262 (let (key value attr)
9263 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9264 (setq key (match-string 1 tag) value (match-string 2 tag)
9265 tag (replace-match "" t t tag)
9266 attr (plist-put attr (intern key) value)))
9267 (cons tag attr)))
9269 (defun org-attributes-to-string (plist)
9270 "Format a property list into an HTML attribute list."
9271 (let ((s "") key value)
9272 (while plist
9273 (setq key (pop plist) value (pop plist))
9274 (and value
9275 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9278 ;;; Opening/following a link
9280 (defvar org-link-search-failed nil)
9282 (defvar org-open-link-functions nil
9283 "Hook for functions finding a plain text link.
9284 These functions must take a single argument, the link content.
9285 They will be called for links that look like [[link text][description]]
9286 when LINK TEXT does not have a protocol like \"http:\" and does not look
9287 like a filename (e.g. \"./blue.png\").
9289 These functions will be called *before* Org attempts to resolve the
9290 link by doing text searches in the current buffer - so if you want a
9291 link \"[[target]]\" to still find \"<<target>>\", your function should
9292 handle this as a special case.
9294 When the function does handle the link, it must return a non-nil value.
9295 If it decides that it is not responsible for this link, it must return
9296 nil to indicate that that Org-mode can continue with other options
9297 like exact and fuzzy text search.")
9299 (defun org-next-link ()
9300 "Move forward to the next link.
9301 If the link is in hidden text, expose it."
9302 (interactive)
9303 (when (and org-link-search-failed (eq this-command last-command))
9304 (goto-char (point-min))
9305 (message "Link search wrapped back to beginning of buffer"))
9306 (setq org-link-search-failed nil)
9307 (let* ((pos (point))
9308 (ct (org-context))
9309 (a (assoc :link ct)))
9310 (if a (goto-char (nth 2 a)))
9311 (if (re-search-forward org-any-link-re nil t)
9312 (progn
9313 (goto-char (match-beginning 0))
9314 (if (outline-invisible-p) (org-show-context)))
9315 (goto-char pos)
9316 (setq org-link-search-failed t)
9317 (error "No further link found"))))
9319 (defun org-previous-link ()
9320 "Move backward to the previous link.
9321 If the link is in hidden text, expose it."
9322 (interactive)
9323 (when (and org-link-search-failed (eq this-command last-command))
9324 (goto-char (point-max))
9325 (message "Link search wrapped back to end of buffer"))
9326 (setq org-link-search-failed nil)
9327 (let* ((pos (point))
9328 (ct (org-context))
9329 (a (assoc :link ct)))
9330 (if a (goto-char (nth 1 a)))
9331 (if (re-search-backward org-any-link-re nil t)
9332 (progn
9333 (goto-char (match-beginning 0))
9334 (if (outline-invisible-p) (org-show-context)))
9335 (goto-char pos)
9336 (setq org-link-search-failed t)
9337 (error "No further link found"))))
9339 (defun org-translate-link (s)
9340 "Translate a link string if a translation function has been defined."
9341 (if (and org-link-translation-function
9342 (fboundp org-link-translation-function)
9343 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9344 (progn
9345 (setq s (funcall org-link-translation-function
9346 (match-string 1) (match-string 2)))
9347 (concat (car s) ":" (cdr s)))
9350 (defun org-translate-link-from-planner (type path)
9351 "Translate a link from Emacs Planner syntax so that Org can follow it.
9352 This is still an experimental function, your mileage may vary."
9353 (cond
9354 ((member type '("http" "https" "news" "ftp"))
9355 ;; standard Internet links are the same.
9356 nil)
9357 ((and (equal type "irc") (string-match "^//" path))
9358 ;; Planner has two / at the beginning of an irc link, we have 1.
9359 ;; We should have zero, actually....
9360 (setq path (substring path 1)))
9361 ((and (equal type "lisp") (string-match "^/" path))
9362 ;; Planner has a slash, we do not.
9363 (setq type "elisp" path (substring path 1)))
9364 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9365 ;; A typical message link. Planner has the id after the final slash,
9366 ;; we separate it with a hash mark
9367 (setq path (concat (match-string 1 path) "#"
9368 (org-remove-angle-brackets (match-string 2 path)))))
9370 (cons type path))
9372 (defun org-find-file-at-mouse (ev)
9373 "Open file link or URL at mouse."
9374 (interactive "e")
9375 (mouse-set-point ev)
9376 (org-open-at-point 'in-emacs))
9378 (defun org-open-at-mouse (ev)
9379 "Open file link or URL at mouse.
9380 See the docstring of `org-open-file' for details."
9381 (interactive "e")
9382 (mouse-set-point ev)
9383 (if (eq major-mode 'org-agenda-mode)
9384 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9385 (org-open-at-point))
9387 (defvar org-window-config-before-follow-link nil
9388 "The window configuration before following a link.
9389 This is saved in case the need arises to restore it.")
9391 (defvar org-open-link-marker (make-marker)
9392 "Marker pointing to the location where `org-open-at-point; was called.")
9394 ;;;###autoload
9395 (defun org-open-at-point-global ()
9396 "Follow a link like Org-mode does.
9397 This command can be called in any mode to follow a link that has
9398 Org-mode syntax."
9399 (interactive)
9400 (org-run-like-in-org-mode 'org-open-at-point))
9402 ;;;###autoload
9403 (defun org-open-link-from-string (s &optional arg reference-buffer)
9404 "Open a link in the string S, as if it was in Org-mode."
9405 (interactive "sLink: \nP")
9406 (let ((reference-buffer (or reference-buffer (current-buffer))))
9407 (with-temp-buffer
9408 (let ((org-inhibit-startup t))
9409 (org-mode)
9410 (insert s)
9411 (goto-char (point-min))
9412 (when reference-buffer
9413 (setq org-link-abbrev-alist-local
9414 (with-current-buffer reference-buffer
9415 org-link-abbrev-alist-local)))
9416 (org-open-at-point arg reference-buffer)))))
9418 (defvar org-open-at-point-functions nil
9419 "Hook that is run when following a link at point.
9421 Functions in this hook must return t if they identify and follow
9422 a link at point. If they don't find anything interesting at point,
9423 they must return nil.")
9425 (defun org-open-at-point (&optional arg reference-buffer)
9426 "Open link at or after point.
9427 If there is no link at point, this function will search forward up to
9428 the end of the current line.
9429 Normally, files will be opened by an appropriate application. If the
9430 optional prefix argument ARG is non-nil, Emacs will visit the file.
9431 With a double prefix argument, try to open outside of Emacs, in the
9432 application the system uses for this file type."
9433 (interactive "P")
9434 ;; if in a code block, then open the block's results
9435 (unless (call-interactively #'org-babel-open-src-block-result)
9436 (org-load-modules-maybe)
9437 (move-marker org-open-link-marker (point))
9438 (setq org-window-config-before-follow-link (current-window-configuration))
9439 (org-remove-occur-highlights nil nil t)
9440 (cond
9441 ((and (org-on-heading-p)
9442 (not (org-in-regexp
9443 (concat org-plain-link-re "\\|"
9444 org-bracket-link-regexp "\\|"
9445 org-angle-link-re "\\|"
9446 "[ \t]:[^ \t\n]+:[ \t]*$")))
9447 (not (get-text-property (point) 'org-linked-text)))
9448 (or (org-offer-links-in-entry arg)
9449 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9450 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9451 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9452 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9453 (not (org-in-regexp org-bracket-link-regexp)))
9454 (org-footnote-action))
9456 (let (type path link line search (pos (point)))
9457 (catch 'match
9458 (save-excursion
9459 (skip-chars-forward "^]\n\r")
9460 (when (org-in-regexp org-bracket-link-regexp 1)
9461 (setq link (org-extract-attributes
9462 (org-link-unescape (org-match-string-no-properties 1))))
9463 (while (string-match " *\n *" link)
9464 (setq link (replace-match " " t t link)))
9465 (setq link (org-link-expand-abbrev link))
9466 (cond
9467 ((or (file-name-absolute-p link)
9468 (string-match "^\\.\\.?/" link))
9469 (setq type "file" path link))
9470 ((string-match org-link-re-with-space3 link)
9471 (setq type (match-string 1 link) path (match-string 2 link)))
9472 (t (setq type "thisfile" path link)))
9473 (throw 'match t)))
9475 (when (get-text-property (point) 'org-linked-text)
9476 (setq type "thisfile"
9477 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9478 (1+ (point)) (point))
9479 path (buffer-substring
9480 (or (previous-single-property-change pos 'org-linked-text)
9481 (point-min))
9482 (or (next-single-property-change pos 'org-linked-text)
9483 (point-max))))
9484 (throw 'match t))
9486 (save-excursion
9487 (when (or (org-in-regexp org-angle-link-re)
9488 (org-in-regexp org-plain-link-re))
9489 (setq type (match-string 1)
9490 path (org-link-unescape (match-string 2)))
9491 (throw 'match t)))
9492 (save-excursion
9493 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9494 (setq type "tags"
9495 path (match-string 1))
9496 (while (string-match ":" path)
9497 (setq path (replace-match "+" t t path)))
9498 (throw 'match t)))
9499 (when (org-in-regexp "<\\([^><\n]+\\)>")
9500 (setq type "tree-match"
9501 path (match-string 1))
9502 (throw 'match t)))
9503 (unless path
9504 (error "No link found"))
9506 ;; switch back to reference buffer
9507 ;; needed when if called in a temporary buffer through
9508 ;; org-open-link-from-string
9509 (with-current-buffer (or reference-buffer (current-buffer))
9511 ;; Remove any trailing spaces in path
9512 (if (string-match " +\\'" path)
9513 (setq path (replace-match "" t t path)))
9514 (if (and org-link-translation-function
9515 (fboundp org-link-translation-function))
9516 ;; Check if we need to translate the link
9517 (let ((tmp (funcall org-link-translation-function type path)))
9518 (setq type (car tmp) path (cdr tmp))))
9520 (cond
9522 ((assoc type org-link-protocols)
9523 (funcall (nth 1 (assoc type org-link-protocols)) path))
9525 ((equal type "mailto")
9526 (let ((cmd (car org-link-mailto-program))
9527 (args (cdr org-link-mailto-program)) args1
9528 (address path) (subject "") a)
9529 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9530 (setq address (match-string 1 path)
9531 subject (org-link-escape (match-string 2 path))))
9532 (while args
9533 (cond
9534 ((not (stringp (car args))) (push (pop args) args1))
9535 (t (setq a (pop args))
9536 (if (string-match "%a" a)
9537 (setq a (replace-match address t t a)))
9538 (if (string-match "%s" a)
9539 (setq a (replace-match subject t t a)))
9540 (push a args1))))
9541 (apply cmd (nreverse args1))))
9543 ((member type '("http" "https" "ftp" "news"))
9544 (browse-url (concat type ":" (org-link-escape
9545 path org-link-escape-chars-browser))))
9547 ((string= type "doi")
9548 (browse-url (concat "http://dx.doi.org/"
9549 (org-link-escape
9550 path org-link-escape-chars-browser))))
9552 ((member type '("message"))
9553 (browse-url (concat type ":" path)))
9555 ((string= type "tags")
9556 (org-tags-view arg path))
9558 ((string= type "tree-match")
9559 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9561 ((string= type "file")
9562 (if (string-match "::\\([0-9]+\\)\\'" path)
9563 (setq line (string-to-number (match-string 1 path))
9564 path (substring path 0 (match-beginning 0)))
9565 (if (string-match "::\\(.+\\)\\'" path)
9566 (setq search (match-string 1 path)
9567 path (substring path 0 (match-beginning 0)))))
9568 (if (string-match "[*?{]" (file-name-nondirectory path))
9569 (dired path)
9570 (org-open-file path arg line search)))
9572 ((string= type "shell")
9573 (let ((cmd path))
9574 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9575 (string-match org-confirm-shell-link-not-regexp cmd))
9576 (not org-confirm-shell-link-function)
9577 (funcall org-confirm-shell-link-function
9578 (format "Execute \"%s\" in shell? "
9579 (org-add-props cmd nil
9580 'face 'org-warning))))
9581 (progn
9582 (message "Executing %s" cmd)
9583 (shell-command cmd))
9584 (error "Abort"))))
9586 ((string= type "elisp")
9587 (let ((cmd path))
9588 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9589 (string-match org-confirm-elisp-link-not-regexp cmd))
9590 (not org-confirm-elisp-link-function)
9591 (funcall org-confirm-elisp-link-function
9592 (format "Execute \"%s\" as elisp? "
9593 (org-add-props cmd nil
9594 'face 'org-warning))))
9595 (message "%s => %s" cmd
9596 (if (equal (string-to-char cmd) ?\()
9597 (eval (read cmd))
9598 (call-interactively (read cmd))))
9599 (error "Abort"))))
9601 ((and (string= type "thisfile")
9602 (run-hook-with-args-until-success
9603 'org-open-link-functions path)))
9605 ((string= type "thisfile")
9606 (if arg
9607 (switch-to-buffer-other-window
9608 (org-get-buffer-for-internal-link (current-buffer)))
9609 (org-mark-ring-push))
9610 (let ((cmd `(org-link-search
9611 ,path
9612 ,(cond ((equal arg '(4)) ''occur)
9613 ((equal arg '(16)) ''org-occur)
9614 (t nil))
9615 ,pos)))
9616 (condition-case nil (let ((org-link-search-inhibit-query t))
9617 (eval cmd))
9618 (error (progn (widen) (eval cmd))))))
9621 (browse-url-at-point)))))))
9622 (move-marker org-open-link-marker nil)
9623 (run-hook-with-args 'org-follow-link-hook)))
9625 (defun org-offer-links-in-entry (&optional nth zero)
9626 "Offer links in the current entry and follow the selected link.
9627 If there is only one link, follow it immediately as well.
9628 If NTH is an integer, immediately pick the NTH link found.
9629 If ZERO is a string, check also this string for a link, and if
9630 there is one, offer it as link number zero."
9631 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9632 "\\(" org-angle-link-re "\\)\\|"
9633 "\\(" org-plain-link-re "\\)"))
9634 (cnt ?0)
9635 (in-emacs (if (integerp nth) nil nth))
9636 have-zero end links link c)
9637 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9638 (push (match-string 0 zero) links)
9639 (setq cnt (1- cnt) have-zero t))
9640 (save-excursion
9641 (org-back-to-heading t)
9642 (setq end (save-excursion (outline-next-heading) (point)))
9643 (while (re-search-forward re end t)
9644 (push (match-string 0) links))
9645 (setq links (org-uniquify (reverse links))))
9647 (cond
9648 ((null links)
9649 (message "No links"))
9650 ((equal (length links) 1)
9651 (setq link (list (car links))))
9652 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9653 (setq link (nth (if have-zero nth (1- nth)) links)))
9654 (t ; we have to select a link
9655 (save-excursion
9656 (save-window-excursion
9657 (delete-other-windows)
9658 (with-output-to-temp-buffer "*Select Link*"
9659 (mapc (lambda (l)
9660 (if (not (string-match org-bracket-link-regexp l))
9661 (princ (format "[%c] %s\n" (incf cnt)
9662 (org-remove-angle-brackets l)))
9663 (if (match-end 3)
9664 (princ (format "[%c] %s (%s)\n" (incf cnt)
9665 (match-string 3 l) (match-string 1 l)))
9666 (princ (format "[%c] %s\n" (incf cnt)
9667 (match-string 1 l))))))
9668 links))
9669 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9670 (message "Select link to open, RET to open all:")
9671 (setq c (read-char-exclusive))
9672 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9673 (when (equal c ?q) (error "Abort"))
9674 (if (equal c ?\C-m)
9675 (setq link links)
9676 (setq nth (- c ?0))
9677 (if have-zero (setq nth (1+ nth)))
9678 (unless (and (integerp nth) (>= (length links) nth))
9679 (error "Invalid link selection"))
9680 (setq link (list (nth (1- nth) links))))))
9681 (if link
9682 (let ((buf (current-buffer)))
9683 (dolist (l link)
9684 (org-open-link-from-string l in-emacs buf))
9686 nil)))
9688 ;; Add special file links that specify the way of opening
9690 (org-add-link-type "file+sys" 'org-open-file-with-system)
9691 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9692 (defun org-open-file-with-system (path)
9693 "Open file at PATH using the system way of opening it."
9694 (org-open-file path 'system))
9695 (defun org-open-file-with-emacs (path)
9696 "Open file at PATH in Emacs."
9697 (org-open-file path 'emacs))
9698 (defun org-remove-file-link-modifiers ()
9699 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9700 (goto-char (point-min))
9701 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9702 (org-if-unprotected
9703 (replace-match "file:" t t))))
9704 (eval-after-load "org-exp"
9705 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9706 'org-remove-file-link-modifiers))
9708 ;;;; Time estimates
9710 (defun org-get-effort (&optional pom)
9711 "Get the effort estimate for the current entry."
9712 (org-entry-get pom org-effort-property))
9714 ;;; File search
9716 (defvar org-create-file-search-functions nil
9717 "List of functions to construct the right search string for a file link.
9718 These functions are called in turn with point at the location to
9719 which the link should point.
9721 A function in the hook should first test if it would like to
9722 handle this file type, for example by checking the `major-mode'
9723 or the file extension. If it decides not to handle this file, it
9724 should just return nil to give other functions a chance. If it
9725 does handle the file, it must return the search string to be used
9726 when following the link. The search string will be part of the
9727 file link, given after a double colon, and `org-open-at-point'
9728 will automatically search for it. If special measures must be
9729 taken to make the search successful, another function should be
9730 added to the companion hook `org-execute-file-search-functions',
9731 which see.
9733 A function in this hook may also use `setq' to set the variable
9734 `description' to provide a suggestion for the descriptive text to
9735 be used for this link when it gets inserted into an Org-mode
9736 buffer with \\[org-insert-link].")
9738 (defvar org-execute-file-search-functions nil
9739 "List of functions to execute a file search triggered by a link.
9741 Functions added to this hook must accept a single argument, the
9742 search string that was part of the file link, the part after the
9743 double colon. The function must first check if it would like to
9744 handle this search, for example by checking the `major-mode' or
9745 the file extension. If it decides not to handle this search, it
9746 should just return nil to give other functions a chance. If it
9747 does handle the search, it must return a non-nil value to keep
9748 other functions from trying.
9750 Each function can access the current prefix argument through the
9751 variable `current-prefix-argument'. Note that a single prefix is
9752 used to force opening a link in Emacs, so it may be good to only
9753 use a numeric or double prefix to guide the search function.
9755 In case this is needed, a function in this hook can also restore
9756 the window configuration before `org-open-at-point' was called using:
9758 (set-window-configuration org-window-config-before-follow-link)")
9760 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9761 (defun org-link-search (s &optional type avoid-pos)
9762 "Search for a link search option.
9763 If S is surrounded by forward slashes, it is interpreted as a
9764 regular expression. In org-mode files, this will create an `org-occur'
9765 sparse tree. In ordinary files, `occur' will be used to list matches.
9766 If the current buffer is in `dired-mode', grep will be used to search
9767 in all files. If AVOID-POS is given, ignore matches near that position."
9768 (let ((case-fold-search t)
9769 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9770 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9771 (append '(("") (" ") ("\t") ("\n"))
9772 org-emphasis-alist)
9773 "\\|") "\\)"))
9774 (pos (point))
9775 (pre nil) (post nil)
9776 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9777 (cond
9778 ;; First check if there are any special search functions
9779 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9780 ;; Now try the builtin stuff
9781 ((and (equal (string-to-char s0) ?#)
9782 (> (length s0) 1)
9783 (save-excursion
9784 (goto-char (point-min))
9785 (and
9786 (re-search-forward
9787 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9788 (setq type 'dedicated
9789 pos (match-beginning 0))))
9790 ;; There is an exact target for this
9791 (goto-char pos)
9792 (org-back-to-heading t)))
9793 ((save-excursion
9794 (goto-char (point-min))
9795 (and
9796 (re-search-forward
9797 (concat "<<" (regexp-quote s0) ">>") nil t)
9798 (setq type 'dedicated
9799 pos (match-beginning 0))))
9800 ;; There is an exact target for this
9801 (goto-char pos))
9802 ((and (string-match "^(\\(.*\\))$" s0)
9803 (save-excursion
9804 (goto-char (point-min))
9805 (and
9806 (re-search-forward
9807 (concat "[^[]" (regexp-quote
9808 (format org-coderef-label-format
9809 (match-string 1 s0))))
9810 nil t)
9811 (setq type 'dedicated
9812 pos (1+ (match-beginning 0))))))
9813 ;; There is a coderef target for this
9814 (goto-char pos))
9815 ((string-match "^/\\(.*\\)/$" s)
9816 ;; A regular expression
9817 (cond
9818 ((eq major-mode 'org-mode)
9819 (org-occur (match-string 1 s)))
9820 ;;((eq major-mode 'dired-mode)
9821 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9822 (t (org-do-occur (match-string 1 s)))))
9823 ((and (eq major-mode 'org-mode) org-link-search-must-match-exact-headline)
9824 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9825 (goto-char (point-min))
9826 (cond
9827 ((let (case-fold-search)
9828 (re-search-forward (format org-complex-heading-regexp-format
9829 (regexp-quote s))
9830 nil t))
9831 ;; OK, found a match
9832 (setq type 'dedicated)
9833 (goto-char (match-beginning 0)))
9834 ((and (not org-link-search-inhibit-query)
9835 (eq org-link-search-must-match-exact-headline 'query-to-create)
9836 (y-or-n-p "No match - create this as a new heading? "))
9837 (goto-char (point-max))
9838 (or (bolp) (newline))
9839 (insert "* " s "\n")
9840 (beginning-of-line 0))
9842 (goto-char pos)
9843 (error "No match"))))
9845 ;; A normal search string
9846 (when (equal (string-to-char s) ?*)
9847 ;; Anchor on headlines, post may include tags.
9848 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9849 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9850 s (substring s 1)))
9851 (remove-text-properties
9852 0 (length s)
9853 '(face nil mouse-face nil keymap nil fontified nil) s)
9854 ;; Make a series of regular expressions to find a match
9855 (setq words (org-split-string s "[ \n\r\t]+")
9857 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9858 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9859 "\\)" markers)
9860 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9861 re2a (concat "[ \t\r\n]" re2a_)
9862 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9863 re4 (concat "[^a-zA-Z_]" re4_)
9865 re1 (concat pre re2 post)
9866 re3 (concat pre (if pre re4_ re4) post)
9867 re5 (concat pre ".*" re4)
9868 re2 (concat pre re2)
9869 re2a (concat pre (if pre re2a_ re2a))
9870 re4 (concat pre (if pre re4_ re4))
9871 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9872 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9873 re5 "\\)"
9875 (cond
9876 ((eq type 'org-occur) (org-occur reall))
9877 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9878 (t (goto-char (point-min))
9879 (setq type 'fuzzy)
9880 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9881 (org-search-not-self 1 re1 nil t)
9882 (org-search-not-self 1 re2 nil t)
9883 (org-search-not-self 1 re2a nil t)
9884 (org-search-not-self 1 re3 nil t)
9885 (org-search-not-self 1 re4 nil t)
9886 (org-search-not-self 1 re5 nil t)
9888 (goto-char (match-beginning 1))
9889 (goto-char pos)
9890 (error "No match"))))))
9891 (and (eq major-mode 'org-mode) (org-show-context 'link-search))
9892 type))
9894 (defun org-search-not-self (group &rest args)
9895 "Execute `re-search-forward', but only accept matches that do not
9896 enclose the position of `org-open-link-marker'."
9897 (let ((m org-open-link-marker))
9898 (catch 'exit
9899 (while (apply 're-search-forward args)
9900 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9901 (goto-char (match-end group))
9902 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9903 (> (match-beginning 0) (marker-position m))
9904 (< (match-end 0) (marker-position m)))
9905 (save-match-data
9906 (or (not (org-in-regexp
9907 org-bracket-link-analytic-regexp 1))
9908 (not (match-end 4)) ; no description
9909 (and (<= (match-beginning 4) (point))
9910 (>= (match-end 4) (point))))))
9911 (throw 'exit (point))))))))
9913 (defun org-get-buffer-for-internal-link (buffer)
9914 "Return a buffer to be used for displaying the link target of internal links."
9915 (cond
9916 ((not org-display-internal-link-with-indirect-buffer)
9917 buffer)
9918 ((string-match "(Clone)$" (buffer-name buffer))
9919 (message "Buffer is already a clone, not making another one")
9920 ;; we also do not modify visibility in this case
9921 buffer)
9922 (t ; make a new indirect buffer for displaying the link
9923 (let* ((bn (buffer-name buffer))
9924 (ibn (concat bn "(Clone)"))
9925 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9926 (with-current-buffer ib (org-overview))
9927 ib))))
9929 (defun org-do-occur (regexp &optional cleanup)
9930 "Call the Emacs command `occur'.
9931 If CLEANUP is non-nil, remove the printout of the regular expression
9932 in the *Occur* buffer. This is useful if the regex is long and not useful
9933 to read."
9934 (occur regexp)
9935 (when cleanup
9936 (let ((cwin (selected-window)) win beg end)
9937 (when (setq win (get-buffer-window "*Occur*"))
9938 (select-window win))
9939 (goto-char (point-min))
9940 (when (re-search-forward "match[a-z]+" nil t)
9941 (setq beg (match-end 0))
9942 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9943 (setq end (1- (match-beginning 0)))))
9944 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9945 (goto-char (point-min))
9946 (select-window cwin))))
9948 ;;; The mark ring for links jumps
9950 (defvar org-mark-ring nil
9951 "Mark ring for positions before jumps in Org-mode.")
9952 (defvar org-mark-ring-last-goto nil
9953 "Last position in the mark ring used to go back.")
9954 ;; Fill and close the ring
9955 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9956 (loop for i from 1 to org-mark-ring-length do
9957 (push (make-marker) org-mark-ring))
9958 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9959 org-mark-ring)
9961 (defun org-mark-ring-push (&optional pos buffer)
9962 "Put the current position or POS into the mark ring and rotate it."
9963 (interactive)
9964 (setq pos (or pos (point)))
9965 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9966 (move-marker (car org-mark-ring)
9967 (or pos (point))
9968 (or buffer (current-buffer)))
9969 (message "%s"
9970 (substitute-command-keys
9971 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9973 (defun org-mark-ring-goto (&optional n)
9974 "Jump to the previous position in the mark ring.
9975 With prefix arg N, jump back that many stored positions. When
9976 called several times in succession, walk through the entire ring.
9977 Org-mode commands jumping to a different position in the current file,
9978 or to another Org-mode file, automatically push the old position
9979 onto the ring."
9980 (interactive "p")
9981 (let (p m)
9982 (if (eq last-command this-command)
9983 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9984 (setq p org-mark-ring))
9985 (setq org-mark-ring-last-goto p)
9986 (setq m (car p))
9987 (org-pop-to-buffer-same-window (marker-buffer m))
9988 (goto-char m)
9989 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9991 (defun org-remove-angle-brackets (s)
9992 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9993 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9995 (defun org-add-angle-brackets (s)
9996 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9997 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9999 (defun org-remove-double-quotes (s)
10000 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10001 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10004 ;;; Following specific links
10006 (defun org-follow-timestamp-link ()
10007 (cond
10008 ((org-at-date-range-p t)
10009 (let ((org-agenda-start-on-weekday)
10010 (t1 (match-string 1))
10011 (t2 (match-string 2)))
10012 (setq t1 (time-to-days (org-time-string-to-time t1))
10013 t2 (time-to-days (org-time-string-to-time t2)))
10014 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10015 ((org-at-timestamp-p t)
10016 (org-agenda-list nil (time-to-days (org-time-string-to-time
10017 (substring (match-string 1) 0 10)))
10019 (t (error "This should not happen"))))
10022 ;;; Following file links
10023 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10024 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10025 (declare-function mailcap-mime-info
10026 "mailcap" (string &optional request no-decode))
10027 (defvar org-wait nil)
10028 (defun org-open-file (path &optional in-emacs line search)
10029 "Open the file at PATH.
10030 First, this expands any special file name abbreviations. Then the
10031 configuration variable `org-file-apps' is checked if it contains an
10032 entry for this file type, and if yes, the corresponding command is launched.
10034 If no application is found, Emacs simply visits the file.
10036 With optional prefix argument IN-EMACS, Emacs will visit the file.
10037 With a double \\[universal-argument] \\[universal-argument] \
10038 prefix arg, Org tries to avoid opening in Emacs
10039 and to use an external application to visit the file.
10041 Optional LINE specifies a line to go to, optional SEARCH a string
10042 to search for. If LINE or SEARCH is given, the file will be
10043 opened in Emacs, unless an entry from org-file-apps that makes
10044 use of groups in a regexp matches.
10046 If you want to change the way frames are used when following a
10047 link, please customize `org-link-frame-setup'.
10049 If the file does not exist, an error is thrown."
10050 (let* ((file (if (equal path "")
10051 buffer-file-name
10052 (substitute-in-file-name (expand-file-name path))))
10053 (file-apps (append org-file-apps (org-default-apps)))
10054 (apps (org-remove-if
10055 'org-file-apps-entry-match-against-dlink-p file-apps))
10056 (apps-dlink (org-remove-if-not
10057 'org-file-apps-entry-match-against-dlink-p file-apps))
10058 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10059 (dirp (if remp nil (file-directory-p file)))
10060 (file (if (and dirp org-open-directory-means-index-dot-org)
10061 (concat (file-name-as-directory file) "index.org")
10062 file))
10063 (a-m-a-p (assq 'auto-mode apps))
10064 (dfile (downcase file))
10065 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10066 (link (cond ((and (eq line nil)
10067 (eq search nil))
10068 file)
10069 (line
10070 (concat file "::" (number-to-string line)))
10071 (search
10072 (concat file "::" search))))
10073 (dlink (downcase link))
10074 (old-buffer (current-buffer))
10075 (old-pos (point))
10076 (old-mode major-mode)
10077 ext cmd link-match-data)
10078 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10079 (setq ext (match-string 1 dfile))
10080 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10081 (setq ext (match-string 1 dfile))))
10082 (cond
10083 ((member in-emacs '((16) system))
10084 (setq cmd (cdr (assoc 'system apps))))
10085 (in-emacs (setq cmd 'emacs))
10087 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10088 (and dirp (cdr (assoc 'directory apps)))
10089 ; first, try matching against apps-dlink
10090 ; if we get a match here, store the match data for later
10091 (let ((match (assoc-default dlink apps-dlink
10092 'string-match)))
10093 (if match
10094 (progn (setq link-match-data (match-data))
10095 match)
10096 (progn (setq in-emacs (or in-emacs line search))
10097 nil))) ; if we have no match in apps-dlink,
10098 ; always open the file in emacs if line or search
10099 ; is given (for backwards compatibility)
10100 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10101 'string-match)
10102 (cdr (assoc ext apps))
10103 (cdr (assoc t apps))))))
10104 (when (eq cmd 'system)
10105 (setq cmd (cdr (assoc 'system apps))))
10106 (when (eq cmd 'default)
10107 (setq cmd (cdr (assoc t apps))))
10108 (when (eq cmd 'mailcap)
10109 (require 'mailcap)
10110 (mailcap-parse-mailcaps)
10111 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10112 (command (mailcap-mime-info mime-type)))
10113 (if (stringp command)
10114 (setq cmd command)
10115 (setq cmd 'emacs))))
10116 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10117 (not (file-exists-p file))
10118 (not org-open-non-existing-files))
10119 (error "No such file: %s" file))
10120 (cond
10121 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10122 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10123 (while (string-match "['\"]%s['\"]" cmd)
10124 (setq cmd (replace-match "%s" t t cmd)))
10125 (while (string-match "%s" cmd)
10126 (setq cmd (replace-match
10127 (save-match-data
10128 (shell-quote-argument
10129 (convert-standard-filename file)))
10130 t t cmd)))
10132 ;; Replace "%1", "%2" etc. in command with group matches from regex
10133 (save-match-data
10134 (let ((match-index 1)
10135 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10136 (set-match-data link-match-data)
10137 (while (<= match-index number-of-groups)
10138 (let ((regex (concat "%" (number-to-string match-index)))
10139 (replace-with (match-string match-index dlink)))
10140 (while (string-match regex cmd)
10141 (setq cmd (replace-match replace-with t t cmd))))
10142 (setq match-index (+ match-index 1)))))
10144 (save-window-excursion
10145 (start-process-shell-command cmd nil cmd)
10146 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10148 ((or (stringp cmd)
10149 (eq cmd 'emacs))
10150 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10151 (widen)
10152 (if line (org-goto-line line)
10153 (if search (org-link-search search))))
10154 ((consp cmd)
10155 (let ((file (convert-standard-filename file)))
10156 (save-match-data
10157 (set-match-data link-match-data)
10158 (eval cmd))))
10159 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10160 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
10161 (or (not (equal old-buffer (current-buffer)))
10162 (not (equal old-pos (point))))
10163 (org-mark-ring-push old-pos old-buffer))))
10165 (defun org-file-apps-entry-match-against-dlink-p (entry)
10166 "This function returns non-nil if `entry' uses a regular
10167 expression which should be matched against the whole link by
10168 org-open-file.
10170 It assumes that is the case when the entry uses a regular
10171 expression which has at least one grouping construct and the
10172 action is either a lisp form or a command string containing
10173 '%1', i.e. using at least one subexpression match as a
10174 parameter."
10175 (let ((selector (car entry))
10176 (action (cdr entry)))
10177 (if (stringp selector)
10178 (and (> (regexp-opt-depth selector) 0)
10179 (or (and (stringp action)
10180 (string-match "%[0-9]" action))
10181 (consp action)))
10182 nil)))
10184 (defun org-default-apps ()
10185 "Return the default applications for this operating system."
10186 (cond
10187 ((eq system-type 'darwin)
10188 org-file-apps-defaults-macosx)
10189 ((eq system-type 'windows-nt)
10190 org-file-apps-defaults-windowsnt)
10191 (t org-file-apps-defaults-gnu)))
10193 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10194 "Convert extensions to regular expressions in the cars of LIST.
10195 Also, weed out any non-string entries, because the return value is used
10196 only for regexp matching.
10197 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10198 point to the symbol `emacs', indicating that the file should
10199 be opened in Emacs."
10200 (append
10201 (delq nil
10202 (mapcar (lambda (x)
10203 (if (not (stringp (car x)))
10205 (if (string-match "\\W" (car x))
10207 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10208 list))
10209 (if add-auto-mode
10210 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10212 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10213 (defun org-file-remote-p (file)
10214 "Test whether FILE specifies a location on a remote system.
10215 Return non-nil if the location is indeed remote.
10217 For example, the filename \"/user@host:/foo\" specifies a location
10218 on the system \"/user@host:\"."
10219 (cond ((fboundp 'file-remote-p)
10220 (file-remote-p file))
10221 ((fboundp 'tramp-handle-file-remote-p)
10222 (tramp-handle-file-remote-p file))
10223 ((and (boundp 'ange-ftp-name-format)
10224 (string-match (car ange-ftp-name-format) file))
10226 (t nil)))
10229 ;;;; Refiling
10231 (defun org-get-org-file ()
10232 "Read a filename, with default directory `org-directory'."
10233 (let ((default (or org-default-notes-file remember-data-file)))
10234 (read-file-name (format "File name [%s]: " default)
10235 (file-name-as-directory org-directory)
10236 default)))
10238 (defun org-notes-order-reversed-p ()
10239 "Check if the current file should receive notes in reversed order."
10240 (cond
10241 ((not org-reverse-note-order) nil)
10242 ((eq t org-reverse-note-order) t)
10243 ((not (listp org-reverse-note-order)) nil)
10244 (t (catch 'exit
10245 (let ((all org-reverse-note-order)
10246 entry)
10247 (while (setq entry (pop all))
10248 (if (string-match (car entry) buffer-file-name)
10249 (throw 'exit (cdr entry))))
10250 nil)))))
10252 (defvar org-refile-target-table nil
10253 "The list of refile targets, created by `org-refile'.")
10255 (defvar org-agenda-new-buffers nil
10256 "Buffers created to visit agenda files.")
10258 (defvar org-refile-cache nil
10259 "Cache for refile targets.")
10261 (defvar org-refile-markers nil
10262 "All the markers used for caching refile locations.")
10264 (defun org-refile-marker (pos)
10265 "Get a new refile marker, but only if caching is in use."
10266 (if (not org-refile-use-cache)
10268 (let ((m (make-marker)))
10269 (move-marker m pos)
10270 (push m org-refile-markers)
10271 m)))
10273 (defun org-refile-cache-clear ()
10274 "Clear the refile cache and disable all the markers."
10275 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10276 (setq org-refile-markers nil)
10277 (setq org-refile-cache nil)
10278 (message "Refile cache has been cleared"))
10280 (defun org-refile-cache-check-set (set)
10281 "Check if all the markers in the cache still have live buffers."
10282 (let (marker)
10283 (catch 'exit
10284 (while (and set (setq marker (nth 3 (pop set))))
10285 ;; if org-refile-use-outline-path is 'file, marker may be nil
10286 (when (and marker (null (marker-buffer marker)))
10287 (message "not found") (sit-for 3)
10288 (throw 'exit nil)))
10289 t)))
10291 (defun org-refile-cache-put (set &rest identifiers)
10292 "Push the refile targets SET into the cache, under IDENTIFIERS."
10293 (let* ((key (sha1 (prin1-to-string identifiers)))
10294 (entry (assoc key org-refile-cache)))
10295 (if entry
10296 (setcdr entry set)
10297 (push (cons key set) org-refile-cache))))
10299 (defun org-refile-cache-get (&rest identifiers)
10300 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10301 (cond
10302 ((not org-refile-cache) nil)
10303 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10305 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10306 org-refile-cache))))
10307 (and set (org-refile-cache-check-set set) set)))))
10309 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10310 "Produce a table with refile targets."
10311 (let ((case-fold-search nil)
10312 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10313 (entries (or org-refile-targets '((nil . (:level . 1)))))
10314 targets tgs txt re files f desc descre fast-path-p level pos0)
10315 (message "Getting targets...")
10316 (with-current-buffer (or default-buffer (current-buffer))
10317 (while (setq entry (pop entries))
10318 (setq files (car entry) desc (cdr entry))
10319 (setq fast-path-p nil)
10320 (cond
10321 ((null files) (setq files (list (current-buffer))))
10322 ((eq files 'org-agenda-files)
10323 (setq files (org-agenda-files 'unrestricted)))
10324 ((and (symbolp files) (fboundp files))
10325 (setq files (funcall files)))
10326 ((and (symbolp files) (boundp files))
10327 (setq files (symbol-value files))))
10328 (if (stringp files) (setq files (list files)))
10329 (cond
10330 ((eq (car desc) :tag)
10331 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10332 ((eq (car desc) :todo)
10333 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10334 ((eq (car desc) :regexp)
10335 (setq descre (cdr desc)))
10336 ((eq (car desc) :level)
10337 (setq descre (concat "^\\*\\{" (number-to-string
10338 (if org-odd-levels-only
10339 (1- (* 2 (cdr desc)))
10340 (cdr desc)))
10341 "\\}[ \t]")))
10342 ((eq (car desc) :maxlevel)
10343 (setq fast-path-p t)
10344 (setq descre (concat "^\\*\\{1," (number-to-string
10345 (if org-odd-levels-only
10346 (1- (* 2 (cdr desc)))
10347 (cdr desc)))
10348 "\\}[ \t]")))
10349 (t (error "Bad refiling target description %s" desc)))
10350 (while (setq f (pop files))
10351 (with-current-buffer
10352 (if (bufferp f) f (org-get-agenda-file-buffer f))
10354 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10355 (progn
10356 (if (bufferp f) (setq f (buffer-file-name
10357 (buffer-base-buffer f))))
10358 (setq f (and f (expand-file-name f)))
10359 (if (eq org-refile-use-outline-path 'file)
10360 (push (list (file-name-nondirectory f) f nil nil) tgs))
10361 (save-excursion
10362 (save-restriction
10363 (widen)
10364 (goto-char (point-min))
10365 (while (re-search-forward descre nil t)
10366 (goto-char (setq pos0 (point-at-bol)))
10367 (catch 'next
10368 (when org-refile-target-verify-function
10369 (save-match-data
10370 (or (funcall org-refile-target-verify-function)
10371 (throw 'next t))))
10372 (when (and (looking-at org-complex-heading-regexp)
10373 (not (member (match-string 4) excluded-entries)))
10374 (setq level (org-reduced-level
10375 (- (match-end 1) (match-beginning 1)))
10376 txt (org-link-display-format (match-string 4))
10377 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10378 re (format org-complex-heading-regexp-format
10379 (regexp-quote (match-string 4))))
10380 (when org-refile-use-outline-path
10381 (setq txt (mapconcat
10382 'org-protect-slash
10383 (append
10384 (if (eq org-refile-use-outline-path
10385 'file)
10386 (list (file-name-nondirectory
10387 (buffer-file-name
10388 (buffer-base-buffer))))
10389 (if (eq org-refile-use-outline-path
10390 'full-file-path)
10391 (list (buffer-file-name
10392 (buffer-base-buffer)))))
10393 (org-get-outline-path fast-path-p
10394 level txt)
10395 (list txt))
10396 "/")))
10397 (push (list txt f re (org-refile-marker (point)))
10398 tgs)))
10399 (when (= (point) pos0)
10400 ;; verification function has not moved point
10401 (goto-char (point-at-eol))))))))
10402 (when org-refile-use-cache
10403 (org-refile-cache-put tgs (buffer-file-name) descre))
10404 (setq targets (append tgs targets))
10405 ))))
10406 (message "Getting targets...done")
10407 (nreverse targets)))
10409 (defun org-protect-slash (s)
10410 (while (string-match "/" s)
10411 (setq s (replace-match "\\" t t s)))
10414 (defvar org-olpa (make-vector 20 nil))
10416 (defun org-get-outline-path (&optional fastp level heading)
10417 "Return the outline path to the current entry, as a list.
10419 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10420 routine which makes outline path derivations for an entire file,
10421 avoiding backtracing. Refile target collection makes use of that."
10422 (if fastp
10423 (progn
10424 (if (> level 19)
10425 (error "Outline path failure, more than 19 levels"))
10426 (loop for i from level upto 19 do
10427 (aset org-olpa i nil))
10428 (prog1
10429 (delq nil (append org-olpa nil))
10430 (aset org-olpa level heading)))
10431 (let (rtn case-fold-search)
10432 (save-excursion
10433 (save-restriction
10434 (widen)
10435 (while (org-up-heading-safe)
10436 (when (looking-at org-complex-heading-regexp)
10437 (push (org-match-string-no-properties 4) rtn)))
10438 rtn)))))
10440 (defun org-format-outline-path (path &optional width prefix)
10441 "Format the outline path PATH for display.
10442 Width is the maximum number of characters that is available.
10443 Prefix is a prefix to be included in the returned string,
10444 such as the file name."
10445 (setq width (or width 79))
10446 (if prefix (setq width (- width (length prefix))))
10447 (if (not path)
10448 (or prefix "")
10449 (let* ((nsteps (length path))
10450 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10451 (maxwidth (if (<= total-width width)
10452 10000 ;; everything fits
10453 ;; we need to shorten the level headings
10454 (/ (- width nsteps) nsteps)))
10455 (org-odd-levels-only nil)
10456 (n 0)
10457 (total (1+ (length prefix))))
10458 (setq maxwidth (max maxwidth 10))
10459 (concat prefix
10460 (mapconcat
10461 (lambda (h)
10462 (setq n (1+ n))
10463 (if (and (= n nsteps) (< maxwidth 10000))
10464 (setq maxwidth (- total-width total)))
10465 (if (< (length h) maxwidth)
10466 (progn (setq total (+ total (length h) 1)) h)
10467 (setq h (substring h 0 (- maxwidth 2))
10468 total (+ total maxwidth 1))
10469 (if (string-match "[ \t]+\\'" h)
10470 (setq h (substring h 0 (match-beginning 0))))
10471 (setq h (concat h "..")))
10472 (org-add-props h nil 'face
10473 (nth (% (1- n) org-n-level-faces)
10474 org-level-faces))
10476 path "/")))))
10478 (defun org-display-outline-path (&optional file current)
10479 "Display the current outline path in the echo area."
10480 (interactive "P")
10481 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10482 (case-fold-search nil)
10483 (path (and (eq major-mode 'org-mode) (org-get-outline-path))))
10484 (if current (setq path (append path
10485 (save-excursion
10486 (org-back-to-heading t)
10487 (if (looking-at org-complex-heading-regexp)
10488 (list (match-string 4)))))))
10489 (message "%s"
10490 (org-format-outline-path
10491 path
10492 (1- (frame-width))
10493 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10495 (defvar org-refile-history nil
10496 "History for refiling operations.")
10498 (defvar org-after-refile-insert-hook nil
10499 "Hook run after `org-refile' has inserted its stuff at the new location.
10500 Note that this is still *before* the stuff will be removed from
10501 the *old* location.")
10503 (defvar org-capture-last-stored-marker)
10504 (defun org-refile (&optional goto default-buffer rfloc)
10505 "Move the entry or entries at point to another heading.
10506 The list of target headings is compiled using the information in
10507 `org-refile-targets', which see.
10509 At the target location, the entry is filed as a subitem of the target
10510 heading. Depending on `org-reverse-note-order', the new subitem will
10511 either be the first or the last subitem.
10513 If there is an active region, all entries in that region will be moved.
10514 However, the region must fulfill the requirement that the first heading
10515 is the first one sets the top-level of the moved text - at most siblings
10516 below it are allowed.
10518 With prefix arg GOTO, the command will only visit the target location
10519 and not actually move anything.
10521 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10522 go to the location where the last refiling operation has put the subtree.
10523 With a prefix argument of `2', refile to the running clock.
10525 RFLOC can be a refile location obtained in a different way.
10527 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10529 If you are using target caching (see `org-refile-use-cache'),
10530 You have to clear the target cache in order to find new targets.
10531 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10532 prefix argument (`C-u C-u C-u C-c C-w')."
10534 (interactive "P")
10535 (if (member goto '(0 (64)))
10536 (org-refile-cache-clear)
10537 (let* ((cbuf (current-buffer))
10538 (regionp (org-region-active-p))
10539 (region-start (and regionp (region-beginning)))
10540 (region-end (and regionp (region-end)))
10541 (region-length (and regionp (- region-end region-start)))
10542 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10543 pos it nbuf file re level reversed)
10544 (setq last-command nil)
10545 (when regionp
10546 (goto-char region-start)
10547 (or (bolp) (goto-char (point-at-bol)))
10548 (setq region-start (point))
10549 (unless (or (org-kill-is-subtree-p
10550 (buffer-substring region-start region-end))
10551 (prog1 org-refile-active-region-within-subtree
10552 (org-toggle-heading)))
10553 (error "The region is not a (sequence of) subtree(s)")))
10554 (if (equal goto '(16))
10555 (org-refile-goto-last-stored)
10556 (when (or
10557 (and (equal goto 2)
10558 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10559 (prog1
10560 (setq it (list (or org-clock-heading "running clock")
10561 (buffer-file-name
10562 (marker-buffer org-clock-hd-marker))
10564 (marker-position org-clock-hd-marker)))
10565 (setq goto nil)))
10566 (setq it (or rfloc
10567 (let (heading-text)
10568 (save-excursion
10569 (unless goto
10570 (org-back-to-heading t)
10571 (setq heading-text
10572 (nth 4 (org-heading-components))))
10573 (org-refile-get-location
10574 (cond (goto "Goto")
10575 (regionp "Refile region to")
10576 (t (concat "Refile subtree \""
10577 heading-text "\" to")))
10578 default-buffer
10579 org-refile-allow-creating-parent-nodes
10580 goto))))))
10581 (setq file (nth 1 it)
10582 re (nth 2 it)
10583 pos (nth 3 it))
10584 (if (and (not goto)
10586 (equal (buffer-file-name) file)
10587 (if regionp
10588 (and (>= pos region-start)
10589 (<= pos region-end))
10590 (and (>= pos (point))
10591 (< pos (save-excursion
10592 (org-end-of-subtree t t))))))
10593 (error "Cannot refile to position inside the tree or region"))
10595 (setq nbuf (or (find-buffer-visiting file)
10596 (find-file-noselect file)))
10597 (if goto
10598 (progn
10599 (org-pop-to-buffer-same-window nbuf)
10600 (goto-char pos)
10601 (org-show-context 'org-goto))
10602 (if regionp
10603 (progn
10604 (org-kill-new (buffer-substring region-start region-end))
10605 (org-save-markers-in-region region-start region-end))
10606 (org-copy-subtree 1 nil t))
10607 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10608 (find-file-noselect file)))
10609 (setq reversed (org-notes-order-reversed-p))
10610 (save-excursion
10611 (save-restriction
10612 (widen)
10613 (if pos
10614 (progn
10615 (goto-char pos)
10616 (looking-at org-outline-regexp)
10617 (setq level (org-get-valid-level (funcall outline-level) 1))
10618 (goto-char
10619 (if reversed
10620 (or (outline-next-heading) (point-max))
10621 (or (save-excursion (org-get-next-sibling))
10622 (org-end-of-subtree t t)
10623 (point-max)))))
10624 (setq level 1)
10625 (if (not reversed)
10626 (goto-char (point-max))
10627 (goto-char (point-min))
10628 (or (outline-next-heading) (goto-char (point-max)))))
10629 (if (not (bolp)) (newline))
10630 (org-paste-subtree level)
10631 (when org-log-refile
10632 (org-add-log-setup 'refile nil nil 'findpos
10633 org-log-refile)
10634 (unless (eq org-log-refile 'note)
10635 (save-excursion (org-add-log-note))))
10636 (and org-auto-align-tags (org-set-tags nil t))
10637 (bookmark-set "org-refile-last-stored")
10638 ;; If we are refiling for capture, make sure that the
10639 ;; last-capture pointers point here
10640 (when (org-bound-and-true-p org-refile-for-capture)
10641 (bookmark-set "org-capture-last-stored-marker")
10642 (move-marker org-capture-last-stored-marker (point)))
10643 (if (fboundp 'deactivate-mark) (deactivate-mark))
10644 (run-hooks 'org-after-refile-insert-hook))))
10645 (if regionp
10646 (delete-region (point) (+ (point) region-length))
10647 (org-cut-subtree))
10648 (when (featurep 'org-inlinetask)
10649 (org-inlinetask-remove-END-maybe))
10650 (setq org-markers-to-move nil)
10651 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10653 (defun org-refile-goto-last-stored ()
10654 "Go to the location where the last refile was stored."
10655 (interactive)
10656 (bookmark-jump "org-refile-last-stored")
10657 (message "This is the location of the last refile"))
10659 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10660 no-exclude)
10661 "Prompt the user for a refile location, using PROMPT.
10662 PROMPT should not be suffixed with a colon and a space, because
10663 this function appends the default value from
10664 `org-refile-history' automatically, if that is not empty.
10665 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10666 this is used for the GOTO interface."
10667 (let ((org-refile-targets org-refile-targets)
10668 (org-refile-use-outline-path org-refile-use-outline-path)
10669 excluded-entries)
10670 (when (and (eq major-mode 'org-mode)
10671 (not org-refile-use-cache)
10672 (not no-exclude))
10673 (org-map-tree
10674 (lambda()
10675 (setq excluded-entries
10676 (append excluded-entries (list (org-get-heading t t)))))))
10677 (setq org-refile-target-table
10678 (org-refile-get-targets default-buffer excluded-entries)))
10679 (unless org-refile-target-table
10680 (error "No refile targets"))
10681 (let* ((prompt (concat prompt
10682 (and (car org-refile-history)
10683 (concat " (default " (car org-refile-history) ")"))
10684 ": "))
10685 (cbuf (current-buffer))
10686 (partial-completion-mode nil)
10687 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10688 (cfunc (if (and org-refile-use-outline-path
10689 org-outline-path-complete-in-steps)
10690 'org-olpath-completing-read
10691 'org-icompleting-read))
10692 (extra (if org-refile-use-outline-path "/" ""))
10693 (filename (and cfn (expand-file-name cfn)))
10694 (tbl (mapcar
10695 (lambda (x)
10696 (if (and (not (member org-refile-use-outline-path
10697 '(file full-file-path)))
10698 (not (equal filename (nth 1 x))))
10699 (cons (concat (car x) extra " ("
10700 (file-name-nondirectory (nth 1 x)) ")")
10701 (cdr x))
10702 (cons (concat (car x) extra) (cdr x))))
10703 org-refile-target-table))
10704 (completion-ignore-case t)
10705 pa answ parent-target child parent old-hist)
10706 (setq old-hist org-refile-history)
10707 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10708 nil 'org-refile-history (car org-refile-history)))
10709 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10710 (org-refile-check-position pa)
10711 (if pa
10712 (progn
10713 (when (or (not org-refile-history)
10714 (not (eq old-hist org-refile-history))
10715 (not (equal (car pa) (car org-refile-history))))
10716 (setq org-refile-history
10717 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10718 org-refile-history
10719 (cdr org-refile-history))))
10720 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10721 (pop org-refile-history)))
10723 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10724 (progn
10725 (setq parent (match-string 1 answ)
10726 child (match-string 2 answ))
10727 (setq parent-target (or (assoc parent tbl)
10728 (assoc (concat parent "/") tbl)))
10729 (when (and parent-target
10730 (or (eq new-nodes t)
10731 (and (eq new-nodes 'confirm)
10732 (y-or-n-p (format "Create new node \"%s\"? "
10733 child)))))
10734 (org-refile-new-child parent-target child)))
10735 (error "Invalid target location")))))
10737 (defun org-refile-check-position (refile-pointer)
10738 "Check if the refile pointer matches the readline to which it points."
10739 (let* ((file (nth 1 refile-pointer))
10740 (re (nth 2 refile-pointer))
10741 (pos (nth 3 refile-pointer))
10742 buffer)
10743 (when (org-string-nw-p re)
10744 (setq buffer (if (markerp pos)
10745 (marker-buffer pos)
10746 (or (find-buffer-visiting file)
10747 (find-file-noselect file))))
10748 (with-current-buffer buffer
10749 (save-excursion
10750 (save-restriction
10751 (widen)
10752 (goto-char pos)
10753 (beginning-of-line 1)
10754 (unless (org-looking-at-p re)
10755 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10757 (defun org-refile-new-child (parent-target child)
10758 "Use refile target PARENT-TARGET to add new CHILD below it."
10759 (unless parent-target
10760 (error "Cannot find parent for new node"))
10761 (let ((file (nth 1 parent-target))
10762 (pos (nth 3 parent-target))
10763 level)
10764 (with-current-buffer (or (find-buffer-visiting file)
10765 (find-file-noselect file))
10766 (save-excursion
10767 (save-restriction
10768 (widen)
10769 (if pos
10770 (goto-char pos)
10771 (goto-char (point-max))
10772 (if (not (bolp)) (newline)))
10773 (when (looking-at org-outline-regexp)
10774 (setq level (funcall outline-level))
10775 (org-end-of-subtree t t))
10776 (org-back-over-empty-lines)
10777 (insert "\n" (make-string
10778 (if pos (org-get-valid-level level 1) 1) ?*)
10779 " " child "\n")
10780 (beginning-of-line 0)
10781 (list (concat (car parent-target) "/" child) file "" (point)))))))
10783 (defun org-olpath-completing-read (prompt collection &rest args)
10784 "Read an outline path like a file name."
10785 (let ((thetable collection)
10786 (org-completion-use-ido nil) ; does not work with ido.
10787 (org-completion-use-iswitchb nil)) ; or iswitchb
10788 (apply
10789 'org-icompleting-read prompt
10790 (lambda (string predicate &optional flag)
10791 (let (rtn r f (l (length string)))
10792 (cond
10793 ((eq flag nil)
10794 ;; try completion
10795 (try-completion string thetable))
10796 ((eq flag t)
10797 ;; all-completions
10798 (setq rtn (all-completions string thetable predicate))
10799 (mapcar
10800 (lambda (x)
10801 (setq r (substring x l))
10802 (if (string-match " ([^)]*)$" x)
10803 (setq f (match-string 0 x))
10804 (setq f ""))
10805 (if (string-match "/" r)
10806 (concat string (substring r 0 (match-end 0)) f)
10808 rtn))
10809 ((eq flag 'lambda)
10810 ;; exact match?
10811 (assoc string thetable)))
10813 args)))
10815 ;;;; Dynamic blocks
10817 (defun org-find-dblock (name)
10818 "Find the first dynamic block with name NAME in the buffer.
10819 If not found, stay at current position and return nil."
10820 (let (pos)
10821 (save-excursion
10822 (goto-char (point-min))
10823 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10824 nil t)
10825 (match-beginning 0))))
10826 (if pos (goto-char pos))
10827 pos))
10829 (defconst org-dblock-start-re
10830 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10831 "Matches the start line of a dynamic block, with parameters.")
10833 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10834 "Matches the end of a dynamic block.")
10836 (defun org-create-dblock (plist)
10837 "Create a dynamic block section, with parameters taken from PLIST.
10838 PLIST must contain a :name entry which is used as name of the block."
10839 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10840 (end-of-line 1)
10841 (newline))
10842 (let ((col (current-column))
10843 (name (plist-get plist :name)))
10844 (insert "#+BEGIN: " name)
10845 (while plist
10846 (if (eq (car plist) :name)
10847 (setq plist (cddr plist))
10848 (insert " " (prin1-to-string (pop plist)))))
10849 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10850 (beginning-of-line -2)))
10852 (defun org-prepare-dblock ()
10853 "Prepare dynamic block for refresh.
10854 This empties the block, puts the cursor at the insert position and returns
10855 the property list including an extra property :name with the block name."
10856 (unless (looking-at org-dblock-start-re)
10857 (error "Not at a dynamic block"))
10858 (let* ((begdel (1+ (match-end 0)))
10859 (name (org-no-properties (match-string 1)))
10860 (params (append (list :name name)
10861 (read (concat "(" (match-string 3) ")")))))
10862 (save-excursion
10863 (beginning-of-line 1)
10864 (skip-chars-forward " \t")
10865 (setq params (plist-put params :indentation-column (current-column))))
10866 (unless (re-search-forward org-dblock-end-re nil t)
10867 (error "Dynamic block not terminated"))
10868 (setq params
10869 (append params
10870 (list :content (buffer-substring
10871 begdel (match-beginning 0)))))
10872 (delete-region begdel (match-beginning 0))
10873 (goto-char begdel)
10874 (open-line 1)
10875 params))
10877 (defun org-map-dblocks (&optional command)
10878 "Apply COMMAND to all dynamic blocks in the current buffer.
10879 If COMMAND is not given, use `org-update-dblock'."
10880 (let ((cmd (or command 'org-update-dblock)))
10881 (save-excursion
10882 (goto-char (point-min))
10883 (while (re-search-forward org-dblock-start-re nil t)
10884 (goto-char (match-beginning 0))
10885 (save-excursion
10886 (condition-case nil
10887 (funcall cmd)
10888 (error (message "Error during update of dynamic block"))))
10889 (unless (re-search-forward org-dblock-end-re nil t)
10890 (error "Dynamic block not terminated"))))))
10892 (defun org-dblock-update (&optional arg)
10893 "User command for updating dynamic blocks.
10894 Update the dynamic block at point. With prefix ARG, update all dynamic
10895 blocks in the buffer."
10896 (interactive "P")
10897 (if arg
10898 (org-update-all-dblocks)
10899 (or (looking-at org-dblock-start-re)
10900 (org-beginning-of-dblock))
10901 (org-update-dblock)))
10903 (defun org-update-dblock ()
10904 "Update the dynamic block at point.
10905 This means to empty the block, parse for parameters and then call
10906 the correct writing function."
10907 (interactive)
10908 (save-window-excursion
10909 (let* ((pos (point))
10910 (line (org-current-line))
10911 (params (org-prepare-dblock))
10912 (name (plist-get params :name))
10913 (indent (plist-get params :indentation-column))
10914 (cmd (intern (concat "org-dblock-write:" name))))
10915 (message "Updating dynamic block `%s' at line %d..." name line)
10916 (funcall cmd params)
10917 (message "Updating dynamic block `%s' at line %d...done" name line)
10918 (goto-char pos)
10919 (when (and indent (> indent 0))
10920 (setq indent (make-string indent ?\ ))
10921 (save-excursion
10922 (org-beginning-of-dblock)
10923 (forward-line 1)
10924 (while (not (looking-at org-dblock-end-re))
10925 (insert indent)
10926 (beginning-of-line 2))
10927 (when (looking-at org-dblock-end-re)
10928 (and (looking-at "[ \t]+")
10929 (replace-match ""))
10930 (insert indent)))))))
10932 (defun org-beginning-of-dblock ()
10933 "Find the beginning of the dynamic block at point.
10934 Error if there is no such block at point."
10935 (let ((pos (point))
10936 beg)
10937 (end-of-line 1)
10938 (if (and (re-search-backward org-dblock-start-re nil t)
10939 (setq beg (match-beginning 0))
10940 (re-search-forward org-dblock-end-re nil t)
10941 (> (match-end 0) pos))
10942 (goto-char beg)
10943 (goto-char pos)
10944 (error "Not in a dynamic block"))))
10946 (defun org-update-all-dblocks ()
10947 "Update all dynamic blocks in the buffer.
10948 This function can be used in a hook."
10949 (interactive)
10950 (when (eq major-mode 'org-mode)
10951 (org-map-dblocks 'org-update-dblock)))
10954 ;;;; Completion
10956 (defconst org-additional-option-like-keywords
10957 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
10958 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
10959 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
10960 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
10961 "BEGIN:" "END:"
10962 "ORGTBL" "TBLFM:" "TBLNAME:"
10963 "BEGIN_EXAMPLE" "END_EXAMPLE"
10964 "BEGIN_QUOTE" "END_QUOTE"
10965 "BEGIN_VERSE" "END_VERSE"
10966 "BEGIN_CENTER" "END_CENTER"
10967 "BEGIN_SRC" "END_SRC"
10968 "BEGIN_RESULT" "END_RESULT"
10969 "SOURCE:" "SRCNAME:" "FUNCTION:"
10970 "RESULTS:" "DATA:"
10971 "HEADER:" "HEADERS:"
10972 "BABEL:"
10973 "CATEGORY:" "COLUMNS:" "PROPERTY:"
10974 "CAPTION:" "LABEL:"
10975 "SETUPFILE:"
10976 "INCLUDE:"
10977 "BIND:"
10978 "MACRO:"))
10980 (defcustom org-structure-template-alist
10982 ("s" "#+begin_src ?\n\n#+end_src"
10983 "<src lang=\"?\">\n\n</src>")
10984 ("e" "#+begin_example\n?\n#+end_example"
10985 "<example>\n?\n</example>")
10986 ("q" "#+begin_quote\n?\n#+end_quote"
10987 "<quote>\n?\n</quote>")
10988 ("v" "#+begin_verse\n?\n#+end_verse"
10989 "<verse>\n?\n/verse>")
10990 ("c" "#+begin_center\n?\n#+end_center"
10991 "<center>\n?\n/center>")
10992 ("l" "#+begin_latex\n?\n#+end_latex"
10993 "<literal style=\"latex\">\n?\n</literal>")
10994 ("L" "#+latex: "
10995 "<literal style=\"latex\">?</literal>")
10996 ("h" "#+begin_html\n?\n#+end_html"
10997 "<literal style=\"html\">\n?\n</literal>")
10998 ("H" "#+html: "
10999 "<literal style=\"html\">?</literal>")
11000 ("a" "#+begin_ascii\n?\n#+end_ascii")
11001 ("A" "#+ascii: ")
11002 ("i" "#+index: ?"
11003 "#+index: ?")
11004 ("I" "#+include %file ?"
11005 "<include file=%file markup=\"?\">")
11007 "Structure completion elements.
11008 This is a list of abbreviation keys and values. The value gets inserted
11009 if you type `<' followed by the key and then press the completion key,
11010 usually `M-TAB'. %file will be replaced by a file name after prompting
11011 for the file using completion. The cursor will be placed at the position
11012 of the `?` in the template.
11013 There are two templates for each key, the first uses the original Org syntax,
11014 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11015 the default when the /org-mtags.el/ module has been loaded. See also the
11016 variable `org-mtags-prefer-muse-templates'.
11017 This is an experimental feature, it is undecided if it is going to stay in."
11018 :group 'org-completion
11019 :type '(repeat
11020 (string :tag "Key")
11021 (string :tag "Template")
11022 (string :tag "Muse Template")))
11024 (defun org-try-structure-completion ()
11025 "Try to complete a structure template before point.
11026 This looks for strings like \"<e\" on an otherwise empty line and
11027 expands them."
11028 (let ((l (buffer-substring (point-at-bol) (point)))
11030 (when (and (looking-at "[ \t]*$")
11031 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11032 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11033 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11034 (match-beginning 1)) a)
11035 t)))
11037 (defun org-complete-expand-structure-template (start cell)
11038 "Expand a structure template."
11039 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11040 (rpl (nth (if musep 2 1) cell))
11041 (ind ""))
11042 (delete-region start (point))
11043 (when (string-match "\\`#\\+" rpl)
11044 (cond
11045 ((bolp))
11046 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11047 (setq ind (buffer-substring (point-at-bol) (point))))
11048 (t (newline))))
11049 (setq start (point))
11050 (if (string-match "%file" rpl)
11051 (setq rpl (replace-match
11052 (concat
11053 "\""
11054 (save-match-data
11055 (abbreviate-file-name (read-file-name "Include file: ")))
11056 "\"")
11057 t t rpl)))
11058 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11059 (concat "\n" ind)))
11060 (insert rpl)
11061 (if (re-search-backward "\\?" start t) (delete-char 1))))
11063 ;;;; TODO, DEADLINE, Comments
11065 (defun org-toggle-comment ()
11066 "Change the COMMENT state of an entry."
11067 (interactive)
11068 (save-excursion
11069 (org-back-to-heading)
11070 (let (case-fold-search)
11071 (cond
11072 ((looking-at (format org-heading-keyword-regexp-format
11073 org-comment-string))
11074 (goto-char (match-end 1))
11075 (looking-at (concat " +" org-comment-string))
11076 (replace-match "" t t)
11077 (when (eolp) (insert " ")))
11078 ((looking-at org-outline-regexp)
11079 (goto-char (match-end 0))
11080 (insert org-comment-string " "))))))
11082 (defvar org-last-todo-state-is-todo nil
11083 "This is non-nil when the last TODO state change led to a TODO state.
11084 If the last change removed the TODO tag or switched to DONE, then
11085 this is nil.")
11087 (defvar org-setting-tags nil) ; dynamically skipped
11089 (defvar org-todo-setup-filter-hook nil
11090 "Hook for functions that pre-filter todo specs.
11091 Each function takes a todo spec and returns either nil or the spec
11092 transformed into canonical form." )
11094 (defvar org-todo-get-default-hook nil
11095 "Hook for functions that get a default item for todo.
11096 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11097 nil or a string to be used for the todo mark." )
11099 (defvar org-agenda-headline-snapshot-before-repeat)
11101 (defun org-current-effective-time ()
11102 "Return current time adjusted for `org-extend-today-until' variable"
11103 (let* ((ct (org-current-time))
11104 (dct (decode-time ct))
11105 (ct1
11106 (if (and org-use-effective-time
11107 (< (nth 2 dct) org-extend-today-until))
11108 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11109 ct)))
11110 ct1))
11112 (defun org-todo-yesterday (&optional arg)
11113 "Like `org-todo' but the time of change will be 23:59 of yesterday"
11114 (interactive "P")
11115 (let* ((hour (third (decode-time
11116 (org-current-time))))
11117 (org-extend-today-until (1+ hour)))
11118 (org-todo arg)))
11120 (defun org-todo (&optional arg)
11121 "Change the TODO state of an item.
11122 The state of an item is given by a keyword at the start of the heading,
11123 like
11124 *** TODO Write paper
11125 *** DONE Call mom
11127 The different keywords are specified in the variable `org-todo-keywords'.
11128 By default the available states are \"TODO\" and \"DONE\".
11129 So for this example: when the item starts with TODO, it is changed to DONE.
11130 When it starts with DONE, the DONE is removed. And when neither TODO nor
11131 DONE are present, add TODO at the beginning of the heading.
11133 With \\[universal-argument] prefix arg, use completion to determine the new \
11134 state.
11135 With numeric prefix arg, switch to that state.
11136 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11137 keywords (nextset).
11138 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11140 For calling through lisp, arg is also interpreted in the following way:
11141 'none -> empty state
11142 \"\"(empty string) -> switch to empty state
11143 'done -> switch to DONE
11144 'nextset -> switch to the next set of keywords
11145 'previousset -> switch to the previous set of keywords
11146 \"WAITING\" -> switch to the specified keyword, but only if it
11147 really is a member of `org-todo-keywords'."
11148 (interactive "P")
11149 (if (equal arg '(16)) (setq arg 'nextset))
11150 (let ((org-blocker-hook org-blocker-hook)
11151 (case-fold-search nil))
11152 (when (equal arg '(64))
11153 (setq arg nil org-blocker-hook nil))
11154 (when (and org-blocker-hook
11155 (or org-inhibit-blocking
11156 (org-entry-get nil "NOBLOCKING")))
11157 (setq org-blocker-hook nil))
11158 (save-excursion
11159 (catch 'exit
11160 (org-back-to-heading t)
11161 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11162 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11163 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11164 (let* ((match-data (match-data))
11165 (startpos (point-at-bol))
11166 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11167 (org-log-done org-log-done)
11168 (org-log-repeat org-log-repeat)
11169 (org-todo-log-states org-todo-log-states)
11170 (this (match-string 1))
11171 (hl-pos (match-beginning 0))
11172 (head (org-get-todo-sequence-head this))
11173 (ass (assoc head org-todo-kwd-alist))
11174 (interpret (nth 1 ass))
11175 (done-word (nth 3 ass))
11176 (final-done-word (nth 4 ass))
11177 (last-state (or this ""))
11178 (completion-ignore-case t)
11179 (member (member this org-todo-keywords-1))
11180 (tail (cdr member))
11181 (state (cond
11182 ((and org-todo-key-trigger
11183 (or (and (equal arg '(4))
11184 (eq org-use-fast-todo-selection 'prefix))
11185 (and (not arg) org-use-fast-todo-selection
11186 (not (eq org-use-fast-todo-selection
11187 'prefix)))))
11188 ;; Use fast selection
11189 (org-fast-todo-selection))
11190 ((and (equal arg '(4))
11191 (or (not org-use-fast-todo-selection)
11192 (not org-todo-key-trigger)))
11193 ;; Read a state with completion
11194 (org-icompleting-read
11195 "State: " (mapcar (lambda(x) (list x))
11196 org-todo-keywords-1)
11197 nil t))
11198 ((eq arg 'right)
11199 (if this
11200 (if tail (car tail) nil)
11201 (car org-todo-keywords-1)))
11202 ((eq arg 'left)
11203 (if (equal member org-todo-keywords-1)
11205 (if this
11206 (nth (- (length org-todo-keywords-1)
11207 (length tail) 2)
11208 org-todo-keywords-1)
11209 (org-last org-todo-keywords-1))))
11210 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11211 (setq arg nil))) ; hack to fall back to cycling
11212 (arg
11213 ;; user or caller requests a specific state
11214 (cond
11215 ((equal arg "") nil)
11216 ((eq arg 'none) nil)
11217 ((eq arg 'done) (or done-word (car org-done-keywords)))
11218 ((eq arg 'nextset)
11219 (or (car (cdr (member head org-todo-heads)))
11220 (car org-todo-heads)))
11221 ((eq arg 'previousset)
11222 (let ((org-todo-heads (reverse org-todo-heads)))
11223 (or (car (cdr (member head org-todo-heads)))
11224 (car org-todo-heads))))
11225 ((car (member arg org-todo-keywords-1)))
11226 ((stringp arg)
11227 (error "State `%s' not valid in this file" arg))
11228 ((nth (1- (prefix-numeric-value arg))
11229 org-todo-keywords-1))))
11230 ((null member) (or head (car org-todo-keywords-1)))
11231 ((equal this final-done-word) nil) ;; -> make empty
11232 ((null tail) nil) ;; -> first entry
11233 ((memq interpret '(type priority))
11234 (if (eq this-command last-command)
11235 (car tail)
11236 (if (> (length tail) 0)
11237 (or done-word (car org-done-keywords))
11238 nil)))
11240 (car tail))))
11241 (state (or
11242 (run-hook-with-args-until-success
11243 'org-todo-get-default-hook state last-state)
11244 state))
11245 (next (if state (concat " " state " ") " "))
11246 (change-plist (list :type 'todo-state-change :from this :to state
11247 :position startpos))
11248 dolog now-done-p)
11249 (when org-blocker-hook
11250 (setq org-last-todo-state-is-todo
11251 (not (member this org-done-keywords)))
11252 (unless (save-excursion
11253 (save-match-data
11254 (org-with-wide-buffer
11255 (run-hook-with-args-until-failure
11256 'org-blocker-hook change-plist))))
11257 (if (org-called-interactively-p 'interactive)
11258 (error "TODO state change from %s to %s blocked" this state)
11259 ;; fail silently
11260 (message "TODO state change from %s to %s blocked" this state)
11261 (throw 'exit nil))))
11262 (store-match-data match-data)
11263 (replace-match next t t)
11264 (unless (pos-visible-in-window-p hl-pos)
11265 (message "TODO state changed to %s" (org-trim next)))
11266 (unless head
11267 (setq head (org-get-todo-sequence-head state)
11268 ass (assoc head org-todo-kwd-alist)
11269 interpret (nth 1 ass)
11270 done-word (nth 3 ass)
11271 final-done-word (nth 4 ass)))
11272 (when (memq arg '(nextset previousset))
11273 (message "Keyword-Set %d/%d: %s"
11274 (- (length org-todo-sets) -1
11275 (length (memq (assoc state org-todo-sets) org-todo-sets)))
11276 (length org-todo-sets)
11277 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11278 (setq org-last-todo-state-is-todo
11279 (not (member state org-done-keywords)))
11280 (setq now-done-p (and (member state org-done-keywords)
11281 (not (member this org-done-keywords))))
11282 (and logging (org-local-logging logging))
11283 (when (and (or org-todo-log-states org-log-done)
11284 (not (eq org-inhibit-logging t))
11285 (not (memq arg '(nextset previousset))))
11286 ;; we need to look at recording a time and note
11287 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
11288 (nth 2 (assoc this org-todo-log-states))))
11289 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11290 (setq dolog 'time))
11291 (when (and state
11292 (member state org-not-done-keywords)
11293 (not (member this org-not-done-keywords)))
11294 ;; This is now a todo state and was not one before
11295 ;; If there was a CLOSED time stamp, get rid of it.
11296 (org-add-planning-info nil nil 'closed))
11297 (when (and now-done-p org-log-done)
11298 ;; It is now done, and it was not done before
11299 (org-add-planning-info 'closed (org-current-effective-time))
11300 (if (and (not dolog) (eq 'note org-log-done))
11301 (org-add-log-setup 'done state this 'findpos 'note)))
11302 (when (and state dolog)
11303 ;; This is a non-nil state, and we need to log it
11304 (org-add-log-setup 'state state this 'findpos dolog)))
11305 ;; Fixup tag positioning
11306 (org-todo-trigger-tag-changes state)
11307 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11308 (when org-provide-todo-statistics
11309 (org-update-parent-todo-statistics))
11310 (run-hooks 'org-after-todo-state-change-hook)
11311 (if (and arg (not (member state org-done-keywords)))
11312 (setq head (org-get-todo-sequence-head state)))
11313 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11314 ;; Do we need to trigger a repeat?
11315 (when now-done-p
11316 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11317 ;; This is for the agenda, take a snapshot of the headline.
11318 (save-match-data
11319 (setq org-agenda-headline-snapshot-before-repeat
11320 (org-get-heading))))
11321 (org-auto-repeat-maybe state))
11322 ;; Fixup cursor location if close to the keyword
11323 (if (and (outline-on-heading-p)
11324 (not (bolp))
11325 (save-excursion (beginning-of-line 1)
11326 (looking-at org-todo-line-regexp))
11327 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11328 (progn
11329 (goto-char (or (match-end 2) (match-end 1)))
11330 (and (looking-at " ") (just-one-space))))
11331 (when org-trigger-hook
11332 (save-excursion
11333 (run-hook-with-args 'org-trigger-hook change-plist))))))))
11335 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11336 "Block turning an entry into a TODO, using the hierarchy.
11337 This checks whether the current task should be blocked from state
11338 changes. Such blocking occurs when:
11340 1. The task has children which are not all in a completed state.
11342 2. A task has a parent with the property :ORDERED:, and there
11343 are siblings prior to the current task with incomplete
11344 status.
11346 3. The parent of the task is blocked because it has siblings that should
11347 be done first, or is child of a block grandparent TODO entry."
11349 (if (not org-enforce-todo-dependencies)
11350 t ; if locally turned off don't block
11351 (catch 'dont-block
11352 ;; If this is not a todo state change, or if this entry is already DONE,
11353 ;; do not block
11354 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11355 (member (plist-get change-plist :from)
11356 (cons 'done org-done-keywords))
11357 (member (plist-get change-plist :to)
11358 (cons 'todo org-not-done-keywords))
11359 (not (plist-get change-plist :to)))
11360 (throw 'dont-block t))
11361 ;; If this task has children, and any are undone, it's blocked
11362 (save-excursion
11363 (org-back-to-heading t)
11364 (let ((this-level (funcall outline-level)))
11365 (outline-next-heading)
11366 (let ((child-level (funcall outline-level)))
11367 (while (and (not (eobp))
11368 (> child-level this-level))
11369 ;; this todo has children, check whether they are all
11370 ;; completed
11371 (if (and (not (org-entry-is-done-p))
11372 (org-entry-is-todo-p))
11373 (throw 'dont-block nil))
11374 (outline-next-heading)
11375 (setq child-level (funcall outline-level))))))
11376 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11377 ;; any previous siblings are undone, it's blocked
11378 (save-excursion
11379 (org-back-to-heading t)
11380 (let* ((pos (point))
11381 (parent-pos (and (org-up-heading-safe) (point))))
11382 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11383 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11384 (forward-line 1)
11385 (re-search-forward org-not-done-heading-regexp pos t))
11386 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11387 ;; Search further up the hierarchy, to see if an anchestor is blocked
11388 (while t
11389 (goto-char parent-pos)
11390 (if (not (looking-at org-not-done-heading-regexp))
11391 (throw 'dont-block t)) ; do not block, parent is not a TODO
11392 (setq pos (point))
11393 (setq parent-pos (and (org-up-heading-safe) (point)))
11394 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11395 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11396 (forward-line 1)
11397 (re-search-forward org-not-done-heading-regexp pos t))
11398 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11400 (defcustom org-track-ordered-property-with-tag nil
11401 "Should the ORDERED property also be shown as a tag?
11402 The ORDERED property decides if an entry should require subtasks to be
11403 completed in sequence. Since a property is not very visible, setting
11404 this option means that toggling the ORDERED property with the command
11405 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11406 not relevant for the behavior, but it makes things more visible.
11408 Note that toggling the tag with tags commands will not change the property
11409 and therefore not influence behavior!
11411 This can be t, meaning the tag ORDERED should be used, It can also be a
11412 string to select a different tag for this task."
11413 :group 'org-todo
11414 :type '(choice
11415 (const :tag "No tracking" nil)
11416 (const :tag "Track with ORDERED tag" t)
11417 (string :tag "Use other tag")))
11419 (defun org-toggle-ordered-property ()
11420 "Toggle the ORDERED property of the current entry.
11421 For better visibility, you can track the value of this property with a tag.
11422 See variable `org-track-ordered-property-with-tag'."
11423 (interactive)
11424 (let* ((t1 org-track-ordered-property-with-tag)
11425 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11426 (save-excursion
11427 (org-back-to-heading)
11428 (if (org-entry-get nil "ORDERED")
11429 (progn
11430 (org-delete-property "ORDERED")
11431 (and tag (org-toggle-tag tag 'off))
11432 (message "Subtasks can be completed in arbitrary order"))
11433 (org-entry-put nil "ORDERED" "t")
11434 (and tag (org-toggle-tag tag 'on))
11435 (message "Subtasks must be completed in sequence")))))
11437 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11438 (defun org-block-todo-from-checkboxes (change-plist)
11439 "Block turning an entry into a TODO, using checkboxes.
11440 This checks whether the current task should be blocked from state
11441 changes because there are unchecked boxes in this entry."
11442 (if (not org-enforce-todo-checkbox-dependencies)
11443 t ; if locally turned off don't block
11444 (catch 'dont-block
11445 ;; If this is not a todo state change, or if this entry is already DONE,
11446 ;; do not block
11447 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11448 (member (plist-get change-plist :from)
11449 (cons 'done org-done-keywords))
11450 (member (plist-get change-plist :to)
11451 (cons 'todo org-not-done-keywords))
11452 (not (plist-get change-plist :to)))
11453 (throw 'dont-block t))
11454 ;; If this task has checkboxes that are not checked, it's blocked
11455 (save-excursion
11456 (org-back-to-heading t)
11457 (let ((beg (point)) end)
11458 (outline-next-heading)
11459 (setq end (point))
11460 (goto-char beg)
11461 (if (org-list-search-forward
11462 (concat (org-item-beginning-re)
11463 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11464 "\\[[- ]\\]")
11465 end t)
11466 (progn
11467 (if (boundp 'org-blocked-by-checkboxes)
11468 (setq org-blocked-by-checkboxes t))
11469 (throw 'dont-block nil)))))
11470 t))) ; do not block
11472 (defun org-entry-blocked-p ()
11473 "Is the current entry blocked?"
11474 (if (org-entry-get nil "NOBLOCKING")
11475 nil ;; Never block this entry
11476 (not
11477 (run-hook-with-args-until-failure
11478 'org-blocker-hook
11479 (list :type 'todo-state-change
11480 :position (point)
11481 :from 'todo
11482 :to 'done)))))
11484 (defun org-update-statistics-cookies (all)
11485 "Update the statistics cookie, either from TODO or from checkboxes.
11486 This should be called with the cursor in a line with a statistics cookie."
11487 (interactive "P")
11488 (if all
11489 (progn
11490 (org-update-checkbox-count 'all)
11491 (org-map-entries 'org-update-parent-todo-statistics))
11492 (if (not (org-on-heading-p))
11493 (org-update-checkbox-count)
11494 (let ((pos (move-marker (make-marker) (point)))
11495 end l1 l2)
11496 (ignore-errors (org-back-to-heading t))
11497 (if (not (org-on-heading-p))
11498 (org-update-checkbox-count)
11499 (setq l1 (org-outline-level))
11500 (setq end (save-excursion
11501 (outline-next-heading)
11502 (if (org-on-heading-p) (setq l2 (org-outline-level)))
11503 (point)))
11504 (if (and (save-excursion
11505 (re-search-forward
11506 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11507 (not (save-excursion (re-search-forward
11508 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11509 (org-update-checkbox-count)
11510 (if (and l2 (> l2 l1))
11511 (progn
11512 (goto-char end)
11513 (org-update-parent-todo-statistics))
11514 (goto-char pos)
11515 (beginning-of-line 1)
11516 (while (re-search-forward
11517 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11518 (point-at-eol) t)
11519 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11520 (goto-char pos)
11521 (move-marker pos nil)))))
11523 (defvar org-entry-property-inherited-from) ;; defined below
11524 (defun org-update-parent-todo-statistics ()
11525 "Update any statistics cookie in the parent of the current headline.
11526 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11527 the entire subtree and this will travel up the hierarchy and update
11528 statistics everywhere."
11529 (let* ((prop (save-excursion (org-up-heading-safe)
11530 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11531 (recursive (or (not org-hierarchical-todo-statistics)
11532 (and prop (string-match "\\<recursive\\>" prop))))
11533 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11535 (first t)
11536 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11537 level ltoggle l1 new ndel
11538 (cnt-all 0) (cnt-done 0) is-percent kwd
11539 checkbox-beg ov ovs ove cookie-present)
11540 (catch 'exit
11541 (save-excursion
11542 (beginning-of-line 1)
11543 (setq ltoggle (funcall outline-level))
11544 ;; Three situations are to consider:
11546 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11547 ;; to the top-level ancestor on the headline;
11549 ;; 2. If parent has "recursive" property, repeat up to the
11550 ;; headline setting that property, taking inheritance into
11551 ;; account;
11553 ;; 3. Else, move up to direct parent and proceed only once.
11554 (while (and (setq level (org-up-heading-safe))
11555 (or recursive first)
11556 (>= (point) lim))
11557 (setq first nil cookie-present nil)
11558 (unless (and level
11559 (not (string-match
11560 "\\<checkbox\\>"
11561 (downcase (or (org-entry-get nil "COOKIE_DATA")
11562 "")))))
11563 (throw 'exit nil))
11564 (while (re-search-forward box-re (point-at-eol) t)
11565 (setq cnt-all 0 cnt-done 0 cookie-present t)
11566 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11567 (save-match-data
11568 (unless (outline-next-heading) (throw 'exit nil))
11569 (while (and (looking-at org-complex-heading-regexp)
11570 (> (setq l1 (length (match-string 1))) level))
11571 (setq kwd (and (or recursive (= l1 ltoggle))
11572 (match-string 2)))
11573 (if (or (eq org-provide-todo-statistics 'all-headlines)
11574 (and (listp org-provide-todo-statistics)
11575 (or (member kwd org-provide-todo-statistics)
11576 (member kwd org-done-keywords))))
11577 (setq cnt-all (1+ cnt-all))
11578 (if (eq org-provide-todo-statistics t)
11579 (and kwd (setq cnt-all (1+ cnt-all)))))
11580 (and (member kwd org-done-keywords)
11581 (setq cnt-done (1+ cnt-done)))
11582 (outline-next-heading)))
11583 (setq new
11584 (if is-percent
11585 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11586 (format "[%d/%d]" cnt-done cnt-all))
11587 ndel (- (match-end 0) checkbox-beg))
11588 ;; handle overlays when updating cookie from column view
11589 (when (setq ov (car (overlays-at checkbox-beg)))
11590 (setq ovs (overlay-start ov) ove (overlay-end ov))
11591 (delete-overlay ov))
11592 (goto-char checkbox-beg)
11593 (insert new)
11594 (delete-region (point) (+ (point) ndel))
11595 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11596 (when ov (move-overlay ov ovs ove)))
11597 (when cookie-present
11598 (run-hook-with-args 'org-after-todo-statistics-hook
11599 cnt-done (- cnt-all cnt-done))))))
11600 (run-hooks 'org-todo-statistics-hook)))
11602 (defvar org-after-todo-statistics-hook nil
11603 "Hook that is called after a TODO statistics cookie has been updated.
11604 Each function is called with two arguments: the number of not-done entries
11605 and the number of done entries.
11607 For example, the following function, when added to this hook, will switch
11608 an entry to DONE when all children are done, and back to TODO when new
11609 entries are set to a TODO status. Note that this hook is only called
11610 when there is a statistics cookie in the headline!
11612 (defun org-summary-todo (n-done n-not-done)
11613 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11614 (let (org-log-done org-log-states) ; turn off logging
11615 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11618 (defvar org-todo-statistics-hook nil
11619 "Hook that is run whenever Org thinks TODO statistics should be updated.
11620 This hook runs even if there is no statistics cookie present, in which case
11621 `org-after-todo-statistics-hook' would not run.")
11623 (defun org-todo-trigger-tag-changes (state)
11624 "Apply the changes defined in `org-todo-state-tags-triggers'."
11625 (let ((l org-todo-state-tags-triggers)
11626 changes)
11627 (when (or (not state) (equal state ""))
11628 (setq changes (append changes (cdr (assoc "" l)))))
11629 (when (and (stringp state) (> (length state) 0))
11630 (setq changes (append changes (cdr (assoc state l)))))
11631 (when (member state org-not-done-keywords)
11632 (setq changes (append changes (cdr (assoc 'todo l)))))
11633 (when (member state org-done-keywords)
11634 (setq changes (append changes (cdr (assoc 'done l)))))
11635 (dolist (c changes)
11636 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11638 (defun org-local-logging (value)
11639 "Get logging settings from a property VALUE."
11640 (let* (words w a)
11641 ;; directly set the variables, they are already local.
11642 (setq org-log-done nil
11643 org-log-repeat nil
11644 org-todo-log-states nil)
11645 (setq words (org-split-string value))
11646 (while (setq w (pop words))
11647 (cond
11648 ((setq a (assoc w org-startup-options))
11649 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11650 (set (nth 1 a) (nth 2 a))))
11651 ((setq a (org-extract-log-state-settings w))
11652 (and (member (car a) org-todo-keywords-1)
11653 (push a org-todo-log-states)))))))
11655 (defun org-get-todo-sequence-head (kwd)
11656 "Return the head of the TODO sequence to which KWD belongs.
11657 If KWD is not set, check if there is a text property remembering the
11658 right sequence."
11659 (let (p)
11660 (cond
11661 ((not kwd)
11662 (or (get-text-property (point-at-bol) 'org-todo-head)
11663 (progn
11664 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11665 nil (point-at-eol)))
11666 (get-text-property p 'org-todo-head))))
11667 ((not (member kwd org-todo-keywords-1))
11668 (car org-todo-keywords-1))
11669 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11671 (defun org-fast-todo-selection ()
11672 "Fast TODO keyword selection with single keys.
11673 Returns the new TODO keyword, or nil if no state change should occur."
11674 (let* ((fulltable org-todo-key-alist)
11675 (done-keywords org-done-keywords) ;; needed for the faces.
11676 (maxlen (apply 'max (mapcar
11677 (lambda (x)
11678 (if (stringp (car x)) (string-width (car x)) 0))
11679 fulltable)))
11680 (expert nil)
11681 (fwidth (+ maxlen 3 1 3))
11682 (ncol (/ (- (window-width) 4) fwidth))
11683 tg cnt e c tbl
11684 groups ingroup)
11685 (save-excursion
11686 (save-window-excursion
11687 (if expert
11688 (set-buffer (get-buffer-create " *Org todo*"))
11689 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11690 (erase-buffer)
11691 (org-set-local 'org-done-keywords done-keywords)
11692 (setq tbl fulltable cnt 0)
11693 (while (setq e (pop tbl))
11694 (cond
11695 ((equal e '(:startgroup))
11696 (push '() groups) (setq ingroup t)
11697 (when (not (= cnt 0))
11698 (setq cnt 0)
11699 (insert "\n"))
11700 (insert "{ "))
11701 ((equal e '(:endgroup))
11702 (setq ingroup nil cnt 0)
11703 (insert "}\n"))
11704 ((equal e '(:newline))
11705 (when (not (= cnt 0))
11706 (setq cnt 0)
11707 (insert "\n")
11708 (setq e (car tbl))
11709 (while (equal (car tbl) '(:newline))
11710 (insert "\n")
11711 (setq tbl (cdr tbl)))))
11713 (setq tg (car e) c (cdr e))
11714 (if ingroup (push tg (car groups)))
11715 (setq tg (org-add-props tg nil 'face
11716 (org-get-todo-face tg)))
11717 (if (and (= cnt 0) (not ingroup)) (insert " "))
11718 (insert "[" c "] " tg (make-string
11719 (- fwidth 4 (length tg)) ?\ ))
11720 (when (= (setq cnt (1+ cnt)) ncol)
11721 (insert "\n")
11722 (if ingroup (insert " "))
11723 (setq cnt 0)))))
11724 (insert "\n")
11725 (goto-char (point-min))
11726 (if (not expert) (org-fit-window-to-buffer))
11727 (message "[a-z..]:Set [SPC]:clear")
11728 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11729 (cond
11730 ((or (= c ?\C-g)
11731 (and (= c ?q) (not (rassoc c fulltable))))
11732 (setq quit-flag t))
11733 ((= c ?\ ) nil)
11734 ((setq e (rassoc c fulltable) tg (car e))
11736 (t (setq quit-flag t)))))))
11738 (defun org-entry-is-todo-p ()
11739 (member (org-get-todo-state) org-not-done-keywords))
11741 (defun org-entry-is-done-p ()
11742 (member (org-get-todo-state) org-done-keywords))
11744 (defun org-get-todo-state ()
11745 (save-excursion
11746 (org-back-to-heading t)
11747 (and (looking-at org-todo-line-regexp)
11748 (match-end 2)
11749 (match-string 2))))
11751 (defun org-at-date-range-p (&optional inactive-ok)
11752 "Is the cursor inside a date range?"
11753 (interactive)
11754 (save-excursion
11755 (catch 'exit
11756 (let ((pos (point)))
11757 (skip-chars-backward "^[<\r\n")
11758 (skip-chars-backward "<[")
11759 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11760 (>= (match-end 0) pos)
11761 (throw 'exit t))
11762 (skip-chars-backward "^<[\r\n")
11763 (skip-chars-backward "<[")
11764 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11765 (>= (match-end 0) pos)
11766 (throw 'exit t)))
11767 nil)))
11769 (defun org-get-repeat (&optional tagline)
11770 "Check if there is a deadline/schedule with repeater in this entry."
11771 (save-match-data
11772 (save-excursion
11773 (org-back-to-heading t)
11774 (and (re-search-forward (if tagline
11775 (concat tagline "\\s-*" org-repeat-re)
11776 org-repeat-re)
11777 (org-entry-end-position) t)
11778 (match-string-no-properties 1)))))
11780 (defvar org-last-changed-timestamp)
11781 (defvar org-last-inserted-timestamp)
11782 (defvar org-log-post-message)
11783 (defvar org-log-note-purpose)
11784 (defvar org-log-note-how)
11785 (defvar org-log-note-extra)
11786 (defun org-auto-repeat-maybe (done-word)
11787 "Check if the current headline contains a repeated deadline/schedule.
11788 If yes, set TODO state back to what it was and change the base date
11789 of repeating deadline/scheduled time stamps to new date.
11790 This function is run automatically after each state change to a DONE state."
11791 ;; last-state is dynamically scoped into this function
11792 (let* ((repeat (org-get-repeat))
11793 (aa (assoc last-state org-todo-kwd-alist))
11794 (interpret (nth 1 aa))
11795 (head (nth 2 aa))
11796 (whata '(("d" . day) ("m" . month) ("y" . year)))
11797 (msg "Entry repeats: ")
11798 (org-log-done nil)
11799 (org-todo-log-states nil)
11800 re type n what ts time to-state)
11801 (when repeat
11802 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11803 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11804 org-todo-repeat-to-state))
11805 (unless (and to-state (member to-state org-todo-keywords-1))
11806 (setq to-state (if (eq interpret 'type) last-state head)))
11807 (org-todo to-state)
11808 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11809 (org-entry-put nil "LAST_REPEAT" (format-time-string
11810 (org-time-stamp-format t t))))
11811 (when org-log-repeat
11812 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11813 (memq 'org-add-log-note post-command-hook))
11814 ;; OK, we are already setup for some record
11815 (if (eq org-log-repeat 'note)
11816 ;; make sure we take a note, not only a time stamp
11817 (setq org-log-note-how 'note))
11818 ;; Set up for taking a record
11819 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11820 last-state
11821 'findpos org-log-repeat)))
11822 (org-back-to-heading t)
11823 (org-add-planning-info nil nil 'closed)
11824 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11825 org-deadline-time-regexp "\\)\\|\\("
11826 org-ts-regexp "\\)"))
11827 (while (re-search-forward
11828 re (save-excursion (outline-next-heading) (point)) t)
11829 (setq type (if (match-end 1) org-scheduled-string
11830 (if (match-end 3) org-deadline-string "Plain:"))
11831 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11832 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11833 (setq n (string-to-number (match-string 2 ts))
11834 what (match-string 3 ts))
11835 (if (equal what "w") (setq n (* n 7) what "d"))
11836 ;; Preparation, see if we need to modify the start date for the change
11837 (when (match-end 1)
11838 (setq time (save-match-data (org-time-string-to-time ts)))
11839 (cond
11840 ((equal (match-string 1 ts) ".")
11841 ;; Shift starting date to today
11842 (org-timestamp-change
11843 (- (org-today) (time-to-days time))
11844 'day))
11845 ((equal (match-string 1 ts) "+")
11846 (let ((nshiftmax 10) (nshift 0))
11847 (while (or (= nshift 0)
11848 (<= (time-to-days time)
11849 (time-to-days (current-time))))
11850 (when (= (incf nshift) nshiftmax)
11851 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11852 (error "Abort")))
11853 (org-timestamp-change n (cdr (assoc what whata)))
11854 (org-at-timestamp-p t)
11855 (setq ts (match-string 1))
11856 (setq time (save-match-data (org-time-string-to-time ts)))))
11857 (org-timestamp-change (- n) (cdr (assoc what whata)))
11858 ;; rematch, so that we have everything in place for the real shift
11859 (org-at-timestamp-p t)
11860 (setq ts (match-string 1))
11861 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11862 (org-timestamp-change n (cdr (assoc what whata)))
11863 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11864 (setq org-log-post-message msg)
11865 (message "%s" msg))))
11867 (defun org-show-todo-tree (arg)
11868 "Make a compact tree which shows all headlines marked with TODO.
11869 The tree will show the lines where the regexp matches, and all higher
11870 headlines above the match.
11871 With a \\[universal-argument] prefix, prompt for a regexp to match.
11872 With a numeric prefix N, construct a sparse tree for the Nth element
11873 of `org-todo-keywords-1'."
11874 (interactive "P")
11875 (let ((case-fold-search nil)
11876 (kwd-re
11877 (cond ((null arg) org-not-done-regexp)
11878 ((equal arg '(4))
11879 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11880 (mapcar 'list org-todo-keywords-1))))
11881 (concat "\\("
11882 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11883 "\\)\\>")))
11884 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11885 (regexp-quote (nth (1- (prefix-numeric-value arg))
11886 org-todo-keywords-1)))
11887 (t (error "Invalid prefix argument: %s" arg)))))
11888 (message "%d TODO entries found"
11889 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
11891 (defun org-deadline (&optional remove time)
11892 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11893 With argument REMOVE, remove any deadline from the item.
11894 With argument TIME, set the deadline at the corresponding date. TIME
11895 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
11896 (interactive "P")
11897 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11898 (let (org-loop-over-headlines-in-active-region)
11899 (org-map-entries
11900 `(org-deadline ',remove ,time) org-loop-over-headlines-in-active-region 'region (if (outline-invisible-p) (org-end-of-subtree nil t))))
11901 (let* ((old-date (org-entry-get nil "DEADLINE"))
11902 (repeater (and old-date
11903 (string-match
11904 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11905 old-date)
11906 (match-string 1 old-date))))
11907 (if remove
11908 (progn
11909 (when (and old-date org-log-redeadline)
11910 (org-add-log-setup 'deldeadline nil old-date 'findpos
11911 org-log-redeadline))
11912 (org-remove-timestamp-with-keyword org-deadline-string)
11913 (message "Item no longer has a deadline."))
11914 (org-add-planning-info 'deadline time 'closed)
11915 (when (and old-date org-log-redeadline
11916 (not (equal old-date
11917 (substring org-last-inserted-timestamp 1 -1))))
11918 (org-add-log-setup 'redeadline nil old-date 'findpos
11919 org-log-redeadline))
11920 (when repeater
11921 (save-excursion
11922 (org-back-to-heading t)
11923 (when (re-search-forward (concat org-deadline-string " "
11924 org-last-inserted-timestamp)
11925 (save-excursion
11926 (outline-next-heading) (point)) t)
11927 (goto-char (1- (match-end 0)))
11928 (insert " " repeater)
11929 (setq org-last-inserted-timestamp
11930 (concat (substring org-last-inserted-timestamp 0 -1)
11931 " " repeater
11932 (substring org-last-inserted-timestamp -1))))))
11933 (message "Deadline on %s" org-last-inserted-timestamp)))))
11935 (defun org-schedule (&optional remove time)
11936 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11937 With argument REMOVE, remove any scheduling date from the item.
11938 With argument TIME, scheduled at the corresponding date. TIME can
11939 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
11940 (interactive "P")
11941 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11942 (let (org-loop-over-headlines-in-active-region)
11943 (org-map-entries
11944 `(org-schedule ',remove ,time) org-loop-over-headlines-in-active-region 'region (if (outline-invisible-p) (org-end-of-subtree nil t))))
11945 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11946 (repeater (and old-date
11947 (string-match
11948 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11949 old-date)
11950 (match-string 1 old-date))))
11951 (if remove
11952 (progn
11953 (when (and old-date org-log-reschedule)
11954 (org-add-log-setup 'delschedule nil old-date 'findpos
11955 org-log-reschedule))
11956 (org-remove-timestamp-with-keyword org-scheduled-string)
11957 (message "Item is no longer scheduled."))
11958 (org-add-planning-info 'scheduled time 'closed)
11959 (when (and old-date org-log-reschedule
11960 (not (equal old-date
11961 (substring org-last-inserted-timestamp 1 -1))))
11962 (org-add-log-setup 'reschedule nil old-date 'findpos
11963 org-log-reschedule))
11964 (when repeater
11965 (save-excursion
11966 (org-back-to-heading t)
11967 (when (re-search-forward (concat org-scheduled-string " "
11968 org-last-inserted-timestamp)
11969 (save-excursion
11970 (outline-next-heading) (point)) t)
11971 (goto-char (1- (match-end 0)))
11972 (insert " " repeater)
11973 (setq org-last-inserted-timestamp
11974 (concat (substring org-last-inserted-timestamp 0 -1)
11975 " " repeater
11976 (substring org-last-inserted-timestamp -1))))))
11977 (message "Scheduled to %s" org-last-inserted-timestamp)))))
11979 (defun org-get-scheduled-time (pom &optional inherit)
11980 "Get the scheduled time as a time tuple, of a format suitable
11981 for calling org-schedule with, or if there is no scheduling,
11982 returns nil."
11983 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
11984 (when time
11985 (apply 'encode-time (org-parse-time-string time)))))
11987 (defun org-get-deadline-time (pom &optional inherit)
11988 "Get the deadline as a time tuple, of a format suitable for
11989 calling org-deadline with, or if there is no scheduling, returns
11990 nil."
11991 (let ((time (org-entry-get pom "DEADLINE" inherit)))
11992 (when time
11993 (apply 'encode-time (org-parse-time-string time)))))
11995 (defun org-remove-timestamp-with-keyword (keyword)
11996 "Remove all time stamps with KEYWORD in the current entry."
11997 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
11998 beg)
11999 (save-excursion
12000 (org-back-to-heading t)
12001 (setq beg (point))
12002 (outline-next-heading)
12003 (while (re-search-backward re beg t)
12004 (replace-match "")
12005 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12006 (equal (char-before) ?\ ))
12007 (backward-delete-char 1)
12008 (if (string-match "^[ \t]*$" (buffer-substring
12009 (point-at-bol) (point-at-eol)))
12010 (delete-region (point-at-bol)
12011 (min (point-max) (1+ (point-at-eol))))))))))
12013 (defun org-add-planning-info (what &optional time &rest remove)
12014 "Insert new timestamp with keyword in the line directly after the headline.
12015 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12016 If non is given, the user is prompted for a date.
12017 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12018 be removed."
12019 (interactive)
12020 (let (org-time-was-given org-end-time-was-given ts
12021 end default-time default-input)
12023 (catch 'exit
12024 (when (and (memq what '(scheduled deadline))
12025 (or (not time)
12026 (and (stringp time)
12027 (string-match "^[-+]+[0-9]" time))))
12028 ;; Try to get a default date/time from existing timestamp
12029 (save-excursion
12030 (org-back-to-heading t)
12031 (setq end (save-excursion (outline-next-heading) (point)))
12032 (when (re-search-forward (if (eq what 'scheduled)
12033 org-scheduled-time-regexp
12034 org-deadline-time-regexp)
12035 end t)
12036 (setq ts (match-string 1)
12037 default-time
12038 (apply 'encode-time (org-parse-time-string ts))
12039 default-input (and ts (org-get-compact-tod ts))))))
12040 (when what
12041 (setq time
12042 (if (and (stringp time)
12043 (string-match "^[-+]+[0-9]" time))
12044 ;; This is a relative time, set the proper date
12045 (apply 'encode-time
12046 (org-read-date-analyze
12047 time default-time (decode-time default-time)))
12048 ;; If necessary, get the time from the user
12049 (or time (org-read-date nil 'to-time nil nil
12050 default-time default-input)))))
12052 (when (and org-insert-labeled-timestamps-at-point
12053 (member what '(scheduled deadline)))
12054 (insert
12055 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12056 (org-insert-time-stamp time org-time-was-given
12057 nil nil nil (list org-end-time-was-given))
12058 (setq what nil))
12059 (save-excursion
12060 (save-restriction
12061 (let (col list elt ts buffer-invisibility-spec)
12062 (org-back-to-heading t)
12063 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12064 (goto-char (match-end 1))
12065 (setq col (current-column))
12066 (goto-char (match-end 0))
12067 (if (eobp) (insert "\n") (forward-char 1))
12068 (when (and (not what)
12069 (not (looking-at
12070 (concat "[ \t]*"
12071 org-keyword-time-not-clock-regexp))))
12072 ;; Nothing to add, nothing to remove...... :-)
12073 (throw 'exit nil))
12074 (if (and (not (looking-at org-outline-regexp))
12075 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12076 "[^\r\n]*"))
12077 (not (equal (match-string 1) org-clock-string)))
12078 (narrow-to-region (match-beginning 0) (match-end 0))
12079 (insert-before-markers "\n")
12080 (backward-char 1)
12081 (narrow-to-region (point) (point))
12082 (and org-adapt-indentation (org-indent-to-column col)))
12083 ;; Check if we have to remove something.
12084 (setq list (cons what remove))
12085 (while list
12086 (setq elt (pop list))
12087 (when (or (and (eq elt 'scheduled)
12088 (re-search-forward org-scheduled-time-regexp nil t))
12089 (and (eq elt 'deadline)
12090 (re-search-forward org-deadline-time-regexp nil t))
12091 (and (eq elt 'closed)
12092 (re-search-forward org-closed-time-regexp nil t)))
12093 (replace-match "")
12094 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12095 (and (looking-at "[ \t]+") (replace-match ""))
12096 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12097 (when what
12098 (insert
12099 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12100 (cond ((eq what 'scheduled) org-scheduled-string)
12101 ((eq what 'deadline) org-deadline-string)
12102 ((eq what 'closed) org-closed-string))
12103 " ")
12104 (setq ts (org-insert-time-stamp
12105 time
12106 (or org-time-was-given
12107 (and (eq what 'closed) org-log-done-with-time))
12108 (eq what 'closed)
12109 nil nil (list org-end-time-was-given)))
12110 (insert
12111 (if (not (or (bolp) (eq (char-before) ?\ )
12112 (memq (char-after) '(32 10))
12113 (eobp))) " " ""))
12114 (end-of-line 1))
12115 (goto-char (point-min))
12116 (widen)
12117 (if (and (looking-at "[ \t]*\n")
12118 (equal (char-before) ?\n))
12119 (delete-region (1- (point)) (point-at-eol)))
12120 ts))))))
12122 (defvar org-log-note-marker (make-marker))
12123 (defvar org-log-note-purpose nil)
12124 (defvar org-log-note-state nil)
12125 (defvar org-log-note-previous-state nil)
12126 (defvar org-log-note-how nil)
12127 (defvar org-log-note-extra nil)
12128 (defvar org-log-note-window-configuration nil)
12129 (defvar org-log-note-return-to (make-marker))
12130 (defvar org-log-note-effective-time nil
12131 "Remembered current time so that dynamically scoped
12132 `org-extend-today-until' affects tha timestamps in state change
12133 log")
12135 (defvar org-log-post-message nil
12136 "Message to be displayed after a log note has been stored.
12137 The auto-repeater uses this.")
12139 (defun org-add-note ()
12140 "Add a note to the current entry.
12141 This is done in the same way as adding a state change note."
12142 (interactive)
12143 (org-add-log-setup 'note nil nil 'findpos nil))
12145 (defvar org-property-end-re)
12146 (defun org-add-log-setup (&optional purpose state prev-state
12147 findpos how extra)
12148 "Set up the post command hook to take a note.
12149 If this is about to TODO state change, the new state is expected in STATE.
12150 When FINDPOS is non-nil, find the correct position for the note in
12151 the current entry. If not, assume that it can be inserted at point.
12152 HOW is an indicator what kind of note should be created.
12153 EXTRA is additional text that will be inserted into the notes buffer."
12154 (let* ((org-log-into-drawer (org-log-into-drawer))
12155 (drawer (cond ((stringp org-log-into-drawer)
12156 org-log-into-drawer)
12157 (org-log-into-drawer "LOGBOOK")
12158 (t nil))))
12159 (save-restriction
12160 (save-excursion
12161 (when findpos
12162 (org-back-to-heading t)
12163 (narrow-to-region (point) (save-excursion
12164 (outline-next-heading) (point)))
12165 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12166 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12167 "[^\r\n]*\\)?"))
12168 (goto-char (match-end 0))
12169 (cond
12170 (drawer
12171 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12172 nil t)
12173 (progn
12174 (goto-char (match-end 0))
12175 (or org-log-states-order-reversed
12176 (and (re-search-forward org-property-end-re nil t)
12177 (goto-char (1- (match-beginning 0))))))
12178 (insert "\n:" drawer ":\n:END:")
12179 (beginning-of-line 0)
12180 (org-indent-line-function)
12181 (beginning-of-line 2)
12182 (org-indent-line-function)
12183 (end-of-line 0)))
12184 ((and org-log-state-notes-insert-after-drawers
12185 (save-excursion
12186 (forward-line) (looking-at org-drawer-regexp)))
12187 (forward-line)
12188 (while (looking-at org-drawer-regexp)
12189 (goto-char (match-end 0))
12190 (re-search-forward org-property-end-re (point-max) t)
12191 (forward-line))
12192 (forward-line -1)))
12193 (unless org-log-states-order-reversed
12194 (and (= (char-after) ?\n) (forward-char 1))
12195 (org-skip-over-state-notes)
12196 (skip-chars-backward " \t\n\r")))
12197 (move-marker org-log-note-marker (point))
12198 (setq org-log-note-purpose purpose
12199 org-log-note-state state
12200 org-log-note-previous-state prev-state
12201 org-log-note-how how
12202 org-log-note-extra extra
12203 org-log-note-effective-time (org-current-effective-time))
12204 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12206 (defun org-skip-over-state-notes ()
12207 "Skip past the list of State notes in an entry."
12208 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12209 (when (ignore-errors (goto-char (org-in-item-p)))
12210 (let* ((struct (org-list-struct))
12211 (prevs (org-list-prevs-alist struct)))
12212 (while (looking-at "[ \t]*- State")
12213 (goto-char (or (org-list-get-next-item (point) struct prevs)
12214 (org-list-get-item-end (point) struct)))))))
12216 (defun org-add-log-note (&optional purpose)
12217 "Pop up a window for taking a note, and add this note later at point."
12218 (remove-hook 'post-command-hook 'org-add-log-note)
12219 (setq org-log-note-window-configuration (current-window-configuration))
12220 (delete-other-windows)
12221 (move-marker org-log-note-return-to (point))
12222 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12223 (goto-char org-log-note-marker)
12224 (org-switch-to-buffer-other-window "*Org Note*")
12225 (erase-buffer)
12226 (if (memq org-log-note-how '(time state))
12227 (let (current-prefix-arg) (org-store-log-note))
12228 (let ((org-inhibit-startup t)) (org-mode))
12229 (insert (format "# Insert note for %s.
12230 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12231 (cond
12232 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12233 ((eq org-log-note-purpose 'done) "closed todo item")
12234 ((eq org-log-note-purpose 'state)
12235 (format "state change from \"%s\" to \"%s\""
12236 (or org-log-note-previous-state "")
12237 (or org-log-note-state "")))
12238 ((eq org-log-note-purpose 'reschedule)
12239 "rescheduling")
12240 ((eq org-log-note-purpose 'delschedule)
12241 "no longer scheduled")
12242 ((eq org-log-note-purpose 'redeadline)
12243 "changing deadline")
12244 ((eq org-log-note-purpose 'deldeadline)
12245 "removing deadline")
12246 ((eq org-log-note-purpose 'refile)
12247 "refiling")
12248 ((eq org-log-note-purpose 'note)
12249 "this entry")
12250 (t (error "This should not happen")))))
12251 (if org-log-note-extra (insert org-log-note-extra))
12252 (org-set-local 'org-finish-function 'org-store-log-note)
12253 (run-hooks 'org-log-buffer-setup-hook)))
12255 (defvar org-note-abort nil) ; dynamically scoped
12256 (defun org-store-log-note ()
12257 "Finish taking a log note, and insert it to where it belongs."
12258 (let ((txt (buffer-string))
12259 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12260 lines ind bul)
12261 (kill-buffer (current-buffer))
12262 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12263 (setq txt (replace-match "" t t txt)))
12264 (if (string-match "\\s-+\\'" txt)
12265 (setq txt (replace-match "" t t txt)))
12266 (setq lines (org-split-string txt "\n"))
12267 (when (and note (string-match "\\S-" note))
12268 (setq note
12269 (org-replace-escapes
12270 note
12271 (list (cons "%u" (user-login-name))
12272 (cons "%U" user-full-name)
12273 (cons "%t" (format-time-string
12274 (org-time-stamp-format 'long 'inactive)
12275 org-log-note-effective-time))
12276 (cons "%T" (format-time-string
12277 (org-time-stamp-format 'long nil)
12278 org-log-note-effective-time))
12279 (cons "%d" (format-time-string
12280 (org-time-stamp-format nil 'inactive)
12281 org-log-note-effective-time))
12282 (cons "%D" (format-time-string
12283 (org-time-stamp-format nil nil)
12284 org-log-note-effective-time))
12285 (cons "%s" (if org-log-note-state
12286 (concat "\"" org-log-note-state "\"")
12287 ""))
12288 (cons "%S" (if org-log-note-previous-state
12289 (concat "\"" org-log-note-previous-state "\"")
12290 "\"\"")))))
12291 (if lines (setq note (concat note " \\\\")))
12292 (push note lines))
12293 (when (or current-prefix-arg org-note-abort)
12294 (when org-log-into-drawer
12295 (org-remove-empty-drawer-at
12296 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12297 org-log-note-marker))
12298 (setq lines nil))
12299 (when lines
12300 (with-current-buffer (marker-buffer org-log-note-marker)
12301 (save-excursion
12302 (goto-char org-log-note-marker)
12303 (move-marker org-log-note-marker nil)
12304 (end-of-line 1)
12305 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12306 (setq ind (save-excursion
12307 (if (ignore-errors (goto-char (org-in-item-p)))
12308 (let ((struct (org-list-struct)))
12309 (org-list-get-ind
12310 (org-list-get-top-point struct) struct))
12311 (skip-chars-backward " \r\t\n")
12312 (cond
12313 ((and (org-at-heading-p)
12314 org-adapt-indentation)
12315 (1+ (org-current-level)))
12316 ((org-at-heading-p) 0)
12317 (t (org-get-indentation))))))
12318 (setq bul (org-list-bullet-string "-"))
12319 (org-indent-line-to ind)
12320 (insert bul (pop lines))
12321 (let ((ind-body (+ (length bul) ind)))
12322 (while lines
12323 (insert "\n")
12324 (org-indent-line-to ind-body)
12325 (insert (pop lines))))
12326 (message "Note stored")
12327 (org-back-to-heading t)
12328 (org-cycle-hide-drawers 'children)))))
12329 (set-window-configuration org-log-note-window-configuration)
12330 (with-current-buffer (marker-buffer org-log-note-return-to)
12331 (goto-char org-log-note-return-to))
12332 (move-marker org-log-note-return-to nil)
12333 (and org-log-post-message (message "%s" org-log-post-message)))
12335 (defun org-remove-empty-drawer-at (drawer pos)
12336 "Remove an empty drawer DRAWER at position POS.
12337 POS may also be a marker."
12338 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12339 (save-excursion
12340 (save-restriction
12341 (widen)
12342 (goto-char pos)
12343 (if (org-in-regexp
12344 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12345 (replace-match ""))))))
12347 (defun org-sparse-tree (&optional arg)
12348 "Create a sparse tree, prompt for the details.
12349 This command can create sparse trees. You first need to select the type
12350 of match used to create the tree:
12352 t Show all TODO entries.
12353 T Show entries with a specific TODO keyword.
12354 m Show entries selected by a tags/property match.
12355 p Enter a property name and its value (both with completion on existing
12356 names/values) and show entries with that property.
12357 r Show entries matching a regular expression (`/' can be used as well)
12358 d Show deadlines due within `org-deadline-warning-days'.
12359 b Show deadlines and scheduled items before a date.
12360 a Show deadlines and scheduled items after a date."
12361 (interactive "P")
12362 (let (ans kwd value)
12363 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date")
12364 (setq ans (read-char-exclusive))
12365 (cond
12366 ((equal ans ?d)
12367 (call-interactively 'org-check-deadlines))
12368 ((equal ans ?b)
12369 (call-interactively 'org-check-before-date))
12370 ((equal ans ?a)
12371 (call-interactively 'org-check-after-date))
12372 ((equal ans ?t)
12373 (org-show-todo-tree nil))
12374 ((equal ans ?T)
12375 (org-show-todo-tree '(4)))
12376 ((member ans '(?T ?m))
12377 (call-interactively 'org-match-sparse-tree))
12378 ((member ans '(?p ?P))
12379 (setq kwd (org-icompleting-read "Property: "
12380 (mapcar 'list (org-buffer-property-keys))))
12381 (setq value (org-icompleting-read "Value: "
12382 (mapcar 'list (org-property-values kwd))))
12383 (unless (string-match "\\`{.*}\\'" value)
12384 (setq value (concat "\"" value "\"")))
12385 (org-match-sparse-tree arg (concat kwd "=" value)))
12386 ((member ans '(?r ?R ?/))
12387 (call-interactively 'org-occur))
12388 (t (error "No such sparse tree command \"%c\"" ans)))))
12390 (defvar org-occur-highlights nil
12391 "List of overlays used for occur matches.")
12392 (make-variable-buffer-local 'org-occur-highlights)
12393 (defvar org-occur-parameters nil
12394 "Parameters of the active org-occur calls.
12395 This is a list, each call to org-occur pushes as cons cell,
12396 containing the regular expression and the callback, onto the list.
12397 The list can contain several entries if `org-occur' has been called
12398 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12399 will only contain one set of parameters. When the highlights are
12400 removed (for example with `C-c C-c', or with the next edit (depending
12401 on `org-remove-highlights-with-change'), this variable is emptied
12402 as well.")
12403 (make-variable-buffer-local 'org-occur-parameters)
12405 (defun org-occur (regexp &optional keep-previous callback)
12406 "Make a compact tree which shows all matches of REGEXP.
12407 The tree will show the lines where the regexp matches, and all higher
12408 headlines above the match. It will also show the heading after the match,
12409 to make sure editing the matching entry is easy.
12410 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12411 call to `org-occur' will be kept, to allow stacking of calls to this
12412 command.
12413 If CALLBACK is non-nil, it is a function which is called to confirm
12414 that the match should indeed be shown."
12415 (interactive "sRegexp: \nP")
12416 (when (equal regexp "")
12417 (error "Regexp cannot be empty"))
12418 (unless keep-previous
12419 (org-remove-occur-highlights nil nil t))
12420 (push (cons regexp callback) org-occur-parameters)
12421 (let ((cnt 0))
12422 (save-excursion
12423 (goto-char (point-min))
12424 (if (or (not keep-previous) ; do not want to keep
12425 (not org-occur-highlights)) ; no previous matches
12426 ;; hide everything
12427 (org-overview))
12428 (while (re-search-forward regexp nil t)
12429 (when (or (not callback)
12430 (save-match-data (funcall callback)))
12431 (setq cnt (1+ cnt))
12432 (when org-highlight-sparse-tree-matches
12433 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12434 (org-show-context 'occur-tree))))
12435 (when org-remove-highlights-with-change
12436 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12437 nil 'local))
12438 (unless org-sparse-tree-open-archived-trees
12439 (org-hide-archived-subtrees (point-min) (point-max)))
12440 (run-hooks 'org-occur-hook)
12441 (if (org-called-interactively-p 'interactive)
12442 (message "%d match(es) for regexp %s" cnt regexp))
12443 cnt))
12445 (defun org-occur-next-match (&optional n reset)
12446 "Function for `next-error-function' to find sparse tree matches.
12447 N is the number of matches to move, when negative move backwards.
12448 RESET is entirely ignored - this function always goes back to the
12449 starting point when no match is found."
12450 (let* ((limit (if (< n 0) (point-min) (point-max)))
12451 (search-func (if (< n 0)
12452 'previous-single-char-property-change
12453 'next-single-char-property-change))
12454 (n (abs n))
12455 (pos (point))
12457 (catch 'exit
12458 (while (setq p1 (funcall search-func (point) 'org-type))
12459 (when (equal p1 limit)
12460 (goto-char pos)
12461 (error "No more matches"))
12462 (when (equal (get-char-property p1 'org-type) 'org-occur)
12463 (setq n (1- n))
12464 (when (= n 0)
12465 (goto-char p1)
12466 (throw 'exit (point))))
12467 (goto-char p1))
12468 (goto-char p1)
12469 (error "No more matches"))))
12471 (defun org-show-context (&optional key)
12472 "Make sure point and context are visible.
12473 How much context is shown depends upon the variables
12474 `org-show-hierarchy-above', `org-show-following-heading'. and
12475 `org-show-siblings'."
12476 (let ((heading-p (org-on-heading-p t))
12477 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12478 (following-p (org-get-alist-option org-show-following-heading key))
12479 (entry-p (org-get-alist-option org-show-entry-below key))
12480 (siblings-p (org-get-alist-option org-show-siblings key)))
12481 (catch 'exit
12482 ;; Show heading or entry text
12483 (if (and heading-p (not entry-p))
12484 (org-flag-heading nil) ; only show the heading
12485 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12486 (org-show-hidden-entry))) ; show entire entry
12487 (when following-p
12488 ;; Show next sibling, or heading below text
12489 (save-excursion
12490 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12491 (org-flag-heading nil))))
12492 (when siblings-p (org-show-siblings))
12493 (when hierarchy-p
12494 ;; show all higher headings, possibly with siblings
12495 (save-excursion
12496 (while (and (condition-case nil
12497 (progn (org-up-heading-all 1) t)
12498 (error nil))
12499 (not (bobp)))
12500 (org-flag-heading nil)
12501 (when siblings-p (org-show-siblings))))))))
12503 (defvar org-reveal-start-hook nil
12504 "Hook run before revealing a location.")
12506 (defun org-reveal (&optional siblings)
12507 "Show current entry, hierarchy above it, and the following headline.
12508 This can be used to show a consistent set of context around locations
12509 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12510 not t for the search context.
12512 With optional argument SIBLINGS, on each level of the hierarchy all
12513 siblings are shown. This repairs the tree structure to what it would
12514 look like when opened with hierarchical calls to `org-cycle'.
12515 With double optional argument \\[universal-argument] \\[universal-argument], \
12516 go to the parent and show the
12517 entire tree."
12518 (interactive "P")
12519 (run-hooks 'org-reveal-start-hook)
12520 (let ((org-show-hierarchy-above t)
12521 (org-show-following-heading t)
12522 (org-show-siblings (if siblings t org-show-siblings)))
12523 (org-show-context nil))
12524 (when (equal siblings '(16))
12525 (save-excursion
12526 (when (org-up-heading-safe)
12527 (org-show-subtree)
12528 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12530 (defun org-highlight-new-match (beg end)
12531 "Highlight from BEG to END and mark the highlight is an occur headline."
12532 (let ((ov (make-overlay beg end)))
12533 (overlay-put ov 'face 'secondary-selection)
12534 (overlay-put ov 'org-type 'org-occur)
12535 (push ov org-occur-highlights)))
12537 (defun org-remove-occur-highlights (&optional beg end noremove)
12538 "Remove the occur highlights from the buffer.
12539 BEG and END are ignored. If NOREMOVE is nil, remove this function
12540 from the `before-change-functions' in the current buffer."
12541 (interactive)
12542 (unless org-inhibit-highlight-removal
12543 (mapc 'delete-overlay org-occur-highlights)
12544 (setq org-occur-highlights nil)
12545 (setq org-occur-parameters nil)
12546 (unless noremove
12547 (remove-hook 'before-change-functions
12548 'org-remove-occur-highlights 'local))))
12550 ;;;; Priorities
12552 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12553 "Regular expression matching the priority indicator.")
12555 (defvar org-remove-priority-next-time nil)
12557 (defun org-priority-up ()
12558 "Increase the priority of the current item."
12559 (interactive)
12560 (org-priority 'up))
12562 (defun org-priority-down ()
12563 "Decrease the priority of the current item."
12564 (interactive)
12565 (org-priority 'down))
12567 (defun org-priority (&optional action)
12568 "Change the priority of an item by ARG.
12569 ACTION can be `set', `up', `down', or a character."
12570 (interactive)
12571 (unless org-enable-priority-commands
12572 (error "Priority commands are disabled"))
12573 (setq action (or action 'set))
12574 (let (current new news have remove)
12575 (save-excursion
12576 (org-back-to-heading t)
12577 (if (looking-at org-priority-regexp)
12578 (setq current (string-to-char (match-string 2))
12579 have t))
12580 (cond
12581 ((eq action 'remove)
12582 (setq remove t new ?\ ))
12583 ((or (eq action 'set)
12584 (if (featurep 'xemacs) (characterp action) (integerp action)))
12585 (if (not (eq action 'set))
12586 (setq new action)
12587 (message "Priority %c-%c, SPC to remove: "
12588 org-highest-priority org-lowest-priority)
12589 (save-match-data
12590 (setq new (read-char-exclusive))))
12591 (if (and (= (upcase org-highest-priority) org-highest-priority)
12592 (= (upcase org-lowest-priority) org-lowest-priority))
12593 (setq new (upcase new)))
12594 (cond ((equal new ?\ ) (setq remove t))
12595 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12596 (error "Priority must be between `%c' and `%c'"
12597 org-highest-priority org-lowest-priority))))
12598 ((eq action 'up)
12599 (setq new (if have
12600 (1- current) ; normal cycling
12601 ;; last priority was empty
12602 (if (eq last-command this-command)
12603 org-lowest-priority ; wrap around empty to lowest
12604 ;; default
12605 (if org-priority-start-cycle-with-default
12606 org-default-priority
12607 (1- org-default-priority))))))
12608 ((eq action 'down)
12609 (setq new (if have
12610 (1+ current) ; normal cycling
12611 ;; last priority was empty
12612 (if (eq last-command this-command)
12613 org-highest-priority ; wrap around empty to highest
12614 ;; default
12615 (if org-priority-start-cycle-with-default
12616 org-default-priority
12617 (1+ org-default-priority))))))
12618 (t (error "Invalid action")))
12619 (if (or (< (upcase new) org-highest-priority)
12620 (> (upcase new) org-lowest-priority))
12621 (if (and (memq action '(up down))
12622 (not have) (not (eq last-command this-command)))
12623 ;; `new' is from default priority
12624 (error
12625 "The default can not be set, see `org-default-priority' why")
12626 ;; normal cycling: `new' is beyond highest/lowest priority
12627 ;; and is wrapped around to the empty priority
12628 (setq remove t)))
12629 (setq news (format "%c" new))
12630 (if have
12631 (if remove
12632 (replace-match "" t t nil 1)
12633 (replace-match news t t nil 2))
12634 (if remove
12635 (error "No priority cookie found in line")
12636 (let ((case-fold-search nil))
12637 (looking-at org-todo-line-regexp))
12638 (if (match-end 2)
12639 (progn
12640 (goto-char (match-end 2))
12641 (insert " [#" news "]"))
12642 (goto-char (match-beginning 3))
12643 (insert "[#" news "] "))))
12644 (org-preserve-lc (org-set-tags nil 'align)))
12645 (if remove
12646 (message "Priority removed")
12647 (message "Priority of current item set to %s" news))))
12649 (defun org-get-priority (s)
12650 "Find priority cookie and return priority."
12651 (if (functionp org-get-priority-function)
12652 (funcall org-get-priority-function)
12653 (save-match-data
12654 (if (not (string-match org-priority-regexp s))
12655 (* 1000 (- org-lowest-priority org-default-priority))
12656 (* 1000 (- org-lowest-priority
12657 (string-to-char (match-string 2 s))))))))
12659 ;;;; Tags
12661 (defvar org-agenda-archives-mode)
12662 (defvar org-map-continue-from nil
12663 "Position from where mapping should continue.
12664 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
12666 (defvar org-scanner-tags nil
12667 "The current tag list while the tags scanner is running.")
12668 (defvar org-trust-scanner-tags nil
12669 "Should `org-get-tags-at' use the tags for the scanner.
12670 This is for internal dynamical scoping only.
12671 When this is non-nil, the function `org-get-tags-at' will return the value
12672 of `org-scanner-tags' instead of building the list by itself. This
12673 can lead to large speed-ups when the tags scanner is used in a file with
12674 many entries, and when the list of tags is retrieved, for example to
12675 obtain a list of properties. Building the tags list for each entry in such
12676 a file becomes an N^2 operation - but with this variable set, it scales
12677 as N.")
12679 (defun org-scan-tags (action matcher &optional todo-only)
12680 "Scan headline tags with inheritance and produce output ACTION.
12682 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12683 or `agenda' to produce an entry list for an agenda view. It can also be
12684 a Lisp form or a function that should be called at each matched headline, in
12685 this case the return value is a list of all return values from these calls.
12687 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12688 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12689 only lines with a TODO keyword are included in the output."
12690 (require 'org-agenda)
12691 (let* ((re (concat "^" org-outline-regexp " *\\(\\<\\("
12692 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12693 (org-re
12694 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12695 (props (list 'face 'default
12696 'done-face 'org-agenda-done
12697 'undone-face 'default
12698 'mouse-face 'highlight
12699 'org-not-done-regexp org-not-done-regexp
12700 'org-todo-regexp org-todo-regexp
12701 'help-echo
12702 (format "mouse-2 or RET jump to org file %s"
12703 (abbreviate-file-name
12704 (or (buffer-file-name (buffer-base-buffer))
12705 (buffer-name (buffer-base-buffer)))))))
12706 (case-fold-search nil)
12707 (org-map-continue-from nil)
12708 lspos tags tags-list
12709 (tags-alist (list (cons 0 org-file-tags)))
12710 (llast 0) rtn rtn1 level category i txt
12711 todo marker entry priority)
12712 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12713 (setq action (list 'lambda nil action)))
12714 (save-excursion
12715 (goto-char (point-min))
12716 (when (eq action 'sparse-tree)
12717 (org-overview)
12718 (org-remove-occur-highlights))
12719 (while (re-search-forward re nil t)
12720 (catch :skip
12721 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12722 tags (if (match-end 4) (org-match-string-no-properties 4)))
12723 (goto-char (setq lspos (match-beginning 0)))
12724 (setq level (org-reduced-level (funcall outline-level))
12725 category (org-get-category))
12726 (setq i llast llast level)
12727 ;; remove tag lists from same and sublevels
12728 (while (>= i level)
12729 (when (setq entry (assoc i tags-alist))
12730 (setq tags-alist (delete entry tags-alist)))
12731 (setq i (1- i)))
12732 ;; add the next tags
12733 (when tags
12734 (setq tags (org-split-string tags ":")
12735 tags-alist
12736 (cons (cons level tags) tags-alist)))
12737 ;; compile tags for current headline
12738 (setq tags-list
12739 (if org-use-tag-inheritance
12740 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12741 tags)
12742 org-scanner-tags tags-list)
12743 (when org-use-tag-inheritance
12744 (setcdr (car tags-alist)
12745 (mapcar (lambda (x)
12746 (setq x (copy-sequence x))
12747 (org-add-prop-inherited x))
12748 (cdar tags-alist))))
12749 (when (and tags org-use-tag-inheritance
12750 (or (not (eq t org-use-tag-inheritance))
12751 org-tags-exclude-from-inheritance))
12752 ;; selective inheritance, remove uninherited ones
12753 (setcdr (car tags-alist)
12754 (org-remove-uninherited-tags (cdar tags-alist))))
12755 (when (and
12757 ;; eval matcher only when the todo condition is OK
12758 (and (or (not todo-only) (member todo org-not-done-keywords))
12759 (let ((case-fold-search t)) (eval matcher)))
12761 ;; Call the skipper, but return t if it does not skip,
12762 ;; so that the `and' form continues evaluating
12763 (progn
12764 (unless (eq action 'sparse-tree) (org-agenda-skip))
12767 ;; Check if timestamps are deselecting this entry
12768 (or (not todo-only)
12769 (and (member todo org-not-done-keywords)
12770 (or (not org-agenda-tags-todo-honor-ignore-options)
12771 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12773 ;; Extra check for the archive tag
12774 ;; FIXME: Does the skipper already do this????
12776 (not (member org-archive-tag tags-list))
12777 ;; we have an archive tag, should we use this anyway?
12778 (or (not org-agenda-skip-archived-trees)
12779 (and (eq action 'agenda) org-agenda-archives-mode))))
12781 ;; select this headline
12783 (cond
12784 ((eq action 'sparse-tree)
12785 (and org-highlight-sparse-tree-matches
12786 (org-get-heading) (match-end 0)
12787 (org-highlight-new-match
12788 (match-beginning 0) (match-beginning 1)))
12789 (org-show-context 'tags-tree))
12790 ((eq action 'agenda)
12791 (setq txt (org-agenda-format-item
12793 (concat
12794 (if (eq org-tags-match-list-sublevels 'indented)
12795 (make-string (1- level) ?.) "")
12796 (org-get-heading))
12797 category
12798 tags-list
12800 priority (org-get-priority txt))
12801 (goto-char lspos)
12802 (setq marker (org-agenda-new-marker))
12803 (org-add-props txt props
12804 'org-marker marker 'org-hd-marker marker 'org-category category
12805 'todo-state todo
12806 'priority priority 'type "tagsmatch")
12807 (push txt rtn))
12808 ((functionp action)
12809 (setq org-map-continue-from nil)
12810 (save-excursion
12811 (setq rtn1 (funcall action))
12812 (push rtn1 rtn)))
12813 (t (error "Invalid action")))
12815 ;; if we are to skip sublevels, jump to end of subtree
12816 (unless org-tags-match-list-sublevels
12817 (org-end-of-subtree t)
12818 (backward-char 1))))
12819 ;; Get the correct position from where to continue
12820 (if org-map-continue-from
12821 (goto-char org-map-continue-from)
12822 (and (= (point) lspos) (end-of-line 1)))))
12823 (when (and (eq action 'sparse-tree)
12824 (not org-sparse-tree-open-archived-trees))
12825 (org-hide-archived-subtrees (point-min) (point-max)))
12826 (nreverse rtn)))
12828 (defun org-remove-uninherited-tags (tags)
12829 "Remove all tags that are not inherited from the list TAGS."
12830 (cond
12831 ((eq org-use-tag-inheritance t)
12832 (if org-tags-exclude-from-inheritance
12833 (org-delete-all org-tags-exclude-from-inheritance tags)
12834 tags))
12835 ((not org-use-tag-inheritance) nil)
12836 ((stringp org-use-tag-inheritance)
12837 (delq nil (mapcar
12838 (lambda (x)
12839 (if (and (string-match org-use-tag-inheritance x)
12840 (not (member x org-tags-exclude-from-inheritance)))
12841 x nil))
12842 tags)))
12843 ((listp org-use-tag-inheritance)
12844 (delq nil (mapcar
12845 (lambda (x)
12846 (if (member x org-use-tag-inheritance) x nil))
12847 tags)))))
12849 (defvar todo-only) ;; dynamically scoped
12851 (defun org-match-sparse-tree (&optional todo-only match)
12852 "Create a sparse tree according to tags string MATCH.
12853 MATCH can contain positive and negative selection of tags, like
12854 \"+WORK+URGENT-WITHBOSS\".
12855 If optional argument TODO-ONLY is non-nil, only select lines that are
12856 also TODO lines."
12857 (interactive "P")
12858 (org-prepare-agenda-buffers (list (current-buffer)))
12859 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12861 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12863 (defvar org-cached-props nil)
12864 (defun org-cached-entry-get (pom property)
12865 (if (or (eq t org-use-property-inheritance)
12866 (and (stringp org-use-property-inheritance)
12867 (string-match org-use-property-inheritance property))
12868 (and (listp org-use-property-inheritance)
12869 (member property org-use-property-inheritance)))
12870 ;; Caching is not possible, check it directly
12871 (org-entry-get pom property 'inherit)
12872 ;; Get all properties, so that we can do complicated checks easily
12873 (cdr (assoc property (or org-cached-props
12874 (setq org-cached-props
12875 (org-entry-properties pom)))))))
12877 (defun org-global-tags-completion-table (&optional files)
12878 "Return the list of all tags in all agenda buffer/files.
12879 Optional FILES argument is a list of files to which can be used
12880 instead of the agenda files."
12881 (save-excursion
12882 (org-uniquify
12883 (delq nil
12884 (apply 'append
12885 (mapcar
12886 (lambda (file)
12887 (set-buffer (find-file-noselect file))
12888 (append (org-get-buffer-tags)
12889 (mapcar (lambda (x) (if (stringp (car-safe x))
12890 (list (car-safe x)) nil))
12891 org-tag-alist)))
12892 (if (and files (car files))
12893 files
12894 (org-agenda-files))))))))
12896 (defun org-make-tags-matcher (match)
12897 "Create the TAGS/TODO matcher form for the selection string MATCH."
12898 ;; todo-only is scoped dynamically into this function, and the function
12899 ;; may change it if the matcher asks for it.
12900 (unless match
12901 ;; Get a new match request, with completion
12902 (let ((org-last-tags-completion-table
12903 (org-global-tags-completion-table)))
12904 (setq match (org-completing-read-no-i
12905 "Match: " 'org-tags-completion-function nil nil nil
12906 'org-tags-history))))
12908 ;; Parse the string and create a lisp form
12909 (let ((match0 match)
12910 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
12911 minus tag mm
12912 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12913 orterms term orlist re-p str-p level-p level-op time-p
12914 prop-p pn pv po gv rest)
12915 (if (string-match "/+" match)
12916 ;; match contains also a todo-matching request
12917 (progn
12918 (setq tagsmatch (substring match 0 (match-beginning 0))
12919 todomatch (substring match (match-end 0)))
12920 (if (string-match "^!" todomatch)
12921 (setq todo-only t todomatch (substring todomatch 1)))
12922 (if (string-match "^\\s-*$" todomatch)
12923 (setq todomatch nil)))
12924 ;; only matching tags
12925 (setq tagsmatch match todomatch nil))
12927 ;; Make the tags matcher
12928 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12929 (setq tagsmatcher t)
12930 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12931 (while (setq term (pop orterms))
12932 (while (and (equal (substring term -1) "\\") orterms)
12933 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12934 (while (string-match re term)
12935 (setq rest (substring term (match-end 0))
12936 minus (and (match-end 1)
12937 (equal (match-string 1 term) "-"))
12938 tag (save-match-data (replace-regexp-in-string
12939 "\\\\-" "-"
12940 (match-string 2 term)))
12941 re-p (equal (string-to-char tag) ?{)
12942 level-p (match-end 4)
12943 prop-p (match-end 5)
12944 mm (cond
12945 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12946 (level-p
12947 (setq level-op (org-op-to-function (match-string 3 term)))
12948 `(,level-op level ,(string-to-number
12949 (match-string 4 term))))
12950 (prop-p
12951 (setq pn (match-string 5 term)
12952 po (match-string 6 term)
12953 pv (match-string 7 term)
12954 re-p (equal (string-to-char pv) ?{)
12955 str-p (equal (string-to-char pv) ?\")
12956 time-p (save-match-data
12957 (string-match "^\"[[<].*[]>]\"$" pv))
12958 pv (if (or re-p str-p) (substring pv 1 -1) pv))
12959 (if time-p (setq pv (org-matcher-time pv)))
12960 (setq po (org-op-to-function po (if time-p 'time str-p)))
12961 (cond
12962 ((equal pn "CATEGORY")
12963 (setq gv '(get-text-property (point) 'org-category)))
12964 ((equal pn "TODO")
12965 (setq gv 'todo))
12967 (setq gv `(org-cached-entry-get nil ,pn))))
12968 (if re-p
12969 (if (eq po 'org<>)
12970 `(not (string-match ,pv (or ,gv "")))
12971 `(string-match ,pv (or ,gv "")))
12972 (if str-p
12973 `(,po (or ,gv "") ,pv)
12974 `(,po (string-to-number (or ,gv ""))
12975 ,(string-to-number pv) ))))
12976 (t `(member ,tag tags-list)))
12977 mm (if minus (list 'not mm) mm)
12978 term rest)
12979 (push mm tagsmatcher))
12980 (push (if (> (length tagsmatcher) 1)
12981 (cons 'and tagsmatcher)
12982 (car tagsmatcher))
12983 orlist)
12984 (setq tagsmatcher nil))
12985 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
12986 (setq tagsmatcher
12987 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
12988 ;; Make the todo matcher
12989 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
12990 (setq todomatcher t)
12991 (setq orterms (org-split-string todomatch "|") orlist nil)
12992 (while (setq term (pop orterms))
12993 (while (string-match re term)
12994 (setq minus (and (match-end 1)
12995 (equal (match-string 1 term) "-"))
12996 kwd (match-string 2 term)
12997 re-p (equal (string-to-char kwd) ?{)
12998 term (substring term (match-end 0))
12999 mm (if re-p
13000 `(string-match ,(substring kwd 1 -1) todo)
13001 (list 'equal 'todo kwd))
13002 mm (if minus (list 'not mm) mm))
13003 (push mm todomatcher))
13004 (push (if (> (length todomatcher) 1)
13005 (cons 'and todomatcher)
13006 (car todomatcher))
13007 orlist)
13008 (setq todomatcher nil))
13009 (setq todomatcher (if (> (length orlist) 1)
13010 (cons 'or orlist) (car orlist))))
13012 ;; Return the string and lisp forms of the matcher
13013 (setq matcher (if todomatcher
13014 (list 'and tagsmatcher todomatcher)
13015 tagsmatcher))
13016 (cons match0 matcher)))
13018 (defun org-op-to-function (op &optional stringp)
13019 "Turn an operator into the appropriate function."
13020 (setq op
13021 (cond
13022 ((equal op "<" ) '(< string< org-time<))
13023 ((equal op ">" ) '(> org-string> org-time>))
13024 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13025 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13026 ((member op '("=" "==")) '(= string= org-time=))
13027 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13028 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13030 (defun org<> (a b) (not (= a b)))
13031 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13032 (defun org-string>= (a b) (not (string< a b)))
13033 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13034 (defun org-string<> (a b) (not (string= a b)))
13035 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13036 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13037 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13038 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13039 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13040 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13041 (defun org-2ft (s)
13042 "Convert S to a floating point time.
13043 If S is already a number, just return it. If it is a string, parse
13044 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13045 (cond
13046 ((numberp s) s)
13047 ((stringp s)
13048 (condition-case nil
13049 (float-time (apply 'encode-time (org-parse-time-string s)))
13050 (error 0.)))
13051 (t 0.)))
13053 (defun org-time-today ()
13054 "Time in seconds today at 0:00.
13055 Returns the float number of seconds since the beginning of the
13056 epoch to the beginning of today (00:00)."
13057 (float-time (apply 'encode-time
13058 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13060 (defun org-matcher-time (s)
13061 "Interpret a time comparison value."
13062 (save-match-data
13063 (cond
13064 ((string= s "<now>") (float-time))
13065 ((string= s "<today>") (org-time-today))
13066 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13067 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13068 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
13069 (+ (org-time-today)
13070 (* (string-to-number (match-string 1 s))
13071 (cdr (assoc (match-string 2 s)
13072 '(("d" . 86400.0) ("w" . 604800.0)
13073 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13074 (t (org-2ft s)))))
13076 (defun org-match-any-p (re list)
13077 "Does re match any element of list?"
13078 (setq list (mapcar (lambda (x) (string-match re x)) list))
13079 (delq nil list))
13081 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13082 (defvar org-tags-overlay (make-overlay 1 1))
13083 (org-detach-overlay org-tags-overlay)
13085 (defun org-get-local-tags-at (&optional pos)
13086 "Get a list of tags defined in the current headline."
13087 (org-get-tags-at pos 'local))
13089 (defun org-get-local-tags ()
13090 "Get a list of tags defined in the current headline."
13091 (org-get-tags-at nil 'local))
13093 (defun org-get-tags-at (&optional pos local)
13094 "Get a list of all headline tags applicable at POS.
13095 POS defaults to point. If tags are inherited, the list contains
13096 the targets in the same sequence as the headlines appear, i.e.
13097 the tags of the current headline come last.
13098 When LOCAL is non-nil, only return tags from the current headline,
13099 ignore inherited ones."
13100 (interactive)
13101 (if (and org-trust-scanner-tags
13102 (or (not pos) (equal pos (point)))
13103 (not local))
13104 org-scanner-tags
13105 (let (tags ltags lastpos parent)
13106 (save-excursion
13107 (save-restriction
13108 (widen)
13109 (goto-char (or pos (point)))
13110 (save-match-data
13111 (catch 'done
13112 (condition-case nil
13113 (progn
13114 (org-back-to-heading t)
13115 (while (not (equal lastpos (point)))
13116 (setq lastpos (point))
13117 (when (looking-at
13118 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13119 (setq ltags (org-split-string
13120 (org-match-string-no-properties 1) ":"))
13121 (when parent
13122 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13123 (setq tags (append
13124 (if parent
13125 (org-remove-uninherited-tags ltags)
13126 ltags)
13127 tags)))
13128 (or org-use-tag-inheritance (throw 'done t))
13129 (if local (throw 'done t))
13130 (or (org-up-heading-safe) (error nil))
13131 (setq parent t)))
13132 (error nil)))))
13133 (if local
13134 tags
13135 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13137 (defun org-add-prop-inherited (s)
13138 (add-text-properties 0 (length s) '(inherited t) s)
13141 (defun org-toggle-tag (tag &optional onoff)
13142 "Toggle the tag TAG for the current line.
13143 If ONOFF is `on' or `off', don't toggle but set to this state."
13144 (let (res current)
13145 (save-excursion
13146 (org-back-to-heading t)
13147 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13148 (point-at-eol) t)
13149 (progn
13150 (setq current (match-string 1))
13151 (replace-match ""))
13152 (setq current ""))
13153 (setq current (nreverse (org-split-string current ":")))
13154 (cond
13155 ((eq onoff 'on)
13156 (setq res t)
13157 (or (member tag current) (push tag current)))
13158 ((eq onoff 'off)
13159 (or (not (member tag current)) (setq current (delete tag current))))
13160 (t (if (member tag current)
13161 (setq current (delete tag current))
13162 (setq res t)
13163 (push tag current))))
13164 (end-of-line 1)
13165 (if current
13166 (progn
13167 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13168 (org-set-tags nil t))
13169 (delete-horizontal-space))
13170 (run-hooks 'org-after-tags-change-hook))
13171 res))
13173 (defun org-align-tags-here (to-col)
13174 ;; Assumes that this is a headline
13175 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13176 (beginning-of-line 1)
13177 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13178 (< pos (match-beginning 2)))
13179 (progn
13180 (setq tags-l (- (match-end 2) (match-beginning 2)))
13181 (goto-char (match-beginning 1))
13182 (insert " ")
13183 (delete-region (point) (1+ (match-beginning 2)))
13184 (setq ncol (max (current-column)
13185 (1+ col)
13186 (if (> to-col 0)
13187 to-col
13188 (- (abs to-col) tags-l))))
13189 (setq p (point))
13190 (insert (make-string (- ncol (current-column)) ?\ ))
13191 (setq ncol (current-column))
13192 (when indent-tabs-mode (tabify p (point-at-eol)))
13193 (org-move-to-column (min ncol col) t))
13194 (goto-char pos))))
13196 (defun org-set-tags-command (&optional arg just-align)
13197 "Call the set-tags command for the current entry."
13198 (interactive "P")
13199 (if (org-on-heading-p)
13200 (org-set-tags arg just-align)
13201 (save-excursion
13202 (org-back-to-heading t)
13203 (org-set-tags arg just-align))))
13205 (defun org-set-tags-to (data)
13206 "Set the tags of the current entry to DATA, replacing the current tags.
13207 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13208 If DATA is nil or the empty string, any tags will be removed."
13209 (interactive "sTags: ")
13210 (setq data
13211 (cond
13212 ((eq data nil) "")
13213 ((equal data "") "")
13214 ((stringp data)
13215 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13216 ":"))
13217 ((listp data)
13218 (concat ":" (mapconcat 'identity data ":") ":"))
13219 (t nil)))
13220 (when data
13221 (save-excursion
13222 (org-back-to-heading t)
13223 (when (looking-at org-complex-heading-regexp)
13224 (if (match-end 5)
13225 (progn
13226 (goto-char (match-beginning 5))
13227 (insert data)
13228 (delete-region (point) (point-at-eol))
13229 (org-set-tags nil 'align))
13230 (goto-char (point-at-eol))
13231 (insert " " data)
13232 (org-set-tags nil 'align)))
13233 (beginning-of-line 1)
13234 (if (looking-at ".*?\\([ \t]+\\)$")
13235 (delete-region (match-beginning 1) (match-end 1))))))
13237 (defun org-align-all-tags ()
13238 "Align the tags i all headings."
13239 (interactive)
13240 (save-excursion
13241 (or (ignore-errors (org-back-to-heading t))
13242 (outline-next-heading))
13243 (if (org-on-heading-p)
13244 (org-set-tags t)
13245 (message "No headings"))))
13247 (defvar org-indent-indentation-per-level)
13248 (defun org-set-tags (&optional arg just-align)
13249 "Set the tags for the current headline.
13250 With prefix ARG, realign all tags in headings in the current buffer."
13251 (interactive "P")
13252 (let* ((re org-outline-regexp-bol)
13253 (current (org-get-tags-string))
13254 (col (current-column))
13255 (org-setting-tags t)
13256 table current-tags inherited-tags ; computed below when needed
13257 tags p0 c0 c1 rpl di tc level)
13258 (if arg
13259 (save-excursion
13260 (goto-char (point-min))
13261 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13262 (while (re-search-forward re nil t)
13263 (org-set-tags nil t)
13264 (end-of-line 1)))
13265 (message "All tags realigned to column %d" org-tags-column))
13266 (if just-align
13267 (setq tags current)
13268 ;; Get a new set of tags from the user
13269 (save-excursion
13270 (setq table (append org-tag-persistent-alist
13271 (or org-tag-alist (org-get-buffer-tags))
13272 (and
13273 org-complete-tags-always-offer-all-agenda-tags
13274 (org-global-tags-completion-table
13275 (org-agenda-files))))
13276 org-last-tags-completion-table table
13277 current-tags (org-split-string current ":")
13278 inherited-tags (nreverse
13279 (nthcdr (length current-tags)
13280 (nreverse (org-get-tags-at))))
13281 tags
13282 (if (or (eq t org-use-fast-tag-selection)
13283 (and org-use-fast-tag-selection
13284 (delq nil (mapcar 'cdr table))))
13285 (org-fast-tag-selection
13286 current-tags inherited-tags table
13287 (if org-fast-tag-selection-include-todo
13288 org-todo-key-alist))
13289 (let ((org-add-colon-after-tag-completion t))
13290 (org-trim
13291 (org-icompleting-read "Tags: "
13292 'org-tags-completion-function
13293 nil nil current 'org-tags-history))))))
13294 (while (string-match "[-+&]+" tags)
13295 ;; No boolean logic, just a list
13296 (setq tags (replace-match ":" t t tags))))
13298 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13300 (if org-tags-sort-function
13301 (setq tags (mapconcat 'identity
13302 (sort (org-split-string
13303 tags (org-re "[^[:alnum:]_@#%]+"))
13304 org-tags-sort-function) ":")))
13306 (if (string-match "\\`[\t ]*\\'" tags)
13307 (setq tags "")
13308 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13309 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13311 ;; Insert new tags at the correct column
13312 (beginning-of-line 1)
13313 (setq level (or (and (looking-at org-outline-regexp)
13314 (- (match-end 0) (point) 1))
13316 (cond
13317 ((and (equal current "") (equal tags "")))
13318 ((re-search-forward
13319 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13320 (point-at-eol) t)
13321 (if (equal tags "")
13322 (setq rpl "")
13323 (goto-char (match-beginning 0))
13324 (setq c0 (current-column)
13325 ;; compute offset for the case of org-indent-mode active
13326 di (if org-indent-mode
13327 (* (1- org-indent-indentation-per-level) (1- level))
13329 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13330 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13331 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13332 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13333 (replace-match rpl t t)
13334 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13335 tags)
13336 (t (error "Tags alignment failed")))
13337 (org-move-to-column col)
13338 (unless just-align
13339 (run-hooks 'org-after-tags-change-hook)))))
13341 (defun org-change-tag-in-region (beg end tag off)
13342 "Add or remove TAG for each entry in the region.
13343 This works in the agenda, and also in an org-mode buffer."
13344 (interactive
13345 (list (region-beginning) (region-end)
13346 (let ((org-last-tags-completion-table
13347 (if (eq major-mode 'org-mode)
13348 (org-get-buffer-tags)
13349 (org-global-tags-completion-table))))
13350 (org-icompleting-read
13351 "Tag: " 'org-tags-completion-function nil nil nil
13352 'org-tags-history))
13353 (progn
13354 (message "[s]et or [r]emove? ")
13355 (equal (read-char-exclusive) ?r))))
13356 (if (fboundp 'deactivate-mark) (deactivate-mark))
13357 (let ((agendap (equal major-mode 'org-agenda-mode))
13358 l1 l2 m buf pos newhead (cnt 0))
13359 (goto-char end)
13360 (setq l2 (1- (org-current-line)))
13361 (goto-char beg)
13362 (setq l1 (org-current-line))
13363 (loop for l from l1 to l2 do
13364 (org-goto-line l)
13365 (setq m (get-text-property (point) 'org-hd-marker))
13366 (when (or (and (eq major-mode 'org-mode) (org-on-heading-p))
13367 (and agendap m))
13368 (setq buf (if agendap (marker-buffer m) (current-buffer))
13369 pos (if agendap m (point)))
13370 (with-current-buffer buf
13371 (save-excursion
13372 (save-restriction
13373 (goto-char pos)
13374 (setq cnt (1+ cnt))
13375 (org-toggle-tag tag (if off 'off 'on))
13376 (setq newhead (org-get-heading)))))
13377 (and agendap (org-agenda-change-all-lines newhead m))))
13378 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13380 (defun org-tags-completion-function (string predicate &optional flag)
13381 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13382 (confirm (lambda (x) (stringp (car x)))))
13383 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13384 (setq s1 (match-string 1 string)
13385 s2 (match-string 2 string))
13386 (setq s1 "" s2 string))
13387 (cond
13388 ((eq flag nil)
13389 ;; try completion
13390 (setq rtn (try-completion s2 ctable confirm))
13391 (if (stringp rtn)
13392 (setq rtn
13393 (concat s1 s2 (substring rtn (length s2))
13394 (if (and org-add-colon-after-tag-completion
13395 (assoc rtn ctable))
13396 ":" ""))))
13397 rtn)
13398 ((eq flag t)
13399 ;; all-completions
13400 (all-completions s2 ctable confirm)
13402 ((eq flag 'lambda)
13403 ;; exact match?
13404 (assoc s2 ctable)))
13407 (defun org-fast-tag-insert (kwd tags face &optional end)
13408 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13409 (insert (format "%-12s" (concat kwd ":"))
13410 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13411 (or end "")))
13413 (defun org-fast-tag-show-exit (flag)
13414 (save-excursion
13415 (org-goto-line 3)
13416 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13417 (replace-match ""))
13418 (when flag
13419 (end-of-line 1)
13420 (org-move-to-column (- (window-width) 19) t)
13421 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13423 (defun org-set-current-tags-overlay (current prefix)
13424 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13425 (if (featurep 'xemacs)
13426 (org-overlay-display org-tags-overlay (concat prefix s)
13427 'secondary-selection)
13428 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13429 (org-overlay-display org-tags-overlay (concat prefix s)))))
13431 (defvar org-last-tag-selection-key nil)
13432 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13433 "Fast tag selection with single keys.
13434 CURRENT is the current list of tags in the headline, INHERITED is the
13435 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13436 possibly with grouping information. TODO-TABLE is a similar table with
13437 TODO keywords, should these have keys assigned to them.
13438 If the keys are nil, a-z are automatically assigned.
13439 Returns the new tags string, or nil to not change the current settings."
13440 (let* ((fulltable (append table todo-table))
13441 (maxlen (apply 'max (mapcar
13442 (lambda (x)
13443 (if (stringp (car x)) (string-width (car x)) 0))
13444 fulltable)))
13445 (buf (current-buffer))
13446 (expert (eq org-fast-tag-selection-single-key 'expert))
13447 (buffer-tags nil)
13448 (fwidth (+ maxlen 3 1 3))
13449 (ncol (/ (- (window-width) 4) fwidth))
13450 (i-face 'org-done)
13451 (c-face 'org-todo)
13452 tg cnt e c char c1 c2 ntable tbl rtn
13453 ov-start ov-end ov-prefix
13454 (exit-after-next org-fast-tag-selection-single-key)
13455 (done-keywords org-done-keywords)
13456 groups ingroup)
13457 (save-excursion
13458 (beginning-of-line 1)
13459 (if (looking-at
13460 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13461 (setq ov-start (match-beginning 1)
13462 ov-end (match-end 1)
13463 ov-prefix "")
13464 (setq ov-start (1- (point-at-eol))
13465 ov-end (1+ ov-start))
13466 (skip-chars-forward "^\n\r")
13467 (setq ov-prefix
13468 (concat
13469 (buffer-substring (1- (point)) (point))
13470 (if (> (current-column) org-tags-column)
13472 (make-string (- org-tags-column (current-column)) ?\ ))))))
13473 (move-overlay org-tags-overlay ov-start ov-end)
13474 (save-window-excursion
13475 (if expert
13476 (set-buffer (get-buffer-create " *Org tags*"))
13477 (delete-other-windows)
13478 (split-window-vertically)
13479 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13480 (erase-buffer)
13481 (org-set-local 'org-done-keywords done-keywords)
13482 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13483 (org-fast-tag-insert "Current" current c-face "\n\n")
13484 (org-fast-tag-show-exit exit-after-next)
13485 (org-set-current-tags-overlay current ov-prefix)
13486 (setq tbl fulltable char ?a cnt 0)
13487 (while (setq e (pop tbl))
13488 (cond
13489 ((equal (car e) :startgroup)
13490 (push '() groups) (setq ingroup t)
13491 (when (not (= cnt 0))
13492 (setq cnt 0)
13493 (insert "\n"))
13494 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13495 ((equal (car e) :endgroup)
13496 (setq ingroup nil cnt 0)
13497 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13498 ((equal e '(:newline))
13499 (when (not (= cnt 0))
13500 (setq cnt 0)
13501 (insert "\n")
13502 (setq e (car tbl))
13503 (while (equal (car tbl) '(:newline))
13504 (insert "\n")
13505 (setq tbl (cdr tbl)))))
13507 (setq tg (copy-sequence (car e)) c2 nil)
13508 (if (cdr e)
13509 (setq c (cdr e))
13510 ;; automatically assign a character.
13511 (setq c1 (string-to-char
13512 (downcase (substring
13513 tg (if (= (string-to-char tg) ?@) 1 0)))))
13514 (if (or (rassoc c1 ntable) (rassoc c1 table))
13515 (while (or (rassoc char ntable) (rassoc char table))
13516 (setq char (1+ char)))
13517 (setq c2 c1))
13518 (setq c (or c2 char)))
13519 (if ingroup (push tg (car groups)))
13520 (setq tg (org-add-props tg nil 'face
13521 (cond
13522 ((not (assoc tg table))
13523 (org-get-todo-face tg))
13524 ((member tg current) c-face)
13525 ((member tg inherited) i-face)
13526 (t nil))))
13527 (if (and (= cnt 0) (not ingroup)) (insert " "))
13528 (insert "[" c "] " tg (make-string
13529 (- fwidth 4 (length tg)) ?\ ))
13530 (push (cons tg c) ntable)
13531 (when (= (setq cnt (1+ cnt)) ncol)
13532 (insert "\n")
13533 (if ingroup (insert " "))
13534 (setq cnt 0)))))
13535 (setq ntable (nreverse ntable))
13536 (insert "\n")
13537 (goto-char (point-min))
13538 (if (not expert) (org-fit-window-to-buffer))
13539 (setq rtn
13540 (catch 'exit
13541 (while t
13542 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13543 (if (not groups) "no " "")
13544 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13545 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13546 (setq org-last-tag-selection-key c)
13547 (cond
13548 ((= c ?\r) (throw 'exit t))
13549 ((= c ?!)
13550 (setq groups (not groups))
13551 (goto-char (point-min))
13552 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13553 ((= c ?\C-c)
13554 (if (not expert)
13555 (org-fast-tag-show-exit
13556 (setq exit-after-next (not exit-after-next)))
13557 (setq expert nil)
13558 (delete-other-windows)
13559 (set-window-buffer (split-window-vertically) " *Org tags*")
13560 (org-switch-to-buffer-other-window " *Org tags*")
13561 (org-fit-window-to-buffer)))
13562 ((or (= c ?\C-g)
13563 (and (= c ?q) (not (rassoc c ntable))))
13564 (org-detach-overlay org-tags-overlay)
13565 (setq quit-flag t))
13566 ((= c ?\ )
13567 (setq current nil)
13568 (if exit-after-next (setq exit-after-next 'now)))
13569 ((= c ?\t)
13570 (condition-case nil
13571 (setq tg (org-icompleting-read
13572 "Tag: "
13573 (or buffer-tags
13574 (with-current-buffer buf
13575 (org-get-buffer-tags)))))
13576 (quit (setq tg "")))
13577 (when (string-match "\\S-" tg)
13578 (add-to-list 'buffer-tags (list tg))
13579 (if (member tg current)
13580 (setq current (delete tg current))
13581 (push tg current)))
13582 (if exit-after-next (setq exit-after-next 'now)))
13583 ((setq e (rassoc c todo-table) tg (car e))
13584 (with-current-buffer buf
13585 (save-excursion (org-todo tg)))
13586 (if exit-after-next (setq exit-after-next 'now)))
13587 ((setq e (rassoc c ntable) tg (car e))
13588 (if (member tg current)
13589 (setq current (delete tg current))
13590 (loop for g in groups do
13591 (if (member tg g)
13592 (mapc (lambda (x)
13593 (setq current (delete x current)))
13594 g)))
13595 (push tg current))
13596 (if exit-after-next (setq exit-after-next 'now))))
13598 ;; Create a sorted list
13599 (setq current
13600 (sort current
13601 (lambda (a b)
13602 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13603 (if (eq exit-after-next 'now) (throw 'exit t))
13604 (goto-char (point-min))
13605 (beginning-of-line 2)
13606 (delete-region (point) (point-at-eol))
13607 (org-fast-tag-insert "Current" current c-face)
13608 (org-set-current-tags-overlay current ov-prefix)
13609 (while (re-search-forward
13610 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13611 (setq tg (match-string 1))
13612 (add-text-properties
13613 (match-beginning 1) (match-end 1)
13614 (list 'face
13615 (cond
13616 ((member tg current) c-face)
13617 ((member tg inherited) i-face)
13618 (t (get-text-property (match-beginning 1) 'face))))))
13619 (goto-char (point-min)))))
13620 (org-detach-overlay org-tags-overlay)
13621 (if rtn
13622 (mapconcat 'identity current ":")
13623 nil))))
13625 (defun org-get-tags-string ()
13626 "Get the TAGS string in the current headline."
13627 (unless (org-on-heading-p t)
13628 (error "Not on a heading"))
13629 (save-excursion
13630 (beginning-of-line 1)
13631 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13632 (org-match-string-no-properties 1)
13633 "")))
13635 (defun org-get-tags ()
13636 "Get the list of tags specified in the current headline."
13637 (org-split-string (org-get-tags-string) ":"))
13639 (defun org-get-buffer-tags ()
13640 "Get a table of all tags used in the buffer, for completion."
13641 (let (tags)
13642 (save-excursion
13643 (goto-char (point-min))
13644 (while (re-search-forward
13645 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13646 (when (equal (char-after (point-at-bol 0)) ?*)
13647 (mapc (lambda (x) (add-to-list 'tags x))
13648 (org-split-string (org-match-string-no-properties 1) ":")))))
13649 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13650 (mapcar 'list tags)))
13652 ;;;; The mapping API
13654 ;;;###autoload
13655 (defun org-map-entries (func &optional match scope &rest skip)
13656 "Call FUNC at each headline selected by MATCH in SCOPE.
13658 FUNC is a function or a lisp form. The function will be called without
13659 arguments, with the cursor positioned at the beginning of the headline.
13660 The return values of all calls to the function will be collected and
13661 returned as a list.
13663 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13664 does not need to preserve point. After evaluation, the cursor will be
13665 moved to the end of the line (presumably of the headline of the
13666 processed entry) and search continues from there. Under some
13667 circumstances, this may not produce the wanted results. For example,
13668 if you have removed (e.g. archived) the current (sub)tree it could
13669 mean that the next entry will be skipped entirely. In such cases, you
13670 can specify the position from where search should continue by making
13671 FUNC set the variable `org-map-continue-from' to the desired buffer
13672 position.
13674 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13675 Only headlines that are matched by this query will be considered during
13676 the iteration. When MATCH is nil or t, all headlines will be
13677 visited by the iteration.
13679 SCOPE determines the scope of this command. It can be any of:
13681 nil The current buffer, respecting the restriction if any
13682 tree The subtree started with the entry at point
13683 region The entries within the active region, if any
13684 file The current buffer, without restriction
13685 file-with-archives
13686 The current buffer, and any archives associated with it
13687 agenda All agenda files
13688 agenda-with-archives
13689 All agenda files with any archive files associated with them
13690 \(file1 file2 ...)
13691 If this is a list, all files in the list will be scanned
13693 The remaining args are treated as settings for the skipping facilities of
13694 the scanner. The following items can be given here:
13696 archive skip trees with the archive tag.
13697 comment skip trees with the COMMENT keyword
13698 function or Emacs Lisp form:
13699 will be used as value for `org-agenda-skip-function', so whenever
13700 the function returns t, FUNC will not be called for that
13701 entry and search will continue from the point where the
13702 function leaves it.
13704 If your function needs to retrieve the tags including inherited tags
13705 at the *current* entry, you can use the value of the variable
13706 `org-scanner-tags' which will be much faster than getting the value
13707 with `org-get-tags-at'. If your function gets properties with
13708 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13709 to t around the call to `org-entry-properties' to get the same speedup.
13710 Note that if your function moves around to retrieve tags and properties at
13711 a *different* entry, you cannot use these techniques."
13712 (unless (and (eq scope 'region) (not (org-region-active-p)))
13713 (let* ((org-agenda-archives-mode nil) ; just to make sure
13714 (org-agenda-skip-archived-trees (memq 'archive skip))
13715 (org-agenda-skip-comment-trees (memq 'comment skip))
13716 (org-agenda-skip-function
13717 (car (org-delete-all '(comment archive) skip)))
13718 (org-tags-match-list-sublevels t)
13719 matcher file res
13720 org-todo-keywords-for-agenda
13721 org-done-keywords-for-agenda
13722 org-todo-keyword-alist-for-agenda
13723 org-drawers-for-agenda
13724 org-tag-alist-for-agenda)
13726 (cond
13727 ((eq match t) (setq matcher t))
13728 ((eq match nil) (setq matcher t))
13729 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13731 (save-excursion
13732 (save-restriction
13733 (cond ((eq scope 'tree)
13734 (org-back-to-heading t)
13735 (org-narrow-to-subtree)
13736 (setq scope nil))
13737 ((and (eq scope 'region) (org-region-active-p))
13738 (narrow-to-region (region-beginning)
13739 (save-excursion
13740 (goto-char (region-end))
13741 (unless (and (bolp) (org-at-heading-p))
13742 (outline-next-heading))
13743 (point)))
13744 (setq scope nil)))
13746 (if (not scope)
13747 (progn
13748 (org-prepare-agenda-buffers
13749 (list (buffer-file-name (current-buffer))))
13750 (setq res (org-scan-tags func matcher)))
13751 ;; Get the right scope
13752 (cond
13753 ((and scope (listp scope) (symbolp (car scope)))
13754 (setq scope (eval scope)))
13755 ((eq scope 'agenda)
13756 (setq scope (org-agenda-files t)))
13757 ((eq scope 'agenda-with-archives)
13758 (setq scope (org-agenda-files t))
13759 (setq scope (org-add-archive-files scope)))
13760 ((eq scope 'file)
13761 (setq scope (list (buffer-file-name))))
13762 ((eq scope 'file-with-archives)
13763 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13764 (org-prepare-agenda-buffers scope)
13765 (while (setq file (pop scope))
13766 (with-current-buffer (org-find-base-buffer-visiting file)
13767 (save-excursion
13768 (save-restriction
13769 (widen)
13770 (goto-char (point-min))
13771 (setq res (append res (org-scan-tags func matcher))))))))))
13772 res)))
13774 ;;;; Properties
13776 ;;; Setting and retrieving properties
13778 (defconst org-special-properties
13779 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13780 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13781 "The special properties valid in Org-mode.
13783 These are properties that are not defined in the property drawer,
13784 but in some other way.")
13786 (defconst org-default-properties
13787 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13788 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13789 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13790 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13791 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13792 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13793 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13794 "Some properties that are used by Org-mode for various purposes.
13795 Being in this list makes sure that they are offered for completion.")
13797 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13798 "Regular expression matching the first line of a property drawer.")
13800 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13801 "Regular expression matching the last line of a property drawer.")
13803 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13804 "Regular expression matching the first line of a property drawer.")
13806 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13807 "Regular expression matching the first line of a property drawer.")
13809 (defconst org-property-drawer-re
13810 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13811 org-property-end-re "\\)\n?")
13812 "Matches an entire property drawer.")
13814 (defconst org-clock-drawer-re
13815 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13816 org-property-end-re "\\)\n?")
13817 "Matches an entire clock drawer.")
13819 (defsubst org-re-property (property)
13820 "Return a regexp matching PROPERTY.
13821 Match group 1 will be set to the value "
13822 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
13824 (defun org-property-action ()
13825 "Do an action on properties."
13826 (interactive)
13827 (let (c)
13828 (org-at-property-p)
13829 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13830 (setq c (read-char-exclusive))
13831 (cond
13832 ((equal c ?s)
13833 (call-interactively 'org-set-property))
13834 ((equal c ?d)
13835 (call-interactively 'org-delete-property))
13836 ((equal c ?D)
13837 (call-interactively 'org-delete-property-globally))
13838 ((equal c ?c)
13839 (call-interactively 'org-compute-property-at-point))
13840 (t (error "No such property action %c" c)))))
13842 (defun org-set-effort (&optional value)
13843 "Set the effort property of the current entry.
13844 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13845 allowed value."
13846 (interactive "P")
13847 (if (equal value 0) (setq value 10))
13848 (let* ((completion-ignore-case t)
13849 (prop org-effort-property)
13850 (cur (org-entry-get nil prop))
13851 (allowed (org-property-get-allowed-values nil prop 'table))
13852 (existing (mapcar 'list (org-property-values prop)))
13854 (val (cond
13855 ((stringp value) value)
13856 ((and allowed (integerp value))
13857 (or (car (nth (1- value) allowed))
13858 (car (org-last allowed))))
13859 (allowed
13860 (message "Select 1-9,0, [RET%s]: %s"
13861 (if cur (concat "=" cur) "")
13862 (mapconcat 'car allowed " "))
13863 (setq rpl (read-char-exclusive))
13864 (if (equal rpl ?\r)
13866 (setq rpl (- rpl ?0))
13867 (if (equal rpl 0) (setq rpl 10))
13868 (if (and (> rpl 0) (<= rpl (length allowed)))
13869 (car (nth (1- rpl) allowed))
13870 (org-completing-read "Effort: " allowed nil))))
13872 (let (org-completion-use-ido org-completion-use-iswitchb)
13873 (org-completing-read
13874 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13875 (concat "[" cur "]") "")
13876 ": ")
13877 existing nil nil "" nil cur))))))
13878 (unless (equal (org-entry-get nil prop) val)
13879 (org-entry-put nil prop val))
13880 (message "%s is now %s" prop val)))
13882 (defun org-at-property-p ()
13883 "Is cursor inside a property drawer?"
13884 (save-excursion
13885 (beginning-of-line 1)
13886 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13887 (save-match-data ;; Used by calling procedures
13888 (let ((p (point))
13889 (range (unless (org-before-first-heading-p)
13890 (org-get-property-block))))
13891 (and range (<= (car range) p) (< p (cdr range))))))))
13893 (defun org-get-property-block (&optional beg end force)
13894 "Return the (beg . end) range of the body of the property drawer.
13895 BEG and END can be beginning and end of subtree, if not given
13896 they will be found.
13897 If the drawer does not exist and FORCE is non-nil, create the drawer."
13898 (catch 'exit
13899 (save-excursion
13900 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13901 (end (or end (progn (outline-next-heading) (point)))))
13902 (goto-char beg)
13903 (if (re-search-forward org-property-start-re end t)
13904 (setq beg (1+ (match-end 0)))
13905 (if force
13906 (save-excursion
13907 (org-insert-property-drawer)
13908 (setq end (progn (outline-next-heading) (point))))
13909 (throw 'exit nil))
13910 (goto-char beg)
13911 (if (re-search-forward org-property-start-re end t)
13912 (setq beg (1+ (match-end 0)))))
13913 (if (re-search-forward org-property-end-re end t)
13914 (setq end (match-beginning 0))
13915 (or force (throw 'exit nil))
13916 (goto-char beg)
13917 (setq end beg)
13918 (org-indent-line-function)
13919 (insert ":END:\n"))
13920 (cons beg end)))))
13922 (defun org-entry-properties (&optional pom which specific)
13923 "Get all properties of the entry at point-or-marker POM.
13924 This includes the TODO keyword, the tags, time strings for deadline,
13925 scheduled, and clocking, and any additional properties defined in the
13926 entry. The return value is an alist, keys may occur multiple times
13927 if the property key was used several times.
13928 POM may also be nil, in which case the current entry is used.
13929 If WHICH is nil or `all', get all properties. If WHICH is
13930 `special' or `standard', only get that subclass. If WHICH
13931 is a string only get exactly this property. SPECIFIC can be a string, the
13932 specific property we are interested in. Specifying it can speed
13933 things up because then unnecessary parsing is avoided."
13934 (setq which (or which 'all))
13935 (org-with-point-at pom
13936 (let ((clockstr (substring org-clock-string 0 -1))
13937 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13938 (case-fold-search nil)
13939 beg end range props sum-props key key1 value string clocksum)
13940 (save-excursion
13941 (when (condition-case nil
13942 (and (eq major-mode 'org-mode) (org-back-to-heading t))
13943 (error nil))
13944 (setq beg (point))
13945 (setq sum-props (get-text-property (point) 'org-summaries))
13946 (setq clocksum (get-text-property (point) :org-clock-minutes))
13947 (outline-next-heading)
13948 (setq end (point))
13949 (when (memq which '(all special))
13950 ;; Get the special properties, like TODO and tags
13951 (goto-char beg)
13952 (when (and (or (not specific) (string= specific "TODO"))
13953 (looking-at org-todo-line-regexp) (match-end 2))
13954 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13955 (when (and (or (not specific) (string= specific "PRIORITY"))
13956 (looking-at org-priority-regexp))
13957 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13958 (when (or (not specific) (string= specific "FILE"))
13959 (push (cons "FILE" buffer-file-name) props))
13960 (when (and (or (not specific) (string= specific "TAGS"))
13961 (setq value (org-get-tags-string))
13962 (string-match "\\S-" value))
13963 (push (cons "TAGS" value) props))
13964 (when (and (or (not specific) (string= specific "ALLTAGS"))
13965 (setq value (org-get-tags-at)))
13966 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
13967 ":"))
13968 props))
13969 (when (or (not specific) (string= specific "BLOCKED"))
13970 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
13971 (when (or (not specific)
13972 (member specific
13973 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
13974 "TIMESTAMP" "TIMESTAMP_IA")))
13975 (catch 'match
13976 (while (re-search-forward org-maybe-keyword-time-regexp end t)
13977 (setq key (if (match-end 1)
13978 (substring (org-match-string-no-properties 1)
13979 0 -1))
13980 string (if (equal key clockstr)
13981 (org-no-properties
13982 (org-trim
13983 (buffer-substring
13984 (match-beginning 3) (goto-char
13985 (point-at-eol)))))
13986 (substring (org-match-string-no-properties 3)
13987 1 -1)))
13988 ;; Get the correct property name from the key. This is
13989 ;; necessary if the user has configured time keywords.
13990 (setq key1 (concat key ":"))
13991 (cond
13992 ((not key)
13993 (setq key
13994 (if (= (char-after (match-beginning 3)) ?\[)
13995 "TIMESTAMP_IA" "TIMESTAMP")))
13996 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
13997 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
13998 ((equal key1 org-closed-string) (setq key "CLOSED"))
13999 ((equal key1 org-clock-string) (setq key "CLOCK")))
14000 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14001 (progn
14002 (push (cons key string) props)
14003 ;; no need to search further if match is found
14004 (throw 'match t))
14005 (when (or (equal key "CLOCK") (not (assoc key props)))
14006 (push (cons key string) props))))))
14009 (when (memq which '(all standard))
14010 ;; Get the standard properties, like :PROP: ...
14011 (setq range (org-get-property-block beg end))
14012 (when range
14013 (goto-char (car range))
14014 (while (re-search-forward
14015 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14016 (cdr range) t)
14017 (setq key (org-match-string-no-properties 1)
14018 value (org-trim (or (org-match-string-no-properties 2) "")))
14019 (unless (member key excluded)
14020 (push (cons key (or value "")) props)))))
14021 (if clocksum
14022 (push (cons "CLOCKSUM"
14023 (org-columns-number-to-string (/ (float clocksum) 60.)
14024 'add_times))
14025 props))
14026 (unless (assoc "CATEGORY" props)
14027 (push (cons "CATEGORY" (org-get-category)) props))
14028 (append sum-props (nreverse props)))))))
14030 (defun org-entry-get (pom property &optional inherit literal-nil)
14031 "Get value of PROPERTY for entry at point-or-marker POM.
14032 If INHERIT is non-nil and the entry does not have the property,
14033 then also check higher levels of the hierarchy.
14034 If INHERIT is the symbol `selective', use inheritance only if the setting
14035 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14036 If the property is present but empty, the return value is the empty string.
14037 If the property is not present at all, nil is returned.
14039 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14040 do not interpret it as the list atom nil. This is used for inheritance
14041 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14042 (org-with-point-at pom
14043 (if (and inherit (if (eq inherit 'selective)
14044 (org-property-inherit-p property)
14046 (org-entry-get-with-inheritance property literal-nil)
14047 (if (member property org-special-properties)
14048 ;; We need a special property. Use `org-entry-properties' to
14049 ;; retrieve it, but specify the wanted property
14050 (cdr (assoc property (org-entry-properties nil 'special property)))
14051 (let ((range (unless (org-before-first-heading-p)
14052 (org-get-property-block))))
14053 (if (and range
14054 (goto-char (car range))
14055 (re-search-forward
14056 (org-re-property property)
14057 (cdr range) t))
14058 ;; Found the property, return it.
14059 (if (match-end 1)
14060 (if literal-nil
14061 (org-match-string-no-properties 1)
14062 (org-not-nil (org-match-string-no-properties 1)))
14063 "")))))))
14065 (defun org-property-or-variable-value (var &optional inherit)
14066 "Check if there is a property fixing the value of VAR.
14067 If yes, return this value. If not, return the current value of the variable."
14068 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14069 (if (and prop (stringp prop) (string-match "\\S-" prop))
14070 (read prop)
14071 (symbol-value var))))
14073 (defun org-entry-delete (pom property)
14074 "Delete the property PROPERTY from entry at point-or-marker POM."
14075 (org-with-point-at pom
14076 (if (member property org-special-properties)
14077 nil ; cannot delete these properties.
14078 (let ((range (org-get-property-block)))
14079 (if (and range
14080 (goto-char (car range))
14081 (re-search-forward
14082 (org-re-property property)
14083 (cdr range) t))
14084 (progn
14085 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14087 nil)))))
14089 ;; Multi-values properties are properties that contain multiple values
14090 ;; These values are assumed to be single words, separated by whitespace.
14091 (defun org-entry-add-to-multivalued-property (pom property value)
14092 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14093 (let* ((old (org-entry-get pom property))
14094 (values (and old (org-split-string old "[ \t]"))))
14095 (setq value (org-entry-protect-space value))
14096 (unless (member value values)
14097 (setq values (cons value values))
14098 (org-entry-put pom property
14099 (mapconcat 'identity values " ")))))
14101 (defun org-entry-remove-from-multivalued-property (pom property value)
14102 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14103 (let* ((old (org-entry-get pom property))
14104 (values (and old (org-split-string old "[ \t]"))))
14105 (setq value (org-entry-protect-space value))
14106 (when (member value values)
14107 (setq values (delete value values))
14108 (org-entry-put pom property
14109 (mapconcat 'identity values " ")))))
14111 (defun org-entry-member-in-multivalued-property (pom property value)
14112 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14113 (let* ((old (org-entry-get pom property))
14114 (values (and old (org-split-string old "[ \t]"))))
14115 (setq value (org-entry-protect-space value))
14116 (member value values)))
14118 (defun org-entry-get-multivalued-property (pom property)
14119 "Return a list of values in a multivalued property."
14120 (let* ((value (org-entry-get pom property))
14121 (values (and value (org-split-string value "[ \t]"))))
14122 (mapcar 'org-entry-restore-space values)))
14124 (defun org-entry-put-multivalued-property (pom property &rest values)
14125 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14126 VALUES should be a list of strings. Spaces will be protected."
14127 (org-entry-put pom property
14128 (mapconcat 'org-entry-protect-space values " "))
14129 (let* ((value (org-entry-get pom property))
14130 (values (and value (org-split-string value "[ \t]"))))
14131 (mapcar 'org-entry-restore-space values)))
14133 (defun org-entry-protect-space (s)
14134 "Protect spaces and newline in string S."
14135 (while (string-match " " s)
14136 (setq s (replace-match "%20" t t s)))
14137 (while (string-match "\n" s)
14138 (setq s (replace-match "%0A" t t s)))
14141 (defun org-entry-restore-space (s)
14142 "Restore spaces and newline in string S."
14143 (while (string-match "%20" s)
14144 (setq s (replace-match " " t t s)))
14145 (while (string-match "%0A" s)
14146 (setq s (replace-match "\n" t t s)))
14149 (defvar org-entry-property-inherited-from (make-marker)
14150 "Marker pointing to the entry from where a property was inherited.
14151 Each call to `org-entry-get-with-inheritance' will set this marker to the
14152 location of the entry where the inheritance search matched. If there was
14153 no match, the marker will point nowhere.
14154 Note that also `org-entry-get' calls this function, if the INHERIT flag
14155 is set.")
14157 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14158 "Get entry property, and search higher levels if not present.
14159 The search will stop at the first ancestor which has the property defined.
14160 If the value found is \"nil\", return nil to show that the property
14161 should be considered as undefined (this is the meaning of nil here).
14162 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14163 (move-marker org-entry-property-inherited-from nil)
14164 (let (tmp)
14165 (unless (org-before-first-heading-p)
14166 (save-excursion
14167 (save-restriction
14168 (widen)
14169 (catch 'ex
14170 (while t
14171 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14172 (org-back-to-heading t)
14173 (move-marker org-entry-property-inherited-from (point))
14174 (throw 'ex tmp))
14175 (or (org-up-heading-safe) (throw 'ex nil)))))))
14176 (setq tmp (or tmp
14177 (cdr (assoc property org-file-properties))
14178 (cdr (assoc property org-global-properties))
14179 (cdr (assoc property org-global-properties-fixed))))
14180 (if literal-nil tmp (org-not-nil tmp))))
14182 (defvar org-property-changed-functions nil
14183 "Hook called when the value of a property has changed.
14184 Each hook function should accept two arguments, the name of the property
14185 and the new value.")
14187 (defun org-entry-put (pom property value)
14188 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14189 (org-with-point-at pom
14190 (org-back-to-heading t)
14191 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14192 range)
14193 (cond
14194 ((equal property "TODO")
14195 (when (and (stringp value) (string-match "\\S-" value)
14196 (not (member value org-todo-keywords-1)))
14197 (error "\"%s\" is not a valid TODO state" value))
14198 (if (or (not value)
14199 (not (string-match "\\S-" value)))
14200 (setq value 'none))
14201 (org-todo value)
14202 (org-set-tags nil 'align))
14203 ((equal property "PRIORITY")
14204 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14205 (string-to-char value) ?\ ))
14206 (org-set-tags nil 'align))
14207 ((equal property "SCHEDULED")
14208 (if (re-search-forward org-scheduled-time-regexp end t)
14209 (cond
14210 ((eq value 'earlier) (org-timestamp-change -1 'day))
14211 ((eq value 'later) (org-timestamp-change 1 'day))
14212 (t (call-interactively 'org-schedule)))
14213 (call-interactively 'org-schedule)))
14214 ((equal property "DEADLINE")
14215 (if (re-search-forward org-deadline-time-regexp end t)
14216 (cond
14217 ((eq value 'earlier) (org-timestamp-change -1 'day))
14218 ((eq value 'later) (org-timestamp-change 1 'day))
14219 (t (call-interactively 'org-deadline)))
14220 (call-interactively 'org-deadline)))
14221 ((member property org-special-properties)
14222 (error "The %s property can not yet be set with `org-entry-put'"
14223 property))
14224 (t ; a non-special property
14225 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14226 (setq range (org-get-property-block beg end 'force))
14227 (goto-char (car range))
14228 (if (re-search-forward
14229 (org-re-property property) (cdr range) t)
14230 (progn
14231 (delete-region (match-beginning 0) (match-end 0))
14232 (goto-char (match-beginning 0)))
14233 (goto-char (cdr range))
14234 (insert "\n")
14235 (backward-char 1)
14236 (org-indent-line-function))
14237 (insert ":" property ":")
14238 (and value (insert " " value))
14239 (org-indent-line-function)))))
14240 (run-hook-with-args 'org-property-changed-functions property value)))
14242 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14243 "Get all property keys in the current buffer.
14244 With INCLUDE-SPECIALS, also list the special properties that reflect things
14245 like tags and TODO state.
14246 With INCLUDE-DEFAULTS, also include properties that has special meaning
14247 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14248 and others.
14249 With INCLUDE-COLUMNS, also include property names given in COLUMN
14250 formats in the current buffer."
14251 (let (rtn range cfmt s p)
14252 (save-excursion
14253 (save-restriction
14254 (widen)
14255 (goto-char (point-min))
14256 (while (re-search-forward org-property-start-re nil t)
14257 (setq range (org-get-property-block))
14258 (goto-char (car range))
14259 (while (re-search-forward
14260 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14261 (cdr range) t)
14262 (add-to-list 'rtn (org-match-string-no-properties 1)))
14263 (outline-next-heading))))
14265 (when include-specials
14266 (setq rtn (append org-special-properties rtn)))
14268 (when include-defaults
14269 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14270 (add-to-list 'rtn org-effort-property))
14272 (when include-columns
14273 (save-excursion
14274 (save-restriction
14275 (widen)
14276 (goto-char (point-min))
14277 (while (re-search-forward
14278 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14279 nil t)
14280 (setq cfmt (match-string 2) s 0)
14281 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14282 cfmt s)
14283 (setq s (match-end 0)
14284 p (match-string 1 cfmt))
14285 (unless (or (equal p "ITEM")
14286 (member p org-special-properties))
14287 (add-to-list 'rtn (match-string 1 cfmt))))))))
14289 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14291 (defun org-property-values (key)
14292 "Return a list of all values of property KEY in the current buffer."
14293 (save-excursion
14294 (save-restriction
14295 (widen)
14296 (goto-char (point-min))
14297 (let ((re (org-re-property key))
14298 values)
14299 (while (re-search-forward re nil t)
14300 (add-to-list 'values (org-trim (match-string 1))))
14301 (delete "" values)))))
14303 (defun org-insert-property-drawer ()
14304 "Insert a property drawer into the current entry."
14305 (interactive)
14306 (org-back-to-heading t)
14307 (looking-at org-outline-regexp)
14308 (let ((indent (if org-adapt-indentation
14309 (- (match-end 0)(match-beginning 0))
14311 (beg (point))
14312 (re (concat "^[ \t]*" org-keyword-time-regexp))
14313 end hiddenp)
14314 (outline-next-heading)
14315 (setq end (point))
14316 (goto-char beg)
14317 (while (re-search-forward re end t))
14318 (setq hiddenp (outline-invisible-p))
14319 (end-of-line 1)
14320 (and (equal (char-after) ?\n) (forward-char 1))
14321 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14322 (if (member (match-string 1) '("CLOCK:" ":END:"))
14323 ;; just skip this line
14324 (beginning-of-line 2)
14325 ;; Drawer start, find the end
14326 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14327 (beginning-of-line 1)))
14328 (org-skip-over-state-notes)
14329 (skip-chars-backward " \t\n\r")
14330 (if (eq (char-before) ?*) (forward-char 1))
14331 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14332 (beginning-of-line 0)
14333 (org-indent-to-column indent)
14334 (beginning-of-line 2)
14335 (org-indent-to-column indent)
14336 (beginning-of-line 0)
14337 (if hiddenp
14338 (save-excursion
14339 (org-back-to-heading t)
14340 (hide-entry))
14341 (org-flag-drawer t))))
14343 (defvar org-property-set-functions-alist nil
14344 "Property set function alist.
14345 Each entry should have the following format:
14347 (PROPERTY . READ-FUNCTION)
14349 The read function will be called with the same argument as
14350 `org-completing-read'.")
14352 (defun org-set-property-function (property)
14353 "Get the function that should be used to set PROPERTY.
14354 This is computed according to `org-property-set-functions-alist'."
14355 (or (cdr (assoc property org-property-set-functions-alist))
14356 'org-completing-read))
14358 (defun org-read-property-value (property)
14359 "Read PROPERTY value from user."
14360 (let* ((completion-ignore-case t)
14361 (allowed (org-property-get-allowed-values nil property 'table))
14362 (cur (org-entry-get nil property))
14363 (prompt (concat property " value"
14364 (if (and cur (string-match "\\S-" cur))
14365 (concat " [" cur "]") "") ": "))
14366 (set-function (org-set-property-function property))
14367 (val (if allowed
14368 (funcall set-function prompt allowed nil
14369 (not (get-text-property 0 'org-unrestricted
14370 (caar allowed))))
14371 (let (org-completion-use-ido org-completion-use-iswitchb)
14372 (funcall set-function prompt
14373 (mapcar 'list (org-property-values property))
14374 nil nil "" nil cur)))))
14375 (if (equal val "")
14377 val)))
14379 (defvar org-last-set-property nil)
14380 (defun org-read-property-name ()
14381 "Read a property name."
14382 (let* ((completion-ignore-case t)
14383 (keys (org-buffer-property-keys nil t t))
14384 (default-prop (or (save-excursion
14385 (save-match-data
14386 (beginning-of-line)
14387 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14388 (null (string= (match-string 1) "END"))
14389 (match-string 1))))
14390 org-last-set-property))
14391 (property (org-icompleting-read
14392 (concat "Property"
14393 (if default-prop (concat " [" default-prop "]") "")
14394 ": ")
14395 (mapcar 'list keys)
14396 nil nil nil nil
14397 default-prop
14399 (if (member property keys)
14400 property
14401 (or (cdr (assoc (downcase property)
14402 (mapcar (lambda (x) (cons (downcase x) x))
14403 keys)))
14404 property))))
14406 (defun org-set-property (property value)
14407 "In the current entry, set PROPERTY to VALUE.
14408 When called interactively, this will prompt for a property name, offering
14409 completion on existing and default properties. And then it will prompt
14410 for a value, offering completion either on allowed values (via an inherited
14411 xxx_ALL property) or on existing values in other instances of this property
14412 in the current file."
14413 (interactive (list nil nil))
14414 (let* ((property (or property (org-read-property-name)))
14415 (value (or value (org-read-property-value property)))
14416 (fn (assoc property org-properties-postprocess-alist)))
14417 (setq org-last-set-property property)
14418 ;; Possibly postprocess the inserted value:
14419 (when fn (setq value (funcall (cadr fn) value)))
14420 (unless (equal (org-entry-get nil property) value)
14421 (org-entry-put nil property value))))
14423 (defun org-delete-property (property)
14424 "In the current entry, delete PROPERTY."
14425 (interactive
14426 (let* ((completion-ignore-case t)
14427 (prop (org-icompleting-read "Property: "
14428 (org-entry-properties nil 'standard))))
14429 (list prop)))
14430 (message "Property %s %s" property
14431 (if (org-entry-delete nil property)
14432 "deleted"
14433 "was not present in the entry")))
14435 (defun org-delete-property-globally (property)
14436 "Remove PROPERTY globally, from all entries."
14437 (interactive
14438 (let* ((completion-ignore-case t)
14439 (prop (org-icompleting-read
14440 "Globally remove property: "
14441 (mapcar 'list (org-buffer-property-keys)))))
14442 (list prop)))
14443 (save-excursion
14444 (save-restriction
14445 (widen)
14446 (goto-char (point-min))
14447 (let ((cnt 0))
14448 (while (re-search-forward
14449 (org-re-property property)
14450 nil t)
14451 (setq cnt (1+ cnt))
14452 (replace-match ""))
14453 (message "Property \"%s\" removed from %d entries" property cnt)))))
14455 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14457 (defun org-compute-property-at-point ()
14458 "Compute the property at point.
14459 This looks for an enclosing column format, extracts the operator and
14460 then applies it to the property in the column format's scope."
14461 (interactive)
14462 (unless (org-at-property-p)
14463 (error "Not at a property"))
14464 (let ((prop (org-match-string-no-properties 2)))
14465 (org-columns-get-format-and-top-level)
14466 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14467 (error "No operator defined for property %s" prop))
14468 (org-columns-compute prop)))
14470 (defvar org-property-allowed-value-functions nil
14471 "Hook for functions supplying allowed values for a specific property.
14472 The functions must take a single argument, the name of the property, and
14473 return a flat list of allowed values. If \":ETC\" is one of
14474 the values, this means that these values are intended as defaults for
14475 completion, but that other values should be allowed too.
14476 The functions must return nil if they are not responsible for this
14477 property.")
14479 (defun org-property-get-allowed-values (pom property &optional table)
14480 "Get allowed values for the property PROPERTY.
14481 When TABLE is non-nil, return an alist that can directly be used for
14482 completion."
14483 (let (vals)
14484 (cond
14485 ((equal property "TODO")
14486 (setq vals (org-with-point-at pom
14487 (append org-todo-keywords-1 '("")))))
14488 ((equal property "PRIORITY")
14489 (let ((n org-lowest-priority))
14490 (while (>= n org-highest-priority)
14491 (push (char-to-string n) vals)
14492 (setq n (1- n)))))
14493 ((member property org-special-properties))
14494 ((setq vals (run-hook-with-args-until-success
14495 'org-property-allowed-value-functions property)))
14497 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14498 (when (and vals (string-match "\\S-" vals))
14499 (setq vals (car (read-from-string (concat "(" vals ")"))))
14500 (setq vals (mapcar (lambda (x)
14501 (cond ((stringp x) x)
14502 ((numberp x) (number-to-string x))
14503 ((symbolp x) (symbol-name x))
14504 (t "???")))
14505 vals)))))
14506 (when (member ":ETC" vals)
14507 (setq vals (remove ":ETC" vals))
14508 (org-add-props (car vals) '(org-unrestricted t)))
14509 (if table (mapcar 'list vals) vals)))
14511 (defun org-property-previous-allowed-value (&optional previous)
14512 "Switch to the next allowed value for this property."
14513 (interactive)
14514 (org-property-next-allowed-value t))
14516 (defun org-property-next-allowed-value (&optional previous)
14517 "Switch to the next allowed value for this property."
14518 (interactive)
14519 (unless (org-at-property-p)
14520 (error "Not at a property"))
14521 (let* ((key (match-string 2))
14522 (value (match-string 3))
14523 (allowed (or (org-property-get-allowed-values (point) key)
14524 (and (member value '("[ ]" "[-]" "[X]"))
14525 '("[ ]" "[X]"))))
14526 nval)
14527 (unless allowed
14528 (error "Allowed values for this property have not been defined"))
14529 (if previous (setq allowed (reverse allowed)))
14530 (if (member value allowed)
14531 (setq nval (car (cdr (member value allowed)))))
14532 (setq nval (or nval (car allowed)))
14533 (if (equal nval value)
14534 (error "Only one allowed value for this property"))
14535 (org-at-property-p)
14536 (replace-match (concat " :" key ": " nval) t t)
14537 (org-indent-line-function)
14538 (beginning-of-line 1)
14539 (skip-chars-forward " \t")
14540 (run-hook-with-args 'org-property-changed-functions key nval)))
14542 (defun org-find-olp (path &optional this-buffer)
14543 "Return a marker pointing to the entry at outline path OLP.
14544 If anything goes wrong, throw an error.
14545 You can wrap this call to catch the error like this:
14547 (condition-case msg
14548 (org-mobile-locate-entry (match-string 4))
14549 (error (nth 1 msg)))
14551 The return value will then be either a string with the error message,
14552 or a marker if everything is OK.
14554 If THIS-BUFFER is set, the outline path does not contain a file,
14555 only headings."
14556 (let* ((file (if this-buffer buffer-file-name (pop path)))
14557 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14558 (level 1)
14559 (lmin 1)
14560 (lmax 1)
14561 limit re end found pos heading cnt flevel)
14562 (unless buffer (error "File not found :%s" file))
14563 (with-current-buffer buffer
14564 (save-excursion
14565 (save-restriction
14566 (widen)
14567 (setq limit (point-max))
14568 (goto-char (point-min))
14569 (while (setq heading (pop path))
14570 (setq re (format org-complex-heading-regexp-format
14571 (regexp-quote heading)))
14572 (setq cnt 0 pos (point))
14573 (while (re-search-forward re end t)
14574 (setq level (- (match-end 1) (match-beginning 1)))
14575 (if (and (>= level lmin) (<= level lmax))
14576 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14577 (when (= cnt 0) (error "Heading not found on level %d: %s"
14578 lmax heading))
14579 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14580 lmax heading))
14581 (goto-char found)
14582 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14583 (setq end (save-excursion (org-end-of-subtree t t))))
14584 (when (org-on-heading-p)
14585 (move-marker (make-marker) (point))))))))
14587 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14588 "Find node HEADING in BUFFER.
14589 Return a marker to the heading if it was found, or nil if not.
14590 If POS-ONLY is set, return just the position instead of a marker.
14592 The heading text must match exact, but it may have a TODO keyword,
14593 a priority cookie and tags in the standard locations."
14594 (with-current-buffer (or buffer (current-buffer))
14595 (save-excursion
14596 (save-restriction
14597 (widen)
14598 (goto-char (point-min))
14599 (let (case-fold-search)
14600 (if (re-search-forward
14601 (format org-complex-heading-regexp-format
14602 (regexp-quote heading)) nil t)
14603 (if pos-only
14604 (match-beginning 0)
14605 (move-marker (make-marker) (match-beginning 0)))))))))
14607 (defun org-find-exact-heading-in-directory (heading &optional dir)
14608 "Find Org node headline HEADING in all .org files in directory DIR.
14609 When the target headline is found, return a marker to this location."
14610 (let ((files (directory-files (or dir default-directory)
14611 nil "\\`[^.#].*\\.org\\'"))
14612 file visiting m buffer)
14613 (catch 'found
14614 (while (setq file (pop files))
14615 (message "trying %s" file)
14616 (setq visiting (org-find-base-buffer-visiting file))
14617 (setq buffer (or visiting (find-file-noselect file)))
14618 (setq m (org-find-exact-headline-in-buffer
14619 heading buffer))
14620 (when (and (not m) (not visiting)) (kill-buffer buffer))
14621 (and m (throw 'found m))))))
14623 (defun org-find-entry-with-id (ident)
14624 "Locate the entry that contains the ID property with exact value IDENT.
14625 IDENT can be a string, a symbol or a number, this function will search for
14626 the string representation of it.
14627 Return the position where this entry starts, or nil if there is no such entry."
14628 (interactive "sID: ")
14629 (let ((id (cond
14630 ((stringp ident) ident)
14631 ((symbol-name ident) (symbol-name ident))
14632 ((numberp ident) (number-to-string ident))
14633 (t (error "IDENT %s must be a string, symbol or number" ident))))
14634 (case-fold-search nil))
14635 (save-excursion
14636 (save-restriction
14637 (widen)
14638 (goto-char (point-min))
14639 (when (re-search-forward
14640 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14641 nil t)
14642 (org-back-to-heading t)
14643 (point))))))
14645 ;;;; Timestamps
14647 (defvar org-last-changed-timestamp nil)
14648 (defvar org-last-inserted-timestamp nil
14649 "The last time stamp inserted with `org-insert-time-stamp'.")
14650 (defvar org-time-was-given) ; dynamically scoped parameter
14651 (defvar org-end-time-was-given) ; dynamically scoped parameter
14652 (defvar org-ts-what) ; dynamically scoped parameter
14654 (defun org-time-stamp (arg &optional inactive)
14655 "Prompt for a date/time and insert a time stamp.
14656 If the user specifies a time like HH:MM, or if this command is called
14657 with a prefix argument, the time stamp will contain date and time.
14658 Otherwise, only the date will be included. All parts of a date not
14659 specified by the user will be filled in from the current date/time.
14660 So if you press just return without typing anything, the time stamp
14661 will represent the current date/time. If there is already a timestamp
14662 at the cursor, it will be modified."
14663 (interactive "P")
14664 (let* ((ts nil)
14665 (default-time
14666 ;; Default time is either today, or, when entering a range,
14667 ;; the range start.
14668 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14669 (save-excursion
14670 (re-search-backward
14671 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14672 (- (point) 20) t)))
14673 (apply 'encode-time (org-parse-time-string (match-string 1)))
14674 (current-time)))
14675 (default-input (and ts (org-get-compact-tod ts)))
14676 (repeater (save-excursion
14677 (save-match-data
14678 (beginning-of-line)
14679 (when (re-search-forward
14680 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14681 (save-excursion (progn (end-of-line) (point))) t)
14682 (match-string 0)))))
14683 org-time-was-given org-end-time-was-given time)
14684 (cond
14685 ((and (org-at-timestamp-p t)
14686 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14687 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14688 (insert "--")
14689 (setq time (let ((this-command this-command))
14690 (org-read-date arg 'totime nil nil
14691 default-time default-input)))
14692 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14693 ((org-at-timestamp-p t)
14694 (setq time (let ((this-command this-command))
14695 (org-read-date arg 'totime nil nil default-time default-input)))
14696 (when (org-at-timestamp-p t) ; just to get the match data
14697 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14698 (replace-match "")
14699 (setq org-last-changed-timestamp
14700 (org-insert-time-stamp
14701 time (or org-time-was-given arg)
14702 inactive nil nil (list org-end-time-was-given)))
14703 (when repeater (goto-char (1- (point))) (insert " " repeater)
14704 (setq org-last-changed-timestamp
14705 (concat (substring org-last-inserted-timestamp 0 -1)
14706 " " repeater ">"))))
14707 (message "Timestamp updated"))
14709 (setq time (let ((this-command this-command))
14710 (org-read-date arg 'totime nil nil default-time default-input)))
14711 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14712 nil nil (list org-end-time-was-given))))))
14714 ;; FIXME: can we use this for something else, like computing time differences?
14715 (defun org-get-compact-tod (s)
14716 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14717 (let* ((t1 (match-string 1 s))
14718 (h1 (string-to-number (match-string 2 s)))
14719 (m1 (string-to-number (match-string 3 s)))
14720 (t2 (and (match-end 4) (match-string 5 s)))
14721 (h2 (and t2 (string-to-number (match-string 6 s))))
14722 (m2 (and t2 (string-to-number (match-string 7 s))))
14723 dh dm)
14724 (if (not t2)
14726 (setq dh (- h2 h1) dm (- m2 m1))
14727 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14728 (concat t1 "+" (number-to-string dh)
14729 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14731 (defun org-time-stamp-inactive (&optional arg)
14732 "Insert an inactive time stamp.
14733 An inactive time stamp is enclosed in square brackets instead of angle
14734 brackets. It is inactive in the sense that it does not trigger agenda entries,
14735 does not link to the calendar and cannot be changed with the S-cursor keys.
14736 So these are more for recording a certain time/date."
14737 (interactive "P")
14738 (org-time-stamp arg 'inactive))
14740 (defvar org-date-ovl (make-overlay 1 1))
14741 (overlay-put org-date-ovl 'face 'org-warning)
14742 (org-detach-overlay org-date-ovl)
14744 (defvar org-ans1) ; dynamically scoped parameter
14745 (defvar org-ans2) ; dynamically scoped parameter
14747 (defvar org-plain-time-of-day-regexp) ; defined below
14749 (defvar org-overriding-default-time nil) ; dynamically scoped
14750 (defvar org-read-date-overlay nil)
14751 (defvar org-dcst nil) ; dynamically scoped
14752 (defvar org-read-date-history nil)
14753 (defvar org-read-date-final-answer nil)
14754 (defvar org-read-date-analyze-futurep nil)
14755 (defvar org-read-date-analyze-forced-year nil)
14757 (defun org-read-date (&optional with-time to-time from-string prompt
14758 default-time default-input)
14759 "Read a date, possibly a time, and make things smooth for the user.
14760 The prompt will suggest to enter an ISO date, but you can also enter anything
14761 which will at least partially be understood by `parse-time-string'.
14762 Unrecognized parts of the date will default to the current day, month, year,
14763 hour and minute. If this command is called to replace a timestamp at point,
14764 of to enter the second timestamp of a range, the default time is taken
14765 from the existing stamp. Furthermore, the command prefers the future,
14766 so if you are giving a date where the year is not given, and the day-month
14767 combination is already past in the current year, it will assume you
14768 mean next year. For details, see the manual. A few examples:
14770 3-2-5 --> 2003-02-05
14771 feb 15 --> currentyear-02-15
14772 2/15 --> currentyear-02-15
14773 sep 12 9 --> 2009-09-12
14774 12:45 --> today 12:45
14775 22 sept 0:34 --> currentyear-09-22 0:34
14776 12 --> currentyear-currentmonth-12
14777 Fri --> nearest Friday (today or later)
14778 etc.
14780 Furthermore you can specify a relative date by giving, as the *first* thing
14781 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14782 change in days weeks, months, years.
14783 With a single plus or minus, the date is relative to today. With a double
14784 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14785 +4d --> four days from today
14786 +4 --> same as above
14787 +2w --> two weeks from today
14788 ++5 --> five days from default date
14790 The function understands only English month and weekday abbreviations,
14791 but this can be configured with the variables `parse-time-months' and
14792 `parse-time-weekdays'.
14794 While prompting, a calendar is popped up - you can also select the
14795 date with the mouse (button 1). The calendar shows a period of three
14796 months. To scroll it to other months, use the keys `>' and `<'.
14797 If you don't like the calendar, turn it off with
14798 \(setq org-read-date-popup-calendar nil)
14800 With optional argument TO-TIME, the date will immediately be converted
14801 to an internal time.
14802 With an optional argument WITH-TIME, the prompt will suggest to also
14803 insert a time. Note that when WITH-TIME is not set, you can still
14804 enter a time, and this function will inform the calling routine about
14805 this change. The calling routine may then choose to change the format
14806 used to insert the time stamp into the buffer to include the time.
14807 With optional argument FROM-STRING, read from this string instead from
14808 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14809 the time/date that is used for everything that is not specified by the
14810 user."
14811 (require 'parse-time)
14812 (let* ((org-time-stamp-rounding-minutes
14813 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14814 (org-dcst org-display-custom-times)
14815 (ct (org-current-time))
14816 (def (or org-overriding-default-time default-time ct))
14817 (defdecode (decode-time def))
14818 (dummy (progn
14819 (when (< (nth 2 defdecode) org-extend-today-until)
14820 (setcar (nthcdr 2 defdecode) -1)
14821 (setcar (nthcdr 1 defdecode) 59)
14822 (setq def (apply 'encode-time defdecode)
14823 defdecode (decode-time def)))))
14824 (calendar-frame-setup nil)
14825 (calendar-setup nil)
14826 (calendar-move-hook nil)
14827 (calendar-view-diary-initially-flag nil)
14828 (calendar-view-holidays-initially-flag nil)
14829 (timestr (format-time-string
14830 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14831 (prompt (concat (if prompt (concat prompt " ") "")
14832 (format "Date+time [%s]: " timestr)))
14833 ans (org-ans0 "") org-ans1 org-ans2 final)
14835 (cond
14836 (from-string (setq ans from-string))
14837 (org-read-date-popup-calendar
14838 (save-excursion
14839 (save-window-excursion
14840 (calendar)
14841 (unwind-protect
14842 (progn
14843 (calendar-forward-day (- (time-to-days def)
14844 (calendar-absolute-from-gregorian
14845 (calendar-current-date))))
14846 (org-eval-in-calendar nil t)
14847 (let* ((old-map (current-local-map))
14848 (map (copy-keymap calendar-mode-map))
14849 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14850 (org-defkey map (kbd "RET") 'org-calendar-select)
14851 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14852 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14853 (org-defkey minibuffer-local-map [(meta shift left)]
14854 (lambda () (interactive)
14855 (org-eval-in-calendar '(calendar-backward-month 1))))
14856 (org-defkey minibuffer-local-map [(meta shift right)]
14857 (lambda () (interactive)
14858 (org-eval-in-calendar '(calendar-forward-month 1))))
14859 (org-defkey minibuffer-local-map [(meta shift up)]
14860 (lambda () (interactive)
14861 (org-eval-in-calendar '(calendar-backward-year 1))))
14862 (org-defkey minibuffer-local-map [(meta shift down)]
14863 (lambda () (interactive)
14864 (org-eval-in-calendar '(calendar-forward-year 1))))
14865 (org-defkey minibuffer-local-map [?\e (shift left)]
14866 (lambda () (interactive)
14867 (org-eval-in-calendar '(calendar-backward-month 1))))
14868 (org-defkey minibuffer-local-map [?\e (shift right)]
14869 (lambda () (interactive)
14870 (org-eval-in-calendar '(calendar-forward-month 1))))
14871 (org-defkey minibuffer-local-map [?\e (shift up)]
14872 (lambda () (interactive)
14873 (org-eval-in-calendar '(calendar-backward-year 1))))
14874 (org-defkey minibuffer-local-map [?\e (shift down)]
14875 (lambda () (interactive)
14876 (org-eval-in-calendar '(calendar-forward-year 1))))
14877 (org-defkey minibuffer-local-map [(shift up)]
14878 (lambda () (interactive)
14879 (org-eval-in-calendar '(calendar-backward-week 1))))
14880 (org-defkey minibuffer-local-map [(shift down)]
14881 (lambda () (interactive)
14882 (org-eval-in-calendar '(calendar-forward-week 1))))
14883 (org-defkey minibuffer-local-map [(shift left)]
14884 (lambda () (interactive)
14885 (org-eval-in-calendar '(calendar-backward-day 1))))
14886 (org-defkey minibuffer-local-map [(shift right)]
14887 (lambda () (interactive)
14888 (org-eval-in-calendar '(calendar-forward-day 1))))
14889 (org-defkey minibuffer-local-map ">"
14890 (lambda () (interactive)
14891 (org-eval-in-calendar '(scroll-calendar-left 1))))
14892 (org-defkey minibuffer-local-map "<"
14893 (lambda () (interactive)
14894 (org-eval-in-calendar '(scroll-calendar-right 1))))
14895 (org-defkey minibuffer-local-map "\C-v"
14896 (lambda () (interactive)
14897 (org-eval-in-calendar
14898 '(calendar-scroll-left-three-months 1))))
14899 (org-defkey minibuffer-local-map "\M-v"
14900 (lambda () (interactive)
14901 (org-eval-in-calendar
14902 '(calendar-scroll-right-three-months 1))))
14903 (run-hooks 'org-read-date-minibuffer-setup-hook)
14904 (unwind-protect
14905 (progn
14906 (use-local-map map)
14907 (add-hook 'post-command-hook 'org-read-date-display)
14908 (setq org-ans0 (read-string prompt default-input
14909 'org-read-date-history nil))
14910 ;; org-ans0: from prompt
14911 ;; org-ans1: from mouse click
14912 ;; org-ans2: from calendar motion
14913 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14914 (remove-hook 'post-command-hook 'org-read-date-display)
14915 (use-local-map old-map)
14916 (when org-read-date-overlay
14917 (delete-overlay org-read-date-overlay)
14918 (setq org-read-date-overlay nil)))))
14919 (bury-buffer "*Calendar*")))))
14921 (t ; Naked prompt only
14922 (unwind-protect
14923 (setq ans (read-string prompt default-input
14924 'org-read-date-history timestr))
14925 (when org-read-date-overlay
14926 (delete-overlay org-read-date-overlay)
14927 (setq org-read-date-overlay nil)))))
14929 (setq final (org-read-date-analyze ans def defdecode))
14931 (when org-read-date-analyze-forced-year
14932 (message "Year was forced into %s"
14933 (if org-read-date-force-compatible-dates
14934 "compatible range (1970-2037)"
14935 "range representable on this machine"))
14936 (ding))
14938 ;; One round trip to get rid of 34th of August and stuff like that....
14939 (setq final (decode-time (apply 'encode-time final)))
14941 (setq org-read-date-final-answer ans)
14943 (if to-time
14944 (apply 'encode-time final)
14945 (if (and (boundp 'org-time-was-given) org-time-was-given)
14946 (format "%04d-%02d-%02d %02d:%02d"
14947 (nth 5 final) (nth 4 final) (nth 3 final)
14948 (nth 2 final) (nth 1 final))
14949 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
14951 (defvar def)
14952 (defvar defdecode)
14953 (defvar with-time)
14954 (defun org-read-date-display ()
14955 "Display the current date prompt interpretation in the minibuffer."
14956 (when org-read-date-display-live
14957 (when org-read-date-overlay
14958 (delete-overlay org-read-date-overlay))
14959 (let ((p (point)))
14960 (end-of-line 1)
14961 (while (not (equal (buffer-substring
14962 (max (point-min) (- (point) 4)) (point))
14963 " "))
14964 (insert " "))
14965 (goto-char p))
14966 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
14967 " " (or org-ans1 org-ans2)))
14968 (org-end-time-was-given nil)
14969 (f (org-read-date-analyze ans def defdecode))
14970 (fmts (if org-dcst
14971 org-time-stamp-custom-formats
14972 org-time-stamp-formats))
14973 (fmt (if (or with-time
14974 (and (boundp 'org-time-was-given) org-time-was-given))
14975 (cdr fmts)
14976 (car fmts)))
14977 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
14978 (when (and org-end-time-was-given
14979 (string-match org-plain-time-of-day-regexp txt))
14980 (setq txt (concat (substring txt 0 (match-end 0)) "-"
14981 org-end-time-was-given
14982 (substring txt (match-end 0)))))
14983 (when org-read-date-analyze-futurep
14984 (setq txt (concat txt " (=>F)")))
14985 (setq org-read-date-overlay
14986 (make-overlay (1- (point-at-eol)) (point-at-eol)))
14987 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
14989 (defun org-read-date-analyze (ans def defdecode)
14990 "Analyze the combined answer of the date prompt."
14991 ;; FIXME: cleanup and comment
14992 (let ((nowdecode (decode-time (current-time)))
14993 delta deltan deltaw deltadef year month day
14994 hour minute second wday pm h2 m2 tl wday1
14995 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
14996 (setq org-read-date-analyze-futurep nil
14997 org-read-date-analyze-forced-year nil)
14998 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
14999 (setq ans "+0"))
15001 (when (setq delta (org-read-date-get-relative ans (current-time) def))
15002 (setq ans (replace-match "" t t ans)
15003 deltan (car delta)
15004 deltaw (nth 1 delta)
15005 deltadef (nth 2 delta)))
15007 ;; Check if there is an iso week date in there
15008 ;; If yes, store the info and postpone interpreting it until the rest
15009 ;; of the parsing is done
15010 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15011 (setq iso-year (if (match-end 1)
15012 (org-small-year-to-year
15013 (string-to-number (match-string 1 ans))))
15014 iso-weekday (if (match-end 3)
15015 (string-to-number (match-string 3 ans)))
15016 iso-week (string-to-number (match-string 2 ans)))
15017 (setq ans (replace-match "" t t ans)))
15019 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15020 (when (string-match
15021 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15022 (setq year (if (match-end 2)
15023 (string-to-number (match-string 2 ans))
15024 (progn (setq kill-year t)
15025 (string-to-number (format-time-string "%Y"))))
15026 month (string-to-number (match-string 3 ans))
15027 day (string-to-number (match-string 4 ans)))
15028 (if (< year 100) (setq year (+ 2000 year)))
15029 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15030 t nil ans)))
15032 ;; Help matching dottet european dates
15033 (when (string-match
15034 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15035 (setq year (if (match-end 3)
15036 (string-to-number (match-string 3 ans))
15037 (progn (setq kill-year t)
15038 (string-to-number (format-time-string "%Y"))))
15039 day (string-to-number (match-string 1 ans))
15040 month (string-to-number (match-string 2 ans))
15041 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15042 t nil ans)))
15044 ;; Help matching american dates, like 5/30 or 5/30/7
15045 (when (string-match
15046 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15047 (setq year (if (match-end 4)
15048 (string-to-number (match-string 4 ans))
15049 (progn (setq kill-year t)
15050 (string-to-number (format-time-string "%Y"))))
15051 month (string-to-number (match-string 1 ans))
15052 day (string-to-number (match-string 2 ans)))
15053 (if (< year 100) (setq year (+ 2000 year)))
15054 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15055 t nil ans)))
15056 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15057 ;; If there is a time with am/pm, and *no* time without it, we convert
15058 ;; so that matching will be successful.
15059 (loop for i from 1 to 2 do ; twice, for end time as well
15060 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15061 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15062 (setq hour (string-to-number (match-string 1 ans))
15063 minute (if (match-end 3)
15064 (string-to-number (match-string 3 ans))
15066 pm (equal ?p
15067 (string-to-char (downcase (match-string 4 ans)))))
15068 (if (and (= hour 12) (not pm))
15069 (setq hour 0)
15070 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15071 (setq ans (replace-match (format "%02d:%02d" hour minute)
15072 t t ans))))
15074 ;; Check if a time range is given as a duration
15075 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15076 (setq hour (string-to-number (match-string 1 ans))
15077 h2 (+ hour (string-to-number (match-string 3 ans)))
15078 minute (string-to-number (match-string 2 ans))
15079 m2 (+ minute (if (match-end 5) (string-to-number
15080 (match-string 5 ans))0)))
15081 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15082 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15083 t t ans)))
15085 ;; Check if there is a time range
15086 (when (boundp 'org-end-time-was-given)
15087 (setq org-time-was-given nil)
15088 (when (and (string-match org-plain-time-of-day-regexp ans)
15089 (match-end 8))
15090 (setq org-end-time-was-given (match-string 8 ans))
15091 (setq ans (concat (substring ans 0 (match-beginning 7))
15092 (substring ans (match-end 7))))))
15094 (setq tl (parse-time-string ans)
15095 day (or (nth 3 tl) (nth 3 defdecode))
15096 month (or (nth 4 tl)
15097 (if (and org-read-date-prefer-future
15098 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15099 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15100 (nth 4 defdecode)))
15101 year (or (and (not kill-year) (nth 5 tl))
15102 (if (and org-read-date-prefer-future
15103 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15104 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15105 (nth 5 defdecode)))
15106 hour (or (nth 2 tl) (nth 2 defdecode))
15107 minute (or (nth 1 tl) (nth 1 defdecode))
15108 second (or (nth 0 tl) 0)
15109 wday (nth 6 tl))
15111 (when (and (eq org-read-date-prefer-future 'time)
15112 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15113 (equal day (nth 3 nowdecode))
15114 (equal month (nth 4 nowdecode))
15115 (equal year (nth 5 nowdecode))
15116 (nth 2 tl)
15117 (or (< (nth 2 tl) (nth 2 nowdecode))
15118 (and (= (nth 2 tl) (nth 2 nowdecode))
15119 (nth 1 tl)
15120 (< (nth 1 tl) (nth 1 nowdecode)))))
15121 (setq day (1+ day)
15122 futurep t))
15124 ;; Special date definitions below
15125 (cond
15126 (iso-week
15127 ;; There was an iso week
15128 (require 'cal-iso)
15129 (setq futurep nil)
15130 (setq year (or iso-year year)
15131 day (or iso-weekday wday 1)
15132 wday nil ; to make sure that the trigger below does not match
15133 iso-date (calendar-gregorian-from-absolute
15134 (calendar-absolute-from-iso
15135 (list iso-week day year))))
15136 ; FIXME: Should we also push ISO weeks into the future?
15137 ; (when (and org-read-date-prefer-future
15138 ; (not iso-year)
15139 ; (< (calendar-absolute-from-gregorian iso-date)
15140 ; (time-to-days (current-time))))
15141 ; (setq year (1+ year)
15142 ; iso-date (calendar-gregorian-from-absolute
15143 ; (calendar-absolute-from-iso
15144 ; (list iso-week day year)))))
15145 (setq month (car iso-date)
15146 year (nth 2 iso-date)
15147 day (nth 1 iso-date)))
15148 (deltan
15149 (setq futurep nil)
15150 (unless deltadef
15151 (let ((now (decode-time (current-time))))
15152 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15153 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15154 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15155 ((equal deltaw "m") (setq month (+ month deltan)))
15156 ((equal deltaw "y") (setq year (+ year deltan)))))
15157 ((and wday (not (nth 3 tl)))
15158 (setq futurep nil)
15159 ;; Weekday was given, but no day, so pick that day in the week
15160 ;; on or after the derived date.
15161 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15162 (unless (equal wday wday1)
15163 (setq day (+ day (% (- wday wday1 -7) 7))))))
15164 (if (and (boundp 'org-time-was-given)
15165 (nth 2 tl))
15166 (setq org-time-was-given t))
15167 (if (< year 100) (setq year (+ 2000 year)))
15168 ;; Check of the date is representable
15169 (if org-read-date-force-compatible-dates
15170 (progn
15171 (if (< year 1970)
15172 (setq year 1970 org-read-date-analyze-forced-year t))
15173 (if (> year 2037)
15174 (setq year 2037 org-read-date-analyze-forced-year t)))
15175 (condition-case nil
15176 (ignore (encode-time second minute hour day month year))
15177 (error
15178 (setq year (nth 5 defdecode))
15179 (setq org-read-date-analyze-forced-year t))))
15180 (setq org-read-date-analyze-futurep futurep)
15181 (list second minute hour day month year)))
15183 (defvar parse-time-weekdays)
15185 (defun org-read-date-get-relative (s today default)
15186 "Check string S for special relative date string.
15187 TODAY and DEFAULT are internal times, for today and for a default.
15188 Return shift list (N what def-flag)
15189 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15190 N is the number of WHATs to shift.
15191 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15192 the DEFAULT date rather than TODAY."
15193 (when (and
15194 (string-match
15195 (concat
15196 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15197 "\\([0-9]+\\)?"
15198 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15199 "\\([ \t]\\|$\\)") s)
15200 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15201 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15202 (string-to-char (substring (match-string 1 s) -1))
15203 ?+))
15204 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15205 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15206 (what (if (match-end 3) (match-string 3 s) "d"))
15207 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15208 (date (if rel default today))
15209 (wday (nth 6 (decode-time date)))
15210 delta)
15211 (if wday1
15212 (progn
15213 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15214 (if (= dir ?-) (setq delta (- delta 7)))
15215 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15216 (list delta "d" rel))
15217 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15219 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15220 "Turn a user-specified date into the internal representation.
15221 The internal representation needed by the calendar is (month day year).
15222 This is a wrapper to handle the brain-dead convention in calendar that
15223 user function argument order change dependent on argument order."
15224 (if (boundp 'calendar-date-style)
15225 (cond
15226 ((eq calendar-date-style 'american)
15227 (list arg1 arg2 arg3))
15228 ((eq calendar-date-style 'european)
15229 (list arg2 arg1 arg3))
15230 ((eq calendar-date-style 'iso)
15231 (list arg2 arg3 arg1)))
15232 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15233 (if (org-bound-and-true-p european-calendar-style)
15234 (list arg2 arg1 arg3)
15235 (list arg1 arg2 arg3)))))
15237 (defun org-eval-in-calendar (form &optional keepdate)
15238 "Eval FORM in the calendar window and return to current window.
15239 Also, store the cursor date in variable org-ans2."
15240 (let ((sf (selected-frame))
15241 (sw (selected-window)))
15242 (select-window (get-buffer-window "*Calendar*" t))
15243 (eval form)
15244 (when (and (not keepdate) (calendar-cursor-to-date))
15245 (let* ((date (calendar-cursor-to-date))
15246 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15247 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15248 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15249 (select-window sw)
15250 (org-select-frame-set-input-focus sf)))
15252 (defun org-calendar-select ()
15253 "Return to `org-read-date' with the date currently selected.
15254 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15255 (interactive)
15256 (when (calendar-cursor-to-date)
15257 (let* ((date (calendar-cursor-to-date))
15258 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15259 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15260 (if (active-minibuffer-window) (exit-minibuffer))))
15262 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15263 "Insert a date stamp for the date given by the internal TIME.
15264 WITH-HM means use the stamp format that includes the time of the day.
15265 INACTIVE means use square brackets instead of angular ones, so that the
15266 stamp will not contribute to the agenda.
15267 PRE and POST are optional strings to be inserted before and after the
15268 stamp.
15269 The command returns the inserted time stamp."
15270 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15271 stamp)
15272 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15273 (insert-before-markers (or pre ""))
15274 (when (listp extra)
15275 (setq extra (car extra))
15276 (if (and (stringp extra)
15277 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15278 (setq extra (format "-%02d:%02d"
15279 (string-to-number (match-string 1 extra))
15280 (string-to-number (match-string 2 extra))))
15281 (setq extra nil)))
15282 (when extra
15283 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15284 (insert-before-markers (setq stamp (format-time-string fmt time)))
15285 (insert-before-markers (or post ""))
15286 (setq org-last-inserted-timestamp stamp)))
15288 (defun org-toggle-time-stamp-overlays ()
15289 "Toggle the use of custom time stamp formats."
15290 (interactive)
15291 (setq org-display-custom-times (not org-display-custom-times))
15292 (unless org-display-custom-times
15293 (let ((p (point-min)) (bmp (buffer-modified-p)))
15294 (while (setq p (next-single-property-change p 'display))
15295 (if (and (get-text-property p 'display)
15296 (eq (get-text-property p 'face) 'org-date))
15297 (remove-text-properties
15298 p (setq p (next-single-property-change p 'display))
15299 '(display t))))
15300 (set-buffer-modified-p bmp)))
15301 (if (featurep 'xemacs)
15302 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15303 (org-restart-font-lock)
15304 (setq org-table-may-need-update t)
15305 (if org-display-custom-times
15306 (message "Time stamps are overlayed with custom format")
15307 (message "Time stamp overlays removed")))
15309 (defun org-display-custom-time (beg end)
15310 "Overlay modified time stamp format over timestamp between BEG and END."
15311 (let* ((ts (buffer-substring beg end))
15312 t1 w1 with-hm tf time str w2 (off 0))
15313 (save-match-data
15314 (setq t1 (org-parse-time-string ts t))
15315 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15316 (setq off (- (match-end 0) (match-beginning 0)))))
15317 (setq end (- end off))
15318 (setq w1 (- end beg)
15319 with-hm (and (nth 1 t1) (nth 2 t1))
15320 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15321 time (org-fix-decoded-time t1)
15322 str (org-add-props
15323 (format-time-string
15324 (substring tf 1 -1) (apply 'encode-time time))
15325 nil 'mouse-face 'highlight)
15326 w2 (length str))
15327 (if (not (= w2 w1))
15328 (add-text-properties (1+ beg) (+ 2 beg)
15329 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15330 (if (featurep 'xemacs)
15331 (progn
15332 (put-text-property beg end 'invisible t)
15333 (put-text-property beg end 'end-glyph (make-glyph str)))
15334 (put-text-property beg end 'display str))))
15336 (defun org-translate-time (string)
15337 "Translate all timestamps in STRING to custom format.
15338 But do this only if the variable `org-display-custom-times' is set."
15339 (when org-display-custom-times
15340 (save-match-data
15341 (let* ((start 0)
15342 (re org-ts-regexp-both)
15343 t1 with-hm inactive tf time str beg end)
15344 (while (setq start (string-match re string start))
15345 (setq beg (match-beginning 0)
15346 end (match-end 0)
15347 t1 (save-match-data
15348 (org-parse-time-string (substring string beg end) t))
15349 with-hm (and (nth 1 t1) (nth 2 t1))
15350 inactive (equal (substring string beg (1+ beg)) "[")
15351 tf (funcall (if with-hm 'cdr 'car)
15352 org-time-stamp-custom-formats)
15353 time (org-fix-decoded-time t1)
15354 str (format-time-string
15355 (concat
15356 (if inactive "[" "<") (substring tf 1 -1)
15357 (if inactive "]" ">"))
15358 (apply 'encode-time time))
15359 string (replace-match str t t string)
15360 start (+ start (length str)))))))
15361 string)
15363 (defun org-fix-decoded-time (time)
15364 "Set 0 instead of nil for the first 6 elements of time.
15365 Don't touch the rest."
15366 (let ((n 0))
15367 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15369 (defun org-days-to-time (timestamp-string)
15370 "Difference between TIMESTAMP-STRING and now in days."
15371 (- (time-to-days (org-time-string-to-time timestamp-string))
15372 (time-to-days (current-time))))
15374 (defun org-deadline-close (timestamp-string &optional ndays)
15375 "Is the time in TIMESTAMP-STRING close to the current date?"
15376 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15377 (and (< (org-days-to-time timestamp-string) ndays)
15378 (not (org-entry-is-done-p))))
15380 (defun org-get-wdays (ts)
15381 "Get the deadline lead time appropriate for timestring TS."
15382 (cond
15383 ((<= org-deadline-warning-days 0)
15384 ;; 0 or negative, enforce this value no matter what
15385 (- org-deadline-warning-days))
15386 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15387 ;; lead time is specified.
15388 (floor (* (string-to-number (match-string 1 ts))
15389 (cdr (assoc (match-string 2 ts)
15390 '(("d" . 1) ("w" . 7)
15391 ("m" . 30.4) ("y" . 365.25)))))))
15392 ;; go for the default.
15393 (t org-deadline-warning-days)))
15395 (defun org-calendar-select-mouse (ev)
15396 "Return to `org-read-date' with the date currently selected.
15397 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15398 (interactive "e")
15399 (mouse-set-point ev)
15400 (when (calendar-cursor-to-date)
15401 (let* ((date (calendar-cursor-to-date))
15402 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15403 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15404 (if (active-minibuffer-window) (exit-minibuffer))))
15406 (defun org-check-deadlines (ndays)
15407 "Check if there are any deadlines due or past due.
15408 A deadline is considered due if it happens within `org-deadline-warning-days'
15409 days from today's date. If the deadline appears in an entry marked DONE,
15410 it is not shown. The prefix arg NDAYS can be used to test that many
15411 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15412 (interactive "P")
15413 (let* ((org-warn-days
15414 (cond
15415 ((equal ndays '(4)) 100000)
15416 (ndays (prefix-numeric-value ndays))
15417 (t (abs org-deadline-warning-days))))
15418 (case-fold-search nil)
15419 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15420 (callback
15421 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15423 (message "%d deadlines past-due or due within %d days"
15424 (org-occur regexp nil callback)
15425 org-warn-days)))
15427 (defun org-check-before-date (date)
15428 "Check if there are deadlines or scheduled entries before DATE."
15429 (interactive (list (org-read-date)))
15430 (let ((case-fold-search nil)
15431 (regexp (concat "\\<\\(" org-deadline-string
15432 "\\|" org-scheduled-string
15433 "\\) *<\\([^>]+\\)>"))
15434 (callback
15435 (lambda () (time-less-p
15436 (org-time-string-to-time (match-string 2))
15437 (org-time-string-to-time date)))))
15438 (message "%d entries before %s"
15439 (org-occur regexp nil callback) date)))
15441 (defun org-check-after-date (date)
15442 "Check if there are deadlines or scheduled entries after DATE."
15443 (interactive (list (org-read-date)))
15444 (let ((case-fold-search nil)
15445 (regexp (concat "\\<\\(" org-deadline-string
15446 "\\|" org-scheduled-string
15447 "\\) *<\\([^>]+\\)>"))
15448 (callback
15449 (lambda () (not
15450 (time-less-p
15451 (org-time-string-to-time (match-string 2))
15452 (org-time-string-to-time date))))))
15453 (message "%d entries after %s"
15454 (org-occur regexp nil callback) date)))
15456 (defun org-evaluate-time-range (&optional to-buffer)
15457 "Evaluate a time range by computing the difference between start and end.
15458 Normally the result is just printed in the echo area, but with prefix arg
15459 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15460 If the time range is actually in a table, the result is inserted into the
15461 next column.
15462 For time difference computation, a year is assumed to be exactly 365
15463 days in order to avoid rounding problems."
15464 (interactive "P")
15466 (org-clock-update-time-maybe)
15467 (save-excursion
15468 (unless (org-at-date-range-p t)
15469 (goto-char (point-at-bol))
15470 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15471 (if (not (org-at-date-range-p t))
15472 (error "Not at a time-stamp range, and none found in current line")))
15473 (let* ((ts1 (match-string 1))
15474 (ts2 (match-string 2))
15475 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15476 (match-end (match-end 0))
15477 (time1 (org-time-string-to-time ts1))
15478 (time2 (org-time-string-to-time ts2))
15479 (t1 (org-float-time time1))
15480 (t2 (org-float-time time2))
15481 (diff (abs (- t2 t1)))
15482 (negative (< (- t2 t1) 0))
15483 ;; (ys (floor (* 365 24 60 60)))
15484 (ds (* 24 60 60))
15485 (hs (* 60 60))
15486 (fy "%dy %dd %02d:%02d")
15487 (fy1 "%dy %dd")
15488 (fd "%dd %02d:%02d")
15489 (fd1 "%dd")
15490 (fh "%02d:%02d")
15491 y d h m align)
15492 (if havetime
15493 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15495 d (floor (/ diff ds)) diff (mod diff ds)
15496 h (floor (/ diff hs)) diff (mod diff hs)
15497 m (floor (/ diff 60)))
15498 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15500 d (floor (+ (/ diff ds) 0.5))
15501 h 0 m 0))
15502 (if (not to-buffer)
15503 (message "%s" (org-make-tdiff-string y d h m))
15504 (if (org-at-table-p)
15505 (progn
15506 (goto-char match-end)
15507 (setq align t)
15508 (and (looking-at " *|") (goto-char (match-end 0))))
15509 (goto-char match-end))
15510 (if (looking-at
15511 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15512 (replace-match ""))
15513 (if negative (insert " -"))
15514 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15515 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15516 (insert " " (format fh h m))))
15517 (if align (org-table-align))
15518 (message "Time difference inserted")))))
15520 (defun org-make-tdiff-string (y d h m)
15521 (let ((fmt "")
15522 (l nil))
15523 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15524 l (push y l)))
15525 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15526 l (push d l)))
15527 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15528 l (push h l)))
15529 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15530 l (push m l)))
15531 (apply 'format fmt (nreverse l))))
15533 (defun org-time-string-to-time (s &optional buffer pos)
15534 (condition-case errdata
15535 (apply 'encode-time (org-parse-time-string s))
15536 (error (error "Bad timestamp `%s'%s\nError was: %s"
15537 s (if (not (and buffer pos))
15539 (format " at %d in buffer `%s'" pos buffer))
15540 (cdr errdata)))))
15542 (defun org-time-string-to-seconds (s)
15543 (org-float-time (org-time-string-to-time s)))
15545 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15546 "Convert a time stamp to an absolute day number.
15547 If there is a specifier for a cyclic time stamp, get the closest date to
15548 DAYNR.
15549 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15550 The variable date is bound by the calendar when this is called."
15551 (cond
15552 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15553 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15554 daynr
15555 (+ daynr 1000)))
15556 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15557 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15558 (time-to-days (current-time))) (match-string 0 s)
15559 prefer show-all))
15560 (t (time-to-days
15561 (condition-case errdata
15562 (apply 'encode-time (org-parse-time-string s))
15563 (error (error "Bad timestamp `%s'%s\nError was: %s"
15564 s (if (not (and buffer pos))
15566 (format " at %d in buffer `%s'" pos buffer))
15567 (cdr errdata))))))))
15569 (defun org-days-to-iso-week (days)
15570 "Return the iso week number."
15571 (require 'cal-iso)
15572 (car (calendar-iso-from-absolute days)))
15574 (defun org-small-year-to-year (year)
15575 "Convert 2-digit years into 4-digit years.
15576 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15577 The year 2000 cannot be abbreviated. Any year larger than 99
15578 is returned unchanged."
15579 (if (< year 38)
15580 (setq year (+ 2000 year))
15581 (if (< year 100)
15582 (setq year (+ 1900 year))))
15583 year)
15585 (defun org-time-from-absolute (d)
15586 "Return the time corresponding to date D.
15587 D may be an absolute day number, or a calendar-type list (month day year)."
15588 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15589 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15591 (defun org-calendar-holiday ()
15592 "List of holidays, for Diary display in Org-mode."
15593 (require 'holidays)
15594 (let ((hl (funcall
15595 (if (fboundp 'calendar-check-holidays)
15596 'calendar-check-holidays 'check-calendar-holidays) date)))
15597 (if hl (mapconcat 'identity hl "; "))))
15599 (defun org-diary-sexp-entry (sexp entry date)
15600 "Process a SEXP diary ENTRY for DATE."
15601 (require 'diary-lib)
15602 (let ((result (if calendar-debug-sexp
15603 (let ((stack-trace-on-error t))
15604 (eval (car (read-from-string sexp))))
15605 (condition-case nil
15606 (eval (car (read-from-string sexp)))
15607 (error
15608 (beep)
15609 (message "Bad sexp at line %d in %s: %s"
15610 (org-current-line)
15611 (buffer-file-name) sexp)
15612 (sleep-for 2))))))
15613 (cond ((stringp result) (split-string result "; "))
15614 ((and (consp result)
15615 (not (consp (cdr result)))
15616 (stringp (cdr result))) (cdr result))
15617 ((and (consp result)
15618 (stringp (car result))) result)
15619 (result entry)
15620 (t nil))))
15622 (defun org-diary-to-ical-string (frombuf)
15623 "Get iCalendar entries from diary entries in buffer FROMBUF.
15624 This uses the icalendar.el library."
15625 (let* ((tmpdir (if (featurep 'xemacs)
15626 (temp-directory)
15627 temporary-file-directory))
15628 (tmpfile (make-temp-name
15629 (expand-file-name "orgics" tmpdir)))
15630 buf rtn b e)
15631 (with-current-buffer frombuf
15632 (icalendar-export-region (point-min) (point-max) tmpfile)
15633 (setq buf (find-buffer-visiting tmpfile))
15634 (set-buffer buf)
15635 (goto-char (point-min))
15636 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15637 (setq b (match-beginning 0)))
15638 (goto-char (point-max))
15639 (if (re-search-backward "^END:VEVENT" nil t)
15640 (setq e (match-end 0)))
15641 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15642 (kill-buffer buf)
15643 (delete-file tmpfile)
15644 rtn))
15646 (defun org-closest-date (start current change prefer show-all)
15647 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15648 When PREFER is `past', return a date that is either CURRENT or past.
15649 When PREFER is `future', return a date that is either CURRENT or future.
15650 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15651 ;; Make the proper lists from the dates
15652 (catch 'exit
15653 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15654 dn dw sday cday n1 n2 n0
15655 d m y y1 y2 date1 date2 nmonths nm ny m2)
15657 (setq start (org-date-to-gregorian start)
15658 current (org-date-to-gregorian
15659 (if show-all
15660 current
15661 (time-to-days (current-time))))
15662 sday (calendar-absolute-from-gregorian start)
15663 cday (calendar-absolute-from-gregorian current))
15665 (if (<= cday sday) (throw 'exit sday))
15667 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15668 (setq dn (string-to-number (match-string 1 change))
15669 dw (cdr (assoc (match-string 2 change) a1)))
15670 (error "Invalid change specifier: %s" change))
15671 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15672 (cond
15673 ((eq dw 'day)
15674 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15675 n2 (+ n1 dn)))
15676 ((eq dw 'year)
15677 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15678 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15679 (setq date1 (list m d y1)
15680 n1 (calendar-absolute-from-gregorian date1)
15681 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15682 n2 (calendar-absolute-from-gregorian date2)))
15683 ((eq dw 'month)
15684 ;; approx number of month between the two dates
15685 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15686 ;; How often does dn fit in there?
15687 (setq d (nth 1 start) m (car start) y (nth 2 start)
15688 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15689 m (+ m nm)
15690 ny (floor (/ m 12))
15691 y (+ y ny)
15692 m (- m (* ny 12)))
15693 (while (> m 12) (setq m (- m 12) y (1+ y)))
15694 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15695 (setq m2 (+ m dn) y2 y)
15696 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15697 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15698 (while (<= n2 cday)
15699 (setq n1 n2 m m2 y y2)
15700 (setq m2 (+ m dn) y2 y)
15701 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15702 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15703 ;; Make sure n1 is the earlier date
15704 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15705 (if show-all
15706 (cond
15707 ((eq prefer 'past) (if (= cday n2) n2 n1))
15708 ((eq prefer 'future) (if (= cday n1) n1 n2))
15709 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15710 (cond
15711 ((eq prefer 'past) (if (= cday n2) n2 n1))
15712 ((eq prefer 'future) (if (= cday n1) n1 n2))
15713 (t (if (= cday n1) n1 n2)))))))
15715 (defun org-date-to-gregorian (date)
15716 "Turn any specification of DATE into a Gregorian date for the calendar."
15717 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15718 ((and (listp date) (= (length date) 3)) date)
15719 ((stringp date)
15720 (setq date (org-parse-time-string date))
15721 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15722 ((listp date)
15723 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15725 (defun org-parse-time-string (s &optional nodefault)
15726 "Parse the standard Org-mode time string.
15727 This should be a lot faster than the normal `parse-time-string'.
15728 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15729 hour and minute fields will be nil if not given."
15730 (if (string-match org-ts-regexp0 s)
15731 (list 0
15732 (if (or (match-beginning 8) (not nodefault))
15733 (string-to-number (or (match-string 8 s) "0")))
15734 (if (or (match-beginning 7) (not nodefault))
15735 (string-to-number (or (match-string 7 s) "0")))
15736 (string-to-number (match-string 4 s))
15737 (string-to-number (match-string 3 s))
15738 (string-to-number (match-string 2 s))
15739 nil nil nil)
15740 (error "Not a standard Org-mode time string: %s" s)))
15742 (defun org-timestamp-up (&optional arg)
15743 "Increase the date item at the cursor by one.
15744 If the cursor is on the year, change the year. If it is on the month,
15745 the day or the time, change that.
15746 With prefix ARG, change by that many units."
15747 (interactive "p")
15748 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15750 (defun org-timestamp-down (&optional arg)
15751 "Decrease the date item at the cursor by one.
15752 If the cursor is on the year, change the year. If it is on the month,
15753 the day or the time, change that.
15754 With prefix ARG, change by that many units."
15755 (interactive "p")
15756 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15758 (defun org-timestamp-up-day (&optional arg)
15759 "Increase the date in the time stamp by one day.
15760 With prefix ARG, change that many days."
15761 (interactive "p")
15762 (if (and (not (org-at-timestamp-p t))
15763 (org-on-heading-p))
15764 (org-todo 'up)
15765 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15767 (defun org-timestamp-down-day (&optional arg)
15768 "Decrease the date in the time stamp by one day.
15769 With prefix ARG, change that many days."
15770 (interactive "p")
15771 (if (and (not (org-at-timestamp-p t))
15772 (org-on-heading-p))
15773 (org-todo 'down)
15774 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15776 (defun org-at-timestamp-p (&optional inactive-ok)
15777 "Determine if the cursor is in or at a timestamp."
15778 (interactive)
15779 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15780 (pos (point))
15781 (ans (or (looking-at tsr)
15782 (save-excursion
15783 (skip-chars-backward "^[<\n\r\t")
15784 (if (> (point) (point-min)) (backward-char 1))
15785 (and (looking-at tsr)
15786 (> (- (match-end 0) pos) -1))))))
15787 (and ans
15788 (boundp 'org-ts-what)
15789 (setq org-ts-what
15790 (cond
15791 ((= pos (match-beginning 0)) 'bracket)
15792 ;; Point is considered to be "on the bracket" whether
15793 ;; it's really on it or right after it.
15794 ((or (= pos (1- (match-end 0)))
15795 (= pos (match-end 0))) 'bracket)
15796 ((org-pos-in-match-range pos 2) 'year)
15797 ((org-pos-in-match-range pos 3) 'month)
15798 ((org-pos-in-match-range pos 7) 'hour)
15799 ((org-pos-in-match-range pos 8) 'minute)
15800 ((or (org-pos-in-match-range pos 4)
15801 (org-pos-in-match-range pos 5)) 'day)
15802 ((and (> pos (or (match-end 8) (match-end 5)))
15803 (< pos (match-end 0)))
15804 (- pos (or (match-end 8) (match-end 5))))
15805 (t 'day))))
15806 ans))
15808 (defun org-toggle-timestamp-type ()
15809 "Toggle the type (<active> or [inactive]) of a time stamp."
15810 (interactive)
15811 (when (org-at-timestamp-p t)
15812 (let ((beg (match-beginning 0)) (end (match-end 0))
15813 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
15814 (save-excursion
15815 (goto-char beg)
15816 (while (re-search-forward "[][<>]" end t)
15817 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
15818 t t)))
15819 (message "Timestamp is now %sactive"
15820 (if (equal (char-after beg) ?<) "" "in")))))
15822 (defun org-timestamp-change (n &optional what updown)
15823 "Change the date in the time stamp at point.
15824 The date will be changed by N times WHAT. WHAT can be `day', `month',
15825 `year', `minute', `second'. If WHAT is not given, the cursor position
15826 in the timestamp determines what will be changed."
15827 (let ((origin (point)) origin-cat
15828 with-hm inactive
15829 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
15830 org-ts-what
15831 extra rem
15832 ts time time0)
15833 (if (not (org-at-timestamp-p t))
15834 (error "Not at a timestamp"))
15835 (if (and (not what) (eq org-ts-what 'bracket))
15836 (org-toggle-timestamp-type)
15837 ;; Point isn't on brackets. Remember the part of the time-stamp
15838 ;; the point was in. Indeed, size of time-stamps may change,
15839 ;; but point must be kept in the same category nonetheless.
15840 (setq origin-cat org-ts-what)
15841 (if (and (not what) (not (eq org-ts-what 'day))
15842 org-display-custom-times
15843 (get-text-property (point) 'display)
15844 (not (get-text-property (1- (point)) 'display)))
15845 (setq org-ts-what 'day))
15846 (setq org-ts-what (or what org-ts-what)
15847 inactive (= (char-after (match-beginning 0)) ?\[)
15848 ts (match-string 0))
15849 (replace-match "")
15850 (if (string-match
15851 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
15853 (setq extra (match-string 1 ts)))
15854 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15855 (setq with-hm t))
15856 (setq time0 (org-parse-time-string ts))
15857 (when (and updown
15858 (eq org-ts-what 'minute)
15859 (not current-prefix-arg))
15860 ;; This looks like s-up and s-down. Change by one rounding step.
15861 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
15862 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
15863 (setcar (cdr time0) (+ (nth 1 time0)
15864 (if (> n 0) (- rem) (- dm rem))))))
15865 (setq time
15866 (encode-time (or (car time0) 0)
15867 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
15868 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
15869 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
15870 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
15871 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
15872 (nthcdr 6 time0)))
15873 (when (and (member org-ts-what '(hour minute))
15874 extra
15875 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
15876 (setq extra (org-modify-ts-extra
15877 extra
15878 (if (eq org-ts-what 'hour) 2 5)
15879 n dm)))
15880 (when (integerp org-ts-what)
15881 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
15882 (if (eq what 'calendar)
15883 (let ((cal-date (org-get-date-from-calendar)))
15884 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15885 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15886 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15887 (setcar time0 (or (car time0) 0))
15888 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15889 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15890 (setq time (apply 'encode-time time0))))
15891 ;; Insert the new time-stamp, and ensure point stays in the same
15892 ;; category as before (i.e. not after the last position in that
15893 ;; category).
15894 (let ((pos (point)))
15895 ;; Stay before inserted string. `save-excursion' is of no use.
15896 (setq org-last-changed-timestamp
15897 (org-insert-time-stamp time with-hm inactive nil nil extra))
15898 (goto-char pos))
15899 (save-match-data
15900 (looking-at org-ts-regexp3)
15901 (goto-char (cond
15902 ;; `day' category ends before `hour' if any, or at
15903 ;; the end of the day name.
15904 ((eq origin-cat 'day)
15905 (min (or (match-beginning 7) (1- (match-end 5))) origin))
15906 ((eq origin-cat 'hour) (min (match-end 7) origin))
15907 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
15908 ((integerp origin-cat) (min (1- (match-end 0)) origin))
15909 ;; `year' and `month' have both fixed size: point
15910 ;; couldn't have moved into another part.
15911 (t origin))))
15912 ;; Update clock if on a CLOCK line.
15913 (org-clock-update-time-maybe)
15914 ;; Try to recenter the calendar window, if any.
15915 (if (and org-calendar-follow-timestamp-change
15916 (get-buffer-window "*Calendar*" t)
15917 (memq org-ts-what '(day month year)))
15918 (org-recenter-calendar (time-to-days time))))))
15920 (defun org-modify-ts-extra (s pos n dm)
15921 "Change the different parts of the lead-time and repeat fields in timestamp."
15922 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15923 ng h m new rem)
15924 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15925 (cond
15926 ((or (org-pos-in-match-range pos 2)
15927 (org-pos-in-match-range pos 3))
15928 (setq m (string-to-number (match-string 3 s))
15929 h (string-to-number (match-string 2 s)))
15930 (if (org-pos-in-match-range pos 2)
15931 (setq h (+ h n))
15932 (setq n (* dm (org-no-warnings (signum n))))
15933 (when (not (= 0 (setq rem (% m dm))))
15934 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
15935 (setq m (+ m n)))
15936 (if (< m 0) (setq m (+ m 60) h (1- h)))
15937 (if (> m 59) (setq m (- m 60) h (1+ h)))
15938 (setq h (min 24 (max 0 h)))
15939 (setq ng 1 new (format "-%02d:%02d" h m)))
15940 ((org-pos-in-match-range pos 6)
15941 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15942 ((org-pos-in-match-range pos 5)
15943 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
15945 ((org-pos-in-match-range pos 9)
15946 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
15947 ((org-pos-in-match-range pos 8)
15948 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
15950 (when ng
15951 (setq s (concat
15952 (substring s 0 (match-beginning ng))
15954 (substring s (match-end ng))))))
15957 (defun org-recenter-calendar (date)
15958 "If the calendar is visible, recenter it to DATE."
15959 (let* ((win (selected-window))
15960 (cwin (get-buffer-window "*Calendar*" t))
15961 (calendar-move-hook nil))
15962 (when cwin
15963 (select-window cwin)
15964 (calendar-goto-date (if (listp date) date
15965 (calendar-gregorian-from-absolute date)))
15966 (select-window win))))
15968 (defun org-goto-calendar (&optional arg)
15969 "Go to the Emacs calendar at the current date.
15970 If there is a time stamp in the current line, go to that date.
15971 A prefix ARG can be used to force the current date."
15972 (interactive "P")
15973 (let ((tsr org-ts-regexp) diff
15974 (calendar-move-hook nil)
15975 (calendar-view-holidays-initially-flag nil)
15976 (calendar-view-diary-initially-flag nil))
15977 (if (or (org-at-timestamp-p)
15978 (save-excursion
15979 (beginning-of-line 1)
15980 (looking-at (concat ".*" tsr))))
15981 (let ((d1 (time-to-days (current-time)))
15982 (d2 (time-to-days
15983 (org-time-string-to-time (match-string 1)))))
15984 (setq diff (- d2 d1))))
15985 (calendar)
15986 (calendar-goto-today)
15987 (if (and diff (not arg)) (calendar-forward-day diff))))
15989 (defun org-get-date-from-calendar ()
15990 "Return a list (month day year) of date at point in calendar."
15991 (with-current-buffer "*Calendar*"
15992 (save-match-data
15993 (calendar-cursor-to-date))))
15995 (defun org-date-from-calendar ()
15996 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
15997 If there is already a time stamp at the cursor position, update it."
15998 (interactive)
15999 (if (org-at-timestamp-p t)
16000 (org-timestamp-change 0 'calendar)
16001 (let ((cal-date (org-get-date-from-calendar)))
16002 (org-insert-time-stamp
16003 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16005 (defun org-minutes-to-hh:mm-string (m)
16006 "Compute H:MM from a number of minutes."
16007 (let ((h (/ m 60)))
16008 (setq m (- m (* 60 h)))
16009 (format org-time-clocksum-format h m)))
16011 (defun org-hh:mm-string-to-minutes (s)
16012 "Convert a string H:MM to a number of minutes.
16013 If the string is just a number, interpret it as minutes.
16014 In fact, the first hh:mm or number in the string will be taken,
16015 there can be extra stuff in the string.
16016 If no number is found, the return value is 0."
16017 (cond
16018 ((integerp s) s)
16019 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16020 (+ (* (string-to-number (match-string 1 s)) 60)
16021 (string-to-number (match-string 2 s))))
16022 ((string-match "\\([0-9]+\\)" s)
16023 (string-to-number (match-string 1 s)))
16024 (t 0)))
16026 (defcustom org-effort-durations
16027 `(("h" . 60)
16028 ("d" . ,(* 60 8))
16029 ("w" . ,(* 60 8 5))
16030 ("m" . ,(* 60 8 5 4))
16031 ("y" . ,(* 60 8 5 40)))
16032 "Conversion factor to minutes for an effort modifier.
16034 Each entry has the form (MODIFIER . MINUTES).
16036 In an effort string, a number followed by MODIFIER is multiplied
16037 by the specified number of MINUTES to obtain an effort in
16038 minutes.
16040 For example, if the value of this variable is ((\"hours\" . 60)), then an
16041 effort string \"2hours\" is equivalent to 120 minutes."
16042 :group 'org-agenda
16043 :type '(alist :key-type (string :tag "Modifier")
16044 :value-type (number :tag "Minutes")))
16046 (defun org-duration-string-to-minutes (s)
16047 "Convert a duration string S to minutes.
16049 A bare number is interpreted as minutes, modifiers can be set by
16050 customizing `org-effort-durations' (which see).
16052 Entries containing a colon are interpreted as H:MM by
16053 `org-hh:mm-string-to-minutes'."
16054 (let ((result 0)
16055 (re (concat "\\([0-9]+\\) *\\("
16056 (regexp-opt (mapcar 'car org-effort-durations))
16057 "\\)")))
16058 (while (string-match re s)
16059 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16060 (string-to-number (match-string 1 s))))
16061 (setq s (replace-match "" nil t s)))
16062 (incf result (org-hh:mm-string-to-minutes s))
16063 result))
16065 ;;;; Files
16067 (defun org-save-all-org-buffers ()
16068 "Save all Org-mode buffers without user confirmation."
16069 (interactive)
16070 (message "Saving all Org-mode buffers...")
16071 (save-some-buffers t (lambda () (eq major-mode 'org-mode)))
16072 (when (featurep 'org-id) (org-id-locations-save))
16073 (message "Saving all Org-mode buffers... done"))
16075 (defun org-revert-all-org-buffers ()
16076 "Revert all Org-mode buffers.
16077 Prompt for confirmation when there are unsaved changes.
16078 Be sure you know what you are doing before letting this function
16079 overwrite your changes.
16081 This function is useful in a setup where one tracks org files
16082 with a version control system, to revert on one machine after pulling
16083 changes from another. I believe the procedure must be like this:
16085 1. M-x org-save-all-org-buffers
16086 2. Pull changes from the other machine, resolve conflicts
16087 3. M-x org-revert-all-org-buffers"
16088 (interactive)
16089 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16090 (error "Abort"))
16091 (save-excursion
16092 (save-window-excursion
16093 (mapc
16094 (lambda (b)
16095 (when (and (with-current-buffer b (eq major-mode 'org-mode))
16096 (with-current-buffer b buffer-file-name))
16097 (org-pop-to-buffer-same-window b)
16098 (revert-buffer t 'no-confirm)))
16099 (buffer-list))
16100 (when (and (featurep 'org-id) org-id-track-globally)
16101 (org-id-locations-load)))))
16103 ;;;; Agenda files
16105 ;;;###autoload
16106 (defun org-switchb (&optional arg)
16107 "Switch between Org buffers.
16108 With one prefix argument, restrict available buffers to files.
16109 With two prefix arguments, restrict available buffers to agenda files.
16111 Defaults to `iswitchb' for buffer name completion.
16112 Set `org-completion-use-ido' to make it use ido instead."
16113 (interactive "P")
16114 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16115 ((equal arg '(16)) (org-buffer-list 'agenda))
16116 (t (org-buffer-list))))
16117 (org-completion-use-iswitchb org-completion-use-iswitchb)
16118 (org-completion-use-ido org-completion-use-ido))
16119 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16120 (setq org-completion-use-iswitchb t))
16121 (org-pop-to-buffer-same-window
16122 (org-icompleting-read "Org buffer: "
16123 (mapcar 'list (mapcar 'buffer-name blist))
16124 nil t))))
16126 ;;; Define some older names previously used for this functionality
16127 ;;;###autoload
16128 (defalias 'org-ido-switchb 'org-switchb)
16129 ;;;###autoload
16130 (defalias 'org-iswitchb 'org-switchb)
16132 (defun org-buffer-list (&optional predicate exclude-tmp)
16133 "Return a list of Org buffers.
16134 PREDICATE can be `export', `files' or `agenda'.
16136 export restrict the list to Export buffers.
16137 files restrict the list to buffers visiting Org files.
16138 agenda restrict the list to buffers visiting agenda files.
16140 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16141 (let* ((bfn nil)
16142 (agenda-files (and (eq predicate 'agenda)
16143 (mapcar 'file-truename (org-agenda-files t))))
16144 (filter
16145 (cond
16146 ((eq predicate 'files)
16147 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
16148 ((eq predicate 'export)
16149 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16150 ((eq predicate 'agenda)
16151 (lambda (b)
16152 (with-current-buffer b
16153 (and (eq major-mode 'org-mode)
16154 (setq bfn (buffer-file-name b))
16155 (member (file-truename bfn) agenda-files)))))
16156 (t (lambda (b) (with-current-buffer b
16157 (or (eq major-mode 'org-mode)
16158 (string-match "\*Org .*Export"
16159 (buffer-name b)))))))))
16160 (delq nil
16161 (mapcar
16162 (lambda(b)
16163 (if (and (funcall filter b)
16164 (or (not exclude-tmp)
16165 (not (string-match "tmp" (buffer-name b)))))
16167 nil))
16168 (buffer-list)))))
16170 (defun org-agenda-files (&optional unrestricted archives)
16171 "Get the list of agenda files.
16172 Optional UNRESTRICTED means return the full list even if a restriction
16173 is currently in place.
16174 When ARCHIVES is t, include all archive files that are really being
16175 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16176 `org-agenda-archives-mode' is t."
16177 (let ((files
16178 (cond
16179 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16180 ((stringp org-agenda-files) (org-read-agenda-file-list))
16181 ((listp org-agenda-files) org-agenda-files)
16182 (t (error "Invalid value of `org-agenda-files'")))))
16183 (setq files (apply 'append
16184 (mapcar (lambda (f)
16185 (if (file-directory-p f)
16186 (directory-files
16187 f t org-agenda-file-regexp)
16188 (list f)))
16189 files)))
16190 (when org-agenda-skip-unavailable-files
16191 (setq files (delq nil
16192 (mapcar (function
16193 (lambda (file)
16194 (and (file-readable-p file) file)))
16195 files))))
16196 (when (or (eq archives t)
16197 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16198 (setq files (org-add-archive-files files)))
16199 files))
16201 (defun org-agenda-file-p (&optional file)
16202 "Return non-nil, if FILE is an agenda file.
16203 If FILE is omitted, use the file associated with the current
16204 buffer."
16205 (member (or file (buffer-file-name))
16206 (org-agenda-files t)))
16208 (defun org-edit-agenda-file-list ()
16209 "Edit the list of agenda files.
16210 Depending on setup, this either uses customize to edit the variable
16211 `org-agenda-files', or it visits the file that is holding the list. In the
16212 latter case, the buffer is set up in a way that saving it automatically kills
16213 the buffer and restores the previous window configuration."
16214 (interactive)
16215 (if (stringp org-agenda-files)
16216 (let ((cw (current-window-configuration)))
16217 (find-file org-agenda-files)
16218 (org-set-local 'org-window-configuration cw)
16219 (org-add-hook 'after-save-hook
16220 (lambda ()
16221 (set-window-configuration
16222 (prog1 org-window-configuration
16223 (kill-buffer (current-buffer))))
16224 (org-install-agenda-files-menu)
16225 (message "New agenda file list installed"))
16226 nil 'local)
16227 (message "%s" (substitute-command-keys
16228 "Edit list and finish with \\[save-buffer]")))
16229 (customize-variable 'org-agenda-files)))
16231 (defun org-store-new-agenda-file-list (list)
16232 "Set new value for the agenda file list and save it correctly."
16233 (if (stringp org-agenda-files)
16234 (let ((fe (org-read-agenda-file-list t)) b u)
16235 (while (setq b (find-buffer-visiting org-agenda-files))
16236 (kill-buffer b))
16237 (with-temp-file org-agenda-files
16238 (insert
16239 (mapconcat
16240 (lambda (f) ;; Keep un-expanded entries.
16241 (if (setq u (assoc f fe))
16242 (cdr u)
16244 list "\n")
16245 "\n")))
16246 (let ((org-mode-hook nil) (org-inhibit-startup t)
16247 (org-insert-mode-line-in-empty-file nil))
16248 (setq org-agenda-files list)
16249 (customize-save-variable 'org-agenda-files org-agenda-files))))
16251 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16252 "Read the list of agenda files from a file.
16253 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16254 filenames, used by `org-store-new-agenda-file-list' to write back
16255 un-expanded file names."
16256 (when (file-directory-p org-agenda-files)
16257 (error "`org-agenda-files' cannot be a single directory"))
16258 (when (stringp org-agenda-files)
16259 (with-temp-buffer
16260 (insert-file-contents org-agenda-files)
16261 (mapcar
16262 (lambda (f)
16263 (let ((e (expand-file-name (substitute-in-file-name f)
16264 org-directory)))
16265 (if pair-with-expansion
16266 (cons e f)
16267 e)))
16268 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16270 ;;;###autoload
16271 (defun org-cycle-agenda-files ()
16272 "Cycle through the files in `org-agenda-files'.
16273 If the current buffer visits an agenda file, find the next one in the list.
16274 If the current buffer does not, find the first agenda file."
16275 (interactive)
16276 (let* ((fs (org-agenda-files t))
16277 (files (append fs (list (car fs))))
16278 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16279 file)
16280 (unless files (error "No agenda files"))
16281 (catch 'exit
16282 (while (setq file (pop files))
16283 (if (equal (file-truename file) tcf)
16284 (when (car files)
16285 (find-file (car files))
16286 (throw 'exit t))))
16287 (find-file (car fs)))
16288 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16290 (defun org-agenda-file-to-front (&optional to-end)
16291 "Move/add the current file to the top of the agenda file list.
16292 If the file is not present in the list, it is added to the front. If it is
16293 present, it is moved there. With optional argument TO-END, add/move to the
16294 end of the list."
16295 (interactive "P")
16296 (let ((org-agenda-skip-unavailable-files nil)
16297 (file-alist (mapcar (lambda (x)
16298 (cons (file-truename x) x))
16299 (org-agenda-files t)))
16300 (ctf (file-truename buffer-file-name))
16301 x had)
16302 (setq x (assoc ctf file-alist) had x)
16304 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16305 (if to-end
16306 (setq file-alist (append (delq x file-alist) (list x)))
16307 (setq file-alist (cons x (delq x file-alist))))
16308 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16309 (org-install-agenda-files-menu)
16310 (message "File %s to %s of agenda file list"
16311 (if had "moved" "added") (if to-end "end" "front"))))
16313 (defun org-remove-file (&optional file)
16314 "Remove current file from the list of files in variable `org-agenda-files'.
16315 These are the files which are being checked for agenda entries.
16316 Optional argument FILE means use this file instead of the current."
16317 (interactive)
16318 (let* ((org-agenda-skip-unavailable-files nil)
16319 (file (or file buffer-file-name))
16320 (true-file (file-truename file))
16321 (afile (abbreviate-file-name file))
16322 (files (delq nil (mapcar
16323 (lambda (x)
16324 (if (equal true-file
16325 (file-truename x))
16326 nil x))
16327 (org-agenda-files t)))))
16328 (if (not (= (length files) (length (org-agenda-files t))))
16329 (progn
16330 (org-store-new-agenda-file-list files)
16331 (org-install-agenda-files-menu)
16332 (message "Removed file: %s" afile))
16333 (message "File was not in list: %s (not removed)" afile))))
16335 (defun org-file-menu-entry (file)
16336 (vector file (list 'find-file file) t))
16338 (defun org-check-agenda-file (file)
16339 "Make sure FILE exists. If not, ask user what to do."
16340 (when (not (file-exists-p file))
16341 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16342 (abbreviate-file-name file))
16343 (let ((r (downcase (read-char-exclusive))))
16344 (cond
16345 ((equal r ?r)
16346 (org-remove-file file)
16347 (throw 'nextfile t))
16348 (t (error "Abort"))))))
16350 (defun org-get-agenda-file-buffer (file)
16351 "Get a buffer visiting FILE. If the buffer needs to be created, add
16352 it to the list of buffers which might be released later."
16353 (let ((buf (org-find-base-buffer-visiting file)))
16354 (if buf
16355 buf ; just return it
16356 ;; Make a new buffer and remember it
16357 (setq buf (find-file-noselect file))
16358 (if buf (push buf org-agenda-new-buffers))
16359 buf)))
16361 (defun org-release-buffers (blist)
16362 "Release all buffers in list, asking the user for confirmation when needed.
16363 When a buffer is unmodified, it is just killed. When modified, it is saved
16364 \(if the user agrees) and then killed."
16365 (let (buf file)
16366 (while (setq buf (pop blist))
16367 (setq file (buffer-file-name buf))
16368 (when (and (buffer-modified-p buf)
16369 file
16370 (y-or-n-p (format "Save file %s? " file)))
16371 (with-current-buffer buf (save-buffer)))
16372 (kill-buffer buf))))
16374 (defun org-prepare-agenda-buffers (files)
16375 "Create buffers for all agenda files, protect archived trees and comments."
16376 (interactive)
16377 (let ((pa '(:org-archived t))
16378 (pc '(:org-comment t))
16379 (pall '(:org-archived t :org-comment t))
16380 (inhibit-read-only t)
16381 (rea (concat ":" org-archive-tag ":"))
16382 bmp file re)
16383 (save-excursion
16384 (save-restriction
16385 (while (setq file (pop files))
16386 (catch 'nextfile
16387 (if (bufferp file)
16388 (set-buffer file)
16389 (org-check-agenda-file file)
16390 (set-buffer (org-get-agenda-file-buffer file)))
16391 (widen)
16392 (setq bmp (buffer-modified-p))
16393 (org-refresh-category-properties)
16394 (setq org-todo-keywords-for-agenda
16395 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16396 (setq org-done-keywords-for-agenda
16397 (append org-done-keywords-for-agenda org-done-keywords))
16398 (setq org-todo-keyword-alist-for-agenda
16399 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16400 (setq org-drawers-for-agenda
16401 (append org-drawers-for-agenda org-drawers))
16402 (setq org-tag-alist-for-agenda
16403 (append org-tag-alist-for-agenda org-tag-alist))
16405 (save-excursion
16406 (remove-text-properties (point-min) (point-max) pall)
16407 (when org-agenda-skip-archived-trees
16408 (goto-char (point-min))
16409 (while (re-search-forward rea nil t)
16410 (if (org-on-heading-p t)
16411 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16412 (goto-char (point-min))
16413 (setq re (format org-heading-keyword-regexp-format
16414 org-comment-string))
16415 (while (re-search-forward re nil t)
16416 (add-text-properties
16417 (match-beginning 0) (org-end-of-subtree t) pc)))
16418 (set-buffer-modified-p bmp)))))
16419 (setq org-todo-keywords-for-agenda
16420 (org-uniquify org-todo-keywords-for-agenda))
16421 (setq org-todo-keyword-alist-for-agenda
16422 (org-uniquify org-todo-keyword-alist-for-agenda)
16423 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16425 ;;;; Embedded LaTeX
16427 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16428 "Keymap for the minor `org-cdlatex-mode'.")
16430 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16431 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16432 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16433 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16434 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16436 (defvar org-cdlatex-texmathp-advice-is-done nil
16437 "Flag remembering if we have applied the advice to texmathp already.")
16439 (define-minor-mode org-cdlatex-mode
16440 "Toggle the minor `org-cdlatex-mode'.
16441 This mode supports entering LaTeX environment and math in LaTeX fragments
16442 in Org-mode.
16443 \\{org-cdlatex-mode-map}"
16444 nil " OCDL" nil
16445 (when org-cdlatex-mode
16446 (require 'cdlatex)
16447 (run-hooks 'cdlatex-mode-hook)
16448 (cdlatex-compute-tables))
16449 (unless org-cdlatex-texmathp-advice-is-done
16450 (setq org-cdlatex-texmathp-advice-is-done t)
16451 (defadvice texmathp (around org-math-always-on activate)
16452 "Always return t in org-mode buffers.
16453 This is because we want to insert math symbols without dollars even outside
16454 the LaTeX math segments. If Orgmode thinks that point is actually inside
16455 an embedded LaTeX fragment, let texmathp do its job.
16456 \\[org-cdlatex-mode-map]"
16457 (interactive)
16458 (let (p)
16459 (cond
16460 ((not (eq major-mode 'org-mode)) ad-do-it)
16461 ((eq this-command 'cdlatex-math-symbol)
16462 (setq ad-return-value t
16463 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16465 (let ((p (org-inside-LaTeX-fragment-p)))
16466 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16467 (setq ad-return-value t
16468 texmathp-why '("Org-mode embedded math" . 0))
16469 (if p ad-do-it)))))))))
16471 (defun turn-on-org-cdlatex ()
16472 "Unconditionally turn on `org-cdlatex-mode'."
16473 (org-cdlatex-mode 1))
16475 (defun org-inside-LaTeX-fragment-p ()
16476 "Test if point is inside a LaTeX fragment.
16477 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16478 sequence appearing also before point.
16479 Even though the matchers for math are configurable, this function assumes
16480 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16481 delimiters are skipped when they have been removed by customization.
16482 The return value is nil, or a cons cell with the delimiter and the
16483 position of this delimiter.
16485 This function does a reasonably good job, but can locally be fooled by
16486 for example currency specifications. For example it will assume being in
16487 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16488 fragments that are properly closed, but during editing, we have to live
16489 with the uncertainty caused by missing closing delimiters. This function
16490 looks only before point, not after."
16491 (catch 'exit
16492 (let ((pos (point))
16493 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16494 (lim (progn
16495 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16496 (point)))
16497 dd-on str (start 0) m re)
16498 (goto-char pos)
16499 (when dodollar
16500 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16501 re (nth 1 (assoc "$" org-latex-regexps)))
16502 (while (string-match re str start)
16503 (cond
16504 ((= (match-end 0) (length str))
16505 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16506 ((= (match-end 0) (- (length str) 5))
16507 (throw 'exit nil))
16508 (t (setq start (match-end 0))))))
16509 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16510 (goto-char pos)
16511 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16512 (and (match-beginning 2) (throw 'exit nil))
16513 ;; count $$
16514 (while (re-search-backward "\\$\\$" lim t)
16515 (setq dd-on (not dd-on)))
16516 (goto-char pos)
16517 (if dd-on (cons "$$" m))))))
16519 (defun org-inside-latex-macro-p ()
16520 "Is point inside a LaTeX macro or its arguments?"
16521 (save-match-data
16522 (org-in-regexp
16523 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16525 (defun org-try-cdlatex-tab ()
16526 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16527 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16528 - inside a LaTeX fragment, or
16529 - after the first word in a line, where an abbreviation expansion could
16530 insert a LaTeX environment."
16531 (when org-cdlatex-mode
16532 (cond
16533 ((save-excursion
16534 (skip-chars-backward "a-zA-Z0-9*")
16535 (skip-chars-backward " \t")
16536 (bolp))
16537 (cdlatex-tab) t)
16538 ((org-inside-LaTeX-fragment-p)
16539 (cdlatex-tab) t)
16540 (t nil))))
16542 (defun org-cdlatex-underscore-caret (&optional arg)
16543 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16544 Revert to the normal definition outside of these fragments."
16545 (interactive "P")
16546 (if (org-inside-LaTeX-fragment-p)
16547 (call-interactively 'cdlatex-sub-superscript)
16548 (let (org-cdlatex-mode)
16549 (call-interactively (key-binding (vector last-input-event))))))
16551 (defun org-cdlatex-math-modify (&optional arg)
16552 "Execute `cdlatex-math-modify' in LaTeX fragments.
16553 Revert to the normal definition outside of these fragments."
16554 (interactive "P")
16555 (if (org-inside-LaTeX-fragment-p)
16556 (call-interactively 'cdlatex-math-modify)
16557 (let (org-cdlatex-mode)
16558 (call-interactively (key-binding (vector last-input-event))))))
16560 (defvar org-latex-fragment-image-overlays nil
16561 "List of overlays carrying the images of latex fragments.")
16562 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16564 (defun org-remove-latex-fragment-image-overlays ()
16565 "Remove all overlays with LaTeX fragment images in current buffer."
16566 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16567 (setq org-latex-fragment-image-overlays nil))
16569 (defun org-preview-latex-fragment (&optional subtree)
16570 "Preview the LaTeX fragment at point, or all locally or globally.
16571 If the cursor is in a LaTeX fragment, create the image and overlay
16572 it over the source code. If there is no fragment at point, display
16573 all fragments in the current text, from one headline to the next. With
16574 prefix SUBTREE, display all fragments in the current subtree. With a
16575 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16576 the cursor is before the first headline,
16577 display all fragments in the buffer.
16578 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16579 (interactive "P")
16580 (org-remove-latex-fragment-image-overlays)
16581 (save-excursion
16582 (save-restriction
16583 (let (beg end at msg)
16584 (cond
16585 ((or (equal subtree '(16))
16586 (not (save-excursion
16587 (re-search-backward org-outline-regexp-bol nil t))))
16588 (setq beg (point-min) end (point-max)
16589 msg "Creating images for buffer...%s"))
16590 ((equal subtree '(4))
16591 (org-back-to-heading)
16592 (setq beg (point) end (org-end-of-subtree t)
16593 msg "Creating images for subtree...%s"))
16595 (if (setq at (org-inside-LaTeX-fragment-p))
16596 (goto-char (max (point-min) (- (cdr at) 2)))
16597 (org-back-to-heading))
16598 (setq beg (point) end (progn (outline-next-heading) (point))
16599 msg (if at "Creating image...%s"
16600 "Creating images for entry...%s"))))
16601 (message msg "")
16602 (narrow-to-region beg end)
16603 (goto-char beg)
16604 (org-format-latex
16605 (concat "ltxpng/" (file-name-sans-extension
16606 (file-name-nondirectory
16607 buffer-file-name)))
16608 default-directory 'overlays msg at 'forbuffer 'dvipng)
16609 (message msg "done. Use `C-c C-c' to remove images.")))))
16611 (defvar org-latex-regexps
16612 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16613 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16614 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16615 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16616 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16617 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16618 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16619 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16620 "Regular expressions for matching embedded LaTeX.")
16622 (defvar org-export-have-math nil) ;; dynamic scoping
16623 (defun org-format-latex (prefix &optional dir overlays msg at
16624 forbuffer processing-type)
16625 "Replace LaTeX fragments with links to an image, and produce images.
16626 Some of the options can be changed using the variable
16627 `org-format-latex-options'."
16628 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16629 (let* ((prefixnodir (file-name-nondirectory prefix))
16630 (absprefix (expand-file-name prefix dir))
16631 (todir (file-name-directory absprefix))
16632 (opt org-format-latex-options)
16633 (matchers (plist-get opt :matchers))
16634 (re-list org-latex-regexps)
16635 (org-format-latex-header-extra
16636 (plist-get (org-infile-export-plist) :latex-header-extra))
16637 (cnt 0) txt hash link beg end re e checkdir
16638 executables-checked string
16639 m n block-type block linkfile movefile ov)
16640 ;; Check the different regular expressions
16641 (while (setq e (pop re-list))
16642 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
16643 block (if block-type "\n\n" ""))
16644 (when (member m matchers)
16645 (goto-char (point-min))
16646 (while (re-search-forward re nil t)
16647 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16648 (not (get-text-property (match-beginning n)
16649 'org-protected))
16650 (or (not overlays)
16651 (not (eq (get-char-property (match-beginning n)
16652 'org-overlay-type)
16653 'org-latex-overlay))))
16654 (setq org-export-have-math t)
16655 (cond
16656 ((eq processing-type 'verbatim)
16657 ;; Leave the text verbatim, just protect it
16658 (add-text-properties (match-beginning n) (match-end n)
16659 '(org-protected t)))
16660 ((eq processing-type 'mathjax)
16661 ;; Prepare for MathJax processing
16662 (setq string (match-string n))
16663 (if (member m '("$" "$1"))
16664 (save-excursion
16665 (delete-region (match-beginning n) (match-end n))
16666 (goto-char (match-beginning n))
16667 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16668 "\\)")
16669 '(org-protected t))))
16670 (add-text-properties (match-beginning n) (match-end n)
16671 '(org-protected t))))
16672 ((eq processing-type 'dvipng)
16673 ;; Process to an image
16674 (setq txt (match-string n)
16675 beg (match-beginning n) end (match-end n)
16676 cnt (1+ cnt))
16677 (let (print-length print-level) ; make sure full list is printed
16678 (setq hash (sha1 (prin1-to-string
16679 (list org-format-latex-header
16680 org-format-latex-header-extra
16681 org-export-latex-default-packages-alist
16682 org-export-latex-packages-alist
16683 org-format-latex-options
16684 forbuffer txt)))
16685 linkfile (format "%s_%s.png" prefix hash)
16686 movefile (format "%s_%s.png" absprefix hash)))
16687 (setq link (concat block "[[file:" linkfile "]]" block))
16688 (if msg (message msg cnt))
16689 (goto-char beg)
16690 (unless checkdir ; make sure the directory exists
16691 (setq checkdir t)
16692 (or (file-directory-p todir) (make-directory todir t)))
16694 (unless executables-checked
16695 (org-check-external-command
16696 "latex" "needed to convert LaTeX fragments to images")
16697 (org-check-external-command
16698 "dvipng" "needed to convert LaTeX fragments to images")
16699 (setq executables-checked t))
16701 (unless (file-exists-p movefile)
16702 (org-create-formula-image
16703 txt movefile opt forbuffer))
16704 (if overlays
16705 (progn
16706 (mapc (lambda (o)
16707 (if (eq (overlay-get o 'org-overlay-type)
16708 'org-latex-overlay)
16709 (delete-overlay o)))
16710 (overlays-in beg end))
16711 (setq ov (make-overlay beg end))
16712 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16713 (if (featurep 'xemacs)
16714 (progn
16715 (overlay-put ov 'invisible t)
16716 (overlay-put
16717 ov 'end-glyph
16718 (make-glyph (vector 'png :file movefile))))
16719 (overlay-put
16720 ov 'display
16721 (list 'image :type 'png :file movefile :ascent 'center)))
16722 (push ov org-latex-fragment-image-overlays)
16723 (goto-char end))
16724 (delete-region beg end)
16725 (insert (org-add-props link
16726 (list 'org-latex-src
16727 (replace-regexp-in-string
16728 "\"" "" txt)
16729 'org-latex-src-embed-type
16730 (if block-type 'paragraph 'character))))))
16731 ((eq processing-type 'mathml)
16732 ;; Process to MathML
16733 (unless executables-checked
16734 (unless (save-match-data (org-format-latex-mathml-available-p))
16735 (error "LaTeX to MathML converter not configured"))
16736 (setq executables-checked t))
16737 (setq txt (match-string n)
16738 beg (match-beginning n) end (match-end n)
16739 cnt (1+ cnt))
16740 (if msg (message msg cnt))
16741 (goto-char beg)
16742 (delete-region beg end)
16743 (insert (org-format-latex-as-mathml
16744 txt block-type prefix dir)))
16746 (error "Unknown conversion type %s for latex fragments"
16747 processing-type)))))))))
16749 (defun org-create-math-formula (latex-frag &optional mathml-file)
16750 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
16751 Use `org-latex-to-mathml-convert-command'. If the conversion is
16752 sucessful, return the portion between \"<math...> </math>\"
16753 elements otherwise return nil. When MATHML-FILE is specified,
16754 write the results in to that file. When invoked as an
16755 interactive command, prompt for LATEX-FRAG, with initial value
16756 set to the current active region and echo the results for user
16757 inspection."
16758 (interactive (list (let ((frag (when (region-active-p)
16759 (buffer-substring-no-properties
16760 (region-beginning) (region-end)))))
16761 (read-string "LaTeX Fragment: " frag nil frag))))
16762 (unless latex-frag (error "Invalid latex-frag"))
16763 (let* ((tmp-in-file (file-relative-name
16764 (make-temp-name (expand-file-name "ltxmathml-in"))))
16765 (ignore (write-region latex-frag nil tmp-in-file))
16766 (tmp-out-file (file-relative-name
16767 (make-temp-name (expand-file-name "ltxmathml-out"))))
16768 (cmd (format-spec
16769 org-latex-to-mathml-convert-command
16770 `((?j . ,(shell-quote-argument
16771 (expand-file-name org-latex-to-mathml-jar-file)))
16772 (?I . ,(shell-quote-argument tmp-in-file))
16773 (?o . ,(shell-quote-argument tmp-out-file)))))
16774 mathml shell-command-output)
16775 (when (org-called-interactively-p 'any)
16776 (unless (org-format-latex-mathml-available-p)
16777 (error "LaTeX to MathML converter not configured")))
16778 (message "Running %s" cmd)
16779 (setq shell-command-output (shell-command-to-string cmd))
16780 (setq mathml
16781 (when (file-readable-p tmp-out-file)
16782 (with-current-buffer (find-file-noselect tmp-out-file t)
16783 (goto-char (point-min))
16784 (when (re-search-forward
16785 (concat
16786 (regexp-quote
16787 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
16788 "\\(.\\|\n\\)*"
16789 (regexp-quote "</math>")) nil t)
16790 (prog1 (match-string 0) (kill-buffer))))))
16791 (cond
16792 (mathml
16793 (setq mathml
16794 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
16795 (when mathml-file
16796 (write-region mathml nil mathml-file))
16797 (when (org-called-interactively-p 'any)
16798 (message mathml)))
16799 ((message "LaTeX to MathML conversion failed")
16800 (message shell-command-output)))
16801 (delete-file tmp-in-file)
16802 (when (file-exists-p tmp-out-file)
16803 (delete-file tmp-out-file))
16804 mathml))
16806 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
16807 prefix &optional dir)
16808 "Use `org-create-math-formula' but check local cache first."
16809 (let* ((absprefix (expand-file-name prefix dir))
16810 (print-length nil) (print-level nil)
16811 (formula-id (concat
16812 "formula-"
16813 (sha1
16814 (prin1-to-string
16815 (list latex-frag
16816 org-latex-to-mathml-convert-command)))))
16817 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
16818 (formula-cache-dir (file-name-directory formula-cache)))
16820 (unless (file-directory-p formula-cache-dir)
16821 (make-directory formula-cache-dir t))
16823 (unless (file-exists-p formula-cache)
16824 (org-create-math-formula latex-frag formula-cache))
16826 (if (file-exists-p formula-cache)
16827 ;; Successful conversion. Return the link to MathML file.
16828 (org-add-props
16829 (format "[[file:%s]]" (file-relative-name formula-cache dir))
16830 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
16831 'org-latex-src-embed-type (if latex-frag-type
16832 'paragraph 'character)))
16833 ;; Failed conversion. Return the LaTeX fragment verbatim
16834 (add-text-properties
16835 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
16836 latex-frag)))
16838 ;; This function borrows from Ganesh Swami's latex2png.el
16839 (defun org-create-formula-image (string tofile options buffer)
16840 "This calls dvipng."
16841 (require 'org-latex)
16842 (let* ((tmpdir (if (featurep 'xemacs)
16843 (temp-directory)
16844 temporary-file-directory))
16845 (texfilebase (make-temp-name
16846 (expand-file-name "orgtex" tmpdir)))
16847 (texfile (concat texfilebase ".tex"))
16848 (dvifile (concat texfilebase ".dvi"))
16849 (pngfile (concat texfilebase ".png"))
16850 (fnh (if (featurep 'xemacs)
16851 (font-height (get-face-font 'default))
16852 (face-attribute 'default :height nil)))
16853 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
16854 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
16855 (fg (or (plist-get options (if buffer :foreground :html-foreground))
16856 "Black"))
16857 (bg (or (plist-get options (if buffer :background :html-background))
16858 "Transparent")))
16859 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
16860 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
16861 (with-temp-file texfile
16862 (insert (org-splice-latex-header
16863 org-format-latex-header
16864 org-export-latex-default-packages-alist
16865 org-export-latex-packages-alist t
16866 org-format-latex-header-extra))
16867 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
16868 (require 'org-latex)
16869 (org-export-latex-fix-inputenc))
16870 (let ((dir default-directory))
16871 (condition-case nil
16872 (progn
16873 (cd tmpdir)
16874 (call-process "latex" nil nil nil texfile))
16875 (error nil))
16876 (cd dir))
16877 (if (not (file-exists-p dvifile))
16878 (progn (message "Failed to create dvi file from %s" texfile) nil)
16879 (condition-case nil
16880 (call-process "dvipng" nil nil nil
16881 "-fg" fg "-bg" bg
16882 "-D" dpi
16883 ;;"-x" scale "-y" scale
16884 "-T" "tight"
16885 "-o" pngfile
16886 dvifile)
16887 (error nil))
16888 (if (not (file-exists-p pngfile))
16889 (if org-format-latex-signal-error
16890 (error "Failed to create png file from %s" texfile)
16891 (message "Failed to create png file from %s" texfile)
16892 nil)
16893 ;; Use the requested file name and clean up
16894 (copy-file pngfile tofile 'replace)
16895 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16896 (delete-file (concat texfilebase e)))
16897 pngfile))))
16899 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
16900 "Fill a LaTeX header template TPL.
16901 In the template, the following place holders will be recognized:
16903 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
16904 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
16905 [PACKAGES] \\usepackage statements for PKG
16906 [NO-PACKAGES] do not include PKG
16907 [EXTRA] the string EXTRA
16908 [NO-EXTRA] do not include EXTRA
16910 For backward compatibility, if both the positive and the negative place
16911 holder is missing, the positive one (without the \"NO-\") will be
16912 assumed to be present at the end of the template.
16913 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
16914 EXTRA is a string.
16915 SNIPPETS-P indicates if this is run to create snippet images for HTML."
16916 (let (rpl (end ""))
16917 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
16918 (setq rpl (if (or (match-end 1) (not def-pkg))
16919 "" (org-latex-packages-to-string def-pkg snippets-p t))
16920 tpl (replace-match rpl t t tpl))
16921 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
16923 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
16924 (setq rpl (if (or (match-end 1) (not pkg))
16925 "" (org-latex-packages-to-string pkg snippets-p t))
16926 tpl (replace-match rpl t t tpl))
16927 (if pkg (setq end
16928 (concat end "\n"
16929 (org-latex-packages-to-string pkg snippets-p)))))
16931 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
16932 (setq rpl (if (or (match-end 1) (not extra))
16933 "" (concat extra "\n"))
16934 tpl (replace-match rpl t t tpl))
16935 (if (and extra (string-match "\\S-" extra))
16936 (setq end (concat end "\n" extra))))
16938 (if (string-match "\\S-" end)
16939 (concat tpl "\n" end)
16940 tpl)))
16942 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
16943 "Turn an alist of packages into a string with the \\usepackage macros."
16944 (setq pkg (mapconcat (lambda(p)
16945 (cond
16946 ((stringp p) p)
16947 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
16948 (format "%% Package %s omitted" (cadr p)))
16949 ((equal "" (car p))
16950 (format "\\usepackage{%s}" (cadr p)))
16952 (format "\\usepackage[%s]{%s}"
16953 (car p) (cadr p)))))
16955 "\n"))
16956 (if newline (concat pkg "\n") pkg))
16958 (defun org-dvipng-color (attr)
16959 "Return an rgb color specification for dvipng."
16960 (apply 'format "rgb %s %s %s"
16961 (mapcar 'org-normalize-color
16962 (color-values (face-attribute 'default attr nil)))))
16964 (defun org-normalize-color (value)
16965 "Return string to be used as color value for an RGB component."
16966 (format "%g" (/ value 65535.0)))
16968 ;; Image display
16971 (defvar org-inline-image-overlays nil)
16972 (make-variable-buffer-local 'org-inline-image-overlays)
16974 (defun org-toggle-inline-images (&optional include-linked)
16975 "Toggle the display of inline images.
16976 INCLUDE-LINKED is passed to `org-display-inline-images'."
16977 (interactive "P")
16978 (if org-inline-image-overlays
16979 (progn
16980 (org-remove-inline-images)
16981 (message "Inline image display turned off"))
16982 (org-display-inline-images include-linked)
16983 (if org-inline-image-overlays
16984 (message "%d images displayed inline"
16985 (length org-inline-image-overlays))
16986 (message "No images to display inline"))))
16988 (defun org-display-inline-images (&optional include-linked refresh beg end)
16989 "Display inline images.
16990 Normally only links without a description part are inlined, because this
16991 is how it will work for export. When INCLUDE-LINKED is set, also links
16992 with a description part will be inlined. This can be nice for a quick
16993 look at those images, but it does not reflect what exported files will look
16994 like.
16995 When REFRESH is set, refresh existing images between BEG and END.
16996 This will create new image displays only if necessary.
16997 BEG and END default to the buffer boundaries."
16998 (interactive "P")
16999 (unless refresh
17000 (org-remove-inline-images)
17001 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17002 (save-excursion
17003 (save-restriction
17004 (widen)
17005 (setq beg (or beg (point-min)) end (or end (point-max)))
17006 (goto-char (point-min))
17007 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17008 (substring (org-image-file-name-regexp) 0 -2)
17009 "\\)\\]" (if include-linked "" "\\]")))
17010 old file ov img)
17011 (while (re-search-forward re end t)
17012 (setq old (get-char-property-and-overlay (match-beginning 1)
17013 'org-image-overlay))
17014 (setq file (expand-file-name
17015 (concat (or (match-string 3) "") (match-string 4))))
17016 (when (file-exists-p file)
17017 (if (and (car-safe old) refresh)
17018 (image-refresh (overlay-get (cdr old) 'display))
17019 (setq img (save-match-data (create-image file)))
17020 (when img
17021 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17022 (overlay-put ov 'display img)
17023 (overlay-put ov 'face 'default)
17024 (overlay-put ov 'org-image-overlay t)
17025 (overlay-put ov 'modification-hooks
17026 (list 'org-display-inline-modification-hook))
17027 (push ov org-inline-image-overlays)))))))))
17029 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17030 "Remove inline-display overlay if a corresponding region is modified."
17031 (let ((inhibit-modification-hooks t))
17032 (when (and ov after)
17033 (delete ov org-inline-image-overlays)
17034 (delete-overlay ov))))
17036 (defun org-remove-inline-images ()
17037 "Remove inline display of images."
17038 (interactive)
17039 (mapc 'delete-overlay org-inline-image-overlays)
17040 (setq org-inline-image-overlays nil))
17042 ;;;; Key bindings
17044 ;; Remap outline keys
17045 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17046 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17048 ;; Make `C-c C-x' a prefix key
17049 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17051 ;; TAB key with modifiers
17052 (org-defkey org-mode-map "\C-i" 'org-cycle)
17053 (org-defkey org-mode-map [(tab)] 'org-cycle)
17054 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17055 (org-defkey org-mode-map [(meta tab)] 'pcomplete)
17056 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17057 (org-defkey org-mode-map "\M-\C-i" 'pcomplete)
17058 ;; The following line is necessary under Suse GNU/Linux
17059 (unless (featurep 'xemacs)
17060 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17061 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17062 (define-key org-mode-map [backtab] 'org-shifttab)
17064 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17065 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17066 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17068 ;; Cursor keys with modifiers
17069 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17070 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17071 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17072 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17074 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17075 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17076 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17077 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17079 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17080 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17081 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17082 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17084 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17085 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17086 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17087 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17089 ;; Babel keys
17090 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17091 (mapc (lambda (pair)
17092 (define-key org-babel-map (car pair) (cdr pair)))
17093 org-babel-key-bindings)
17095 ;;; Extra keys for tty access.
17096 ;; We only set them when really needed because otherwise the
17097 ;; menus don't show the simple keys
17099 (when (or org-use-extra-keys
17100 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17101 (not window-system))
17102 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17103 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17104 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17105 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17106 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17107 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17108 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17109 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17110 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17111 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17112 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17113 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17114 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17115 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17116 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17117 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17118 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17119 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17120 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17121 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17122 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17123 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17124 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17125 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17126 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17127 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17128 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17129 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17131 ;; All the other keys
17133 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17134 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17135 (if (boundp 'narrow-map)
17136 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17137 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17138 (if (boundp 'narrow-map)
17139 (org-defkey narrow-map "b" 'org-narrow-to-block)
17140 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17141 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
17142 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
17143 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
17144 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
17145 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
17146 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
17147 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
17148 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17149 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
17150 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
17151 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
17152 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
17153 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
17154 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
17155 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
17156 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
17157 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
17158 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
17159 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
17160 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
17161 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
17162 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
17163 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
17164 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
17165 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
17166 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
17167 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
17168 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
17169 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
17170 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
17171 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17172 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17173 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17174 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17175 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
17176 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
17177 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17178 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17179 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
17180 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
17181 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
17182 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17183 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
17184 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
17185 (org-defkey org-mode-map "\C-c^" 'org-sort)
17186 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17187 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
17188 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
17189 (org-defkey org-mode-map "\C-m" 'org-return)
17190 (org-defkey org-mode-map "\C-j" 'org-return-indent)
17191 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
17192 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
17193 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
17194 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
17195 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
17196 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
17197 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17198 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17199 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
17200 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
17201 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
17202 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
17203 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
17204 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17205 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
17206 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
17207 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
17208 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
17209 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
17210 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
17211 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
17213 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
17214 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17215 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17216 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17218 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17219 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17220 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17221 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17222 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17223 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17224 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17225 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17226 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17227 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17228 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17229 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17230 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17231 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17232 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17233 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17234 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17235 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17237 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17238 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17239 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17240 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17241 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17243 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17245 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17247 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17248 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17250 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17253 (when (featurep 'xemacs)
17254 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17257 (defconst org-speed-commands-default
17259 ("Outline Navigation")
17260 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17261 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17262 ("f" . (org-speed-move-safe 'org-forward-same-level))
17263 ("b" . (org-speed-move-safe 'org-backward-same-level))
17264 ("u" . (org-speed-move-safe 'outline-up-heading))
17265 ("j" . org-goto)
17266 ("g" . (org-refile t))
17267 ("Outline Visibility")
17268 ("c" . org-cycle)
17269 ("C" . org-shifttab)
17270 (" " . org-display-outline-path)
17271 ("Outline Structure Editing")
17272 ("U" . org-shiftmetaup)
17273 ("D" . org-shiftmetadown)
17274 ("r" . org-metaright)
17275 ("l" . org-metaleft)
17276 ("R" . org-shiftmetaright)
17277 ("L" . org-shiftmetaleft)
17278 ("i" . (progn (forward-char 1) (call-interactively
17279 'org-insert-heading-respect-content)))
17280 ("^" . org-sort)
17281 ("w" . org-refile)
17282 ("a" . org-archive-subtree-default-with-confirmation)
17283 ("." . org-mark-subtree)
17284 ("Clock Commands")
17285 ("I" . org-clock-in)
17286 ("O" . org-clock-out)
17287 ("Meta Data Editing")
17288 ("t" . org-todo)
17289 ("0" . (org-priority ?\ ))
17290 ("1" . (org-priority ?A))
17291 ("2" . (org-priority ?B))
17292 ("3" . (org-priority ?C))
17293 (";" . org-set-tags-command)
17294 ("e" . org-set-effort)
17295 ("Agenda Views etc")
17296 ("v" . org-agenda)
17297 ("/" . org-sparse-tree)
17298 ("Misc")
17299 ("o" . org-open-at-point)
17300 ("?" . org-speed-command-help)
17301 ("<" . (org-agenda-set-restriction-lock 'subtree))
17302 (">" . (org-agenda-remove-restriction-lock))
17304 "The default speed commands.")
17306 (defun org-print-speed-command (e)
17307 (if (> (length (car e)) 1)
17308 (progn
17309 (princ "\n")
17310 (princ (car e))
17311 (princ "\n")
17312 (princ (make-string (length (car e)) ?-))
17313 (princ "\n"))
17314 (princ (car e))
17315 (princ " ")
17316 (if (symbolp (cdr e))
17317 (princ (symbol-name (cdr e)))
17318 (prin1 (cdr e)))
17319 (princ "\n")))
17321 (defun org-speed-command-help ()
17322 "Show the available speed commands."
17323 (interactive)
17324 (if (not org-use-speed-commands)
17325 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17326 (with-output-to-temp-buffer "*Help*"
17327 (princ "User-defined Speed commands\n===========================\n")
17328 (mapc 'org-print-speed-command org-speed-commands-user)
17329 (princ "\n")
17330 (princ "Built-in Speed commands\n=======================\n")
17331 (mapc 'org-print-speed-command org-speed-commands-default))
17332 (with-current-buffer "*Help*"
17333 (setq truncate-lines t))))
17335 (defun org-speed-move-safe (cmd)
17336 "Execute CMD, but make sure that the cursor always ends up in a headline.
17337 If not, return to the original position and throw an error."
17338 (interactive)
17339 (let ((pos (point)))
17340 (call-interactively cmd)
17341 (unless (and (bolp) (org-on-heading-p))
17342 (goto-char pos)
17343 (error "Boundary reached while executing %s" cmd))))
17345 (defvar org-self-insert-command-undo-counter 0)
17347 (defvar org-table-auto-blank-field) ; defined in org-table.el
17348 (defvar org-speed-command nil)
17350 (defun org-speed-command-default-hook (keys)
17351 "Hook for activating single-letter speed commands.
17352 `org-speed-commands-default' specifies a minimal command set.
17353 Use `org-speed-commands-user' for further customization."
17354 (when (or (and (bolp) (looking-at org-outline-regexp))
17355 (and (functionp org-use-speed-commands)
17356 (funcall org-use-speed-commands)))
17357 (cdr (assoc keys (append org-speed-commands-user
17358 org-speed-commands-default)))))
17360 (defun org-babel-speed-command-hook (keys)
17361 "Hook for activating single-letter code block commands."
17362 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17363 (cdr (assoc keys org-babel-key-bindings))))
17365 (defcustom org-speed-command-hook
17366 '(org-speed-command-default-hook org-babel-speed-command-hook)
17367 "Hook for activating speed commands at strategic locations.
17368 Hook functions are called in sequence until a valid handler is
17369 found.
17371 Each hook takes a single argument, a user-pressed command key
17372 which is also a `self-insert-command' from the global map.
17374 Within the hook, examine the cursor position and the command key
17375 and return nil or a valid handler as appropriate. Handler could
17376 be one of an interactive command, a function, or a form.
17378 Set `org-use-speed-commands' to non-nil value to enable this
17379 hook. The default setting is `org-speed-command-default-hook'."
17380 :group 'org-structure
17381 :type 'hook)
17383 (defun org-self-insert-command (N)
17384 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17385 If the cursor is in a table looking at whitespace, the whitespace is
17386 overwritten, and the table is not marked as requiring realignment."
17387 (interactive "p")
17388 (cond
17389 ((and org-use-speed-commands
17390 (setq org-speed-command
17391 (run-hook-with-args-until-success
17392 'org-speed-command-hook (this-command-keys))))
17393 (cond
17394 ((commandp org-speed-command)
17395 (setq this-command org-speed-command)
17396 (call-interactively org-speed-command))
17397 ((functionp org-speed-command)
17398 (funcall org-speed-command))
17399 ((and org-speed-command (listp org-speed-command))
17400 (eval org-speed-command))
17401 (t (let (org-use-speed-commands)
17402 (call-interactively 'org-self-insert-command)))))
17403 ((and
17404 (org-table-p)
17405 (progn
17406 ;; check if we blank the field, and if that triggers align
17407 (and (featurep 'org-table) org-table-auto-blank-field
17408 (member last-command
17409 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17410 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17411 ;; got extra space, this field does not determine column width
17412 (let (org-table-may-need-update) (org-table-blank-field))
17413 ;; no extra space, this field may determine column width
17414 (org-table-blank-field)))
17416 (eq N 1)
17417 (looking-at "[^|\n]* |"))
17418 (let (org-table-may-need-update)
17419 (goto-char (1- (match-end 0)))
17420 (delete-char -1)
17421 (goto-char (match-beginning 0))
17422 (self-insert-command N)))
17424 (setq org-table-may-need-update t)
17425 (self-insert-command N)
17426 (org-fix-tags-on-the-fly)
17427 (if org-self-insert-cluster-for-undo
17428 (if (not (eq last-command 'org-self-insert-command))
17429 (setq org-self-insert-command-undo-counter 1)
17430 (if (>= org-self-insert-command-undo-counter 20)
17431 (setq org-self-insert-command-undo-counter 1)
17432 (and (> org-self-insert-command-undo-counter 0)
17433 buffer-undo-list (listp buffer-undo-list)
17434 (not (cadr buffer-undo-list)) ; remove nil entry
17435 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17436 (setq org-self-insert-command-undo-counter
17437 (1+ org-self-insert-command-undo-counter))))))))
17439 (defun org-fix-tags-on-the-fly ()
17440 (when (and (equal (char-after (point-at-bol)) ?*)
17441 (org-on-heading-p))
17442 (org-align-tags-here org-tags-column)))
17444 (defun org-delete-backward-char (N)
17445 "Like `delete-backward-char', insert whitespace at field end in tables.
17446 When deleting backwards, in tables this function will insert whitespace in
17447 front of the next \"|\" separator, to keep the table aligned. The table will
17448 still be marked for re-alignment if the field did fill the entire column,
17449 because, in this case the deletion might narrow the column."
17450 (interactive "p")
17451 (if (and (org-table-p)
17452 (eq N 1)
17453 (string-match "|" (buffer-substring (point-at-bol) (point)))
17454 (looking-at ".*?|"))
17455 (let ((pos (point))
17456 (noalign (looking-at "[^|\n\r]* |"))
17457 (c org-table-may-need-update))
17458 (backward-delete-char N)
17459 (if (not overwrite-mode)
17460 (progn
17461 (skip-chars-forward "^|")
17462 (insert " ")
17463 (goto-char (1- pos))))
17464 ;; noalign: if there were two spaces at the end, this field
17465 ;; does not determine the width of the column.
17466 (if noalign (setq org-table-may-need-update c)))
17467 (backward-delete-char N)
17468 (org-fix-tags-on-the-fly)))
17470 (defun org-delete-char (N)
17471 "Like `delete-char', but insert whitespace at field end in tables.
17472 When deleting characters, in tables this function will insert whitespace in
17473 front of the next \"|\" separator, to keep the table aligned. The table will
17474 still be marked for re-alignment if the field did fill the entire column,
17475 because, in this case the deletion might narrow the column."
17476 (interactive "p")
17477 (if (and (org-table-p)
17478 (not (bolp))
17479 (not (= (char-after) ?|))
17480 (eq N 1))
17481 (if (looking-at ".*?|")
17482 (let ((pos (point))
17483 (noalign (looking-at "[^|\n\r]* |"))
17484 (c org-table-may-need-update))
17485 (replace-match (concat
17486 (substring (match-string 0) 1 -1)
17487 " |"))
17488 (goto-char pos)
17489 ;; noalign: if there were two spaces at the end, this field
17490 ;; does not determine the width of the column.
17491 (if noalign (setq org-table-may-need-update c)))
17492 (delete-char N))
17493 (delete-char N)
17494 (org-fix-tags-on-the-fly)))
17496 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17497 (put 'org-self-insert-command 'delete-selection t)
17498 (put 'orgtbl-self-insert-command 'delete-selection t)
17499 (put 'org-delete-char 'delete-selection 'supersede)
17500 (put 'org-delete-backward-char 'delete-selection 'supersede)
17501 (put 'org-yank 'delete-selection 'yank)
17503 ;; Make `flyspell-mode' delay after some commands
17504 (put 'org-self-insert-command 'flyspell-delayed t)
17505 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17506 (put 'org-delete-char 'flyspell-delayed t)
17507 (put 'org-delete-backward-char 'flyspell-delayed t)
17509 ;; Make pabbrev-mode expand after org-mode commands
17510 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17511 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17513 ;; How to do this: Measure non-white length of current string
17514 ;; If equal to column width, we should realign.
17516 (defun org-remap (map &rest commands)
17517 "In MAP, remap the functions given in COMMANDS.
17518 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17519 (let (new old)
17520 (while commands
17521 (setq old (pop commands) new (pop commands))
17522 (if (fboundp 'command-remapping)
17523 (org-defkey map (vector 'remap old) new)
17524 (substitute-key-definition old new map global-map)))))
17526 (when (eq org-enable-table-editor 'optimized)
17527 ;; If the user wants maximum table support, we need to hijack
17528 ;; some standard editing functions
17529 (org-remap org-mode-map
17530 'self-insert-command 'org-self-insert-command
17531 'delete-char 'org-delete-char
17532 'delete-backward-char 'org-delete-backward-char)
17533 (org-defkey org-mode-map "|" 'org-force-self-insert))
17535 (defvar org-ctrl-c-ctrl-c-hook nil
17536 "Hook for functions attaching themselves to `C-c C-c'.
17538 This can be used to add additional functionality to the C-c C-c
17539 key which executes context-dependent commands. This hook is run
17540 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
17541 run after the last test.
17543 Each function will be called with no arguments. The function
17544 must check if the context is appropriate for it to act. If yes,
17545 it should do its thing and then return a non-nil value. If the
17546 context is wrong, just do nothing and return nil.")
17548 (defvar org-ctrl-c-ctrl-c-final-hook nil
17549 "Hook for functions attaching themselves to `C-c C-c'.
17551 This can be used to add additional functionality to the C-c C-c
17552 key which executes context-dependent commands. This hook is run
17553 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
17554 before the first test.
17556 Each function will be called with no arguments. The function
17557 must check if the context is appropriate for it to act. If yes,
17558 it should do its thing and then return a non-nil value. If the
17559 context is wrong, just do nothing and return nil.")
17561 (defvar org-tab-first-hook nil
17562 "Hook for functions to attach themselves to TAB.
17563 See `org-ctrl-c-ctrl-c-hook' for more information.
17564 This hook runs as the first action when TAB is pressed, even before
17565 `org-cycle' messes around with the `outline-regexp' to cater for
17566 inline tasks and plain list item folding.
17567 If any function in this hook returns t, any other actions that
17568 would have been caused by TAB (such as table field motion or visibility
17569 cycling) will not occur.")
17571 (defvar org-tab-after-check-for-table-hook nil
17572 "Hook for functions to attach themselves to TAB.
17573 See `org-ctrl-c-ctrl-c-hook' for more information.
17574 This hook runs after it has been established that the cursor is not in a
17575 table, but before checking if the cursor is in a headline or if global cycling
17576 should be done.
17577 If any function in this hook returns t, not other actions like visibility
17578 cycling will be done.")
17580 (defvar org-tab-after-check-for-cycling-hook nil
17581 "Hook for functions to attach themselves to TAB.
17582 See `org-ctrl-c-ctrl-c-hook' for more information.
17583 This hook runs after it has been established that not table field motion and
17584 not visibility should be done because of current context. This is probably
17585 the place where a package like yasnippets can hook in.")
17587 (defvar org-tab-before-tab-emulation-hook nil
17588 "Hook for functions to attach themselves to TAB.
17589 See `org-ctrl-c-ctrl-c-hook' for more information.
17590 This hook runs after every other options for TAB have been exhausted, but
17591 before indentation and \t insertion takes place.")
17593 (defvar org-metaleft-hook nil
17594 "Hook for functions attaching themselves to `M-left'.
17595 See `org-ctrl-c-ctrl-c-hook' for more information.")
17596 (defvar org-metaright-hook nil
17597 "Hook for functions attaching themselves to `M-right'.
17598 See `org-ctrl-c-ctrl-c-hook' for more information.")
17599 (defvar org-metaup-hook nil
17600 "Hook for functions attaching themselves to `M-up'.
17601 See `org-ctrl-c-ctrl-c-hook' for more information.")
17602 (defvar org-metadown-hook nil
17603 "Hook for functions attaching themselves to `M-down'.
17604 See `org-ctrl-c-ctrl-c-hook' for more information.")
17605 (defvar org-shiftmetaleft-hook nil
17606 "Hook for functions attaching themselves to `M-S-left'.
17607 See `org-ctrl-c-ctrl-c-hook' for more information.")
17608 (defvar org-shiftmetaright-hook nil
17609 "Hook for functions attaching themselves to `M-S-right'.
17610 See `org-ctrl-c-ctrl-c-hook' for more information.")
17611 (defvar org-shiftmetaup-hook nil
17612 "Hook for functions attaching themselves to `M-S-up'.
17613 See `org-ctrl-c-ctrl-c-hook' for more information.")
17614 (defvar org-shiftmetadown-hook nil
17615 "Hook for functions attaching themselves to `M-S-down'.
17616 See `org-ctrl-c-ctrl-c-hook' for more information.")
17617 (defvar org-metareturn-hook nil
17618 "Hook for functions attaching themselves to `M-RET'.
17619 See `org-ctrl-c-ctrl-c-hook' for more information.")
17620 (defvar org-shiftup-hook nil
17621 "Hook for functions attaching themselves to `S-up'.
17622 See `org-ctrl-c-ctrl-c-hook' for more information.")
17623 (defvar org-shiftup-final-hook nil
17624 "Hook for functions attaching themselves to `S-up'.
17625 This one runs after all other options except shift-select have been excluded.
17626 See `org-ctrl-c-ctrl-c-hook' for more information.")
17627 (defvar org-shiftdown-hook nil
17628 "Hook for functions attaching themselves to `S-down'.
17629 See `org-ctrl-c-ctrl-c-hook' for more information.")
17630 (defvar org-shiftdown-final-hook nil
17631 "Hook for functions attaching themselves to `S-down'.
17632 This one runs after all other options except shift-select have been excluded.
17633 See `org-ctrl-c-ctrl-c-hook' for more information.")
17634 (defvar org-shiftleft-hook nil
17635 "Hook for functions attaching themselves to `S-left'.
17636 See `org-ctrl-c-ctrl-c-hook' for more information.")
17637 (defvar org-shiftleft-final-hook nil
17638 "Hook for functions attaching themselves to `S-left'.
17639 This one runs after all other options except shift-select have been excluded.
17640 See `org-ctrl-c-ctrl-c-hook' for more information.")
17641 (defvar org-shiftright-hook nil
17642 "Hook for functions attaching themselves to `S-right'.
17643 See `org-ctrl-c-ctrl-c-hook' for more information.")
17644 (defvar org-shiftright-final-hook nil
17645 "Hook for functions attaching themselves to `S-right'.
17646 This one runs after all other options except shift-select have been excluded.
17647 See `org-ctrl-c-ctrl-c-hook' for more information.")
17649 (defun org-modifier-cursor-error ()
17650 "Throw an error, a modified cursor command was applied in wrong context."
17651 (error "This command is active in special context like tables, headlines or items"))
17653 (defun org-shiftselect-error ()
17654 "Throw an error because Shift-Cursor command was applied in wrong context."
17655 (if (and (boundp 'shift-select-mode) shift-select-mode)
17656 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
17657 (error "This command works only in special context like headlines or timestamps")))
17659 (defun org-call-for-shift-select (cmd)
17660 (let ((this-command-keys-shift-translated t))
17661 (call-interactively cmd)))
17663 (defun org-shifttab (&optional arg)
17664 "Global visibility cycling or move to previous table field.
17665 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17666 on context.
17667 See the individual commands for more information."
17668 (interactive "P")
17669 (cond
17670 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17671 ((integerp arg)
17672 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
17673 (message "Content view to level: %d" arg)
17674 (org-content (prefix-numeric-value arg2))
17675 (setq org-cycle-global-status 'overview)))
17676 (t (call-interactively 'org-global-cycle))))
17678 (defun org-shiftmetaleft ()
17679 "Promote subtree or delete table column.
17680 Calls `org-promote-subtree', `org-outdent-item',
17681 or `org-table-delete-column', depending on context.
17682 See the individual commands for more information."
17683 (interactive)
17684 (cond
17685 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
17686 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17687 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
17688 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
17689 (t (org-modifier-cursor-error))))
17691 (defun org-shiftmetaright ()
17692 "Demote subtree or insert table column.
17693 Calls `org-demote-subtree', `org-indent-item',
17694 or `org-table-insert-column', depending on context.
17695 See the individual commands for more information."
17696 (interactive)
17697 (cond
17698 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
17699 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17700 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
17701 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
17702 (t (org-modifier-cursor-error))))
17704 (defun org-shiftmetaup (&optional arg)
17705 "Move subtree up or kill table row.
17706 Calls `org-move-subtree-up' or `org-table-kill-row' or
17707 `org-move-item-up' depending on context. See the individual commands
17708 for more information."
17709 (interactive "P")
17710 (cond
17711 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
17712 ((org-at-table-p) (call-interactively 'org-table-kill-row))
17713 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17714 ((org-at-item-p) (call-interactively 'org-move-item-up))
17715 (t (org-modifier-cursor-error))))
17717 (defun org-shiftmetadown (&optional arg)
17718 "Move subtree down or insert table row.
17719 Calls `org-move-subtree-down' or `org-table-insert-row' or
17720 `org-move-item-down', depending on context. See the individual
17721 commands for more information."
17722 (interactive "P")
17723 (cond
17724 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
17725 ((org-at-table-p) (call-interactively 'org-table-insert-row))
17726 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17727 ((org-at-item-p) (call-interactively 'org-move-item-down))
17728 (t (org-modifier-cursor-error))))
17730 (defsubst org-hidden-tree-error ()
17731 (error
17732 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
17734 (defun org-metaleft (&optional arg)
17735 "Promote heading or move table column to left.
17736 Calls `org-do-promote' or `org-table-move-column', depending on context.
17737 With no specific context, calls the Emacs default `backward-word'.
17738 See the individual commands for more information."
17739 (interactive "P")
17740 (cond
17741 ((run-hook-with-args-until-success 'org-metaleft-hook))
17742 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
17743 ((org-with-limited-levels
17744 (or (org-on-heading-p)
17745 (and (org-region-active-p)
17746 (save-excursion
17747 (goto-char (region-beginning))
17748 (org-on-heading-p)))))
17749 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17750 (call-interactively 'org-do-promote))
17751 ;; At an inline task.
17752 ((org-on-heading-p)
17753 (call-interactively 'org-inlinetask-promote))
17754 ((or (org-at-item-p)
17755 (and (org-region-active-p)
17756 (save-excursion
17757 (goto-char (region-beginning))
17758 (org-at-item-p))))
17759 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17760 (call-interactively 'org-outdent-item))
17761 (t (call-interactively 'backward-word))))
17763 (defun org-metaright (&optional arg)
17764 "Demote subtree or move table column to right.
17765 Calls `org-do-demote' or `org-table-move-column', depending on context.
17766 With no specific context, calls the Emacs default `forward-word'.
17767 See the individual commands for more information."
17768 (interactive "P")
17769 (cond
17770 ((run-hook-with-args-until-success 'org-metaright-hook))
17771 ((org-at-table-p) (call-interactively 'org-table-move-column))
17772 ((org-with-limited-levels
17773 (or (org-on-heading-p)
17774 (and (org-region-active-p)
17775 (save-excursion
17776 (goto-char (region-beginning))
17777 (org-on-heading-p)))))
17778 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17779 (call-interactively 'org-do-demote))
17780 ;; At an inline task.
17781 ((org-on-heading-p)
17782 (call-interactively 'org-inlinetask-demote))
17783 ((or (org-at-item-p)
17784 (and (org-region-active-p)
17785 (save-excursion
17786 (goto-char (region-beginning))
17787 (org-at-item-p))))
17788 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17789 (call-interactively 'org-indent-item))
17790 (t (call-interactively 'forward-word))))
17792 (defun org-check-for-hidden (what)
17793 "Check if there are hidden headlines/items in the current visual line.
17794 WHAT can be either `headlines' or `items'. If the current line is
17795 an outline or item heading and it has a folded subtree below it,
17796 this function returns t, nil otherwise."
17797 (let ((re (cond
17798 ((eq what 'headlines) org-outline-regexp-bol)
17799 ((eq what 'items) (org-item-beginning-re))
17800 (t (error "This should not happen"))))
17801 beg end)
17802 (save-excursion
17803 (catch 'exit
17804 (unless (org-region-active-p)
17805 (setq beg (point-at-bol))
17806 (beginning-of-line 2)
17807 (while (and (not (eobp)) ;; this is like `next-line'
17808 (get-char-property (1- (point)) 'invisible))
17809 (beginning-of-line 2))
17810 (setq end (point))
17811 (goto-char beg)
17812 (goto-char (point-at-eol))
17813 (setq end (max end (point)))
17814 (while (re-search-forward re end t)
17815 (if (get-char-property (match-beginning 0) 'invisible)
17816 (throw 'exit t))))
17817 nil))))
17819 (defun org-metaup (&optional arg)
17820 "Move subtree up or move table row up.
17821 Calls `org-move-subtree-up' or `org-table-move-row' or
17822 `org-move-item-up', depending on context. See the individual commands
17823 for more information."
17824 (interactive "P")
17825 (cond
17826 ((run-hook-with-args-until-success 'org-metaup-hook))
17827 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
17828 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17829 ((org-at-item-p) (call-interactively 'org-move-item-up))
17830 (t (transpose-lines 1) (beginning-of-line -1))))
17832 (defun org-metadown (&optional arg)
17833 "Move subtree down or move table row down.
17834 Calls `org-move-subtree-down' or `org-table-move-row' or
17835 `org-move-item-down', depending on context. See the individual
17836 commands for more information."
17837 (interactive "P")
17838 (cond
17839 ((run-hook-with-args-until-success 'org-metadown-hook))
17840 ((org-at-table-p) (call-interactively 'org-table-move-row))
17841 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17842 ((org-at-item-p) (call-interactively 'org-move-item-down))
17843 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
17845 (defun org-shiftup (&optional arg)
17846 "Increase item in timestamp or increase priority of current headline.
17847 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
17848 depending on context. See the individual commands for more information."
17849 (interactive "P")
17850 (cond
17851 ((run-hook-with-args-until-success 'org-shiftup-hook))
17852 ((and org-support-shift-select (org-region-active-p))
17853 (org-call-for-shift-select 'previous-line))
17854 ((org-at-timestamp-p t)
17855 (call-interactively (if org-edit-timestamp-down-means-later
17856 'org-timestamp-down 'org-timestamp-up)))
17857 ((and (not (eq org-support-shift-select 'always))
17858 org-enable-priority-commands
17859 (org-on-heading-p))
17860 (call-interactively 'org-priority-up))
17861 ((and (not org-support-shift-select) (org-at-item-p))
17862 (call-interactively 'org-previous-item))
17863 ((org-clocktable-try-shift 'up arg))
17864 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
17865 (org-support-shift-select
17866 (org-call-for-shift-select 'previous-line))
17867 (t (org-shiftselect-error))))
17869 (defun org-shiftdown (&optional arg)
17870 "Decrease item in timestamp or decrease priority of current headline.
17871 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
17872 depending on context. See the individual commands for more information."
17873 (interactive "P")
17874 (cond
17875 ((run-hook-with-args-until-success 'org-shiftdown-hook))
17876 ((and org-support-shift-select (org-region-active-p))
17877 (org-call-for-shift-select 'next-line))
17878 ((org-at-timestamp-p t)
17879 (call-interactively (if org-edit-timestamp-down-means-later
17880 'org-timestamp-up 'org-timestamp-down)))
17881 ((and (not (eq org-support-shift-select 'always))
17882 org-enable-priority-commands
17883 (org-on-heading-p))
17884 (call-interactively 'org-priority-down))
17885 ((and (not org-support-shift-select) (org-at-item-p))
17886 (call-interactively 'org-next-item))
17887 ((org-clocktable-try-shift 'down arg))
17888 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
17889 (org-support-shift-select
17890 (org-call-for-shift-select 'next-line))
17891 (t (org-shiftselect-error))))
17893 (defun org-shiftright (&optional arg)
17894 "Cycle the thing at point or in the current line, depending on context.
17895 Depending on context, this does one of the following:
17897 - switch a timestamp at point one day into the future
17898 - on a headline, switch to the next TODO keyword.
17899 - on an item, switch entire list to the next bullet type
17900 - on a property line, switch to the next allowed value
17901 - on a clocktable definition line, move time block into the future"
17902 (interactive "P")
17903 (cond
17904 ((run-hook-with-args-until-success 'org-shiftright-hook))
17905 ((and org-support-shift-select (org-region-active-p))
17906 (org-call-for-shift-select 'forward-char))
17907 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
17908 ((and (not (eq org-support-shift-select 'always))
17909 (org-on-heading-p))
17910 (let ((org-inhibit-logging
17911 (not org-treat-S-cursor-todo-selection-as-state-change))
17912 (org-inhibit-blocking
17913 (not org-treat-S-cursor-todo-selection-as-state-change)))
17914 (org-call-with-arg 'org-todo 'right)))
17915 ((or (and org-support-shift-select
17916 (not (eq org-support-shift-select 'always))
17917 (org-at-item-bullet-p))
17918 (and (not org-support-shift-select) (org-at-item-p)))
17919 (org-call-with-arg 'org-cycle-list-bullet nil))
17920 ((and (not (eq org-support-shift-select 'always))
17921 (org-at-property-p))
17922 (call-interactively 'org-property-next-allowed-value))
17923 ((org-clocktable-try-shift 'right arg))
17924 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
17925 (org-support-shift-select
17926 (org-call-for-shift-select 'forward-char))
17927 (t (org-shiftselect-error))))
17929 (defun org-shiftleft (&optional arg)
17930 "Cycle the thing at point or in the current line, depending on context.
17931 Depending on context, this does one of the following:
17933 - switch a timestamp at point one day into the past
17934 - on a headline, switch to the previous TODO keyword.
17935 - on an item, switch entire list to the previous bullet type
17936 - on a property line, switch to the previous allowed value
17937 - on a clocktable definition line, move time block into the past"
17938 (interactive "P")
17939 (cond
17940 ((run-hook-with-args-until-success 'org-shiftleft-hook))
17941 ((and org-support-shift-select (org-region-active-p))
17942 (org-call-for-shift-select 'backward-char))
17943 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
17944 ((and (not (eq org-support-shift-select 'always))
17945 (org-on-heading-p))
17946 (let ((org-inhibit-logging
17947 (not org-treat-S-cursor-todo-selection-as-state-change))
17948 (org-inhibit-blocking
17949 (not org-treat-S-cursor-todo-selection-as-state-change)))
17950 (org-call-with-arg 'org-todo 'left)))
17951 ((or (and org-support-shift-select
17952 (not (eq org-support-shift-select 'always))
17953 (org-at-item-bullet-p))
17954 (and (not org-support-shift-select) (org-at-item-p)))
17955 (org-call-with-arg 'org-cycle-list-bullet 'previous))
17956 ((and (not (eq org-support-shift-select 'always))
17957 (org-at-property-p))
17958 (call-interactively 'org-property-previous-allowed-value))
17959 ((org-clocktable-try-shift 'left arg))
17960 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
17961 (org-support-shift-select
17962 (org-call-for-shift-select 'backward-char))
17963 (t (org-shiftselect-error))))
17965 (defun org-shiftcontrolright ()
17966 "Switch to next TODO set."
17967 (interactive)
17968 (cond
17969 ((and org-support-shift-select (org-region-active-p))
17970 (org-call-for-shift-select 'forward-word))
17971 ((and (not (eq org-support-shift-select 'always))
17972 (org-on-heading-p))
17973 (org-call-with-arg 'org-todo 'nextset))
17974 (org-support-shift-select
17975 (org-call-for-shift-select 'forward-word))
17976 (t (org-shiftselect-error))))
17978 (defun org-shiftcontrolleft ()
17979 "Switch to previous TODO set."
17980 (interactive)
17981 (cond
17982 ((and org-support-shift-select (org-region-active-p))
17983 (org-call-for-shift-select 'backward-word))
17984 ((and (not (eq org-support-shift-select 'always))
17985 (org-on-heading-p))
17986 (org-call-with-arg 'org-todo 'previousset))
17987 (org-support-shift-select
17988 (org-call-for-shift-select 'backward-word))
17989 (t (org-shiftselect-error))))
17991 (defun org-shiftcontrolup ()
17992 "Change timestamps synchronously up in CLOCK log lines."
17993 (interactive)
17994 (cond ((and (not org-support-shift-select)
17995 (org-at-clock-log-p)
17996 (org-at-timestamp-p t))
17997 (org-clock-timestamps-up))
17998 (t (org-shiftselect-error))))
18000 (defun org-shiftcontroldown ()
18001 "Change timestamps synchronously down in CLOCK log lines."
18002 (interactive)
18003 (cond ((and (not org-support-shift-select)
18004 (org-at-clock-log-p)
18005 (org-at-timestamp-p t))
18006 (org-clock-timestamps-down))
18007 (t (org-shiftselect-error))))
18009 (defun org-ctrl-c-ret ()
18010 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18011 (interactive)
18012 (cond
18013 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18014 (t (call-interactively 'org-insert-heading))))
18016 (defun org-find-visible ()
18017 (let ((s (point)))
18018 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18019 (get-char-property s 'invisible)))
18021 (defun org-find-invisible ()
18022 (let ((s (point)))
18023 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18024 (not (get-char-property s 'invisible))))
18027 (defun org-copy-visible (beg end)
18028 "Copy the visible parts of the region."
18029 (interactive "r")
18030 (let (snippets s)
18031 (save-excursion
18032 (save-restriction
18033 (narrow-to-region beg end)
18034 (setq s (goto-char (point-min)))
18035 (while (not (= (point) (point-max)))
18036 (goto-char (org-find-invisible))
18037 (push (buffer-substring s (point)) snippets)
18038 (setq s (goto-char (org-find-visible))))))
18039 (kill-new (apply 'concat (nreverse snippets)))))
18041 (defun org-copy-special ()
18042 "Copy region in table or copy current subtree.
18043 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18044 See the individual commands for more information."
18045 (interactive)
18046 (call-interactively
18047 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18049 (defun org-cut-special ()
18050 "Cut region in table or cut current subtree.
18051 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18052 See the individual commands for more information."
18053 (interactive)
18054 (call-interactively
18055 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18057 (defun org-paste-special (arg)
18058 "Paste rectangular region into table, or past subtree relative to level.
18059 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18060 See the individual commands for more information."
18061 (interactive "P")
18062 (if (org-at-table-p)
18063 (org-table-paste-rectangle)
18064 (org-paste-subtree arg)))
18066 (defun org-edit-special (&optional arg)
18067 "Call a special editor for the stuff at point.
18068 When at a table, call the formula editor with `org-table-edit-formulas'.
18069 When at the first line of an src example, call `org-edit-src-code'.
18070 When in an #+include line, visit the include file. Otherwise call
18071 `ffap' to visit the file at point."
18072 (interactive)
18073 ;; possibly prep session before editing source
18074 (when arg
18075 (let* ((info (org-babel-get-src-block-info))
18076 (lang (nth 0 info))
18077 (params (nth 2 info))
18078 (session (cdr (assoc :session params))))
18079 (when (and info session) ;; we are in a source-code block with a session
18080 (funcall
18081 (intern (concat "org-babel-prep-session:" lang)) session params))))
18082 (cond ;; proceed with `org-edit-special'
18083 ((save-excursion
18084 (beginning-of-line 1)
18085 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
18086 (find-file (org-trim (match-string 1))))
18087 ((org-edit-src-code))
18088 ((org-edit-fixed-width-region))
18089 ((org-at-table.el-p)
18090 (org-edit-src-code))
18091 ((or (org-at-table-p)
18092 (save-excursion
18093 (beginning-of-line 1)
18094 (looking-at "[ \t]*#\\+TBLFM:")))
18095 (call-interactively 'org-table-edit-formulas))
18096 (t (call-interactively 'ffap))))
18098 (defvar org-table-coordinate-overlays) ; defined in org-table.el
18099 (defun org-ctrl-c-ctrl-c (&optional arg)
18100 "Set tags in headline, or update according to changed information at point.
18102 This command does many different things, depending on context:
18104 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
18105 this is what we do.
18107 - If the cursor is on a statistics cookie, update it.
18109 - If the cursor is in a headline, prompt for tags and insert them
18110 into the current line, aligned to `org-tags-column'. When called
18111 with prefix arg, realign all tags in the current buffer.
18113 - If the cursor is in one of the special #+KEYWORD lines, this
18114 triggers scanning the buffer for these lines and updating the
18115 information.
18117 - If the cursor is inside a table, realign the table. This command
18118 works even if the automatic table editor has been turned off.
18120 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18121 the entire table.
18123 - If the cursor is at a footnote reference or definition, jump to
18124 the corresponding definition or references, respectively.
18126 - If the cursor is a the beginning of a dynamic block, update it.
18128 - If the current buffer is a capture buffer, close note and file it.
18130 - If the cursor is on a <<<target>>>, update radio targets and
18131 corresponding links in this buffer.
18133 - If the cursor is on a numbered item in a plain list, renumber the
18134 ordered list.
18136 - If the cursor is on a checkbox, toggle it.
18138 - If the cursor is on a code block, evaluate it. The variable
18139 `org-confirm-babel-evaluate' can be used to control prompting
18140 before code block evaluation, by default every code block
18141 evaluation requires confirmation. Code block evaluation can be
18142 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
18143 (interactive "P")
18144 (let ((org-enable-table-editor t))
18145 (cond
18146 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
18147 org-occur-highlights
18148 org-latex-fragment-image-overlays)
18149 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
18150 (org-remove-occur-highlights)
18151 (org-remove-latex-fragment-image-overlays)
18152 (message "Temporary highlights/overlays removed from current buffer"))
18153 ((and (local-variable-p 'org-finish-function (current-buffer))
18154 (fboundp org-finish-function))
18155 (funcall org-finish-function))
18156 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
18157 ((or (looking-at org-property-start-re)
18158 (org-at-property-p))
18159 (call-interactively 'org-property-action))
18160 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
18161 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
18162 (or (org-on-heading-p) (org-at-item-p)))
18163 (call-interactively 'org-update-statistics-cookies))
18164 ((org-on-heading-p) (call-interactively 'org-set-tags))
18165 ((org-at-table.el-p)
18166 (message "Use C-c ' to edit table.el tables"))
18167 ((org-at-table-p)
18168 (org-table-maybe-eval-formula)
18169 (if arg
18170 (call-interactively 'org-table-recalculate)
18171 (org-table-maybe-recalculate-line))
18172 (call-interactively 'org-table-align)
18173 (orgtbl-send-table 'maybe))
18174 ((or (org-footnote-at-reference-p)
18175 (org-footnote-at-definition-p))
18176 (call-interactively 'org-footnote-action))
18177 ((org-at-item-checkbox-p)
18178 ;; Cursor at a checkbox: repair list and update checkboxes. Send
18179 ;; list only if at top item.
18180 (let* ((cbox (match-string 1))
18181 (struct (org-list-struct))
18182 (old-struct (copy-tree struct))
18183 (parents (org-list-parents-alist struct))
18184 (orderedp (org-entry-get nil "ORDERED"))
18185 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
18186 block-item)
18187 ;; Use a light version of `org-toggle-checkbox' to avoid
18188 ;; computing list structure twice.
18189 (org-list-set-checkbox (point-at-bol) struct
18190 (cond
18191 ((equal arg '(16)) "[-]")
18192 ((equal arg '(4)) nil)
18193 ((equal "[X]" cbox) "[ ]")
18194 (t "[X]")))
18195 ;; Replicate `org-list-write-struct', while grabbing a return
18196 ;; value from `org-list-struct-fix-box'.
18197 (org-list-struct-fix-ind struct parents 2)
18198 (org-list-struct-fix-item-end struct)
18199 (let ((prevs (org-list-prevs-alist struct)))
18200 (org-list-struct-fix-bul struct prevs)
18201 (org-list-struct-fix-ind struct parents)
18202 (setq block-item
18203 (org-list-struct-fix-box struct parents prevs orderedp)))
18204 (org-list-struct-apply-struct struct old-struct)
18205 (org-update-checkbox-count-maybe)
18206 (when block-item
18207 (message
18208 "Checkboxes were removed due to unchecked box at line %d"
18209 (org-current-line block-item)))
18210 (when firstp (org-list-send-list 'maybe))))
18211 ((org-at-item-p)
18212 ;; Cursor at an item: repair list. Do checkbox related actions
18213 ;; only if function was called with an argument. Send list only
18214 ;; if at top item.
18215 (let* ((struct (org-list-struct))
18216 (firstp (= (org-list-get-top-point struct) (point-at-bol))))
18217 (when arg (org-list-set-checkbox (point-at-bol) struct "[ ]"))
18218 (org-list-write-struct struct (org-list-parents-alist struct))
18219 (when arg (org-update-checkbox-count-maybe))
18220 (when firstp (org-list-send-list 'maybe))))
18221 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
18222 ;; Dynamic block
18223 (beginning-of-line 1)
18224 (save-excursion (org-update-dblock)))
18225 ((save-excursion
18226 (beginning-of-line 1)
18227 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
18228 (cond
18229 ((equal (match-string 1) "TBLFM")
18230 ;; Recalculate the table before this line
18231 (save-excursion
18232 (beginning-of-line 1)
18233 (skip-chars-backward " \r\n\t")
18234 (if (org-at-table-p)
18235 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18237 (let ((org-inhibit-startup-visibility-stuff t)
18238 (org-startup-align-all-tables nil))
18239 (when (boundp 'org-table-coordinate-overlays)
18240 (mapc 'delete-overlay org-table-coordinate-overlays)
18241 (setq org-table-coordinate-overlays nil))
18242 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18243 (message "Local setup has been refreshed"))))
18244 ((org-clock-update-time-maybe))
18246 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18247 (error "C-c C-c can do nothing useful at this location"))))))
18249 (defun org-mode-restart ()
18250 "Restart Org-mode, to scan again for special lines.
18251 Also updates the keyword regular expressions."
18252 (interactive)
18253 (org-mode)
18254 (message "Org-mode restarted"))
18256 (defun org-kill-note-or-show-branches ()
18257 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18258 (interactive)
18259 (if (not org-finish-function)
18260 (progn
18261 (hide-subtree)
18262 (call-interactively 'show-branches))
18263 (let ((org-note-abort t))
18264 (funcall org-finish-function))))
18266 (defun org-return (&optional indent)
18267 "Goto next table row or insert a newline.
18268 Calls `org-table-next-row' or `newline', depending on context.
18269 See the individual commands for more information."
18270 (interactive)
18271 (cond
18272 ((bobp) (if indent (newline-and-indent) (newline)))
18273 ((org-at-table-p)
18274 (org-table-justify-field-maybe)
18275 (call-interactively 'org-table-next-row))
18276 ;; when `newline-and-indent' is called within a list, make sure
18277 ;; text moved stays inside the item.
18278 ((and (org-in-item-p) indent)
18279 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18280 (progn
18281 (save-match-data (newline))
18282 (org-indent-line-to (length (match-string 0))))
18283 (let ((ind (org-get-indentation)))
18284 (newline)
18285 (if (org-looking-back org-list-end-re)
18286 (org-indent-line-function)
18287 (org-indent-line-to ind)))))
18288 ((and org-return-follows-link
18289 (or (eq (get-text-property (point) 'face) 'org-link)
18290 (memq 'org-link (get-text-property (point) 'face))))
18291 (call-interactively 'org-open-at-point))
18292 ((and (org-at-heading-p)
18293 (looking-at
18294 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18295 (org-show-entry)
18296 (end-of-line 1)
18297 (newline))
18298 (t (if indent (newline-and-indent) (newline)))))
18300 (defun org-return-indent ()
18301 "Goto next table row or insert a newline and indent.
18302 Calls `org-table-next-row' or `newline-and-indent', depending on
18303 context. See the individual commands for more information."
18304 (interactive)
18305 (org-return t))
18307 (defun org-ctrl-c-star ()
18308 "Compute table, or change heading status of lines.
18309 Calls `org-table-recalculate' or `org-toggle-heading',
18310 depending on context."
18311 (interactive)
18312 (cond
18313 ((org-at-table-p)
18314 (call-interactively 'org-table-recalculate))
18316 ;; Convert all lines in region to list items
18317 (call-interactively 'org-toggle-heading))))
18319 (defun org-ctrl-c-minus ()
18320 "Insert separator line in table or modify bullet status of line.
18321 Also turns a plain line or a region of lines into list items.
18322 Calls `org-table-insert-hline', `org-toggle-item', or
18323 `org-cycle-list-bullet', depending on context."
18324 (interactive)
18325 (cond
18326 ((org-at-table-p)
18327 (call-interactively 'org-table-insert-hline))
18328 ((org-region-active-p)
18329 (call-interactively 'org-toggle-item))
18330 ((org-in-item-p)
18331 (call-interactively 'org-cycle-list-bullet))
18333 (call-interactively 'org-toggle-item))))
18335 (defun org-toggle-item (arg)
18336 "Convert headings or normal lines to items, items to normal lines.
18337 If there is no active region, only the current line is considered.
18339 If the first non blank line in the region is an headline, convert
18340 all headlines to items, shifting text accordingly.
18342 If it is an item, convert all items to normal lines.
18344 If it is normal text, change region into an item. With a prefix
18345 argument ARG, change each line in region into an item."
18346 (interactive "P")
18347 (let ((shift-text
18348 (function
18349 ;; Shift text in current section to IND, from point to END.
18350 ;; The function leaves point to END line.
18351 (lambda (ind end)
18352 (let ((min-i 1000) (end (copy-marker end)))
18353 ;; First determine the minimum indentation (MIN-I) of
18354 ;; the text.
18355 (save-excursion
18356 (catch 'exit
18357 (while (< (point) end)
18358 (let ((i (org-get-indentation)))
18359 (cond
18360 ;; Skip blank lines and inline tasks.
18361 ((looking-at "^[ \t]*$"))
18362 ((looking-at org-outline-regexp-bol))
18363 ;; We can't find less than 0 indentation.
18364 ((zerop i) (throw 'exit (setq min-i 0)))
18365 ((< i min-i) (setq min-i i))))
18366 (forward-line))))
18367 ;; Then indent each line so that a line indented to
18368 ;; MIN-I becomes indented to IND. Ignore blank lines
18369 ;; and inline tasks in the process.
18370 (let ((delta (- ind min-i)))
18371 (while (< (point) end)
18372 (unless (or (looking-at "^[ \t]*$")
18373 (looking-at org-outline-regexp-bol))
18374 (org-indent-line-to (+ (org-get-indentation) delta)))
18375 (forward-line)))))))
18376 (skip-blanks
18377 (function
18378 ;; Return beginning of first non-blank line, starting from
18379 ;; line at POS.
18380 (lambda (pos)
18381 (save-excursion
18382 (goto-char pos)
18383 (skip-chars-forward " \r\t\n")
18384 (point-at-bol)))))
18385 beg end)
18386 ;; Determine boundaries of changes.
18387 (if (org-region-active-p)
18388 (setq beg (funcall skip-blanks (region-beginning))
18389 end (copy-marker (region-end)))
18390 (setq beg (funcall skip-blanks (point-at-bol))
18391 end (copy-marker (point-at-eol))))
18392 ;; Depending on the starting line, choose an action on the text
18393 ;; between BEG and END.
18394 (org-with-limited-levels
18395 (save-excursion
18396 (goto-char beg)
18397 (cond
18398 ;; Case 1. Start at an item: de-itemize. Note that it only
18399 ;; happens when a region is active: `org-ctrl-c-minus'
18400 ;; would call `org-cycle-list-bullet' otherwise.
18401 ((org-at-item-p)
18402 (while (< (point) end)
18403 (when (org-at-item-p)
18404 (skip-chars-forward " \t")
18405 (delete-region (point) (match-end 0)))
18406 (forward-line)))
18407 ;; Case 2. Start at an heading: convert to items.
18408 ((org-on-heading-p)
18409 (let* ((bul (org-list-bullet-string "-"))
18410 (bul-len (length bul))
18411 ;; Indentation of the first heading. It should be
18412 ;; relative to the indentation of its parent, if any.
18413 (start-ind (save-excursion
18414 (cond
18415 ((not org-adapt-indentation) 0)
18416 ((not (outline-previous-heading)) 0)
18417 (t (length (match-string 0))))))
18418 ;; Level of first heading. Further headings will be
18419 ;; compared to it to determine hierarchy in the list.
18420 (ref-level (org-reduced-level (org-outline-level))))
18421 (while (< (point) end)
18422 (let* ((level (org-reduced-level (org-outline-level)))
18423 (delta (max 0 (- level ref-level))))
18424 ;; If current headline is less indented than the first
18425 ;; one, set it as reference, in order to preserve
18426 ;; subtrees.
18427 (when (< level ref-level) (setq ref-level level))
18428 (replace-match bul t t)
18429 (org-indent-line-to (+ start-ind (* delta bul-len)))
18430 ;; Ensure all text down to END (or SECTION-END) belongs
18431 ;; to the newly created item.
18432 (let ((section-end (save-excursion
18433 (or (outline-next-heading) (point)))))
18434 (forward-line)
18435 (funcall shift-text
18436 (+ start-ind (* (1+ delta) bul-len))
18437 (min end section-end)))))))
18438 ;; Case 3. Normal line with ARG: turn each non-item line into
18439 ;; an item.
18440 (arg
18441 (while (< (point) end)
18442 (unless (or (org-on-heading-p) (org-at-item-p))
18443 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
18444 (replace-match
18445 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
18446 (forward-line)))
18447 ;; Case 4. Normal line without ARG: make the first line of
18448 ;; region an item, and shift indentation of others
18449 ;; lines to set them as item's body.
18450 (t (let* ((bul (org-list-bullet-string "-"))
18451 (bul-len (length bul))
18452 (ref-ind (org-get-indentation)))
18453 (skip-chars-forward " \t")
18454 (insert bul)
18455 (forward-line)
18456 (while (< (point) end)
18457 ;; Ensure that lines less indented than first one
18458 ;; still get included in item body.
18459 (funcall shift-text
18460 (+ ref-ind bul-len)
18461 (min end (save-excursion (or (outline-next-heading)
18462 (point)))))
18463 (forward-line)))))))))
18465 (defun org-toggle-heading (&optional nstars)
18466 "Convert headings to normal text, or items or text to headings.
18467 If there is no active region, only the current line is considered.
18469 If the first non blank line is an headline, remove the stars from
18470 all headlines in the region.
18472 If it is a plain list item, turn all plain list items into headings.
18474 If it is a normal line, turn each and every normal line (i.e. not
18475 an heading or an item) in the region into a heading.
18477 When converting a line into a heading, the number of stars is chosen
18478 such that the lines become children of the current entry. However,
18479 when a prefix argument is given, its value determines the number of
18480 stars to add."
18481 (interactive "P")
18482 (let ((skip-blanks
18483 (function
18484 ;; Return beginning of first non-blank line, starting from
18485 ;; line at POS.
18486 (lambda (pos)
18487 (save-excursion
18488 (goto-char pos)
18489 (skip-chars-forward " \r\t\n")
18490 (point-at-bol)))))
18491 beg end)
18492 ;; Determine boundaries of changes. If region ends at a bol, do
18493 ;; not consider the last line to be in the region.
18494 (if (org-region-active-p)
18495 (setq beg (funcall skip-blanks (region-beginning))
18496 end (copy-marker (save-excursion
18497 (goto-char (region-end))
18498 (if (bolp) (point) (point-at-eol)))))
18499 (setq beg (funcall skip-blanks (point-at-bol))
18500 end (copy-marker (point-at-eol))))
18501 ;; Ensure inline tasks don't count as headings.
18502 (org-with-limited-levels
18503 (save-excursion
18504 (goto-char beg)
18505 (cond
18506 ;; Case 1. Started at an heading: de-star headings.
18507 ((org-on-heading-p)
18508 (while (< (point) end)
18509 (when (org-on-heading-p t)
18510 (looking-at org-outline-regexp) (replace-match ""))
18511 (forward-line)))
18512 ;; Case 2. Started at an item: change items into headlines.
18513 ;; One star will be added by `org-list-to-subtree'.
18514 ((org-at-item-p)
18515 (let* ((stars (make-string
18516 (if nstars
18517 ;; subtract the star that will be added again by
18518 ;; `org-list-to-subtree'
18519 (1- (prefix-numeric-value current-prefix-arg))
18520 (or (org-current-level) 0))
18521 ?*))
18522 (add-stars
18523 (cond (nstars "") ; stars from prefix only
18524 ((equal stars "") "") ; before first heading
18525 (org-odd-levels-only "*") ; inside heading, odd
18526 (t "")))) ; inside heading, oddeven
18527 (while (< (point) end)
18528 (when (org-at-item-p)
18529 ;; Pay attention to cases when region ends before list.
18530 (let* ((struct (org-list-struct))
18531 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18532 (save-restriction
18533 (narrow-to-region (point) list-end)
18534 (insert
18535 (org-list-to-subtree
18536 (org-list-parse-list t)
18537 '(:istart (concat stars add-stars (funcall get-stars depth))
18538 :icount (concat stars add-stars (funcall get-stars depth))))))))
18539 (forward-line))))
18540 ;; Case 3. Started at normal text: make every line an heading,
18541 ;; skipping headlines and items.
18542 (t (let* ((stars (make-string
18543 (if nstars
18544 (prefix-numeric-value current-prefix-arg)
18545 (or (org-current-level) 0))
18546 ?*))
18547 (add-stars
18548 (cond (nstars "") ; stars from prefix only
18549 ((equal stars "") "*") ; before first heading
18550 (org-odd-levels-only "**") ; inside heading, odd
18551 (t "*"))) ; inside heading, oddeven
18552 (rpl (concat stars add-stars " ")))
18553 (while (< (point) end)
18554 (when (and (not (org-on-heading-p)) (not (org-at-item-p))
18555 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18556 (replace-match (concat rpl (match-string 2))))
18557 (forward-line)))))))))
18559 (defun org-meta-return (&optional arg)
18560 "Insert a new heading or wrap a region in a table.
18561 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18562 See the individual commands for more information."
18563 (interactive "P")
18564 (cond
18565 ((run-hook-with-args-until-success 'org-metareturn-hook))
18566 ((org-at-table-p)
18567 (call-interactively 'org-table-wrap-region))
18568 (t (call-interactively 'org-insert-heading))))
18570 ;;; Menu entries
18572 ;; Define the Org-mode menus
18573 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18574 '("Tbl"
18575 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18576 ["Next Field" org-cycle (org-at-table-p)]
18577 ["Previous Field" org-shifttab (org-at-table-p)]
18578 ["Next Row" org-return (org-at-table-p)]
18579 "--"
18580 ["Blank Field" org-table-blank-field (org-at-table-p)]
18581 ["Edit Field" org-table-edit-field (org-at-table-p)]
18582 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18583 "--"
18584 ("Column"
18585 ["Move Column Left" org-metaleft (org-at-table-p)]
18586 ["Move Column Right" org-metaright (org-at-table-p)]
18587 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18588 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18589 ("Row"
18590 ["Move Row Up" org-metaup (org-at-table-p)]
18591 ["Move Row Down" org-metadown (org-at-table-p)]
18592 ["Delete Row" org-shiftmetaup (org-at-table-p)]
18593 ["Insert Row" org-shiftmetadown (org-at-table-p)]
18594 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
18595 "--"
18596 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
18597 ("Rectangle"
18598 ["Copy Rectangle" org-copy-special (org-at-table-p)]
18599 ["Cut Rectangle" org-cut-special (org-at-table-p)]
18600 ["Paste Rectangle" org-paste-special (org-at-table-p)]
18601 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
18602 "--"
18603 ("Calculate"
18604 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
18605 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
18606 ["Edit Formulas" org-edit-special (org-at-table-p)]
18607 "--"
18608 ["Recalculate line" org-table-recalculate (org-at-table-p)]
18609 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
18610 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
18611 "--"
18612 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
18613 "--"
18614 ["Sum Column/Rectangle" org-table-sum
18615 (or (org-at-table-p) (org-region-active-p))]
18616 ["Which Column?" org-table-current-column (org-at-table-p)])
18617 ["Debug Formulas"
18618 org-table-toggle-formula-debugger
18619 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
18620 ["Show Col/Row Numbers"
18621 org-table-toggle-coordinate-overlays
18622 :style toggle
18623 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
18624 "--"
18625 ["Create" org-table-create (and (not (org-at-table-p))
18626 org-enable-table-editor)]
18627 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
18628 ["Import from File" org-table-import (not (org-at-table-p))]
18629 ["Export to File" org-table-export (org-at-table-p)]
18630 "--"
18631 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
18633 (easy-menu-define org-org-menu org-mode-map "Org menu"
18634 '("Org"
18635 ("Show/Hide"
18636 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
18637 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
18638 ["Sparse Tree..." org-sparse-tree t]
18639 ["Reveal Context" org-reveal t]
18640 ["Show All" show-all t]
18641 "--"
18642 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
18643 "--"
18644 ["New Heading" org-insert-heading t]
18645 ("Navigate Headings"
18646 ["Up" outline-up-heading t]
18647 ["Next" outline-next-visible-heading t]
18648 ["Previous" outline-previous-visible-heading t]
18649 ["Next Same Level" outline-forward-same-level t]
18650 ["Previous Same Level" outline-backward-same-level t]
18651 "--"
18652 ["Jump" org-goto t])
18653 ("Edit Structure"
18654 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
18655 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
18656 "--"
18657 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
18658 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
18659 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
18660 "--"
18661 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
18662 "--"
18663 ["Copy visible text" org-copy-visible t]
18664 "--"
18665 ["Promote Heading" org-metaleft (not (org-at-table-p))]
18666 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
18667 ["Demote Heading" org-metaright (not (org-at-table-p))]
18668 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
18669 "--"
18670 ["Sort Region/Children" org-sort (not (org-at-table-p))]
18671 "--"
18672 ["Convert to odd levels" org-convert-to-odd-levels t]
18673 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
18674 ("Editing"
18675 ["Emphasis..." org-emphasize t]
18676 ["Edit Source Example" org-edit-special t]
18677 "--"
18678 ["Footnote new/jump" org-footnote-action t]
18679 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
18680 ("Archive"
18681 ["Archive (default method)" org-archive-subtree-default t]
18682 "--"
18683 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
18684 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
18685 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
18687 "--"
18688 ("Hyperlinks"
18689 ["Store Link (Global)" org-store-link t]
18690 ["Find existing link to here" org-occur-link-in-agenda-files t]
18691 ["Insert Link" org-insert-link t]
18692 ["Follow Link" org-open-at-point t]
18693 "--"
18694 ["Next link" org-next-link t]
18695 ["Previous link" org-previous-link t]
18696 "--"
18697 ["Descriptive Links"
18698 org-toggle-link-display
18699 :style radio
18700 :selected org-descriptive-links
18702 ["Literal Links"
18703 org-toggle-link-display
18704 :style radio
18705 :selected (not org-descriptive-links)])
18706 "--"
18707 ("TODO Lists"
18708 ["TODO/DONE/-" org-todo t]
18709 ("Select keyword"
18710 ["Next keyword" org-shiftright (org-on-heading-p)]
18711 ["Previous keyword" org-shiftleft (org-on-heading-p)]
18712 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
18713 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
18714 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
18715 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
18716 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
18717 "--"
18718 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
18719 :selected org-enforce-todo-dependencies :style toggle :active t]
18720 "Settings for tree at point"
18721 ["Do Children sequentially" org-toggle-ordered-property :style radio
18722 :selected (org-entry-get nil "ORDERED")
18723 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18724 ["Do Children parallel" org-toggle-ordered-property :style radio
18725 :selected (not (org-entry-get nil "ORDERED"))
18726 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18727 "--"
18728 ["Set Priority" org-priority t]
18729 ["Priority Up" org-shiftup t]
18730 ["Priority Down" org-shiftdown t]
18731 "--"
18732 ["Get news from all feeds" org-feed-update-all t]
18733 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
18734 ["Customize feeds" (customize-variable 'org-feed-alist) t])
18735 ("TAGS and Properties"
18736 ["Set Tags" org-set-tags-command t]
18737 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
18738 "--"
18739 ["Set property" org-set-property t]
18740 ["Column view of properties" org-columns t]
18741 ["Insert Column View DBlock" org-insert-columns-dblock t])
18742 ("Dates and Scheduling"
18743 ["Timestamp" org-time-stamp t]
18744 ["Timestamp (inactive)" org-time-stamp-inactive t]
18745 ("Change Date"
18746 ["1 Day Later" org-shiftright t]
18747 ["1 Day Earlier" org-shiftleft t]
18748 ["1 ... Later" org-shiftup t]
18749 ["1 ... Earlier" org-shiftdown t])
18750 ["Compute Time Range" org-evaluate-time-range t]
18751 ["Schedule Item" org-schedule t]
18752 ["Deadline" org-deadline t]
18753 "--"
18754 ["Custom time format" org-toggle-time-stamp-overlays
18755 :style radio :selected org-display-custom-times]
18756 "--"
18757 ["Goto Calendar" org-goto-calendar t]
18758 ["Date from Calendar" org-date-from-calendar t]
18759 "--"
18760 ["Start/Restart Timer" org-timer-start t]
18761 ["Pause/Continue Timer" org-timer-pause-or-continue t]
18762 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
18763 ["Insert Timer String" org-timer t]
18764 ["Insert Timer Item" org-timer-item t])
18765 ("Logging work"
18766 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
18767 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
18768 ["Clock out" org-clock-out t]
18769 ["Clock cancel" org-clock-cancel t]
18770 "--"
18771 ["Mark as default task" org-clock-mark-default-task t]
18772 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
18773 ["Goto running clock" org-clock-goto t]
18774 "--"
18775 ["Display times" org-clock-display t]
18776 ["Create clock table" org-clock-report t]
18777 "--"
18778 ["Record DONE time"
18779 (progn (setq org-log-done (not org-log-done))
18780 (message "Switching to %s will %s record a timestamp"
18781 (car org-done-keywords)
18782 (if org-log-done "automatically" "not")))
18783 :style toggle :selected org-log-done])
18784 "--"
18785 ["Agenda Command..." org-agenda t]
18786 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
18787 ("File List for Agenda")
18788 ("Special views current file"
18789 ["TODO Tree" org-show-todo-tree t]
18790 ["Check Deadlines" org-check-deadlines t]
18791 ["Timeline" org-timeline t]
18792 ["Tags/Property tree" org-match-sparse-tree t])
18793 "--"
18794 ["Export/Publish..." org-export t]
18795 ("LaTeX"
18796 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
18797 :selected org-cdlatex-mode]
18798 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
18799 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
18800 ["Modify math symbol" org-cdlatex-math-modify
18801 (org-inside-LaTeX-fragment-p)]
18802 ["Insert citation" org-reftex-citation t]
18803 "--"
18804 ["Template for BEAMER" org-insert-beamer-options-template t])
18805 "--"
18806 ("MobileOrg"
18807 ["Push Files and Views" org-mobile-push t]
18808 ["Get Captured and Flagged" org-mobile-pull t]
18809 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
18810 "--"
18811 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
18812 "--"
18813 ("Documentation"
18814 ["Show Version" org-version t]
18815 ["Info Documentation" org-info t])
18816 ("Customize"
18817 ["Browse Org Group" org-customize t]
18818 "--"
18819 ["Expand This Menu" org-create-customize-menu
18820 (fboundp 'customize-menu-create)])
18821 ["Send bug report" org-submit-bug-report t]
18822 "--"
18823 ("Refresh/Reload"
18824 ["Refresh setup current buffer" org-mode-restart t]
18825 ["Reload Org (after update)" org-reload t]
18826 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
18829 (defun org-info (&optional node)
18830 "Read documentation for Org-mode in the info system.
18831 With optional NODE, go directly to that node."
18832 (interactive)
18833 (info (format "(org)%s" (or node ""))))
18835 ;;;###autoload
18836 (defun org-submit-bug-report ()
18837 "Submit a bug report on Org-mode via mail.
18839 Don't hesitate to report any problems or inaccurate documentation.
18841 If you don't have setup sending mail from (X)Emacs, please copy the
18842 output buffer into your mail program, as it gives us important
18843 information about your Org-mode version and configuration."
18844 (interactive)
18845 (require 'reporter)
18846 (org-load-modules-maybe)
18847 (org-require-autoloaded-modules)
18848 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
18849 (reporter-submit-bug-report
18850 "emacs-orgmode@gnu.org"
18851 (org-version)
18852 (let (list)
18853 (save-window-excursion
18854 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
18855 (delete-other-windows)
18856 (erase-buffer)
18857 (insert "You are about to submit a bug report to the Org-mode mailing list.
18859 We would like to add your full Org-mode and Outline configuration to the
18860 bug report. This greatly simplifies the work of the maintainer and
18861 other experts on the mailing list.
18863 HOWEVER, some variables you have customized may contain private
18864 information. The names of customers, colleagues, or friends, might
18865 appear in the form of file names, tags, todo states, or search strings.
18866 If you answer yes to the prompt, you might want to check and remove
18867 such private information before sending the email.")
18868 (add-text-properties (point-min) (point-max) '(face org-warning))
18869 (when (yes-or-no-p "Include your Org-mode configuration ")
18870 (mapatoms
18871 (lambda (v)
18872 (and (boundp v)
18873 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
18874 (or (and (symbol-value v)
18875 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
18876 (and
18877 (get v 'custom-type) (get v 'standard-value)
18878 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
18879 (push v list)))))
18880 (kill-buffer (get-buffer "*Warn about privacy*"))
18881 list))
18882 nil nil
18883 "Remember to cover the basics, that is, what you expected to happen and
18884 what in fact did happen. You don't know how to make a good report? See
18886 http://orgmode.org/manual/Feedback.html#Feedback
18888 Your bug report will be posted to the Org-mode mailing list.
18889 ------------------------------------------------------------------------")
18890 (save-excursion
18891 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
18892 (replace-match "\\1Bug: \\3 [\\2]")))))
18895 (defun org-install-agenda-files-menu ()
18896 (let ((bl (buffer-list)))
18897 (save-excursion
18898 (while bl
18899 (set-buffer (pop bl))
18900 (if (eq major-mode 'org-mode) (setq bl nil)))
18901 (when (eq major-mode 'org-mode)
18902 (easy-menu-change
18903 '("Org") "File List for Agenda"
18904 (append
18905 (list
18906 ["Edit File List" (org-edit-agenda-file-list) t]
18907 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
18908 ["Remove Current File from List" org-remove-file t]
18909 ["Cycle through agenda files" org-cycle-agenda-files t]
18910 ["Occur in all agenda files" org-occur-in-agenda-files t]
18911 "--")
18912 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
18914 ;;;; Documentation
18916 ;;;###autoload
18917 (defun org-require-autoloaded-modules ()
18918 (interactive)
18919 (mapc 'require
18920 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
18921 org-docbook org-exp org-html org-icalendar
18922 org-id org-latex
18923 org-publish org-remember org-table
18924 org-timer org-xoxo)))
18926 ;;;###autoload
18927 (defun org-reload (&optional uncompiled)
18928 "Reload all org lisp files.
18929 With prefix arg UNCOMPILED, load the uncompiled versions."
18930 (interactive "P")
18931 (require 'find-func)
18932 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
18933 (dir-org (file-name-directory (org-find-library-name "org")))
18934 (dir-org-contrib (ignore-errors
18935 (file-name-directory
18936 (org-find-library-name "org-contribdir"))))
18937 (babel-files
18938 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
18939 (append (list nil "comint" "eval" "exp" "keys"
18940 "lob" "ref" "table" "tangle")
18941 (delq nil
18942 (mapcar
18943 (lambda (lang)
18944 (when (cdr lang) (symbol-name (car lang))))
18945 org-babel-load-languages)))))
18946 (files
18947 (append (directory-files dir-org t file-re)
18948 babel-files
18949 (and dir-org-contrib
18950 (directory-files dir-org-contrib t file-re))))
18951 (remove-re (concat (if (featurep 'xemacs)
18952 "org-colview" "org-colview-xemacs")
18953 "\\'")))
18954 (setq files (mapcar 'file-name-sans-extension files))
18955 (setq files (mapcar
18956 (lambda (x) (if (string-match remove-re x) nil x))
18957 files))
18958 (setq files (delq nil files))
18959 (mapc
18960 (lambda (f)
18961 (when (featurep (intern (file-name-nondirectory f)))
18962 (if (and (not uncompiled)
18963 (file-exists-p (concat f ".elc")))
18964 (load (concat f ".elc") nil nil t)
18965 (load (concat f ".el") nil nil t))))
18966 files))
18967 (org-version))
18969 ;;;###autoload
18970 (defun org-customize ()
18971 "Call the customize function with org as argument."
18972 (interactive)
18973 (org-load-modules-maybe)
18974 (org-require-autoloaded-modules)
18975 (customize-browse 'org))
18977 (defun org-create-customize-menu ()
18978 "Create a full customization menu for Org-mode, insert it into the menu."
18979 (interactive)
18980 (org-load-modules-maybe)
18981 (org-require-autoloaded-modules)
18982 (if (fboundp 'customize-menu-create)
18983 (progn
18984 (easy-menu-change
18985 '("Org") "Customize"
18986 `(["Browse Org group" org-customize t]
18987 "--"
18988 ,(customize-menu-create 'org)
18989 ["Set" Custom-set t]
18990 ["Save" Custom-save t]
18991 ["Reset to Current" Custom-reset-current t]
18992 ["Reset to Saved" Custom-reset-saved t]
18993 ["Reset to Standard Settings" Custom-reset-standard t]))
18994 (message "\"Org\"-menu now contains full customization menu"))
18995 (error "Cannot expand menu (outdated version of cus-edit.el)")))
18997 ;;;; Miscellaneous stuff
18999 ;;; Generally useful functions
19001 (defun org-get-at-bol (property)
19002 "Get text property PROPERTY at beginning of line."
19003 (get-text-property (point-at-bol) property))
19005 (defun org-find-text-property-in-string (prop s)
19006 "Return the first non-nil value of property PROP in string S."
19007 (or (get-text-property 0 prop s)
19008 (get-text-property (or (next-single-property-change 0 prop s) 0)
19009 prop s)))
19011 (defun org-display-warning (message) ;; Copied from Emacs-Muse
19012 "Display the given MESSAGE as a warning."
19013 (if (fboundp 'display-warning)
19014 (display-warning 'org message
19015 (if (featurep 'xemacs) 'warning :warning))
19016 (let ((buf (get-buffer-create "*Org warnings*")))
19017 (with-current-buffer buf
19018 (goto-char (point-max))
19019 (insert "Warning (Org): " message)
19020 (unless (bolp)
19021 (newline)))
19022 (display-buffer buf)
19023 (sit-for 0))))
19025 (defun org-eval (form)
19026 "Eval FORM and return result."
19027 (condition-case error
19028 (eval form)
19029 (error (format "%%![Error: %s]" error))))
19031 (defun org-in-commented-line ()
19032 "Is point in a line starting with `#'?"
19033 (equal (char-after (point-at-bol)) ?#))
19035 (defun org-in-indented-comment-line ()
19036 "Is point in a line starting with `#' after some white space?"
19037 (save-excursion
19038 (save-match-data
19039 (goto-char (point-at-bol))
19040 (looking-at "[ \t]*#"))))
19042 (defun org-in-verbatim-emphasis ()
19043 (save-match-data
19044 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
19046 (defun org-goto-marker-or-bmk (marker &optional bookmark)
19047 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
19048 (if (and marker (marker-buffer marker)
19049 (buffer-live-p (marker-buffer marker)))
19050 (progn
19051 (org-pop-to-buffer-same-window (marker-buffer marker))
19052 (if (or (> marker (point-max)) (< marker (point-min)))
19053 (widen))
19054 (goto-char marker)
19055 (org-show-context 'org-goto))
19056 (if bookmark
19057 (bookmark-jump bookmark)
19058 (error "Cannot find location"))))
19060 (defun org-quote-csv-field (s)
19061 "Quote field for inclusion in CSV material."
19062 (if (string-match "[\",]" s)
19063 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
19066 (defun org-force-self-insert (N)
19067 "Needed to enforce self-insert under remapping."
19068 (interactive "p")
19069 (self-insert-command N))
19071 (defun org-string-width (s)
19072 "Compute width of string, ignoring invisible characters.
19073 This ignores character with invisibility property `org-link', and also
19074 characters with property `org-cwidth', because these will become invisible
19075 upon the next fontification round."
19076 (let (b l)
19077 (when (or (eq t buffer-invisibility-spec)
19078 (assq 'org-link buffer-invisibility-spec))
19079 (while (setq b (text-property-any 0 (length s)
19080 'invisible 'org-link s))
19081 (setq s (concat (substring s 0 b)
19082 (substring s (or (next-single-property-change
19083 b 'invisible s) (length s)))))))
19084 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
19085 (setq s (concat (substring s 0 b)
19086 (substring s (or (next-single-property-change
19087 b 'org-cwidth s) (length s))))))
19088 (setq l (string-width s) b -1)
19089 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
19090 (setq l (- l (get-text-property b 'org-dwidth-n s))))
19093 (defun org-shorten-string (s maxlength)
19094 "Shorten string S so tht it is no longer than MAXLENGTH characters.
19095 If the string is shorter or has length MAXLENGTH, just return the
19096 original string. If it is longer, the functions finds a space in the
19097 string, breaks this string off at that locations and adds three dots
19098 as ellipsis. Including the ellipsis, the string will not be longer
19099 than MAXLENGTH. If finding a good breaking point in the string does
19100 not work, the string is just chopped off in the middle of a word
19101 if necessary."
19102 (if (<= (length s) maxlength)
19104 (let* ((n (max (- maxlength 4) 1))
19105 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
19106 (if (string-match re s)
19107 (concat (match-string 1 s) "...")
19108 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
19110 (defun org-get-indentation (&optional line)
19111 "Get the indentation of the current line, interpreting tabs.
19112 When LINE is given, assume it represents a line and compute its indentation."
19113 (if line
19114 (if (string-match "^ *" (org-remove-tabs line))
19115 (match-end 0))
19116 (save-excursion
19117 (beginning-of-line 1)
19118 (skip-chars-forward " \t")
19119 (current-column))))
19121 (defun org-get-string-indentation (s)
19122 "What indentation has S due to SPACE and TAB at the beginning of the string?"
19123 (let ((n -1) (i 0) (w tab-width) c)
19124 (catch 'exit
19125 (while (< (setq n (1+ n)) (length s))
19126 (setq c (aref s n))
19127 (cond ((= c ?\ ) (setq i (1+ i)))
19128 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
19129 (t (throw 'exit t)))))
19132 (defun org-remove-tabs (s &optional width)
19133 "Replace tabulators in S with spaces.
19134 Assumes that s is a single line, starting in column 0."
19135 (setq width (or width tab-width))
19136 (while (string-match "\t" s)
19137 (setq s (replace-match
19138 (make-string
19139 (- (* width (/ (+ (match-beginning 0) width) width))
19140 (match-beginning 0)) ?\ )
19141 t t s)))
19144 (defun org-fix-indentation (line ind)
19145 "Fix indentation in LINE.
19146 IND is a cons cell with target and minimum indentation.
19147 If the current indentation in LINE is smaller than the minimum,
19148 leave it alone. If it is larger than ind, set it to the target."
19149 (let* ((l (org-remove-tabs line))
19150 (i (org-get-indentation l))
19151 (i1 (car ind)) (i2 (cdr ind)))
19152 (if (>= i i2) (setq l (substring line i2)))
19153 (if (> i1 0)
19154 (concat (make-string i1 ?\ ) l)
19155 l)))
19157 (defun org-remove-indentation (code &optional n)
19158 "Remove the maximum common indentation from the lines in CODE.
19159 N may optionally be the number of spaces to remove."
19160 (with-temp-buffer
19161 (insert code)
19162 (org-do-remove-indentation n)
19163 (buffer-string)))
19165 (defun org-do-remove-indentation (&optional n)
19166 "Remove the maximum common indentation from the buffer."
19167 (untabify (point-min) (point-max))
19168 (let ((min 10000) re)
19169 (if n
19170 (setq min n)
19171 (goto-char (point-min))
19172 (while (re-search-forward "^ *[^ \n]" nil t)
19173 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
19174 (unless (or (= min 0) (= min 10000))
19175 (setq re (format "^ \\{%d\\}" min))
19176 (goto-char (point-min))
19177 (while (re-search-forward re nil t)
19178 (replace-match "")
19179 (end-of-line 1))
19180 min)))
19182 (defun org-fill-template (template alist)
19183 "Find each %key of ALIST in TEMPLATE and replace it."
19184 (let ((case-fold-search nil)
19185 entry key value)
19186 (setq alist (sort (copy-sequence alist)
19187 (lambda (a b) (< (length (car a)) (length (car b))))))
19188 (while (setq entry (pop alist))
19189 (setq template
19190 (replace-regexp-in-string
19191 (concat "%" (regexp-quote (car entry)))
19192 (cdr entry) template t t)))
19193 template))
19195 (defun org-base-buffer (buffer)
19196 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
19197 (if (not buffer)
19198 buffer
19199 (or (buffer-base-buffer buffer)
19200 buffer)))
19202 (defun org-trim (s)
19203 "Remove whitespace at beginning and end of string."
19204 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
19205 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
19208 (defun org-wrap (string &optional width lines)
19209 "Wrap string to either a number of lines, or a width in characters.
19210 If WIDTH is non-nil, the string is wrapped to that width, however many lines
19211 that costs. If there is a word longer than WIDTH, the text is actually
19212 wrapped to the length of that word.
19213 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
19214 many lines, whatever width that takes.
19215 The return value is a list of lines, without newlines at the end."
19216 (let* ((words (org-split-string string "[ \t\n]+"))
19217 (maxword (apply 'max (mapcar 'org-string-width words)))
19218 w ll)
19219 (cond (width
19220 (org-do-wrap words (max maxword width)))
19221 (lines
19222 (setq w maxword)
19223 (setq ll (org-do-wrap words maxword))
19224 (if (<= (length ll) lines)
19226 (setq ll words)
19227 (while (> (length ll) lines)
19228 (setq w (1+ w))
19229 (setq ll (org-do-wrap words w)))
19230 ll))
19231 (t (error "Cannot wrap this")))))
19233 (defun org-do-wrap (words width)
19234 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19235 (let (lines line)
19236 (while words
19237 (setq line (pop words))
19238 (while (and words (< (+ (length line) (length (car words))) width))
19239 (setq line (concat line " " (pop words))))
19240 (setq lines (push line lines)))
19241 (nreverse lines)))
19243 (defun org-split-string (string &optional separators)
19244 "Splits STRING into substrings at SEPARATORS.
19245 No empty strings are returned if there are matches at the beginning
19246 and end of string."
19247 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19248 (start 0)
19249 notfirst
19250 (list nil))
19251 (while (and (string-match rexp string
19252 (if (and notfirst
19253 (= start (match-beginning 0))
19254 (< start (length string)))
19255 (1+ start) start))
19256 (< (match-beginning 0) (length string)))
19257 (setq notfirst t)
19258 (or (eq (match-beginning 0) 0)
19259 (and (eq (match-beginning 0) (match-end 0))
19260 (eq (match-beginning 0) start))
19261 (setq list
19262 (cons (substring string start (match-beginning 0))
19263 list)))
19264 (setq start (match-end 0)))
19265 (or (eq start (length string))
19266 (setq list
19267 (cons (substring string start)
19268 list)))
19269 (nreverse list)))
19271 (defun org-quote-vert (s)
19272 "Replace \"|\" with \"\\vert\"."
19273 (while (string-match "|" s)
19274 (setq s (replace-match "\\vert" t t s)))
19277 (defun org-uuidgen-p (s)
19278 "Is S an ID created by UUIDGEN?"
19279 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19281 (defun org-context ()
19282 "Return a list of contexts of the current cursor position.
19283 If several contexts apply, all are returned.
19284 Each context entry is a list with a symbol naming the context, and
19285 two positions indicating start and end of the context. Possible
19286 contexts are:
19288 :headline anywhere in a headline
19289 :headline-stars on the leading stars in a headline
19290 :todo-keyword on a TODO keyword (including DONE) in a headline
19291 :tags on the TAGS in a headline
19292 :priority on the priority cookie in a headline
19293 :item on the first line of a plain list item
19294 :item-bullet on the bullet/number of a plain list item
19295 :checkbox on the checkbox in a plain list item
19296 :table in an org-mode table
19297 :table-special on a special filed in a table
19298 :table-table in a table.el table
19299 :link on a hyperlink
19300 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
19301 :target on a <<target>>
19302 :radio-target on a <<<radio-target>>>
19303 :latex-fragment on a LaTeX fragment
19304 :latex-preview on a LaTeX fragment with overlayed preview image
19306 This function expects the position to be visible because it uses font-lock
19307 faces as a help to recognize the following contexts: :table-special, :link,
19308 and :keyword."
19309 (let* ((f (get-text-property (point) 'face))
19310 (faces (if (listp f) f (list f)))
19311 (p (point)) clist o)
19312 ;; First the large context
19313 (cond
19314 ((org-on-heading-p t)
19315 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19316 (when (progn
19317 (beginning-of-line 1)
19318 (looking-at org-todo-line-tags-regexp))
19319 (push (org-point-in-group p 1 :headline-stars) clist)
19320 (push (org-point-in-group p 2 :todo-keyword) clist)
19321 (push (org-point-in-group p 4 :tags) clist))
19322 (goto-char p)
19323 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19324 (if (looking-at "\\[#[A-Z0-9]\\]")
19325 (push (org-point-in-group p 0 :priority) clist)))
19327 ((org-at-item-p)
19328 (push (org-point-in-group p 2 :item-bullet) clist)
19329 (push (list :item (point-at-bol)
19330 (save-excursion (org-end-of-item) (point)))
19331 clist)
19332 (and (org-at-item-checkbox-p)
19333 (push (org-point-in-group p 0 :checkbox) clist)))
19335 ((org-at-table-p)
19336 (push (list :table (org-table-begin) (org-table-end)) clist)
19337 (if (memq 'org-formula faces)
19338 (push (list :table-special
19339 (previous-single-property-change p 'face)
19340 (next-single-property-change p 'face)) clist)))
19341 ((org-at-table-p 'any)
19342 (push (list :table-table) clist)))
19343 (goto-char p)
19345 ;; Now the small context
19346 (cond
19347 ((org-at-timestamp-p)
19348 (push (org-point-in-group p 0 :timestamp) clist))
19349 ((memq 'org-link faces)
19350 (push (list :link
19351 (previous-single-property-change p 'face)
19352 (next-single-property-change p 'face)) clist))
19353 ((memq 'org-special-keyword faces)
19354 (push (list :keyword
19355 (previous-single-property-change p 'face)
19356 (next-single-property-change p 'face)) clist))
19357 ((org-on-target-p)
19358 (push (org-point-in-group p 0 :target) clist)
19359 (goto-char (1- (match-beginning 0)))
19360 (if (looking-at org-radio-target-regexp)
19361 (push (org-point-in-group p 0 :radio-target) clist))
19362 (goto-char p))
19363 ((setq o (car (delq nil
19364 (mapcar
19365 (lambda (x)
19366 (if (memq x org-latex-fragment-image-overlays) x))
19367 (overlays-at (point))))))
19368 (push (list :latex-fragment
19369 (overlay-start o) (overlay-end o)) clist)
19370 (push (list :latex-preview
19371 (overlay-start o) (overlay-end o)) clist))
19372 ((org-inside-LaTeX-fragment-p)
19373 ;; FIXME: positions wrong.
19374 (push (list :latex-fragment (point) (point)) clist)))
19376 (setq clist (nreverse (delq nil clist)))
19377 clist))
19379 ;; FIXME: Compare with at-regexp-p Do we need both?
19380 (defun org-in-regexp (re &optional nlines visually)
19381 "Check if point is inside a match of regexp.
19382 Normally only the current line is checked, but you can include NLINES extra
19383 lines both before and after point into the search.
19384 If VISUALLY is set, require that the cursor is not after the match but
19385 really on, so that the block visually is on the match."
19386 (catch 'exit
19387 (let ((pos (point))
19388 (eol (point-at-eol (+ 1 (or nlines 0))))
19389 (inc (if visually 1 0)))
19390 (save-excursion
19391 (beginning-of-line (- 1 (or nlines 0)))
19392 (while (re-search-forward re eol t)
19393 (if (and (<= (match-beginning 0) pos)
19394 (>= (+ inc (match-end 0)) pos))
19395 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
19397 (defun org-at-regexp-p (regexp)
19398 "Is point inside a match of REGEXP in the current line?"
19399 (catch 'exit
19400 (save-excursion
19401 (let ((pos (point)) (end (point-at-eol)))
19402 (beginning-of-line 1)
19403 (while (re-search-forward regexp end t)
19404 (if (and (<= (match-beginning 0) pos)
19405 (>= (match-end 0) pos))
19406 (throw 'exit t)))
19407 nil))))
19409 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
19410 "Non-nil when point is between matches of START-RE and END-RE.
19412 Also return a non-nil value when point is on one of the matches.
19414 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
19415 buffer positions. Default values are the positions of headlines
19416 surrounding the point.
19418 The functions returns a cons cell whose car (resp. cdr) is the
19419 position before START-RE (resp. after END-RE)."
19420 (save-match-data
19421 (let ((pos (point))
19422 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
19423 (limit-down (or lim-down (save-excursion (outline-next-heading))))
19424 beg end)
19425 (save-excursion
19426 ;; Point is on a block when on START-RE or if START-RE can be
19427 ;; found before it...
19428 (and (or (org-at-regexp-p start-re)
19429 (re-search-backward start-re limit-up t))
19430 (setq beg (match-beginning 0))
19431 ;; ... and END-RE after it...
19432 (goto-char (match-end 0))
19433 (re-search-forward end-re limit-down t)
19434 (> (setq end (match-end 0)) pos)
19435 ;; ... without another START-RE in-between.
19436 (goto-char (match-beginning 0))
19437 (not (re-search-backward start-re (1+ beg) t))
19438 ;; Return value.
19439 (cons beg end))))))
19441 (defun org-in-block-p (names)
19442 "Non-nil when point belongs to a block whose name belongs to NAMES.
19444 NAMES is a list of strings containing names of blocks.
19446 Return first block name matched, or nil. Beware that in case of
19447 nested blocks, the returned name may not belong to the closest
19448 block from point."
19449 (save-match-data
19450 (catch 'exit
19451 (let ((case-fold-search t)
19452 (lim-up (save-excursion (outline-previous-heading)))
19453 (lim-down (save-excursion (outline-next-heading))))
19454 (mapc (lambda (name)
19455 (let ((n (regexp-quote name)))
19456 (when (org-between-regexps-p
19457 (concat "^[ \t]*#\\+begin_" n)
19458 (concat "^[ \t]*#\\+end_" n)
19459 lim-up lim-down)
19460 (throw 'exit n))))
19461 names))
19462 nil)))
19464 (defun org-occur-in-agenda-files (regexp &optional nlines)
19465 "Call `multi-occur' with buffers for all agenda files."
19466 (interactive "sOrg-files matching: \np")
19467 (let* ((files (org-agenda-files))
19468 (tnames (mapcar 'file-truename files))
19469 (extra org-agenda-text-search-extra-files)
19471 (when (eq (car extra) 'agenda-archives)
19472 (setq extra (cdr extra))
19473 (setq files (org-add-archive-files files)))
19474 (while (setq f (pop extra))
19475 (unless (member (file-truename f) tnames)
19476 (add-to-list 'files f 'append)
19477 (add-to-list 'tnames (file-truename f) 'append)))
19478 (multi-occur
19479 (mapcar (lambda (x)
19480 (with-current-buffer
19481 (or (get-file-buffer x) (find-file-noselect x))
19482 (widen)
19483 (current-buffer)))
19484 files)
19485 regexp)))
19487 (if (boundp 'occur-mode-find-occurrence-hook)
19488 ;; Emacs 23
19489 (add-hook 'occur-mode-find-occurrence-hook
19490 (lambda ()
19491 (when (eq major-mode 'org-mode)
19492 (org-reveal))))
19493 ;; Emacs 22
19494 (defadvice occur-mode-goto-occurrence
19495 (after org-occur-reveal activate)
19496 (and (eq major-mode 'org-mode) (org-reveal)))
19497 (defadvice occur-mode-goto-occurrence-other-window
19498 (after org-occur-reveal activate)
19499 (and (eq major-mode 'org-mode) (org-reveal)))
19500 (defadvice occur-mode-display-occurrence
19501 (after org-occur-reveal activate)
19502 (when (eq major-mode 'org-mode)
19503 (let ((pos (occur-mode-find-occurrence)))
19504 (with-current-buffer (marker-buffer pos)
19505 (save-excursion
19506 (goto-char pos)
19507 (org-reveal)))))))
19509 (defun org-occur-link-in-agenda-files ()
19510 "Create a link and search for it in the agendas.
19511 The link is not stored in `org-stored-links', it is just created
19512 for the search purpose."
19513 (interactive)
19514 (let ((link (condition-case nil
19515 (org-store-link nil)
19516 (error "Unable to create a link to here"))))
19517 (org-occur-in-agenda-files (regexp-quote link))))
19519 (defun org-uniquify (list)
19520 "Remove duplicate elements from LIST."
19521 (let (res)
19522 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
19523 res))
19525 (defun org-delete-all (elts list)
19526 "Remove all elements in ELTS from LIST."
19527 (while elts
19528 (setq list (delete (pop elts) list)))
19529 list)
19531 (defun org-count (cl-item cl-seq)
19532 "Count the number of occurrences of ITEM in SEQ.
19533 Taken from `count' in cl-seq.el with all keyword arguments removed."
19534 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
19535 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
19536 (while (< cl-start cl-end)
19537 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
19538 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
19539 (setq cl-start (1+ cl-start)))
19540 cl-count))
19542 (defun org-remove-if (predicate seq)
19543 "Remove everything from SEQ that fulfills PREDICATE."
19544 (let (res e)
19545 (while seq
19546 (setq e (pop seq))
19547 (if (not (funcall predicate e)) (push e res)))
19548 (nreverse res)))
19550 (defun org-remove-if-not (predicate seq)
19551 "Remove everything from SEQ that does not fulfill PREDICATE."
19552 (let (res e)
19553 (while seq
19554 (setq e (pop seq))
19555 (if (funcall predicate e) (push e res)))
19556 (nreverse res)))
19558 (defun org-back-over-empty-lines ()
19559 "Move backwards over whitespace, to the beginning of the first empty line.
19560 Returns the number of empty lines passed."
19561 (let ((pos (point)))
19562 (if (cdr (assoc 'heading org-blank-before-new-entry))
19563 (skip-chars-backward " \t\n\r")
19564 (unless (eobp)
19565 (forward-line -1)))
19566 (beginning-of-line 2)
19567 (goto-char (min (point) pos))
19568 (count-lines (point) pos)))
19570 (defun org-skip-whitespace ()
19571 (skip-chars-forward " \t\n\r"))
19573 (defun org-point-in-group (point group &optional context)
19574 "Check if POINT is in match-group GROUP.
19575 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
19576 match. If the match group does not exist or point is not inside it,
19577 return nil."
19578 (and (match-beginning group)
19579 (>= point (match-beginning group))
19580 (<= point (match-end group))
19581 (if context
19582 (list context (match-beginning group) (match-end group))
19583 t)))
19585 (defun org-switch-to-buffer-other-window (&rest args)
19586 "Switch to buffer in a second window on the current frame.
19587 In particular, do not allow pop-up frames.
19588 Returns the newly created buffer."
19589 (let (pop-up-frames special-display-buffer-names special-display-regexps
19590 special-display-function)
19591 (apply 'switch-to-buffer-other-window args)))
19593 (defun org-combine-plists (&rest plists)
19594 "Create a single property list from all plists in PLISTS.
19595 The process starts by copying the first list, and then setting properties
19596 from the other lists. Settings in the last list are the most significant
19597 ones and overrule settings in the other lists."
19598 (let ((rtn (copy-sequence (pop plists)))
19599 p v ls)
19600 (while plists
19601 (setq ls (pop plists))
19602 (while ls
19603 (setq p (pop ls) v (pop ls))
19604 (setq rtn (plist-put rtn p v))))
19605 rtn))
19607 (defun org-move-line-down (arg)
19608 "Move the current line down. With prefix argument, move it past ARG lines."
19609 (interactive "p")
19610 (let ((col (current-column))
19611 beg end pos)
19612 (beginning-of-line 1) (setq beg (point))
19613 (beginning-of-line 2) (setq end (point))
19614 (beginning-of-line (+ 1 arg))
19615 (setq pos (move-marker (make-marker) (point)))
19616 (insert (delete-and-extract-region beg end))
19617 (goto-char pos)
19618 (org-move-to-column col)))
19620 (defun org-move-line-up (arg)
19621 "Move the current line up. With prefix argument, move it past ARG lines."
19622 (interactive "p")
19623 (let ((col (current-column))
19624 beg end pos)
19625 (beginning-of-line 1) (setq beg (point))
19626 (beginning-of-line 2) (setq end (point))
19627 (beginning-of-line (- arg))
19628 (setq pos (move-marker (make-marker) (point)))
19629 (insert (delete-and-extract-region beg end))
19630 (goto-char pos)
19631 (org-move-to-column col)))
19633 (defun org-replace-escapes (string table)
19634 "Replace %-escapes in STRING with values in TABLE.
19635 TABLE is an association list with keys like \"%a\" and string values.
19636 The sequences in STRING may contain normal field width and padding information,
19637 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
19638 so values can contain further %-escapes if they are define later in TABLE."
19639 (let ((tbl (copy-alist table))
19640 (case-fold-search nil)
19641 (pchg 0)
19642 e re rpl)
19643 (while (setq e (pop tbl))
19644 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
19645 (when (and (cdr e) (string-match re (cdr e)))
19646 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
19647 (safe "SREF"))
19648 (add-text-properties 0 3 (list 'sref sref) safe)
19649 (setcdr e (replace-match safe t t (cdr e)))))
19650 (while (string-match re string)
19651 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
19652 (cdr e)))
19653 (setq string (replace-match rpl t t string))))
19654 (while (setq pchg (next-property-change pchg string))
19655 (let ((sref (get-text-property pchg 'sref string)))
19656 (when (and sref (string-match "SREF" string pchg))
19657 (setq string (replace-match sref t t string)))))
19658 string))
19660 (defun org-sublist (list start end)
19661 "Return a section of LIST, from START to END.
19662 Counting starts at 1."
19663 (let (rtn (c start))
19664 (setq list (nthcdr (1- start) list))
19665 (while (and list (<= c end))
19666 (push (pop list) rtn)
19667 (setq c (1+ c)))
19668 (nreverse rtn)))
19670 (defun org-find-base-buffer-visiting (file)
19671 "Like `find-buffer-visiting' but always return the base buffer and
19672 not an indirect buffer."
19673 (let ((buf (or (get-file-buffer file)
19674 (find-buffer-visiting file))))
19675 (if buf
19676 (or (buffer-base-buffer buf) buf)
19677 nil)))
19679 (defun org-image-file-name-regexp (&optional extensions)
19680 "Return regexp matching the file names of images.
19681 If EXTENSIONS is given, only match these."
19682 (if (and (not extensions) (fboundp 'image-file-name-regexp))
19683 (image-file-name-regexp)
19684 (let ((image-file-name-extensions
19685 (or extensions
19686 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
19687 "xbm" "xpm" "pbm" "pgm" "ppm"))))
19688 (concat "\\."
19689 (regexp-opt (nconc (mapcar 'upcase
19690 image-file-name-extensions)
19691 image-file-name-extensions)
19693 "\\'"))))
19695 (defun org-file-image-p (file &optional extensions)
19696 "Return non-nil if FILE is an image."
19697 (save-match-data
19698 (string-match (org-image-file-name-regexp extensions) file)))
19700 (defun org-get-cursor-date ()
19701 "Return the date at cursor in as a time.
19702 This works in the calendar and in the agenda, anywhere else it just
19703 returns the current time."
19704 (let (date day defd)
19705 (cond
19706 ((eq major-mode 'calendar-mode)
19707 (setq date (calendar-cursor-to-date)
19708 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
19709 ((eq major-mode 'org-agenda-mode)
19710 (setq day (get-text-property (point) 'day))
19711 (if day
19712 (setq date (calendar-gregorian-from-absolute day)
19713 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
19714 (nth 2 date))))))
19715 (or defd (current-time))))
19717 (defvar org-agenda-action-marker (make-marker)
19718 "Marker pointing to the entry for the next agenda action.")
19720 (defun org-mark-entry-for-agenda-action ()
19721 "Mark the current entry as target of an agenda action.
19722 Agenda actions are actions executed from the agenda with the key `k',
19723 which make use of the date at the cursor."
19724 (interactive)
19725 (move-marker org-agenda-action-marker
19726 (save-excursion (org-back-to-heading t) (point))
19727 (current-buffer))
19728 (message
19729 "Entry marked for action; press `k' at desired date in agenda or calendar"))
19731 (defun org-mark-subtree ()
19732 "Mark the current subtree.
19733 This puts point at the start of the current subtree, and mark at the end.
19735 If point is in an inline task, mark that task instead."
19736 (interactive)
19737 (let ((inline-task-p
19738 (and (featurep 'org-inlinetask)
19739 (org-inlinetask-in-task-p)))
19740 (beg))
19741 ;; Get beginning of subtree
19742 (cond
19743 (inline-task-p (org-inlinetask-goto-beginning))
19744 ((org-at-heading-p) (beginning-of-line))
19745 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
19746 (setq beg (point))
19747 ;; Get end of it
19748 (if inline-task-p
19749 (org-inlinetask-goto-end)
19750 (org-end-of-subtree))
19751 ;; Mark zone
19752 (push-mark (point) nil t)
19753 (goto-char beg)))
19755 ;;; Paragraph filling stuff.
19756 ;; We want this to be just right, so use the full arsenal.
19758 (defun org-indent-line-function ()
19759 "Indent line depending on context."
19760 (interactive)
19761 (let* ((pos (point))
19762 (itemp (org-at-item-p))
19763 (case-fold-search t)
19764 (org-drawer-regexp (or org-drawer-regexp "\000"))
19765 (inline-task-p (and (featurep 'org-inlinetask)
19766 (org-inlinetask-in-task-p)))
19767 (inline-re (and inline-task-p
19768 (org-inlinetask-outline-regexp)))
19769 column)
19770 (beginning-of-line 1)
19771 (cond
19772 ;; Comments
19773 ((looking-at "# ") (setq column 0))
19774 ;; Headings
19775 ((looking-at org-outline-regexp) (setq column 0))
19776 ;; Included files
19777 ((looking-at "#\\+include:") (setq column 0))
19778 ;; Footnote definition
19779 ((looking-at org-footnote-definition-re) (setq column 0))
19780 ;; Literal examples
19781 ((looking-at "[ \t]*:\\( \\|$\\)")
19782 (setq column (org-get-indentation))) ; do nothing
19783 ;; Lists
19784 ((ignore-errors (goto-char (org-in-item-p)))
19785 (setq column (if itemp
19786 (org-get-indentation)
19787 (org-list-item-body-column (point))))
19788 (goto-char pos))
19789 ;; Drawers
19790 ((and (looking-at "[ \t]*:END:")
19791 (save-excursion (re-search-backward org-drawer-regexp nil t)))
19792 (save-excursion
19793 (goto-char (1- (match-beginning 1)))
19794 (setq column (current-column))))
19795 ;; Special blocks
19796 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
19797 (save-excursion
19798 (re-search-backward
19799 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
19800 (setq column (org-get-indentation (match-string 0))))
19801 ((and (not (looking-at "[ \t]*#\\+begin_"))
19802 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
19803 (save-excursion
19804 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
19805 (setq column
19806 (cond ((equal (downcase (match-string 1)) "src")
19807 ;; src blocks: let `org-edit-src-exit' handle them
19808 (org-get-indentation))
19809 ((equal (downcase (match-string 1)) "example")
19810 (max (org-get-indentation)
19811 (org-get-indentation (match-string 0))))
19813 (org-get-indentation (match-string 0))))))
19814 ;; This line has nothing special, look at the previous relevant
19815 ;; line to compute indentation
19817 (beginning-of-line 0)
19818 (while (and (not (bobp))
19819 (not (looking-at org-drawer-regexp))
19820 ;; When point started in an inline task, do not move
19821 ;; above task starting line.
19822 (not (and inline-task-p (looking-at inline-re)))
19823 ;; Skip drawers, blocks, empty lines, verbatim,
19824 ;; comments, tables, footnotes definitions, lists,
19825 ;; inline tasks.
19826 (or (and (looking-at "[ \t]*:END:")
19827 (re-search-backward org-drawer-regexp nil t))
19828 (and (looking-at "[ \t]*#\\+end_")
19829 (re-search-backward "[ \t]*#\\+begin_"nil t))
19830 (looking-at "[ \t]*[\n:#|]")
19831 (looking-at org-footnote-definition-re)
19832 (and (ignore-errors (goto-char (org-in-item-p)))
19833 (goto-char
19834 (org-list-get-top-point (org-list-struct))))
19835 (and (not inline-task-p)
19836 (featurep 'org-inlinetask)
19837 (org-inlinetask-in-task-p)
19838 (or (org-inlinetask-goto-beginning) t))))
19839 (beginning-of-line 0))
19840 (cond
19841 ;; There was an heading above.
19842 ((looking-at "\\*+[ \t]+")
19843 (if (not org-adapt-indentation)
19844 (setq column 0)
19845 (goto-char (match-end 0))
19846 (setq column (current-column))))
19847 ;; A drawer had started and is unfinished
19848 ((looking-at org-drawer-regexp)
19849 (goto-char (1- (match-beginning 1)))
19850 (setq column (current-column)))
19851 ;; Else, nothing noticeable found: get indentation and go on.
19852 (t (setq column (org-get-indentation))))))
19853 ;; Now apply indentation and move cursor accordingly
19854 (goto-char pos)
19855 (if (<= (current-column) (current-indentation))
19856 (org-indent-line-to column)
19857 (save-excursion (org-indent-line-to column)))
19858 ;; Special polishing for properties, see `org-property-format'
19859 (setq column (current-column))
19860 (beginning-of-line 1)
19861 (if (looking-at
19862 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
19863 (replace-match (concat (match-string 1)
19864 (format org-property-format
19865 (match-string 2) (match-string 3)))
19866 t t))
19867 (org-move-to-column column)))
19869 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
19870 "Variable to store copy of `adaptive-fill-regexp'.
19871 Since `adaptive-fill-regexp' is set to never match, we need to
19872 store a backup of its value before entering `org-mode' so that
19873 the functionality can be provided as a fall-back.")
19875 (defun org-set-autofill-regexps ()
19876 (interactive)
19877 ;; In the paragraph separator we include headlines, because filling
19878 ;; text in a line directly attached to a headline would otherwise
19879 ;; fill the headline as well.
19880 (org-set-local 'comment-start-skip "^#+[ \t]*")
19881 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
19882 ;; The paragraph starter includes hand-formatted lists.
19883 (org-set-local
19884 'paragraph-start
19885 (concat
19886 "\f" "\\|"
19887 "[ ]*$" "\\|"
19888 org-outline-regexp "\\|"
19889 "[ \t]*#" "\\|"
19890 (org-item-re) "\\|"
19891 "[ \t]*[:|]" "\\|"
19892 "\\$\\$" "\\|"
19893 "\\\\\\(begin\\|end\\|[][]\\)"))
19894 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
19895 ;; But only if the user has not turned off tables or fixed-width regions
19896 (org-set-local
19897 'auto-fill-inhibit-regexp
19898 (concat org-outline-regexp
19899 "\\|#\\+"
19900 "\\|[ \t]*" org-keyword-time-regexp
19901 (if (or org-enable-table-editor org-enable-fixed-width-editor)
19902 (concat
19903 "\\|[ \t]*["
19904 (if org-enable-table-editor "|" "")
19905 (if org-enable-fixed-width-editor ":" "")
19906 "]"))))
19907 ;; We use our own fill-paragraph function, to make sure that tables
19908 ;; and fixed-width regions are not wrapped. That function will pass
19909 ;; through to `fill-paragraph' when appropriate.
19910 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
19911 ;; Prevent auto-fill from inserting unwanted new items.
19912 (if (boundp 'fill-nobreak-predicate)
19913 (org-set-local 'fill-nobreak-predicate
19914 (if (memq 'org-fill-item-nobreak-p fill-nobreak-predicate)
19915 fill-nobreak-predicate
19916 (cons 'org-fill-item-nobreak-p fill-nobreak-predicate))))
19917 ;; Adaptive filling: To get full control, first make sure that
19918 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
19919 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
19920 (org-set-local 'org-adaptive-fill-regexp-backup
19921 adaptive-fill-regexp))
19922 (org-set-local 'adaptive-fill-regexp "\000")
19923 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
19924 (org-set-local 'adaptive-fill-function
19925 'org-adaptive-fill-function)
19926 (org-set-local
19927 'align-mode-rules-list
19928 '((org-in-buffer-settings
19929 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
19930 (modes . '(org-mode))))))
19932 (defun org-fill-item-nobreak-p ()
19933 "Non-nil when a line break at point would insert a new item."
19934 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
19936 (defun org-fill-paragraph (&optional justify)
19937 "Re-align a table, pass through to fill-paragraph if no table."
19938 (let ((table-p (org-at-table-p))
19939 (table.el-p (org-at-table.el-p))
19940 (itemp (org-in-item-p)))
19941 (cond ((and (equal (char-after (point-at-bol)) ?*)
19942 (save-excursion (goto-char (point-at-bol))
19943 (looking-at org-outline-regexp)))
19944 t) ; skip headlines
19945 (table.el-p t) ; skip table.el tables
19946 (table-p (org-table-align) t) ; align Org tables
19947 (itemp ; align text in items
19948 (let* ((struct (save-excursion (goto-char itemp)
19949 (org-list-struct)))
19950 (parents (org-list-parents-alist struct))
19951 (children (org-list-get-children itemp struct parents))
19952 beg end prev next prefix)
19953 ;; Determine in which part of item point is: before
19954 ;; first child, after last child, between two
19955 ;; sub-lists, or simply in item if there's no child.
19956 (cond
19957 ((not children)
19958 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19959 beg itemp
19960 end (org-list-get-item-end itemp struct)))
19961 ((< (point) (setq next (car children)))
19962 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19963 beg itemp
19964 end next))
19965 ((> (point) (setq prev (car (last children))))
19966 (setq beg (org-list-get-item-end prev struct)
19967 end (org-list-get-item-end itemp struct)
19968 prefix (save-excursion
19969 (goto-char beg)
19970 (skip-chars-forward " \t")
19971 (make-string (current-column) ?\ ))))
19972 (t (catch 'exit
19973 (while (setq next (pop children))
19974 (if (> (point) next)
19975 (setq prev next)
19976 (setq beg (org-list-get-item-end prev struct)
19977 end next
19978 prefix (save-excursion
19979 (goto-char beg)
19980 (skip-chars-forward " \t")
19981 (make-string (current-column) ?\ )))
19982 (throw 'exit nil))))))
19983 ;; Use `fill-paragraph' with buffer narrowed to item
19984 ;; without any child, and with our computed PREFIX.
19985 (flet ((fill-context-prefix (from to &optional flr) prefix))
19986 (save-restriction
19987 (narrow-to-region beg end)
19988 (save-excursion (fill-paragraph justify)))) t))
19989 ;; Special case where point is not in a list but is on
19990 ;; a paragraph adjacent to a list: make sure this paragraph
19991 ;; doesn't get merged with the end of the list by narrowing
19992 ;; buffer first.
19993 ((save-excursion (forward-paragraph -1)
19994 (setq itemp (org-in-item-p)))
19995 (let ((struct (save-excursion (goto-char itemp)
19996 (org-list-struct))))
19997 (save-restriction
19998 (narrow-to-region (org-list-get-bottom-point struct)
19999 (save-excursion (forward-paragraph 1)
20000 (point)))
20001 (fill-paragraph justify) t)))
20002 ;; Else simply call `fill-paragraph'.
20003 (t nil))))
20005 ;; For reference, this is the default value of adaptive-fill-regexp
20006 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20008 (defun org-adaptive-fill-function ()
20009 "Return a fill prefix for org-mode files."
20010 (let (itemp)
20011 (save-excursion
20012 (cond
20013 ;; Comment line
20014 ((looking-at "#[ \t]+")
20015 (match-string-no-properties 0))
20016 ;; Plain list item
20017 ((org-at-item-p)
20018 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
20019 ;; Point is in a list after `backward-paragraph': original
20020 ;; point wasn't in the list, or filling would have been taken
20021 ;; care of by `org-auto-fill-function', but the list and the
20022 ;; real paragraph are not separated by a blank line. Thus, move
20023 ;; point after the list to go back to real paragraph and
20024 ;; determine fill-prefix.
20025 ((setq itemp (org-in-item-p))
20026 (goto-char itemp)
20027 (let* ((struct (org-list-struct))
20028 (bottom (org-list-get-bottom-point struct)))
20029 (goto-char bottom)
20030 (make-string (org-get-indentation) ?\ )))
20031 ;; Other text
20032 ((looking-at org-adaptive-fill-regexp-backup)
20033 (match-string-no-properties 0))))))
20035 (defun org-auto-fill-function ()
20036 "Auto-fill function."
20037 (let (itemp prefix)
20038 ;; When in a list, compute an appropriate fill-prefix and make
20039 ;; sure it will be used by `do-auto-fill'.
20040 (if (setq itemp (org-in-item-p))
20041 (progn
20042 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
20043 (flet ((fill-context-prefix (from to &optional flr) prefix))
20044 (do-auto-fill)))
20045 ;; Else just use `do-auto-fill'.
20046 (do-auto-fill))))
20048 ;;; Other stuff.
20050 (defun org-toggle-fixed-width-section (arg)
20051 "Toggle the fixed-width export.
20052 If there is no active region, the QUOTE keyword at the current headline is
20053 inserted or removed. When present, it causes the text between this headline
20054 and the next to be exported as fixed-width text, and unmodified.
20055 If there is an active region, this command adds or removes a colon as the
20056 first character of this line. If the first character of a line is a colon,
20057 this line is also exported in fixed-width font."
20058 (interactive "P")
20059 (let* ((cc 0)
20060 (regionp (org-region-active-p))
20061 (beg (if regionp (region-beginning) (point)))
20062 (end (if regionp (region-end)))
20063 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20064 (case-fold-search nil)
20065 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
20066 off)
20067 (if regionp
20068 (save-excursion
20069 (goto-char beg)
20070 (setq cc (current-column))
20071 (beginning-of-line 1)
20072 (setq off (looking-at re))
20073 (while (> nlines 0)
20074 (setq nlines (1- nlines))
20075 (beginning-of-line 1)
20076 (cond
20077 (arg
20078 (org-move-to-column cc t)
20079 (insert ": \n")
20080 (forward-line -1))
20081 ((and off (looking-at re))
20082 (replace-match "" t t nil 1))
20083 ((not off) (org-move-to-column cc t) (insert ": ")))
20084 (forward-line 1)))
20085 (save-excursion
20086 (org-back-to-heading)
20087 (cond
20088 ((looking-at (format org-heading-keyword-regexp-format
20089 org-quote-string))
20090 (goto-char (match-end 1))
20091 (looking-at (concat " +" org-quote-string))
20092 (replace-match "" t t)
20093 (when (eolp) (insert " ")))
20094 ((looking-at org-outline-regexp)
20095 (goto-char (match-end 0))
20096 (insert org-quote-string " ")))))))
20098 (defun org-reftex-citation ()
20099 "Use reftex-citation to insert a citation into the buffer.
20100 This looks for a line like
20102 #+BIBLIOGRAPHY: foo plain option:-d
20104 and derives from it that foo.bib is the bibliography file relevant
20105 for this document. It then installs the necessary environment for RefTeX
20106 to work in this buffer and calls `reftex-citation' to insert a citation
20107 into the buffer.
20109 Export of such citations to both LaTeX and HTML is handled by the contributed
20110 package org-exp-bibtex by Taru Karttunen."
20111 (interactive)
20112 (let ((reftex-docstruct-symbol 'rds)
20113 (reftex-cite-format "\\cite{%l}")
20114 rds bib)
20115 (save-excursion
20116 (save-restriction
20117 (widen)
20118 (let ((case-fold-search t)
20119 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
20120 (if (not (save-excursion
20121 (or (re-search-forward re nil t)
20122 (re-search-backward re nil t))))
20123 (error "No bibliography defined in file")
20124 (setq bib (concat (match-string 1) ".bib")
20125 rds (list (list 'bib bib)))))))
20126 (call-interactively 'reftex-citation)))
20128 ;;;; Functions extending outline functionality
20130 (defun org-beginning-of-line (&optional arg)
20131 "Go to the beginning of the current line. If that is invisible, continue
20132 to a visible line beginning. This makes the function of C-a more intuitive.
20133 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20134 first attempt, and only move to after the tags when the cursor is already
20135 beyond the end of the headline."
20136 (interactive "P")
20137 (let ((pos (point))
20138 (special (if (consp org-special-ctrl-a/e)
20139 (car org-special-ctrl-a/e)
20140 org-special-ctrl-a/e))
20141 refpos)
20142 (if (org-bound-and-true-p line-move-visual)
20143 (beginning-of-visual-line 1)
20144 (beginning-of-line 1))
20145 (if (and arg (fboundp 'move-beginning-of-line))
20146 (call-interactively 'move-beginning-of-line)
20147 (if (bobp)
20149 (backward-char 1)
20150 (if (org-truely-invisible-p)
20151 (while (and (not (bobp)) (org-truely-invisible-p))
20152 (backward-char 1)
20153 (beginning-of-line 1))
20154 (forward-char 1))))
20155 (when special
20156 (cond
20157 ((and (looking-at org-complex-heading-regexp)
20158 (= (char-after (match-end 1)) ?\ ))
20159 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
20160 (point-at-eol)))
20161 (goto-char
20162 (if (eq special t)
20163 (cond ((> pos refpos) refpos)
20164 ((= pos (point)) refpos)
20165 (t (point)))
20166 (cond ((> pos (point)) (point))
20167 ((not (eq last-command this-command)) (point))
20168 (t refpos)))))
20169 ((org-at-item-p)
20170 (goto-char
20171 (if (eq special t)
20172 (cond ((> pos (match-end 0)) (match-end 0))
20173 ((= pos (point)) (match-end 0))
20174 (t (point)))
20175 (cond ((> pos (point)) (point))
20176 ((not (eq last-command this-command)) (point))
20177 (t (match-end 0))))))))
20178 (org-no-warnings
20179 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20181 (defun org-end-of-line (&optional arg)
20182 "Go to the end of the line.
20183 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
20184 first attempt, and only move to after the tags when the cursor is already
20185 beyond the end of the headline."
20186 (interactive "P")
20187 (let ((special (if (consp org-special-ctrl-a/e)
20188 (cdr org-special-ctrl-a/e)
20189 org-special-ctrl-a/e)))
20190 (cond
20191 ((or (not special) arg
20192 (not (or (org-on-heading-p) (org-at-item-p))))
20193 (call-interactively
20194 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
20195 ((fboundp 'move-end-of-line) 'move-end-of-line)
20196 (t 'end-of-line))))
20197 ((org-on-heading-p)
20198 (let ((pos (point)))
20199 (beginning-of-line 1)
20200 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
20201 (if (eq special t)
20202 (if (or (< pos (match-beginning 1))
20203 (= pos (match-end 0)))
20204 (goto-char (match-beginning 1))
20205 (goto-char (match-end 0)))
20206 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
20207 (goto-char (match-end 0))
20208 (goto-char (match-beginning 1))))
20209 (call-interactively (if (fboundp 'move-end-of-line)
20210 'move-end-of-line
20211 'end-of-line)))))
20212 ;; At an item: Move before any hidden text.
20213 (t (call-interactively 'end-of-line)))
20214 (org-no-warnings
20215 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
20217 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20218 (define-key org-mode-map "\C-e" 'org-end-of-line)
20220 (defun org-backward-sentence (&optional arg)
20221 "Go to beginning of sentence, or beginning of table field.
20222 This will call `backward-sentence' or `org-table-beginning-of-field',
20223 depending on context."
20224 (interactive "P")
20225 (cond
20226 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
20227 (t (call-interactively 'backward-sentence))))
20229 (defun org-forward-sentence (&optional arg)
20230 "Go to end of sentence, or end of table field.
20231 This will call `forward-sentence' or `org-table-end-of-field',
20232 depending on context."
20233 (interactive "P")
20234 (cond
20235 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
20236 (t (call-interactively 'forward-sentence))))
20238 (define-key org-mode-map "\M-a" 'org-backward-sentence)
20239 (define-key org-mode-map "\M-e" 'org-forward-sentence)
20241 (defun org-kill-line (&optional arg)
20242 "Kill line, to tags or end of line."
20243 (interactive "P")
20244 (cond
20245 ((or (not org-special-ctrl-k)
20246 (bolp)
20247 (not (org-on-heading-p)))
20248 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
20249 org-ctrl-k-protect-subtree)
20250 (if (or (eq org-ctrl-k-protect-subtree 'error)
20251 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
20252 (error "C-k aborted - would kill hidden subtree")))
20253 (call-interactively 'kill-line))
20254 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
20255 (kill-region (point) (match-beginning 1))
20256 (org-set-tags nil t))
20257 (t (kill-region (point) (point-at-eol)))))
20259 (define-key org-mode-map "\C-k" 'org-kill-line)
20261 (defun org-yank (&optional arg)
20262 "Yank. If the kill is a subtree, treat it specially.
20263 This command will look at the current kill and check if is a single
20264 subtree, or a series of subtrees[1]. If it passes the test, and if the
20265 cursor is at the beginning of a line or after the stars of a currently
20266 empty headline, then the yank is handled specially. How exactly depends
20267 on the value of the following variables, both set by default.
20269 org-yank-folded-subtrees
20270 When set, the subtree(s) will be folded after insertion, but only
20271 if doing so would now swallow text after the yanked text.
20273 org-yank-adjusted-subtrees
20274 When set, the subtree will be promoted or demoted in order to
20275 fit into the local outline tree structure, which means that the level
20276 will be adjusted so that it becomes the smaller one of the two
20277 *visible* surrounding headings.
20279 Any prefix to this command will cause `yank' to be called directly with
20280 no special treatment. In particular, a simple \\[universal-argument] prefix \
20281 will just
20282 plainly yank the text as it is.
20284 \[1] The test checks if the first non-white line is a heading
20285 and if there are no other headings with fewer stars."
20286 (interactive "P")
20287 (org-yank-generic 'yank arg))
20289 (defun org-yank-generic (command arg)
20290 "Perform some yank-like command.
20292 This function implements the behavior described in the `org-yank'
20293 documentation. However, it has been generalized to work for any
20294 interactive command with similar behavior."
20296 ;; pretend to be command COMMAND
20297 (setq this-command command)
20299 (if arg
20300 (call-interactively command)
20302 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
20303 (and (org-kill-is-subtree-p)
20304 (or (bolp)
20305 (and (looking-at "[ \t]*$")
20306 (string-match
20307 "\\`\\*+\\'"
20308 (buffer-substring (point-at-bol) (point)))))))
20309 swallowp)
20310 (cond
20311 ((and subtreep org-yank-folded-subtrees)
20312 (let ((beg (point))
20313 end)
20314 (if (and subtreep org-yank-adjusted-subtrees)
20315 (org-paste-subtree nil nil 'for-yank)
20316 (call-interactively command))
20318 (setq end (point))
20319 (goto-char beg)
20320 (when (and (bolp) subtreep
20321 (not (setq swallowp
20322 (org-yank-folding-would-swallow-text beg end))))
20323 (org-with-limited-levels
20324 (or (looking-at org-outline-regexp)
20325 (re-search-forward org-outline-regexp-bol end t))
20326 (while (and (< (point) end) (looking-at org-outline-regexp))
20327 (hide-subtree)
20328 (org-cycle-show-empty-lines 'folded)
20329 (condition-case nil
20330 (outline-forward-same-level 1)
20331 (error (goto-char end))))))
20332 (when swallowp
20333 (message
20334 "Inserted text not folded because that would swallow text"))
20336 (goto-char end)
20337 (skip-chars-forward " \t\n\r")
20338 (beginning-of-line 1)
20339 (push-mark beg 'nomsg)))
20340 ((and subtreep org-yank-adjusted-subtrees)
20341 (let ((beg (point-at-bol)))
20342 (org-paste-subtree nil nil 'for-yank)
20343 (push-mark beg 'nomsg)))
20345 (call-interactively command))))))
20347 (defun org-yank-folding-would-swallow-text (beg end)
20348 "Would hide-subtree at BEG swallow any text after END?"
20349 (let (level)
20350 (org-with-limited-levels
20351 (save-excursion
20352 (goto-char beg)
20353 (when (or (looking-at org-outline-regexp)
20354 (re-search-forward org-outline-regexp-bol end t))
20355 (setq level (org-outline-level)))
20356 (goto-char end)
20357 (skip-chars-forward " \t\r\n\v\f")
20358 (if (or (eobp)
20359 (and (bolp) (looking-at org-outline-regexp)
20360 (<= (org-outline-level) level)))
20361 nil ; Nothing would be swallowed
20362 t))))) ; something would swallow
20364 (define-key org-mode-map "\C-y" 'org-yank)
20366 (defun org-truely-invisible-p ()
20367 "Check if point is at a character currently not visible.
20368 This version does not only check the character property, but also
20369 `visible-mode'."
20370 ;; Early versions of noutline don't have `outline-invisible-p'.
20371 (if (org-bound-and-true-p visible-mode)
20373 (outline-invisible-p)))
20375 (defun org-invisible-p2 ()
20376 "Check if point is at a character currently not visible."
20377 (save-excursion
20378 (if (and (eolp) (not (bobp))) (backward-char 1))
20379 ;; Early versions of noutline don't have `outline-invisible-p'.
20380 (outline-invisible-p)))
20382 (defun org-back-to-heading (&optional invisible-ok)
20383 "Call `outline-back-to-heading', but provide a better error message."
20384 (condition-case nil
20385 (outline-back-to-heading invisible-ok)
20386 (error (error "Before first headline at position %d in buffer %s"
20387 (point) (current-buffer)))))
20389 (defun org-beginning-of-defun ()
20390 "Go to the beginning of the subtree, i.e. back to the heading."
20391 (org-back-to-heading))
20392 (defun org-end-of-defun ()
20393 "Go to the end of the subtree."
20394 (org-end-of-subtree nil t))
20396 (defun org-before-first-heading-p ()
20397 "Before first heading?"
20398 (save-excursion
20399 (end-of-line)
20400 (null (re-search-backward org-outline-regexp-bol nil t))))
20402 (defun org-on-heading-p (&optional ignored)
20403 (outline-on-heading-p t))
20404 (defun org-at-heading-p (&optional ignored)
20405 (outline-on-heading-p t))
20407 (defun org-point-at-end-of-empty-headline ()
20408 "If point is at the end of an empty headline, return t, else nil.
20409 If the heading only contains a TODO keyword, it is still still considered
20410 empty."
20411 (and (looking-at "[ \t]*$")
20412 (save-excursion
20413 (beginning-of-line 1)
20414 (let ((case-fold-search nil))
20415 (looking-at org-todo-line-regexp)))
20416 (string= (match-string 3) "")))
20418 (defun org-at-heading-or-item-p ()
20419 (or (org-on-heading-p) (org-at-item-p)))
20421 (defun org-on-target-p ()
20422 (or (org-in-regexp org-radio-target-regexp)
20423 (org-in-regexp org-target-regexp)))
20425 (defun org-up-heading-all (arg)
20426 "Move to the heading line of which the present line is a subheading.
20427 This function considers both visible and invisible heading lines.
20428 With argument, move up ARG levels."
20429 (if (fboundp 'outline-up-heading-all)
20430 (outline-up-heading-all arg) ; emacs 21 version of outline.el
20431 (outline-up-heading arg t))) ; emacs 22 version of outline.el
20433 (defun org-up-heading-safe ()
20434 "Move to the heading line of which the present line is a subheading.
20435 This version will not throw an error. It will return the level of the
20436 headline found, or nil if no higher level is found.
20438 Also, this function will be a lot faster than `outline-up-heading',
20439 because it relies on stars being the outline starters. This can really
20440 make a significant difference in outlines with very many siblings."
20441 (let (start-level re)
20442 (org-back-to-heading t)
20443 (setq start-level (funcall outline-level))
20444 (if (equal start-level 1)
20446 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
20447 (if (re-search-backward re nil t)
20448 (funcall outline-level)))))
20450 (defun org-first-sibling-p ()
20451 "Is this heading the first child of its parents?"
20452 (interactive)
20453 (let ((re org-outline-regexp-bol)
20454 level l)
20455 (unless (org-at-heading-p t)
20456 (error "Not at a heading"))
20457 (setq level (funcall outline-level))
20458 (save-excursion
20459 (if (not (re-search-backward re nil t))
20461 (setq l (funcall outline-level))
20462 (< l level)))))
20464 (defun org-goto-sibling (&optional previous)
20465 "Goto the next sibling, even if it is invisible.
20466 When PREVIOUS is set, go to the previous sibling instead. Returns t
20467 when a sibling was found. When none is found, return nil and don't
20468 move point."
20469 (let ((fun (if previous 're-search-backward 're-search-forward))
20470 (pos (point))
20471 (re org-outline-regexp-bol)
20472 level l)
20473 (when (condition-case nil (org-back-to-heading t) (error nil))
20474 (setq level (funcall outline-level))
20475 (catch 'exit
20476 (or previous (forward-char 1))
20477 (while (funcall fun re nil t)
20478 (setq l (funcall outline-level))
20479 (when (< l level) (goto-char pos) (throw 'exit nil))
20480 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
20481 (goto-char pos)
20482 nil))))
20484 (defun org-show-siblings ()
20485 "Show all siblings of the current headline."
20486 (save-excursion
20487 (while (org-goto-sibling) (org-flag-heading nil)))
20488 (save-excursion
20489 (while (org-goto-sibling 'previous)
20490 (org-flag-heading nil))))
20492 (defun org-goto-first-child ()
20493 "Goto the first child, even if it is invisible.
20494 Return t when a child was found. Otherwise don't move point and
20495 return nil."
20496 (let (level (pos (point)) (re org-outline-regexp-bol))
20497 (when (condition-case nil (org-back-to-heading t) (error nil))
20498 (setq level (outline-level))
20499 (forward-char 1)
20500 (if (and (re-search-forward re nil t) (> (outline-level) level))
20501 (progn (goto-char (match-beginning 0)) t)
20502 (goto-char pos) nil))))
20504 (defun org-show-hidden-entry ()
20505 "Show an entry where even the heading is hidden."
20506 (save-excursion
20507 (org-show-entry)))
20509 (defun org-flag-heading (flag &optional entry)
20510 "Flag the current heading. FLAG non-nil means make invisible.
20511 When ENTRY is non-nil, show the entire entry."
20512 (save-excursion
20513 (org-back-to-heading t)
20514 ;; Check if we should show the entire entry
20515 (if entry
20516 (progn
20517 (org-show-entry)
20518 (save-excursion
20519 (and (outline-next-heading)
20520 (org-flag-heading nil))))
20521 (outline-flag-region (max (point-min) (1- (point)))
20522 (save-excursion (outline-end-of-heading) (point))
20523 flag))))
20525 (defun org-get-next-sibling ()
20526 "Move to next heading of the same level, and return point.
20527 If there is no such heading, return nil.
20528 This is like outline-next-sibling, but invisible headings are ok."
20529 (let ((level (funcall outline-level)))
20530 (outline-next-heading)
20531 (while (and (not (eobp)) (> (funcall outline-level) level))
20532 (outline-next-heading))
20533 (if (or (eobp) (< (funcall outline-level) level))
20535 (point))))
20537 (defun org-get-last-sibling ()
20538 "Move to previous heading of the same level, and return point.
20539 If there is no such heading, return nil."
20540 (let ((opoint (point))
20541 (level (funcall outline-level)))
20542 (outline-previous-heading)
20543 (when (and (/= (point) opoint) (outline-on-heading-p t))
20544 (while (and (> (funcall outline-level) level)
20545 (not (bobp)))
20546 (outline-previous-heading))
20547 (if (< (funcall outline-level) level)
20549 (point)))))
20551 (defun org-end-of-subtree (&optional invisible-OK to-heading)
20552 ;; This contains an exact copy of the original function, but it uses
20553 ;; `org-back-to-heading', to make it work also in invisible
20554 ;; trees. And is uses an invisible-OK argument.
20555 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
20556 ;; Furthermore, when used inside Org, finding the end of a large subtree
20557 ;; with many children and grandchildren etc, this can be much faster
20558 ;; than the outline version.
20559 (org-back-to-heading invisible-OK)
20560 (let ((first t)
20561 (level (funcall outline-level)))
20562 (if (and (eq major-mode 'org-mode) (< level 1000))
20563 ;; A true heading (not a plain list item), in Org-mode
20564 ;; This means we can easily find the end by looking
20565 ;; only for the right number of stars. Using a regexp to do
20566 ;; this is so much faster than using a Lisp loop.
20567 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
20568 (forward-char 1)
20569 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
20570 ;; something else, do it the slow way
20571 (while (and (not (eobp))
20572 (or first (> (funcall outline-level) level)))
20573 (setq first nil)
20574 (outline-next-heading)))
20575 (unless to-heading
20576 (if (memq (preceding-char) '(?\n ?\^M))
20577 (progn
20578 ;; Go to end of line before heading
20579 (forward-char -1)
20580 (if (memq (preceding-char) '(?\n ?\^M))
20581 ;; leave blank line before heading
20582 (forward-char -1))))))
20583 (point))
20585 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
20586 "Use Org version in org-mode, for dramatic speed-up."
20587 (if (eq major-mode 'org-mode)
20588 (progn
20589 (org-end-of-subtree nil t)
20590 (unless (eobp) (backward-char 1)))
20591 ad-do-it))
20593 (defun org-end-of-meta-data-and-drawers ()
20594 "Jump to the first text after meta data and drawers in the current entry.
20595 This will move over empty lines, lines with planning time stamps,
20596 clocking lines, and drawers."
20597 (org-back-to-heading t)
20598 (let ((end (save-excursion (outline-next-heading) (point)))
20599 (re (concat "\\(" org-drawer-regexp "\\)"
20600 "\\|" "[ \t]*" org-keyword-time-regexp)))
20601 (forward-line 1)
20602 (while (re-search-forward re end t)
20603 (if (not (match-end 1))
20604 ;; empty or planning line
20605 (forward-line 1)
20606 ;; a drawer, find the end
20607 (re-search-forward "^[ \t]*:END:" end 'move)
20608 (forward-line 1)))
20609 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
20610 (point)))
20612 (defun org-forward-same-level (arg &optional invisible-ok)
20613 "Move forward to the arg'th subheading at same level as this one.
20614 Stop at the first and last subheadings of a superior heading.
20615 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
20616 it wil also look at invisible ones."
20617 (interactive "p")
20618 (org-back-to-heading invisible-ok)
20619 (org-on-heading-p)
20620 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20621 (re (format "^\\*\\{1,%d\\} " level))
20623 (forward-char 1)
20624 (while (> arg 0)
20625 (while (and (re-search-forward re nil 'move)
20626 (setq l (- (match-end 0) (match-beginning 0) 1))
20627 (= l level)
20628 (not invisible-ok)
20629 (progn (backward-char 1) (outline-invisible-p)))
20630 (if (< l level) (setq arg 1)))
20631 (setq arg (1- arg)))
20632 (beginning-of-line 1)))
20634 (defun org-backward-same-level (arg &optional invisible-ok)
20635 "Move backward to the arg'th subheading at same level as this one.
20636 Stop at the first and last subheadings of a superior heading."
20637 (interactive "p")
20638 (org-back-to-heading)
20639 (org-on-heading-p)
20640 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20641 (re (format "^\\*\\{1,%d\\} " level))
20643 (while (> arg 0)
20644 (while (and (re-search-backward re nil 'move)
20645 (setq l (- (match-end 0) (match-beginning 0) 1))
20646 (= l level)
20647 (not invisible-ok)
20648 (outline-invisible-p))
20649 (if (< l level) (setq arg 1)))
20650 (setq arg (1- arg)))))
20652 (defun org-show-subtree ()
20653 "Show everything after this heading at deeper levels."
20654 (outline-flag-region
20655 (point)
20656 (save-excursion
20657 (org-end-of-subtree t t))
20658 nil))
20660 (defun org-show-entry ()
20661 "Show the body directly following this heading.
20662 Show the heading too, if it is currently invisible."
20663 (interactive)
20664 (save-excursion
20665 (condition-case nil
20666 (progn
20667 (org-back-to-heading t)
20668 (outline-flag-region
20669 (max (point-min) (1- (point)))
20670 (save-excursion
20671 (if (re-search-forward
20672 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
20673 (match-beginning 1)
20674 (point-max)))
20675 nil)
20676 (org-cycle-hide-drawers 'children))
20677 (error nil))))
20679 (defun org-make-options-regexp (kwds &optional extra)
20680 "Make a regular expression for keyword lines."
20681 (concat
20683 "#?[ \t]*\\+\\("
20684 (mapconcat 'regexp-quote kwds "\\|")
20685 (if extra (concat "\\|" extra))
20686 "\\):[ \t]*"
20687 "\\(.*\\)"))
20689 ;; Make isearch reveal the necessary context
20690 (defun org-isearch-end ()
20691 "Reveal context after isearch exits."
20692 (when isearch-success ; only if search was successful
20693 (if (featurep 'xemacs)
20694 ;; Under XEmacs, the hook is run in the correct place,
20695 ;; we directly show the context.
20696 (org-show-context 'isearch)
20697 ;; In Emacs the hook runs *before* restoring the overlays.
20698 ;; So we have to use a one-time post-command-hook to do this.
20699 ;; (Emacs 22 has a special variable, see function `org-mode')
20700 (unless (and (boundp 'isearch-mode-end-hook-quit)
20701 isearch-mode-end-hook-quit)
20702 ;; Only when the isearch was not quitted.
20703 (org-add-hook 'post-command-hook 'org-isearch-post-command
20704 'append 'local)))))
20706 (defun org-isearch-post-command ()
20707 "Remove self from hook, and show context."
20708 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
20709 (org-show-context 'isearch))
20712 ;;;; Integration with and fixes for other packages
20714 ;;; Imenu support
20716 (defvar org-imenu-markers nil
20717 "All markers currently used by Imenu.")
20718 (make-variable-buffer-local 'org-imenu-markers)
20720 (defun org-imenu-new-marker (&optional pos)
20721 "Return a new marker for use by Imenu, and remember the marker."
20722 (let ((m (make-marker)))
20723 (move-marker m (or pos (point)))
20724 (push m org-imenu-markers)
20727 (defun org-imenu-get-tree ()
20728 "Produce the index for Imenu."
20729 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
20730 (setq org-imenu-markers nil)
20731 (let* ((n org-imenu-depth)
20732 (re (concat "^" (org-get-limited-outline-regexp)))
20733 (subs (make-vector (1+ n) nil))
20734 (last-level 0)
20735 m level head)
20736 (save-excursion
20737 (save-restriction
20738 (widen)
20739 (goto-char (point-max))
20740 (while (re-search-backward re nil t)
20741 (setq level (org-reduced-level (funcall outline-level)))
20742 (when (<= level n)
20743 (looking-at org-complex-heading-regexp)
20744 (setq head (org-link-display-format
20745 (org-match-string-no-properties 4))
20746 m (org-imenu-new-marker))
20747 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
20748 (if (>= level last-level)
20749 (push (cons head m) (aref subs level))
20750 (push (cons head (aref subs (1+ level))) (aref subs level))
20751 (loop for i from (1+ level) to n do (aset subs i nil)))
20752 (setq last-level level)))))
20753 (aref subs 1)))
20755 (eval-after-load "imenu"
20756 '(progn
20757 (add-hook 'imenu-after-jump-hook
20758 (lambda ()
20759 (if (eq major-mode 'org-mode)
20760 (org-show-context 'org-goto))))))
20762 (defun org-link-display-format (link)
20763 "Replace a link with either the description, or the link target
20764 if no description is present"
20765 (save-match-data
20766 (if (string-match org-bracket-link-analytic-regexp link)
20767 (replace-match (if (match-end 5)
20768 (match-string 5 link)
20769 (concat (match-string 1 link)
20770 (match-string 3 link)))
20771 nil t link)
20772 link)))
20774 (defun org-toggle-link-display ()
20775 "Toggle the literal or descriptive display of links."
20776 (interactive)
20777 (if org-descriptive-links
20778 (progn (org-remove-from-invisibility-spec '(org-link))
20779 (org-restart-font-lock)
20780 (setq org-descriptive-links nil))
20781 (progn (add-to-invisibility-spec '(org-link))
20782 (org-restart-font-lock)
20783 (setq org-descriptive-links t))))
20785 ;; Speedbar support
20787 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
20788 "Overlay marking the agenda restriction line in speedbar.")
20789 (overlay-put org-speedbar-restriction-lock-overlay
20790 'face 'org-agenda-restriction-lock)
20791 (overlay-put org-speedbar-restriction-lock-overlay
20792 'help-echo "Agendas are currently limited to this item.")
20793 (org-detach-overlay org-speedbar-restriction-lock-overlay)
20795 (defun org-speedbar-set-agenda-restriction ()
20796 "Restrict future agenda commands to the location at point in speedbar.
20797 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
20798 (interactive)
20799 (require 'org-agenda)
20800 (let (p m tp np dir txt)
20801 (cond
20802 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20803 'org-imenu t))
20804 (setq m (get-text-property p 'org-imenu-marker))
20805 (with-current-buffer (marker-buffer m)
20806 (goto-char m)
20807 (org-agenda-set-restriction-lock 'subtree)))
20808 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20809 'speedbar-function 'speedbar-find-file))
20810 (setq tp (previous-single-property-change
20811 (1+ p) 'speedbar-function)
20812 np (next-single-property-change
20813 tp 'speedbar-function)
20814 dir (speedbar-line-directory)
20815 txt (buffer-substring-no-properties (or tp (point-min))
20816 (or np (point-max))))
20817 (with-current-buffer (find-file-noselect
20818 (let ((default-directory dir))
20819 (expand-file-name txt)))
20820 (unless (eq major-mode 'org-mode)
20821 (error "Cannot restrict to non-Org-mode file"))
20822 (org-agenda-set-restriction-lock 'file)))
20823 (t (error "Don't know how to restrict Org-mode's agenda")))
20824 (move-overlay org-speedbar-restriction-lock-overlay
20825 (point-at-bol) (point-at-eol))
20826 (setq current-prefix-arg nil)
20827 (org-agenda-maybe-redo)))
20829 (eval-after-load "speedbar"
20830 '(progn
20831 (speedbar-add-supported-extension ".org")
20832 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
20833 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
20834 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
20835 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
20836 (add-hook 'speedbar-visiting-tag-hook
20837 (lambda () (and (eq major-mode 'org-mode) (org-show-context 'org-goto))))))
20839 ;;; Fixes and Hacks for problems with other packages
20841 ;; Make flyspell not check words in links, to not mess up our keymap
20842 (defun org-mode-flyspell-verify ()
20843 "Don't let flyspell put overlays at active buttons, or on
20844 {todo,all-time,additional-option-like}-keywords."
20845 (let ((pos (max (1- (point)) (point-min)))
20846 (word (thing-at-point 'word)))
20847 (and (not (get-text-property pos 'keymap))
20848 (not (get-text-property pos 'org-no-flyspell))
20849 (not (member word org-todo-keywords-1))
20850 (not (member word org-all-time-keywords))
20851 (not (member word org-additional-option-like-keywords)))))
20853 (defun org-remove-flyspell-overlays-in (beg end)
20854 "Remove flyspell overlays in region."
20855 (and (org-bound-and-true-p flyspell-mode)
20856 (fboundp 'flyspell-delete-region-overlays)
20857 (flyspell-delete-region-overlays beg end))
20858 (add-text-properties beg end '(org-no-flyspell t)))
20860 ;; Make `bookmark-jump' shows the jump location if it was hidden.
20861 (eval-after-load "bookmark"
20862 '(if (boundp 'bookmark-after-jump-hook)
20863 ;; We can use the hook
20864 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
20865 ;; Hook not available, use advice
20866 (defadvice bookmark-jump (after org-make-visible activate)
20867 "Make the position visible."
20868 (org-bookmark-jump-unhide))))
20870 ;; Make sure saveplace shows the location if it was hidden
20871 (eval-after-load "saveplace"
20872 '(defadvice save-place-find-file-hook (after org-make-visible activate)
20873 "Make the position visible."
20874 (org-bookmark-jump-unhide)))
20876 ;; Make sure ecb shows the location if it was hidden
20877 (eval-after-load "ecb"
20878 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
20879 "Make hierarchy visible when jumping into location from ECB tree buffer."
20880 (if (eq major-mode 'org-mode)
20881 (org-show-context))))
20883 (defun org-bookmark-jump-unhide ()
20884 "Unhide the current position, to show the bookmark location."
20885 (and (eq major-mode 'org-mode)
20886 (or (outline-invisible-p)
20887 (save-excursion (goto-char (max (point-min) (1- (point))))
20888 (outline-invisible-p)))
20889 (org-show-context 'bookmark-jump)))
20891 ;; Make session.el ignore our circular variable
20892 (eval-after-load "session"
20893 '(add-to-list 'session-globals-exclude 'org-mark-ring))
20895 ;;;; Experimental code
20897 (defun org-closed-in-range ()
20898 "Sparse tree of items closed in a certain time range.
20899 Still experimental, may disappear in the future."
20900 (interactive)
20901 ;; Get the time interval from the user.
20902 (let* ((time1 (org-float-time
20903 (org-read-date nil 'to-time nil "Starting date: ")))
20904 (time2 (org-float-time
20905 (org-read-date nil 'to-time nil "End date:")))
20906 ;; callback function
20907 (callback (lambda ()
20908 (let ((time
20909 (org-float-time
20910 (apply 'encode-time
20911 (org-parse-time-string
20912 (match-string 1))))))
20913 ;; check if time in interval
20914 (and (>= time time1) (<= time time2))))))
20915 ;; make tree, check each match with the callback
20916 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
20918 ;;;; Finish up
20920 (provide 'org)
20922 (run-hooks 'org-load-hook)
20924 ;;; org.el ends here