Allow subscripts and superscripts to start at bol
[org-mode.git] / lisp / org.el
blobb26e1a31ca4928d094b6d652dc7a031b795a2978
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 (defgroup org-startup nil
407 "Options concerning startup of Org-mode."
408 :tag "Org Startup"
409 :group 'org)
411 (defcustom org-startup-folded t
412 "Non-nil means entering Org-mode will switch to OVERVIEW.
413 This can also be configured on a per-file basis by adding one of
414 the following lines anywhere in the buffer:
416 #+STARTUP: fold (or `overview', this is equivalent)
417 #+STARTUP: nofold (or `showall', this is equivalent)
418 #+STARTUP: content
419 #+STARTUP: showeverything"
420 :group 'org-startup
421 :type '(choice
422 (const :tag "nofold: show all" nil)
423 (const :tag "fold: overview" t)
424 (const :tag "content: all headlines" content)
425 (const :tag "show everything, even drawers" showeverything)))
427 (defcustom org-startup-truncated t
428 "Non-nil means entering Org-mode will set `truncate-lines'.
429 This is useful since some lines containing links can be very long and
430 uninteresting. Also tables look terrible when wrapped."
431 :group 'org-startup
432 :type 'boolean)
434 (defcustom org-startup-indented nil
435 "Non-nil means turn on `org-indent-mode' on startup.
436 This can also be configured on a per-file basis by adding one of
437 the following lines anywhere in the buffer:
439 #+STARTUP: indent
440 #+STARTUP: noindent"
441 :group 'org-structure
442 :type '(choice
443 (const :tag "Not" nil)
444 (const :tag "Globally (slow on startup in large files)" t)))
446 (defcustom org-use-sub-superscripts t
447 "Non-nil means interpret \"_\" and \"^\" for export.
448 When this option is turned on, you can use TeX-like syntax for sub- and
449 superscripts. Several characters after \"_\" or \"^\" will be
450 considered as a single item - so grouping with {} is normally not
451 needed. For example, the following things will be parsed as single
452 sub- or superscripts.
454 10^24 or 10^tau several digits will be considered 1 item.
455 10^-12 or 10^-tau a leading sign with digits or a word
456 x^2-y^3 will be read as x^2 - y^3, because items are
457 terminated by almost any nonword/nondigit char.
458 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
460 Still, ambiguity is possible - so when in doubt use {} to enclose the
461 sub/superscript. If you set this variable to the symbol `{}',
462 the braces are *required* in order to trigger interpretations as
463 sub/superscript. This can be helpful in documents that need \"_\"
464 frequently in plain text.
466 Not all export backends support this, but HTML does.
468 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
469 :group 'org-startup
470 :group 'org-export-translation
471 :type '(choice
472 (const :tag "Always interpret" t)
473 (const :tag "Only with braces" {})
474 (const :tag "Never interpret" nil)))
476 (if (fboundp 'defvaralias)
477 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
480 (defcustom org-startup-with-beamer-mode nil
481 "Non-nil means turn on `org-beamer-mode' on startup.
482 This can also be configured on a per-file basis by adding one of
483 the following lines anywhere in the buffer:
485 #+STARTUP: beamer"
486 :group 'org-startup
487 :type 'boolean)
489 (defcustom org-startup-align-all-tables nil
490 "Non-nil means align all tables when visiting a file.
491 This is useful when the column width in tables is forced with <N> cookies
492 in table fields. Such tables will look correct only after the first re-align.
493 This can also be configured on a per-file basis by adding one of
494 the following lines anywhere in the buffer:
495 #+STARTUP: align
496 #+STARTUP: noalign"
497 :group 'org-startup
498 :type 'boolean)
500 (defcustom org-startup-with-inline-images nil
501 "Non-nil means show inline images when loading a new Org file.
502 This can also be configured on a per-file basis by adding one of
503 the following lines anywhere in the buffer:
504 #+STARTUP: inlineimages
505 #+STARTUP: noinlineimages"
506 :group 'org-startup
507 :type 'boolean)
509 (defcustom org-insert-mode-line-in-empty-file nil
510 "Non-nil means insert the first line setting Org-mode in empty files.
511 When the function `org-mode' is called interactively in an empty file, this
512 normally means that the file name does not automatically trigger Org-mode.
513 To ensure that the file will always be in Org-mode in the future, a
514 line enforcing Org-mode will be inserted into the buffer, if this option
515 has been set."
516 :group 'org-startup
517 :type 'boolean)
519 (defcustom org-replace-disputed-keys nil
520 "Non-nil means use alternative key bindings for some keys.
521 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
522 These keys are also used by other packages like shift-selection-mode'
523 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
524 If you want to use Org-mode together with one of these other modes,
525 or more generally if you would like to move some Org-mode commands to
526 other keys, set this variable and configure the keys with the variable
527 `org-disputed-keys'.
529 This option is only relevant at load-time of Org-mode, and must be set
530 *before* org.el is loaded. Changing it requires a restart of Emacs to
531 become effective."
532 :group 'org-startup
533 :type 'boolean)
535 (defcustom org-use-extra-keys nil
536 "Non-nil means use extra key sequence definitions for certain commands.
537 This happens automatically if you run XEmacs or if `window-system'
538 is nil. This variable lets you do the same manually. You must
539 set it before loading org.
541 Example: on Carbon Emacs 22 running graphically, with an external
542 keyboard on a Powerbook, the default way of setting M-left might
543 not work for either Alt or ESC. Setting this variable will make
544 it work for ESC."
545 :group 'org-startup
546 :type 'boolean)
548 (if (fboundp 'defvaralias)
549 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
551 (defcustom org-disputed-keys
552 '(([(shift up)] . [(meta p)])
553 ([(shift down)] . [(meta n)])
554 ([(shift left)] . [(meta -)])
555 ([(shift right)] . [(meta +)])
556 ([(control shift right)] . [(meta shift +)])
557 ([(control shift left)] . [(meta shift -)]))
558 "Keys for which Org-mode and other modes compete.
559 This is an alist, cars are the default keys, second element specifies
560 the alternative to use when `org-replace-disputed-keys' is t.
562 Keys can be specified in any syntax supported by `define-key'.
563 The value of this option takes effect only at Org-mode's startup,
564 therefore you'll have to restart Emacs to apply it after changing."
565 :group 'org-startup
566 :type 'alist)
568 (defun org-key (key)
569 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
570 Or return the original if not disputed.
571 Also apply the translations defined in `org-xemacs-key-equivalents'."
572 (when org-replace-disputed-keys
573 (let* ((nkey (key-description key))
574 (x (org-find-if (lambda (x)
575 (equal (key-description (car x)) nkey))
576 org-disputed-keys)))
577 (setq key (if x (cdr x) key))))
578 (when (featurep 'xemacs)
579 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
580 key)
582 (defun org-find-if (predicate seq)
583 (catch 'exit
584 (while seq
585 (if (funcall predicate (car seq))
586 (throw 'exit (car seq))
587 (pop seq)))))
589 (defun org-defkey (keymap key def)
590 "Define a key, possibly translated, as returned by `org-key'."
591 (define-key keymap (org-key key) def))
593 (defcustom org-ellipsis nil
594 "The ellipsis to use in the Org-mode outline.
595 When nil, just use the standard three dots. When a string, use that instead,
596 When a face, use the standard 3 dots, but with the specified face.
597 The change affects only Org-mode (which will then use its own display table).
598 Changing this requires executing `M-x org-mode' in a buffer to become
599 effective."
600 :group 'org-startup
601 :type '(choice (const :tag "Default" nil)
602 (face :tag "Face" :value org-warning)
603 (string :tag "String" :value "...#")))
605 (defvar org-display-table nil
606 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
608 (defgroup org-keywords nil
609 "Keywords in Org-mode."
610 :tag "Org Keywords"
611 :group 'org)
613 (defcustom org-deadline-string "DEADLINE:"
614 "String to mark deadline entries.
615 A deadline is this string, followed by a time stamp. Should be a word,
616 terminated by a colon. You can insert a schedule keyword and
617 a timestamp with \\[org-deadline].
618 Changes become only effective after restarting Emacs."
619 :group 'org-keywords
620 :type 'string)
622 (defcustom org-scheduled-string "SCHEDULED:"
623 "String to mark scheduled TODO entries.
624 A schedule is this string, followed by a time stamp. Should be a word,
625 terminated by a colon. You can insert a schedule keyword and
626 a timestamp with \\[org-schedule].
627 Changes become only effective after restarting Emacs."
628 :group 'org-keywords
629 :type 'string)
631 (defcustom org-closed-string "CLOSED:"
632 "String used as the prefix for timestamps logging closing a TODO entry."
633 :group 'org-keywords
634 :type 'string)
636 (defcustom org-clock-string "CLOCK:"
637 "String used as prefix for timestamps clocking work hours on an item."
638 :group 'org-keywords
639 :type 'string)
641 (defcustom org-comment-string "COMMENT"
642 "Entries starting with this keyword will never be exported.
643 An entry can be toggled between COMMENT and normal with
644 \\[org-toggle-comment].
645 Changes become only effective after restarting Emacs."
646 :group 'org-keywords
647 :type 'string)
649 (defcustom org-quote-string "QUOTE"
650 "Entries starting with this keyword will be exported in fixed-width font.
651 Quoting applies only to the text in the entry following the headline, and does
652 not extend beyond the next headline, even if that is lower level.
653 An entry can be toggled between QUOTE and normal with
654 \\[org-toggle-fixed-width-section]."
655 :group 'org-keywords
656 :type 'string)
658 (defconst org-repeat-re
659 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
660 "Regular expression for specifying repeated events.
661 After a match, group 1 contains the repeat expression.")
663 (defgroup org-structure nil
664 "Options concerning the general structure of Org-mode files."
665 :tag "Org Structure"
666 :group 'org)
668 (defgroup org-reveal-location nil
669 "Options about how to make context of a location visible."
670 :tag "Org Reveal Location"
671 :group 'org-structure)
673 (defconst org-context-choice
674 '(choice
675 (const :tag "Always" t)
676 (const :tag "Never" nil)
677 (repeat :greedy t :tag "Individual contexts"
678 (cons
679 (choice :tag "Context"
680 (const agenda)
681 (const org-goto)
682 (const occur-tree)
683 (const tags-tree)
684 (const link-search)
685 (const mark-goto)
686 (const bookmark-jump)
687 (const isearch)
688 (const default))
689 (boolean))))
690 "Contexts for the reveal options.")
692 (defcustom org-show-hierarchy-above '((default . t))
693 "Non-nil means show full hierarchy when revealing a location.
694 Org-mode often shows locations in an org-mode file which might have
695 been invisible before. When this is set, the hierarchy of headings
696 above the exposed location is shown.
697 Turning this off for example for sparse trees makes them very compact.
698 Instead of t, this can also be an alist specifying this option for different
699 contexts. Valid contexts are
700 agenda when exposing an entry from the agenda
701 org-goto when using the command `org-goto' on key C-c C-j
702 occur-tree when using the command `org-occur' on key C-c /
703 tags-tree when constructing a sparse tree based on tags matches
704 link-search when exposing search matches associated with a link
705 mark-goto when exposing the jump goal of a mark
706 bookmark-jump when exposing a bookmark location
707 isearch when exiting from an incremental search
708 default default for all contexts not set explicitly"
709 :group 'org-reveal-location
710 :type org-context-choice)
712 (defcustom org-show-following-heading '((default . nil))
713 "Non-nil means show following heading when revealing a location.
714 Org-mode often shows locations in an org-mode file which might have
715 been invisible before. When this is set, the heading following the
716 match is shown.
717 Turning this off for example for sparse trees makes them very compact,
718 but makes it harder to edit the location of the match. In such a case,
719 use the command \\[org-reveal] to show more context.
720 Instead of t, this can also be an alist specifying this option for different
721 contexts. See `org-show-hierarchy-above' for valid contexts."
722 :group 'org-reveal-location
723 :type org-context-choice)
725 (defcustom org-show-siblings '((default . nil) (isearch t))
726 "Non-nil means show all sibling heading when revealing a location.
727 Org-mode often shows locations in an org-mode file which might have
728 been invisible before. When this is set, the sibling of the current entry
729 heading are all made visible. If `org-show-hierarchy-above' is t,
730 the same happens on each level of the hierarchy above the current entry.
732 By default this is on for the isearch context, off for all other contexts.
733 Turning this off for example for sparse trees makes them very compact,
734 but makes it harder to edit the location of the match. In such a case,
735 use the command \\[org-reveal] to show more context.
736 Instead of t, this can also be an alist specifying this option for different
737 contexts. See `org-show-hierarchy-above' for valid contexts."
738 :group 'org-reveal-location
739 :type org-context-choice)
741 (defcustom org-show-entry-below '((default . nil))
742 "Non-nil means show the entry below a headline when revealing a location.
743 Org-mode often shows locations in an org-mode file which might have
744 been invisible before. When this is set, the text below the headline that is
745 exposed is also shown.
747 By default this is off for all contexts.
748 Instead of t, this can also be an alist specifying this option for different
749 contexts. See `org-show-hierarchy-above' for valid contexts."
750 :group 'org-reveal-location
751 :type org-context-choice)
753 (defcustom org-indirect-buffer-display 'other-window
754 "How should indirect tree buffers be displayed?
755 This applies to indirect buffers created with the commands
756 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
757 Valid values are:
758 current-window Display in the current window
759 other-window Just display in another window.
760 dedicated-frame Create one new frame, and re-use it each time.
761 new-frame Make a new frame each time. Note that in this case
762 previously-made indirect buffers are kept, and you need to
763 kill these buffers yourself."
764 :group 'org-structure
765 :group 'org-agenda-windows
766 :type '(choice
767 (const :tag "In current window" current-window)
768 (const :tag "In current frame, other window" other-window)
769 (const :tag "Each time a new frame" new-frame)
770 (const :tag "One dedicated frame" dedicated-frame)))
772 (defcustom org-use-speed-commands nil
773 "Non-nil means activate single letter commands at beginning of a headline.
774 This may also be a function to test for appropriate locations where speed
775 commands should be active."
776 :group 'org-structure
777 :type '(choice
778 (const :tag "Never" nil)
779 (const :tag "At beginning of headline stars" t)
780 (function)))
782 (defcustom org-speed-commands-user nil
783 "Alist of additional speed commands.
784 This list will be checked before `org-speed-commands-default'
785 when the variable `org-use-speed-commands' is non-nil
786 and when the cursor is at the beginning of a headline.
787 The car if each entry is a string with a single letter, which must
788 be assigned to `self-insert-command' in the global map.
789 The cdr is either a command to be called interactively, a function
790 to be called, or a form to be evaluated.
791 An entry that is just a list with a single string will be interpreted
792 as a descriptive headline that will be added when listing the speed
793 commands in the Help buffer using the `?' speed command."
794 :group 'org-structure
795 :type '(repeat :value ("k" . ignore)
796 (choice :value ("k" . ignore)
797 (list :tag "Descriptive Headline" (string :tag "Headline"))
798 (cons :tag "Letter and Command"
799 (string :tag "Command letter")
800 (choice
801 (function)
802 (sexp))))))
804 (defgroup org-cycle nil
805 "Options concerning visibility cycling in Org-mode."
806 :tag "Org Cycle"
807 :group 'org-structure)
809 (defcustom org-cycle-skip-children-state-if-no-children t
810 "Non-nil means skip CHILDREN state in entries that don't have any."
811 :group 'org-cycle
812 :type 'boolean)
814 (defcustom org-cycle-max-level nil
815 "Maximum level which should still be subject to visibility cycling.
816 Levels higher than this will, for cycling, be treated as text, not a headline.
817 When `org-odd-levels-only' is set, a value of N in this variable actually
818 means 2N-1 stars as the limiting headline.
819 When nil, cycle all levels.
820 Note that the limiting level of cycling is also influenced by
821 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
822 `org-inlinetask-min-level' is, cycling will be limited to levels one less
823 than its value."
824 :group 'org-cycle
825 :type '(choice
826 (const :tag "No limit" nil)
827 (integer :tag "Maximum level")))
829 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
830 "Names of drawers. Drawers are not opened by cycling on the headline above.
831 Drawers only open with a TAB on the drawer line itself. A drawer looks like
832 this:
833 :DRAWERNAME:
834 .....
835 :END:
836 The drawer \"PROPERTIES\" is special for capturing properties through
837 the property API.
839 Drawers can be defined on the per-file basis with a line like:
841 #+DRAWERS: HIDDEN STATE PROPERTIES"
842 :group 'org-structure
843 :group 'org-cycle
844 :type '(repeat (string :tag "Drawer Name")))
846 (defcustom org-hide-block-startup nil
847 "Non-nil means entering Org-mode will fold all blocks.
848 This can also be set in on a per-file basis with
850 #+STARTUP: hideblocks
851 #+STARTUP: showblocks"
852 :group 'org-startup
853 :group 'org-cycle
854 :type 'boolean)
856 (defcustom org-cycle-global-at-bob nil
857 "Cycle globally if cursor is at beginning of buffer and not at a headline.
858 This makes it possible to do global cycling without having to use S-TAB or
859 \\[universal-argument] TAB. For this special case to work, the first line \
860 of the buffer
861 must not be a headline - it may be empty or some other text. When used in
862 this way, `org-cycle-hook' is disables temporarily, to make sure the
863 cursor stays at the beginning of the buffer.
864 When this option is nil, don't do anything special at the beginning
865 of the buffer."
866 :group 'org-cycle
867 :type 'boolean)
869 (defcustom org-cycle-level-after-item/entry-creation t
870 "Non-nil means cycle entry level or item indentation in new empty entries.
872 When the cursor is at the end of an empty headline, i.e with only stars
873 and maybe a TODO keyword, TAB will then switch the entry to become a child,
874 and then all possible ancestor states, before returning to the original state.
875 This makes data entry extremely fast: M-RET to create a new headline,
876 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
878 When the cursor is at the end of an empty plain list item, one TAB will
879 make it a subitem, two or more tabs will back up to make this an item
880 higher up in the item hierarchy."
881 :group 'org-cycle
882 :type 'boolean)
884 (defcustom org-cycle-emulate-tab t
885 "Where should `org-cycle' emulate TAB.
886 nil Never
887 white Only in completely white lines
888 whitestart Only at the beginning of lines, before the first non-white char
889 t Everywhere except in headlines
890 exc-hl-bol Everywhere except at the start of a headline
891 If TAB is used in a place where it does not emulate TAB, the current subtree
892 visibility is cycled."
893 :group 'org-cycle
894 :type '(choice (const :tag "Never" nil)
895 (const :tag "Only in completely white lines" white)
896 (const :tag "Before first char in a line" whitestart)
897 (const :tag "Everywhere except in headlines" t)
898 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
901 (defcustom org-cycle-separator-lines 2
902 "Number of empty lines needed to keep an empty line between collapsed trees.
903 If you leave an empty line between the end of a subtree and the following
904 headline, this empty line is hidden when the subtree is folded.
905 Org-mode will leave (exactly) one empty line visible if the number of
906 empty lines is equal or larger to the number given in this variable.
907 So the default 2 means at least 2 empty lines after the end of a subtree
908 are needed to produce free space between a collapsed subtree and the
909 following headline.
911 If the number is negative, and the number of empty lines is at least -N,
912 all empty lines are shown.
914 Special case: when 0, never leave empty lines in collapsed view."
915 :group 'org-cycle
916 :type 'integer)
917 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
919 (defcustom org-pre-cycle-hook nil
920 "Hook that is run before visibility cycling is happening.
921 The function(s) in this hook must accept a single argument which indicates
922 the new state that will be set right after running this hook. The
923 argument is a symbol. Before a global state change, it can have the values
924 `overview', `content', or `all'. Before a local state change, it can have
925 the values `folded', `children', or `subtree'."
926 :group 'org-cycle
927 :type 'hook)
929 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
930 org-cycle-hide-drawers
931 org-cycle-show-empty-lines
932 org-optimize-window-after-visibility-change)
933 "Hook that is run after `org-cycle' has changed the buffer visibility.
934 The function(s) in this hook must accept a single argument which indicates
935 the new state that was set by the most recent `org-cycle' command. The
936 argument is a symbol. After a global state change, it can have the values
937 `overview', `content', or `all'. After a local state change, it can have
938 the values `folded', `children', or `subtree'."
939 :group 'org-cycle
940 :type 'hook)
942 (defgroup org-edit-structure nil
943 "Options concerning structure editing in Org-mode."
944 :tag "Org Edit Structure"
945 :group 'org-structure)
947 (defcustom org-odd-levels-only nil
948 "Non-nil means skip even levels and only use odd levels for the outline.
949 This has the effect that two stars are being added/taken away in
950 promotion/demotion commands. It also influences how levels are
951 handled by the exporters.
952 Changing it requires restart of `font-lock-mode' to become effective
953 for fontification also in regions already fontified.
954 You may also set this on a per-file basis by adding one of the following
955 lines to the buffer:
957 #+STARTUP: odd
958 #+STARTUP: oddeven"
959 :group 'org-edit-structure
960 :group 'org-appearance
961 :type 'boolean)
963 (defcustom org-adapt-indentation t
964 "Non-nil means adapt indentation to outline node level.
966 When this variable is set, Org assumes that you write outlines by
967 indenting text in each node to align with the headline (after the stars).
968 The following issues are influenced by this variable:
970 - When this is set and the *entire* text in an entry is indented, the
971 indentation is increased by one space in a demotion command, and
972 decreased by one in a promotion command. If any line in the entry
973 body starts with text at column 0, indentation is not changed at all.
975 - Property drawers and planning information is inserted indented when
976 this variable s set. When nil, they will not be indented.
978 - TAB indents a line relative to context. The lines below a headline
979 will be indented when this variable is set.
981 Note that this is all about true indentation, by adding and removing
982 space characters. See also `org-indent.el' which does level-dependent
983 indentation in a virtual way, i.e. at display time in Emacs."
984 :group 'org-edit-structure
985 :type 'boolean)
987 (defcustom org-special-ctrl-a/e nil
988 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
990 When t, `C-a' will bring back the cursor to the beginning of the
991 headline text, i.e. after the stars and after a possible TODO keyword.
992 In an item, this will be the position after the bullet.
993 When the cursor is already at that position, another `C-a' will bring
994 it to the beginning of the line.
996 `C-e' will jump to the end of the headline, ignoring the presence of tags
997 in the headline. A second `C-e' will then jump to the true end of the
998 line, after any tags. This also means that, when this variable is
999 non-nil, `C-e' also will never jump beyond the end of the heading of a
1000 folded section, i.e. not after the ellipses.
1002 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
1003 going to the true line boundary first. Only a directly following, identical
1004 keypress will bring the cursor to the special positions.
1006 This may also be a cons cell where the behavior for `C-a' and `C-e' is
1007 set separately."
1008 :group 'org-edit-structure
1009 :type '(choice
1010 (const :tag "off" nil)
1011 (const :tag "on: after stars/bullet and before tags first" t)
1012 (const :tag "reversed: true line boundary first" reversed)
1013 (cons :tag "Set C-a and C-e separately"
1014 (choice :tag "Special C-a"
1015 (const :tag "off" nil)
1016 (const :tag "on: after stars/bullet first" t)
1017 (const :tag "reversed: before stars/bullet first" reversed))
1018 (choice :tag "Special C-e"
1019 (const :tag "off" nil)
1020 (const :tag "on: before tags first" t)
1021 (const :tag "reversed: after tags first" reversed)))))
1022 (if (fboundp 'defvaralias)
1023 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1025 (defcustom org-special-ctrl-k nil
1026 "Non-nil means `C-k' will behave specially in headlines.
1027 When nil, `C-k' will call the default `kill-line' command.
1028 When t, the following will happen while the cursor is in the headline:
1030 - When the cursor is at the beginning of a headline, kill the entire
1031 line and possible the folded subtree below the line.
1032 - When in the middle of the headline text, kill the headline up to the tags.
1033 - When after the headline text, kill the tags."
1034 :group 'org-edit-structure
1035 :type 'boolean)
1037 (defcustom org-ctrl-k-protect-subtree nil
1038 "Non-nil means, do not delete a hidden subtree with C-k.
1039 When set to the symbol `error', simply throw an error when C-k is
1040 used to kill (part-of) a headline that has hidden text behind it.
1041 Any other non-nil value will result in a query to the user, if it is
1042 OK to kill that hidden subtree. When nil, kill without remorse."
1043 :group 'org-edit-structure
1044 :type '(choice
1045 (const :tag "Do not protect hidden subtrees" nil)
1046 (const :tag "Protect hidden subtrees with a security query" t)
1047 (const :tag "Never kill a hidden subtree with C-k" error)))
1049 (defcustom org-yank-folded-subtrees t
1050 "Non-nil means when yanking subtrees, fold them.
1051 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1052 it starts with a heading and all other headings in it are either children
1053 or siblings, then fold all the subtrees. However, do this only if no
1054 text after the yank would be swallowed into a folded tree by this action."
1055 :group 'org-edit-structure
1056 :type 'boolean)
1058 (defcustom org-yank-adjusted-subtrees nil
1059 "Non-nil means when yanking subtrees, adjust the level.
1060 With this setting, `org-paste-subtree' is used to insert the subtree, see
1061 this function for details."
1062 :group 'org-edit-structure
1063 :type 'boolean)
1065 (defcustom org-M-RET-may-split-line '((default . t))
1066 "Non-nil means M-RET will split the line at the cursor position.
1067 When nil, it will go to the end of the line before making a
1068 new line.
1069 You may also set this option in a different way for different
1070 contexts. Valid contexts are:
1072 headline when creating a new headline
1073 item when creating a new item
1074 table in a table field
1075 default the value to be used for all contexts not explicitly
1076 customized"
1077 :group 'org-structure
1078 :group 'org-table
1079 :type '(choice
1080 (const :tag "Always" t)
1081 (const :tag "Never" nil)
1082 (repeat :greedy t :tag "Individual contexts"
1083 (cons
1084 (choice :tag "Context"
1085 (const headline)
1086 (const item)
1087 (const table)
1088 (const default))
1089 (boolean)))))
1092 (defcustom org-insert-heading-respect-content nil
1093 "Non-nil means insert new headings after the current subtree.
1094 When nil, the new heading is created directly after the current line.
1095 The commands \\[org-insert-heading-respect-content] and
1096 \\[org-insert-todo-heading-respect-content] turn this variable on
1097 for the duration of the command."
1098 :group 'org-structure
1099 :type 'boolean)
1101 (defcustom org-blank-before-new-entry '((heading . auto)
1102 (plain-list-item . auto))
1103 "Should `org-insert-heading' leave a blank line before new heading/item?
1104 The value is an alist, with `heading' and `plain-list-item' as CAR,
1105 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1106 which case Org will look at the surrounding headings/items and try to
1107 make an intelligent decision whether to insert a blank line or not.
1109 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1110 set, the setting here is ignored and no empty line is inserted, to avoid
1111 breaking the list structure."
1112 :group 'org-edit-structure
1113 :type '(list
1114 (cons (const heading)
1115 (choice (const :tag "Never" nil)
1116 (const :tag "Always" t)
1117 (const :tag "Auto" auto)))
1118 (cons (const plain-list-item)
1119 (choice (const :tag "Never" nil)
1120 (const :tag "Always" t)
1121 (const :tag "Auto" auto)))))
1123 (defcustom org-insert-heading-hook nil
1124 "Hook being run after inserting a new heading."
1125 :group 'org-edit-structure
1126 :type 'hook)
1128 (defcustom org-enable-fixed-width-editor t
1129 "Non-nil means lines starting with \":\" are treated as fixed-width.
1130 This currently only means they are never auto-wrapped.
1131 When nil, such lines will be treated like ordinary lines.
1132 See also the QUOTE keyword."
1133 :group 'org-edit-structure
1134 :type 'boolean)
1136 (defcustom org-goto-auto-isearch t
1137 "Non-nil means typing characters in `org-goto' starts incremental search."
1138 :group 'org-edit-structure
1139 :type 'boolean)
1141 (defgroup org-sparse-trees nil
1142 "Options concerning sparse trees in Org-mode."
1143 :tag "Org Sparse Trees"
1144 :group 'org-structure)
1146 (defcustom org-highlight-sparse-tree-matches t
1147 "Non-nil means highlight all matches that define a sparse tree.
1148 The highlights will automatically disappear the next time the buffer is
1149 changed by an edit command."
1150 :group 'org-sparse-trees
1151 :type 'boolean)
1153 (defcustom org-remove-highlights-with-change t
1154 "Non-nil means any change to the buffer will remove temporary highlights.
1155 Such highlights are created by `org-occur' and `org-clock-display'.
1156 When nil, `C-c C-c needs to be used to get rid of the highlights.
1157 The highlights created by `org-preview-latex-fragment' always need
1158 `C-c C-c' to be removed."
1159 :group 'org-sparse-trees
1160 :group 'org-time
1161 :type 'boolean)
1164 (defcustom org-occur-hook '(org-first-headline-recenter)
1165 "Hook that is run after `org-occur' has constructed a sparse tree.
1166 This can be used to recenter the window to show as much of the structure
1167 as possible."
1168 :group 'org-sparse-trees
1169 :type 'hook)
1171 (defgroup org-imenu-and-speedbar nil
1172 "Options concerning imenu and speedbar in Org-mode."
1173 :tag "Org Imenu and Speedbar"
1174 :group 'org-structure)
1176 (defcustom org-imenu-depth 2
1177 "The maximum level for Imenu access to Org-mode headlines.
1178 This also applied for speedbar access."
1179 :group 'org-imenu-and-speedbar
1180 :type 'integer)
1182 (defgroup org-table nil
1183 "Options concerning tables in Org-mode."
1184 :tag "Org Table"
1185 :group 'org)
1187 (defcustom org-enable-table-editor 'optimized
1188 "Non-nil means lines starting with \"|\" are handled by the table editor.
1189 When nil, such lines will be treated like ordinary lines.
1191 When equal to the symbol `optimized', the table editor will be optimized to
1192 do the following:
1193 - Automatic overwrite mode in front of whitespace in table fields.
1194 This makes the structure of the table stay in tact as long as the edited
1195 field does not exceed the column width.
1196 - Minimize the number of realigns. Normally, the table is aligned each time
1197 TAB or RET are pressed to move to another field. With optimization this
1198 happens only if changes to a field might have changed the column width.
1199 Optimization requires replacing the functions `self-insert-command',
1200 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1201 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1202 very good at guessing when a re-align will be necessary, but you can always
1203 force one with \\[org-ctrl-c-ctrl-c].
1205 If you would like to use the optimized version in Org-mode, but the
1206 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1208 This variable can be used to turn on and off the table editor during a session,
1209 but in order to toggle optimization, a restart is required.
1211 See also the variable `org-table-auto-blank-field'."
1212 :group 'org-table
1213 :type '(choice
1214 (const :tag "off" nil)
1215 (const :tag "on" t)
1216 (const :tag "on, optimized" optimized)))
1218 (defcustom org-self-insert-cluster-for-undo t
1219 "Non-nil means cluster self-insert commands for undo when possible.
1220 If this is set, then, like in the Emacs command loop, 20 consecutive
1221 characters will be undone together.
1222 This is configurable, because there is some impact on typing performance."
1223 :group 'org-table
1224 :type 'boolean)
1226 (defcustom org-table-tab-recognizes-table.el t
1227 "Non-nil means TAB will automatically notice a table.el table.
1228 When it sees such a table, it moves point into it and - if necessary -
1229 calls `table-recognize-table'."
1230 :group 'org-table-editing
1231 :type 'boolean)
1233 (defgroup org-link nil
1234 "Options concerning links in Org-mode."
1235 :tag "Org Link"
1236 :group 'org)
1238 (defvar org-link-abbrev-alist-local nil
1239 "Buffer-local version of `org-link-abbrev-alist', which see.
1240 The value of this is taken from the #+LINK lines.")
1241 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1243 (defcustom org-link-abbrev-alist nil
1244 "Alist of link abbreviations.
1245 The car of each element is a string, to be replaced at the start of a link.
1246 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1247 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1249 [[linkkey:tag][description]]
1251 The 'linkkey' must be a word word, starting with a letter, followed
1252 by letters, numbers, '-' or '_'.
1254 If REPLACE is a string, the tag will simply be appended to create the link.
1255 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1256 the placeholder \"%h\" will cause a url-encoded version of the tag to
1257 be inserted at that point (see the function `url-hexify-string').
1259 REPLACE may also be a function that will be called with the tag as the
1260 only argument to create the link, which should be returned as a string.
1262 See the manual for examples."
1263 :group 'org-link
1264 :type '(repeat
1265 (cons
1266 (string :tag "Protocol")
1267 (choice
1268 (string :tag "Format")
1269 (function)))))
1271 (defcustom org-descriptive-links t
1272 "Non-nil means Org will display descriptive links.
1273 E.g. [[http://orgmode.org][Org website]] will be displayed as
1274 \"Org Website\", hiding the link itself and just displaying its
1275 description. When set to `nil', Org will display the full links
1276 literally.
1278 You can interactively set the value of this variable by calling
1279 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1280 :group 'org-link
1281 :type 'boolean)
1283 (defcustom org-link-file-path-type 'adaptive
1284 "How the path name in file links should be stored.
1285 Valid values are:
1287 relative Relative to the current directory, i.e. the directory of the file
1288 into which the link is being inserted.
1289 absolute Absolute path, if possible with ~ for home directory.
1290 noabbrev Absolute path, no abbreviation of home directory.
1291 adaptive Use relative path for files in the current directory and sub-
1292 directories of it. For other files, use an absolute path."
1293 :group 'org-link
1294 :type '(choice
1295 (const relative)
1296 (const absolute)
1297 (const noabbrev)
1298 (const adaptive)))
1300 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1301 "Types of links that should be activated in Org-mode files.
1302 This is a list of symbols, each leading to the activation of a certain link
1303 type. In principle, it does not hurt to turn on most link types - there may
1304 be a small gain when turning off unused link types. The types are:
1306 bracket The recommended [[link][description]] or [[link]] links with hiding.
1307 angle Links in angular brackets that may contain whitespace like
1308 <bbdb:Carsten Dominik>.
1309 plain Plain links in normal text, no whitespace, like http://google.com.
1310 radio Text that is matched by a radio target, see manual for details.
1311 tag Tag settings in a headline (link to tag search).
1312 date Time stamps (link to calendar).
1313 footnote Footnote labels.
1315 Changing this variable requires a restart of Emacs to become effective."
1316 :group 'org-link
1317 :type '(set :greedy t
1318 (const :tag "Double bracket links" bracket)
1319 (const :tag "Angular bracket links" angle)
1320 (const :tag "Plain text links" plain)
1321 (const :tag "Radio target matches" radio)
1322 (const :tag "Tags" tag)
1323 (const :tag "Timestamps" date)
1324 (const :tag "Footnotes" footnote)))
1326 (defcustom org-make-link-description-function nil
1327 "Function to use to generate link descriptions from links.
1328 If nil the link location will be used. This function must take
1329 two parameters; the first is the link and the second the
1330 description `org-insert-link' has generated, and should return the
1331 description to use."
1332 :group 'org-link
1333 :type 'function)
1335 (defgroup org-link-store nil
1336 "Options concerning storing links in Org-mode."
1337 :tag "Org Store Link"
1338 :group 'org-link)
1340 (defcustom org-email-link-description-format "Email %c: %.30s"
1341 "Format of the description part of a link to an email or usenet message.
1342 The following %-escapes will be replaced by corresponding information:
1344 %F full \"From\" field
1345 %f name, taken from \"From\" field, address if no name
1346 %T full \"To\" field
1347 %t first name in \"To\" field, address if no name
1348 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1349 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1350 %s subject
1351 %d date
1352 %m message-id.
1354 You may use normal field width specification between the % and the letter.
1355 This is for example useful to limit the length of the subject.
1357 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1358 :group 'org-link-store
1359 :type 'string)
1361 (defcustom org-from-is-user-regexp
1362 (let (r1 r2)
1363 (when (and user-mail-address (not (string= user-mail-address "")))
1364 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1365 (when (and user-full-name (not (string= user-full-name "")))
1366 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1367 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1368 "Regexp matched against the \"From:\" header of an email or usenet message.
1369 It should match if the message is from the user him/herself."
1370 :group 'org-link-store
1371 :type 'regexp)
1373 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1374 "Non-nil means storing a link to an Org file will use entry IDs.
1376 Note that before this variable is even considered, org-id must be loaded,
1377 so please customize `org-modules' and turn it on.
1379 The variable can have the following values:
1381 t Create an ID if needed to make a link to the current entry.
1383 create-if-interactive
1384 If `org-store-link' is called directly (interactively, as a user
1385 command), do create an ID to support the link. But when doing the
1386 job for remember, only use the ID if it already exists. The
1387 purpose of this setting is to avoid proliferation of unwanted
1388 IDs, just because you happen to be in an Org file when you
1389 call `org-remember' that automatically and preemptively
1390 creates a link. If you do want to get an ID link in a remember
1391 template to an entry not having an ID, create it first by
1392 explicitly creating a link to it, using `C-c C-l' first.
1394 create-if-interactive-and-no-custom-id
1395 Like create-if-interactive, but do not create an ID if there is
1396 a CUSTOM_ID property defined in the entry. This is the default.
1398 use-existing
1399 Use existing ID, do not create one.
1401 nil Never use an ID to make a link, instead link using a text search for
1402 the headline text."
1403 :group 'org-link-store
1404 :type '(choice
1405 (const :tag "Create ID to make link" t)
1406 (const :tag "Create if storing link interactively"
1407 create-if-interactive)
1408 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1409 create-if-interactive-and-no-custom-id)
1410 (const :tag "Only use existing" use-existing)
1411 (const :tag "Do not use ID to create link" nil)))
1413 (defcustom org-context-in-file-links t
1414 "Non-nil means file links from `org-store-link' contain context.
1415 A search string will be added to the file name with :: as separator and
1416 used to find the context when the link is activated by the command
1417 `org-open-at-point'. When this option is t, the entire active region
1418 will be placed in the search string of the file link. If set to a
1419 positive integer, only the first n lines of context will be stored.
1421 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1422 negates this setting for the duration of the command."
1423 :group 'org-link-store
1424 :type '(choice boolean integer))
1426 (defcustom org-keep-stored-link-after-insertion nil
1427 "Non-nil means keep link in list for entire session.
1429 The command `org-store-link' adds a link pointing to the current
1430 location to an internal list. These links accumulate during a session.
1431 The command `org-insert-link' can be used to insert links into any
1432 Org-mode file (offering completion for all stored links). When this
1433 option is nil, every link which has been inserted once using \\[org-insert-link]
1434 will be removed from the list, to make completing the unused links
1435 more efficient."
1436 :group 'org-link-store
1437 :type 'boolean)
1439 (defgroup org-link-follow nil
1440 "Options concerning following links in Org-mode."
1441 :tag "Org Follow Link"
1442 :group 'org-link)
1444 (defcustom org-link-translation-function nil
1445 "Function to translate links with different syntax to Org syntax.
1446 This can be used to translate links created for example by the Planner
1447 or emacs-wiki packages to Org syntax.
1448 The function must accept two parameters, a TYPE containing the link
1449 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1450 which is everything after the link protocol. It should return a cons
1451 with possibly modified values of type and path.
1452 Org contains a function for this, so if you set this variable to
1453 `org-translate-link-from-planner', you should be able follow many
1454 links created by planner."
1455 :group 'org-link-follow
1456 :type 'function)
1458 (defcustom org-follow-link-hook nil
1459 "Hook that is run after a link has been followed."
1460 :group 'org-link-follow
1461 :type 'hook)
1463 (defcustom org-tab-follows-link nil
1464 "Non-nil means on links TAB will follow the link.
1465 Needs to be set before org.el is loaded.
1466 This really should not be used, it does not make sense, and the
1467 implementation is bad."
1468 :group 'org-link-follow
1469 :type 'boolean)
1471 (defcustom org-return-follows-link nil
1472 "Non-nil means on links RET will follow the link."
1473 :group 'org-link-follow
1474 :type 'boolean)
1476 (defcustom org-mouse-1-follows-link
1477 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1478 "Non-nil means mouse-1 on a link will follow the link.
1479 A longer mouse click will still set point. Does not work on XEmacs.
1480 Needs to be set before org.el is loaded."
1481 :group 'org-link-follow
1482 :type 'boolean)
1484 (defcustom org-mark-ring-length 4
1485 "Number of different positions to be recorded in the ring.
1486 Changing this requires a restart of Emacs to work correctly."
1487 :group 'org-link-follow
1488 :type 'integer)
1490 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1491 "Non-nil means internal links in Org files must exactly match a headline.
1492 When nil, the link search tries to match a phrase with all words
1493 in the search text."
1494 :group 'org-link-follow
1495 :type '(choice
1496 (const :tag "Use fuzy text search" nil)
1497 (const :tag "Match only exact headline" t)
1498 (const :tag "Match extact headline or query to create it"
1499 query-to-create)))
1501 (defcustom org-link-frame-setup
1502 '((vm . vm-visit-folder-other-frame)
1503 (gnus . org-gnus-no-new-news)
1504 (file . find-file-other-window)
1505 (wl . wl-other-frame))
1506 "Setup the frame configuration for following links.
1507 When following a link with Emacs, it may often be useful to display
1508 this link in another window or frame. This variable can be used to
1509 set this up for the different types of links.
1510 For VM, use any of
1511 `vm-visit-folder'
1512 `vm-visit-folder-other-window'
1513 `vm-visit-folder-other-frame'
1514 For Gnus, use any of
1515 `gnus'
1516 `gnus-other-frame'
1517 `org-gnus-no-new-news'
1518 For FILE, use any of
1519 `find-file'
1520 `find-file-other-window'
1521 `find-file-other-frame'
1522 For Wanderlust use any of
1523 `wl'
1524 `wl-other-frame'
1525 For the calendar, use the variable `calendar-setup'.
1526 For BBDB, it is currently only possible to display the matches in
1527 another window."
1528 :group 'org-link-follow
1529 :type '(list
1530 (cons (const vm)
1531 (choice
1532 (const vm-visit-folder)
1533 (const vm-visit-folder-other-window)
1534 (const vm-visit-folder-other-frame)))
1535 (cons (const gnus)
1536 (choice
1537 (const gnus)
1538 (const gnus-other-frame)
1539 (const org-gnus-no-new-news)))
1540 (cons (const file)
1541 (choice
1542 (const find-file)
1543 (const find-file-other-window)
1544 (const find-file-other-frame)))
1545 (cons (const wl)
1546 (choice
1547 (const wl)
1548 (const wl-other-frame)))))
1550 (defcustom org-display-internal-link-with-indirect-buffer nil
1551 "Non-nil means use indirect buffer to display infile links.
1552 Activating internal links (from one location in a file to another location
1553 in the same file) normally just jumps to the location. When the link is
1554 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1555 is displayed in
1556 another window. When this option is set, the other window actually displays
1557 an indirect buffer clone of the current buffer, to avoid any visibility
1558 changes to the current buffer."
1559 :group 'org-link-follow
1560 :type 'boolean)
1562 (defcustom org-open-non-existing-files nil
1563 "Non-nil means `org-open-file' will open non-existing files.
1564 When nil, an error will be generated.
1565 This variable applies only to external applications because they
1566 might choke on non-existing files. If the link is to a file that
1567 will be opened in Emacs, the variable is ignored."
1568 :group 'org-link-follow
1569 :type 'boolean)
1571 (defcustom org-open-directory-means-index-dot-org nil
1572 "Non-nil means a link to a directory really means to index.org.
1573 When nil, following a directory link will run dired or open a finder/explorer
1574 window on that directory."
1575 :group 'org-link-follow
1576 :type 'boolean)
1578 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1579 "Function and arguments to call for following mailto links.
1580 This is a list with the first element being a Lisp function, and the
1581 remaining elements being arguments to the function. In string arguments,
1582 %a will be replaced by the address, and %s will be replaced by the subject
1583 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1584 :group 'org-link-follow
1585 :type '(choice
1586 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1587 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1588 (const :tag "message-mail" (message-mail "%a" "%s"))
1589 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1591 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1592 "Non-nil means ask for confirmation before executing shell links.
1593 Shell links can be dangerous: just think about a link
1595 [[shell:rm -rf ~/*][Google Search]]
1597 This link would show up in your Org-mode document as \"Google Search\",
1598 but really it would remove your entire home directory.
1599 Therefore we advise against setting this variable to nil.
1600 Just change it to `y-or-n-p' if you want to confirm with a
1601 single keystroke rather than having to type \"yes\"."
1602 :group 'org-link-follow
1603 :type '(choice
1604 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1605 (const :tag "with y-or-n (faster)" y-or-n-p)
1606 (const :tag "no confirmation (dangerous)" nil)))
1607 (put 'org-confirm-shell-link-function
1608 'safe-local-variable
1609 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1611 (defcustom org-confirm-shell-link-not-regexp ""
1612 "A regexp to skip confirmation for shell links."
1613 :group 'org-link-follow
1614 :type 'regexp)
1616 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1617 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1618 Elisp links can be dangerous: just think about a link
1620 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1622 This link would show up in your Org-mode document as \"Google Search\",
1623 but really it would remove your entire home directory.
1624 Therefore we advise against setting this variable to nil.
1625 Just change it to `y-or-n-p' if you want to confirm with a
1626 single keystroke rather than having to type \"yes\"."
1627 :group 'org-link-follow
1628 :type '(choice
1629 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1630 (const :tag "with y-or-n (faster)" y-or-n-p)
1631 (const :tag "no confirmation (dangerous)" nil)))
1632 (put 'org-confirm-shell-link-function
1633 'safe-local-variable
1634 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1636 (defcustom org-confirm-elisp-link-not-regexp ""
1637 "A regexp to skip confirmation for Elisp links."
1638 :group 'org-link-follow
1639 :type 'regexp)
1641 (defconst org-file-apps-defaults-gnu
1642 '((remote . emacs)
1643 (system . mailcap)
1644 (t . mailcap))
1645 "Default file applications on a UNIX or GNU/Linux system.
1646 See `org-file-apps'.")
1648 (defconst org-file-apps-defaults-macosx
1649 '((remote . emacs)
1650 (t . "open %s")
1651 (system . "open %s")
1652 ("ps.gz" . "gv %s")
1653 ("eps.gz" . "gv %s")
1654 ("dvi" . "xdvi %s")
1655 ("fig" . "xfig %s"))
1656 "Default file applications on a MacOS X system.
1657 The system \"open\" is known as a default, but we use X11 applications
1658 for some files for which the OS does not have a good default.
1659 See `org-file-apps'.")
1661 (defconst org-file-apps-defaults-windowsnt
1662 (list
1663 '(remote . emacs)
1664 (cons t
1665 (list (if (featurep 'xemacs)
1666 'mswindows-shell-execute
1667 'w32-shell-execute)
1668 "open" 'file))
1669 (cons 'system
1670 (list (if (featurep 'xemacs)
1671 'mswindows-shell-execute
1672 'w32-shell-execute)
1673 "open" 'file)))
1674 "Default file applications on a Windows NT system.
1675 The system \"open\" is used for most files.
1676 See `org-file-apps'.")
1678 (defcustom org-file-apps
1680 (auto-mode . emacs)
1681 ("\\.mm\\'" . default)
1682 ("\\.x?html?\\'" . default)
1683 ("\\.pdf\\'" . default)
1685 "External applications for opening `file:path' items in a document.
1686 Org-mode uses system defaults for different file types, but
1687 you can use this variable to set the application for a given file
1688 extension. The entries in this list are cons cells where the car identifies
1689 files and the cdr the corresponding command. Possible values for the
1690 file identifier are
1691 \"string\" A string as a file identifier can be interpreted in different
1692 ways, depending on its contents:
1694 - Alphanumeric characters only:
1695 Match links with this file extension.
1696 Example: (\"pdf\" . \"evince %s\")
1697 to open PDFs with evince.
1699 - Regular expression: Match links where the
1700 filename matches the regexp. If you want to
1701 use groups here, use shy groups.
1703 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1704 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1705 to open *.html and *.xhtml with firefox.
1707 - Regular expression which contains (non-shy) groups:
1708 Match links where the whole link, including \"::\", and
1709 anything after that, matches the regexp.
1710 In a custom command string, %1, %2, etc. are replaced with
1711 the parts of the link that were matched by the groups.
1712 For backwards compatibility, if a command string is given
1713 that does not use any of the group matches, this case is
1714 handled identically to the second one (i.e. match against
1715 file name only).
1716 In a custom lisp form, you can access the group matches with
1717 (match-string n link).
1719 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1720 to open [[file:document.pdf::5]] with evince at page 5.
1722 `directory' Matches a directory
1723 `remote' Matches a remote file, accessible through tramp or efs.
1724 Remote files most likely should be visited through Emacs
1725 because external applications cannot handle such paths.
1726 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1727 so all files Emacs knows how to handle. Using this with
1728 command `emacs' will open most files in Emacs. Beware that this
1729 will also open html files inside Emacs, unless you add
1730 (\"html\" . default) to the list as well.
1731 t Default for files not matched by any of the other options.
1732 `system' The system command to open files, like `open' on Windows
1733 and Mac OS X, and mailcap under GNU/Linux. This is the command
1734 that will be selected if you call `C-c C-o' with a double
1735 \\[universal-argument] \\[universal-argument] prefix.
1737 Possible values for the command are:
1738 `emacs' The file will be visited by the current Emacs process.
1739 `default' Use the default application for this file type, which is the
1740 association for t in the list, most likely in the system-specific
1741 part.
1742 This can be used to overrule an unwanted setting in the
1743 system-specific variable.
1744 `system' Use the system command for opening files, like \"open\".
1745 This command is specified by the entry whose car is `system'.
1746 Most likely, the system-specific version of this variable
1747 does define this command, but you can overrule/replace it
1748 here.
1749 string A command to be executed by a shell; %s will be replaced
1750 by the path to the file.
1751 sexp A Lisp form which will be evaluated. The file path will
1752 be available in the Lisp variable `file'.
1753 For more examples, see the system specific constants
1754 `org-file-apps-defaults-macosx'
1755 `org-file-apps-defaults-windowsnt'
1756 `org-file-apps-defaults-gnu'."
1757 :group 'org-link-follow
1758 :type '(repeat
1759 (cons (choice :value ""
1760 (string :tag "Extension")
1761 (const :tag "System command to open files" system)
1762 (const :tag "Default for unrecognized files" t)
1763 (const :tag "Remote file" remote)
1764 (const :tag "Links to a directory" directory)
1765 (const :tag "Any files that have Emacs modes"
1766 auto-mode))
1767 (choice :value ""
1768 (const :tag "Visit with Emacs" emacs)
1769 (const :tag "Use default" default)
1770 (const :tag "Use the system command" system)
1771 (string :tag "Command")
1772 (sexp :tag "Lisp form")))))
1776 (defgroup org-refile nil
1777 "Options concerning refiling entries in Org-mode."
1778 :tag "Org Refile"
1779 :group 'org)
1781 (defcustom org-directory "~/org"
1782 "Directory with org files.
1783 This is just a default location to look for Org files. There is no need
1784 at all to put your files into this directory. It is only used in the
1785 following situations:
1787 1. When a remember template specifies a target file that is not an
1788 absolute path. The path will then be interpreted relative to
1789 `org-directory'
1790 2. When a remember note is filed away in an interactive way (when exiting the
1791 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1792 with `org-directory' as the default path."
1793 :group 'org-refile
1794 :group 'org-remember
1795 :type 'directory)
1797 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1798 "Default target for storing notes.
1799 Used as a fall back file for org-remember.el and org-capture.el, for
1800 templates that do not specify a target file."
1801 :group 'org-refile
1802 :group 'org-remember
1803 :type '(choice
1804 (const :tag "Default from remember-data-file" nil)
1805 file))
1807 (defcustom org-goto-interface 'outline
1808 "The default interface to be used for `org-goto'.
1809 Allowed values are:
1810 outline The interface shows an outline of the relevant file
1811 and the correct heading is found by moving through
1812 the outline or by searching with incremental search.
1813 outline-path-completion Headlines in the current buffer are offered via
1814 completion. This is the interface also used by
1815 the refile command."
1816 :group 'org-refile
1817 :type '(choice
1818 (const :tag "Outline" outline)
1819 (const :tag "Outline-path-completion" outline-path-completion)))
1821 (defcustom org-goto-max-level 5
1822 "Maximum target level when running `org-goto' with refile interface."
1823 :group 'org-refile
1824 :type 'integer)
1826 (defcustom org-reverse-note-order nil
1827 "Non-nil means store new notes at the beginning of a file or entry.
1828 When nil, new notes will be filed to the end of a file or entry.
1829 This can also be a list with cons cells of regular expressions that
1830 are matched against file names, and values."
1831 :group 'org-remember
1832 :group 'org-refile
1833 :type '(choice
1834 (const :tag "Reverse always" t)
1835 (const :tag "Reverse never" nil)
1836 (repeat :tag "By file name regexp"
1837 (cons regexp boolean))))
1839 (defcustom org-log-refile nil
1840 "Information to record when a task is refiled.
1842 Possible values are:
1844 nil Don't add anything
1845 time Add a time stamp to the task
1846 note Prompt for a note and add it with template `org-log-note-headings'
1848 This option can also be set with on a per-file-basis with
1850 #+STARTUP: nologrefile
1851 #+STARTUP: logrefile
1852 #+STARTUP: lognoterefile
1854 You can have local logging settings for a subtree by setting the LOGGING
1855 property to one or more of these keywords.
1857 When bulk-refiling from the agenda, the value `note' is forbidden and
1858 will temporarily be changed to `time'."
1859 :group 'org-refile
1860 :group 'org-progress
1861 :type '(choice
1862 (const :tag "No logging" nil)
1863 (const :tag "Record timestamp" time)
1864 (const :tag "Record timestamp with note." note)))
1866 (defcustom org-refile-targets nil
1867 "Targets for refiling entries with \\[org-refile].
1868 This is a list of cons cells. Each cell contains:
1869 - a specification of the files to be considered, either a list of files,
1870 or a symbol whose function or variable value will be used to retrieve
1871 a file name or a list of file names. If you use `org-agenda-files' for
1872 that, all agenda files will be scanned for targets. Nil means consider
1873 headings in the current buffer.
1874 - A specification of how to find candidate refile targets. This may be
1875 any of:
1876 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1877 This tag has to be present in all target headlines, inheritance will
1878 not be considered.
1879 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1880 todo keyword.
1881 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1882 headlines that are refiling targets.
1883 - a cons cell (:level . N). Any headline of level N is considered a target.
1884 Note that, when `org-odd-levels-only' is set, level corresponds to
1885 order in hierarchy, not to the number of stars.
1886 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1887 Note that, when `org-odd-levels-only' is set, level corresponds to
1888 order in hierarchy, not to the number of stars.
1890 Each element of this list generates a set of possible targets.
1891 The union of these sets is presented (with completion) to
1892 the user by `org-refile'.
1894 You can set the variable `org-refile-target-verify-function' to a function
1895 to verify each headline found by the simple criteria above.
1897 When this variable is nil, all top-level headlines in the current buffer
1898 are used, equivalent to the value `((nil . (:level . 1))'."
1899 :group 'org-refile
1900 :type '(repeat
1901 (cons
1902 (choice :value org-agenda-files
1903 (const :tag "All agenda files" org-agenda-files)
1904 (const :tag "Current buffer" nil)
1905 (function) (variable) (file))
1906 (choice :tag "Identify target headline by"
1907 (cons :tag "Specific tag" (const :value :tag) (string))
1908 (cons :tag "TODO keyword" (const :value :todo) (string))
1909 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1910 (cons :tag "Level number" (const :value :level) (integer))
1911 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1913 (defcustom org-refile-target-verify-function nil
1914 "Function to verify if the headline at point should be a refile target.
1915 The function will be called without arguments, with point at the
1916 beginning of the headline. It should return t and leave point
1917 where it is if the headline is a valid target for refiling.
1919 If the target should not be selected, the function must return nil.
1920 In addition to this, it may move point to a place from where the search
1921 should be continued. For example, the function may decide that the entire
1922 subtree of the current entry should be excluded and move point to the end
1923 of the subtree."
1924 :group 'org-refile
1925 :type 'function)
1927 (defcustom org-refile-use-cache nil
1928 "Non-nil means cache refile targets to speed up the process.
1929 The cache for a particular file will be updated automatically when
1930 the buffer has been killed, or when any of the marker used for flagging
1931 refile targets no longer points at a live buffer.
1932 If you have added new entries to a buffer that might themselves be targets,
1933 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1934 find that easier, `C-u C-u C-u C-c C-w'."
1935 :group 'org-refile
1936 :type 'boolean)
1938 (defcustom org-refile-use-outline-path nil
1939 "Non-nil means provide refile targets as paths.
1940 So a level 3 headline will be available as level1/level2/level3.
1942 When the value is `file', also include the file name (without directory)
1943 into the path. In this case, you can also stop the completion after
1944 the file name, to get entries inserted as top level in the file.
1946 When `full-file-path', include the full file path."
1947 :group 'org-refile
1948 :type '(choice
1949 (const :tag "Not" nil)
1950 (const :tag "Yes" t)
1951 (const :tag "Start with file name" file)
1952 (const :tag "Start with full file path" full-file-path)))
1954 (defcustom org-outline-path-complete-in-steps t
1955 "Non-nil means complete the outline path in hierarchical steps.
1956 When Org-mode uses the refile interface to select an outline path
1957 \(see variable `org-refile-use-outline-path'), the completion of
1958 the path can be done is a single go, or if can be done in steps down
1959 the headline hierarchy. Going in steps is probably the best if you
1960 do not use a special completion package like `ido' or `icicles'.
1961 However, when using these packages, going in one step can be very
1962 fast, while still showing the whole path to the entry."
1963 :group 'org-refile
1964 :type 'boolean)
1966 (defcustom org-refile-allow-creating-parent-nodes nil
1967 "Non-nil means allow to create new nodes as refile targets.
1968 New nodes are then created by adding \"/new node name\" to the completion
1969 of an existing node. When the value of this variable is `confirm',
1970 new node creation must be confirmed by the user (recommended)
1971 When nil, the completion must match an existing entry.
1973 Note that, if the new heading is not seen by the criteria
1974 listed in `org-refile-targets', multiple instances of the same
1975 heading would be created by trying again to file under the new
1976 heading."
1977 :group 'org-refile
1978 :type '(choice
1979 (const :tag "Never" nil)
1980 (const :tag "Always" t)
1981 (const :tag "Prompt for confirmation" confirm)))
1983 (defcustom org-refile-active-region-within-subtree nil
1984 "Non-nil means also refile active region within a subtree.
1986 By default `org-refile' doesn't allow refiling regions if they
1987 don't contain a set of subtrees, but it might be convenient to
1988 do so sometimes: in that case, the first line of the region is
1989 converted to a headline before refiling."
1990 :group 'org-refile
1991 :type 'boolean)
1993 (defgroup org-todo nil
1994 "Options concerning TODO items in Org-mode."
1995 :tag "Org TODO"
1996 :group 'org)
1998 (defgroup org-progress nil
1999 "Options concerning Progress logging in Org-mode."
2000 :tag "Org Progress"
2001 :group 'org-time)
2003 (defvar org-todo-interpretation-widgets
2004 '((:tag "Sequence (cycling hits every state)" sequence)
2005 (:tag "Type (cycling directly to DONE)" type))
2006 "The available interpretation symbols for customizing `org-todo-keywords'.
2007 Interested libraries should add to this list.")
2009 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2010 "List of TODO entry keyword sequences and their interpretation.
2011 \\<org-mode-map>This is a list of sequences.
2013 Each sequence starts with a symbol, either `sequence' or `type',
2014 indicating if the keywords should be interpreted as a sequence of
2015 action steps, or as different types of TODO items. The first
2016 keywords are states requiring action - these states will select a headline
2017 for inclusion into the global TODO list Org-mode produces. If one of
2018 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2019 signify that no further action is necessary. If \"|\" is not found,
2020 the last keyword is treated as the only DONE state of the sequence.
2022 The command \\[org-todo] cycles an entry through these states, and one
2023 additional state where no keyword is present. For details about this
2024 cycling, see the manual.
2026 TODO keywords and interpretation can also be set on a per-file basis with
2027 the special #+SEQ_TODO and #+TYP_TODO lines.
2029 Each keyword can optionally specify a character for fast state selection
2030 \(in combination with the variable `org-use-fast-todo-selection')
2031 and specifiers for state change logging, using the same syntax
2032 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2033 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2034 indicates to record a time stamp each time this state is selected.
2036 Each keyword may also specify if a timestamp or a note should be
2037 recorded when entering or leaving the state, by adding additional
2038 characters in the parenthesis after the keyword. This looks like this:
2039 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2040 record only the time of the state change. With X and Y being either
2041 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2042 Y when leaving the state if and only if the *target* state does not
2043 define X. You may omit any of the fast-selection key or X or /Y,
2044 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2046 For backward compatibility, this variable may also be just a list
2047 of keywords - in this case the interpretation (sequence or type) will be
2048 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2049 :group 'org-todo
2050 :group 'org-keywords
2051 :type '(choice
2052 (repeat :tag "Old syntax, just keywords"
2053 (string :tag "Keyword"))
2054 (repeat :tag "New syntax"
2055 (cons
2056 (choice
2057 :tag "Interpretation"
2058 ;;Quick and dirty way to see
2059 ;;`org-todo-interpretations'. This takes the
2060 ;;place of item arguments
2061 :convert-widget
2062 (lambda (widget)
2063 (widget-put widget
2064 :args (mapcar
2065 #'(lambda (x)
2066 (widget-convert
2067 (cons 'const x)))
2068 org-todo-interpretation-widgets))
2069 widget))
2070 (repeat
2071 (string :tag "Keyword"))))))
2073 (defvar org-todo-keywords-1 nil
2074 "All TODO and DONE keywords active in a buffer.")
2075 (make-variable-buffer-local 'org-todo-keywords-1)
2076 (defvar org-todo-keywords-for-agenda nil)
2077 (defvar org-done-keywords-for-agenda nil)
2078 (defvar org-drawers-for-agenda nil)
2079 (defvar org-todo-keyword-alist-for-agenda nil)
2080 (defvar org-tag-alist-for-agenda nil)
2081 (defvar org-agenda-contributing-files nil)
2082 (defvar org-not-done-keywords nil)
2083 (make-variable-buffer-local 'org-not-done-keywords)
2084 (defvar org-done-keywords nil)
2085 (make-variable-buffer-local 'org-done-keywords)
2086 (defvar org-todo-heads nil)
2087 (make-variable-buffer-local 'org-todo-heads)
2088 (defvar org-todo-sets nil)
2089 (make-variable-buffer-local 'org-todo-sets)
2090 (defvar org-todo-log-states nil)
2091 (make-variable-buffer-local 'org-todo-log-states)
2092 (defvar org-todo-kwd-alist nil)
2093 (make-variable-buffer-local 'org-todo-kwd-alist)
2094 (defvar org-todo-key-alist nil)
2095 (make-variable-buffer-local 'org-todo-key-alist)
2096 (defvar org-todo-key-trigger nil)
2097 (make-variable-buffer-local 'org-todo-key-trigger)
2099 (defcustom org-todo-interpretation 'sequence
2100 "Controls how TODO keywords are interpreted.
2101 This variable is in principle obsolete and is only used for
2102 backward compatibility, if the interpretation of todo keywords is
2103 not given already in `org-todo-keywords'. See that variable for
2104 more information."
2105 :group 'org-todo
2106 :group 'org-keywords
2107 :type '(choice (const sequence)
2108 (const type)))
2110 (defcustom org-use-fast-todo-selection t
2111 "Non-nil means use the fast todo selection scheme with C-c C-t.
2112 This variable describes if and under what circumstances the cycling
2113 mechanism for TODO keywords will be replaced by a single-key, direct
2114 selection scheme.
2116 When nil, fast selection is never used.
2118 When the symbol `prefix', it will be used when `org-todo' is called with
2119 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2120 in an agenda buffer.
2122 When t, fast selection is used by default. In this case, the prefix
2123 argument forces cycling instead.
2125 In all cases, the special interface is only used if access keys have actually
2126 been assigned by the user, i.e. if keywords in the configuration are followed
2127 by a letter in parenthesis, like TODO(t)."
2128 :group 'org-todo
2129 :type '(choice
2130 (const :tag "Never" nil)
2131 (const :tag "By default" t)
2132 (const :tag "Only with C-u C-c C-t" prefix)))
2134 (defcustom org-provide-todo-statistics t
2135 "Non-nil means update todo statistics after insert and toggle.
2136 ALL-HEADLINES means update todo statistics by including headlines
2137 with no TODO keyword as well, counting them as not done.
2138 A list of TODO keywords means the same, but skip keywords that are
2139 not in this list.
2141 When this is set, todo statistics is updated in the parent of the
2142 current entry each time a todo state is changed."
2143 :group 'org-todo
2144 :type '(choice
2145 (const :tag "Yes, only for TODO entries" t)
2146 (const :tag "Yes, including all entries" 'all-headlines)
2147 (repeat :tag "Yes, for TODOs in this list"
2148 (string :tag "TODO keyword"))
2149 (other :tag "No TODO statistics" nil)))
2151 (defcustom org-hierarchical-todo-statistics t
2152 "Non-nil means TODO statistics covers just direct children.
2153 When nil, all entries in the subtree are considered.
2154 This has only an effect if `org-provide-todo-statistics' is set.
2155 To set this to nil for only a single subtree, use a COOKIE_DATA
2156 property and include the word \"recursive\" into the value."
2157 :group 'org-todo
2158 :type 'boolean)
2160 (defcustom org-after-todo-state-change-hook nil
2161 "Hook which is run after the state of a TODO item was changed.
2162 The new state (a string with a TODO keyword, or nil) is available in the
2163 Lisp variable `state'."
2164 :group 'org-todo
2165 :type 'hook)
2167 (defvar org-blocker-hook nil
2168 "Hook for functions that are allowed to block a state change.
2170 Each function gets as its single argument a property list, see
2171 `org-trigger-hook' for more information about this list.
2173 If any of the functions in this hook returns nil, the state change
2174 is blocked.")
2176 (defvar org-trigger-hook nil
2177 "Hook for functions that are triggered by a state change.
2179 Each function gets as its single argument a property list with at least
2180 the following elements:
2182 (:type type-of-change :position pos-at-entry-start
2183 :from old-state :to new-state)
2185 Depending on the type, more properties may be present.
2187 This mechanism is currently implemented for:
2189 TODO state changes
2190 ------------------
2191 :type todo-state-change
2192 :from previous state (keyword as a string), or nil, or a symbol
2193 'todo' or 'done', to indicate the general type of state.
2194 :to new state, like in :from")
2196 (defcustom org-enforce-todo-dependencies nil
2197 "Non-nil means undone TODO entries will block switching the parent to DONE.
2198 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2199 be blocked if any prior sibling is not yet done.
2200 Finally, if the parent is blocked because of ordered siblings of its own,
2201 the child will also be blocked.
2202 This variable needs to be set before org.el is loaded, and you need to
2203 restart Emacs after a change to make the change effective. The only way
2204 to change is while Emacs is running is through the customize interface."
2205 :set (lambda (var val)
2206 (set var val)
2207 (if val
2208 (add-hook 'org-blocker-hook
2209 'org-block-todo-from-children-or-siblings-or-parent)
2210 (remove-hook 'org-blocker-hook
2211 'org-block-todo-from-children-or-siblings-or-parent)))
2212 :group 'org-todo
2213 :type 'boolean)
2215 (defcustom org-enforce-todo-checkbox-dependencies nil
2216 "Non-nil means unchecked boxes will block switching the parent to DONE.
2217 When this is nil, checkboxes have no influence on switching TODO states.
2218 When non-nil, you first need to check off all check boxes before the TODO
2219 entry can be switched to DONE.
2220 This variable needs to be set before org.el is loaded, and you need to
2221 restart Emacs after a change to make the change effective. The only way
2222 to change is while Emacs is running is through the customize interface."
2223 :set (lambda (var val)
2224 (set var val)
2225 (if val
2226 (add-hook 'org-blocker-hook
2227 'org-block-todo-from-checkboxes)
2228 (remove-hook 'org-blocker-hook
2229 'org-block-todo-from-checkboxes)))
2230 :group 'org-todo
2231 :type 'boolean)
2233 (defcustom org-treat-insert-todo-heading-as-state-change nil
2234 "Non-nil means inserting a TODO heading is treated as state change.
2235 So when the command \\[org-insert-todo-heading] is used, state change
2236 logging will apply if appropriate. When nil, the new TODO item will
2237 be inserted directly, and no logging will take place."
2238 :group 'org-todo
2239 :type 'boolean)
2241 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2242 "Non-nil means switching TODO states with S-cursor counts as state change.
2243 This is the default behavior. However, setting this to nil allows a
2244 convenient way to select a TODO state and bypass any logging associated
2245 with that."
2246 :group 'org-todo
2247 :type 'boolean)
2249 (defcustom org-todo-state-tags-triggers nil
2250 "Tag changes that should be triggered by TODO state changes.
2251 This is a list. Each entry is
2253 (state-change (tag . flag) .......)
2255 State-change can be a string with a state, and empty string to indicate the
2256 state that has no TODO keyword, or it can be one of the symbols `todo'
2257 or `done', meaning any not-done or done state, respectively."
2258 :group 'org-todo
2259 :group 'org-tags
2260 :type '(repeat
2261 (cons (choice :tag "When changing to"
2262 (const :tag "Not-done state" todo)
2263 (const :tag "Done state" done)
2264 (string :tag "State"))
2265 (repeat
2266 (cons :tag "Tag action"
2267 (string :tag "Tag")
2268 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2270 (defcustom org-log-done nil
2271 "Information to record when a task moves to the DONE state.
2273 Possible values are:
2275 nil Don't add anything, just change the keyword
2276 time Add a time stamp to the task
2277 note Prompt for a note and add it with template `org-log-note-headings'
2279 This option can also be set with on a per-file-basis with
2281 #+STARTUP: nologdone
2282 #+STARTUP: logdone
2283 #+STARTUP: lognotedone
2285 You can have local logging settings for a subtree by setting the LOGGING
2286 property to one or more of these keywords."
2287 :group 'org-todo
2288 :group 'org-progress
2289 :type '(choice
2290 (const :tag "No logging" nil)
2291 (const :tag "Record CLOSED timestamp" time)
2292 (const :tag "Record CLOSED timestamp with note." note)))
2294 ;; Normalize old uses of org-log-done.
2295 (cond
2296 ((eq org-log-done t) (setq org-log-done 'time))
2297 ((and (listp org-log-done) (memq 'done org-log-done))
2298 (setq org-log-done 'note)))
2300 (defcustom org-log-reschedule nil
2301 "Information to record when the scheduling date of a tasks is modified.
2303 Possible values are:
2305 nil Don't add anything, just change the date
2306 time Add a time stamp to the task
2307 note Prompt for a note and add it with template `org-log-note-headings'
2309 This option can also be set with on a per-file-basis with
2311 #+STARTUP: nologreschedule
2312 #+STARTUP: logreschedule
2313 #+STARTUP: lognotereschedule"
2314 :group 'org-todo
2315 :group 'org-progress
2316 :type '(choice
2317 (const :tag "No logging" nil)
2318 (const :tag "Record timestamp" time)
2319 (const :tag "Record timestamp with note." note)))
2321 (defcustom org-log-redeadline nil
2322 "Information to record when the deadline date of a tasks is modified.
2324 Possible values are:
2326 nil Don't add anything, just change the date
2327 time Add a time stamp to the task
2328 note Prompt for a note and add it with template `org-log-note-headings'
2330 This option can also be set with on a per-file-basis with
2332 #+STARTUP: nologredeadline
2333 #+STARTUP: logredeadline
2334 #+STARTUP: lognoteredeadline
2336 You can have local logging settings for a subtree by setting the LOGGING
2337 property to one or more of these keywords."
2338 :group 'org-todo
2339 :group 'org-progress
2340 :type '(choice
2341 (const :tag "No logging" nil)
2342 (const :tag "Record timestamp" time)
2343 (const :tag "Record timestamp with note." note)))
2345 (defcustom org-log-note-clock-out nil
2346 "Non-nil means record a note when clocking out of an item.
2347 This can also be configured on a per-file basis by adding one of
2348 the following lines anywhere in the buffer:
2350 #+STARTUP: lognoteclock-out
2351 #+STARTUP: nolognoteclock-out"
2352 :group 'org-todo
2353 :group 'org-progress
2354 :type 'boolean)
2356 (defcustom org-log-done-with-time t
2357 "Non-nil means the CLOSED time stamp will contain date and time.
2358 When nil, only the date will be recorded."
2359 :group 'org-progress
2360 :type 'boolean)
2362 (defcustom org-log-note-headings
2363 '((done . "CLOSING NOTE %t")
2364 (state . "State %-12s from %-12S %t")
2365 (note . "Note taken on %t")
2366 (reschedule . "Rescheduled from %S on %t")
2367 (delschedule . "Not scheduled, was %S on %t")
2368 (redeadline . "New deadline from %S on %t")
2369 (deldeadline . "Removed deadline, was %S on %t")
2370 (refile . "Refiled on %t")
2371 (clock-out . ""))
2372 "Headings for notes added to entries.
2373 The value is an alist, with the car being a symbol indicating the note
2374 context, and the cdr is the heading to be used. The heading may also be the
2375 empty string.
2376 %t in the heading will be replaced by a time stamp.
2377 %T will be an active time stamp instead the default inactive one
2378 %d will be replaced by a short-format time stamp.
2379 %D will be replaced by an active short-format time stamp.
2380 %s will be replaced by the new TODO state, in double quotes.
2381 %S will be replaced by the old TODO state, in double quotes.
2382 %u will be replaced by the user name.
2383 %U will be replaced by the full user name.
2385 In fact, it is not a good idea to change the `state' entry, because
2386 agenda log mode depends on the format of these entries."
2387 :group 'org-todo
2388 :group 'org-progress
2389 :type '(list :greedy t
2390 (cons (const :tag "Heading when closing an item" done) string)
2391 (cons (const :tag
2392 "Heading when changing todo state (todo sequence only)"
2393 state) string)
2394 (cons (const :tag "Heading when just taking a note" note) string)
2395 (cons (const :tag "Heading when clocking out" clock-out) string)
2396 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2397 (cons (const :tag "Heading when rescheduling" reschedule) string)
2398 (cons (const :tag "Heading when changing deadline" redeadline) string)
2399 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2400 (cons (const :tag "Heading when refiling" refile) string)))
2402 (unless (assq 'note org-log-note-headings)
2403 (push '(note . "%t") org-log-note-headings))
2405 (defcustom org-log-into-drawer nil
2406 "Non-nil means insert state change notes and time stamps into a drawer.
2407 When nil, state changes notes will be inserted after the headline and
2408 any scheduling and clock lines, but not inside a drawer.
2410 The value of this variable should be the name of the drawer to use.
2411 LOGBOOK is proposed as the default drawer for this purpose, you can
2412 also set this to a string to define the drawer of your choice.
2414 A value of t is also allowed, representing \"LOGBOOK\".
2416 If this variable is set, `org-log-state-notes-insert-after-drawers'
2417 will be ignored.
2419 You can set the property LOG_INTO_DRAWER to overrule this setting for
2420 a subtree."
2421 :group 'org-todo
2422 :group 'org-progress
2423 :type '(choice
2424 (const :tag "Not into a drawer" nil)
2425 (const :tag "LOGBOOK" t)
2426 (string :tag "Other")))
2428 (if (fboundp 'defvaralias)
2429 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2431 (defun org-log-into-drawer ()
2432 "Return the value of `org-log-into-drawer', but let properties overrule.
2433 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2434 used instead of the default value."
2435 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2436 (cond
2437 ((or (not p) (equal p "nil")) org-log-into-drawer)
2438 ((equal p "t") "LOGBOOK")
2439 (t p))))
2441 (defcustom org-log-state-notes-insert-after-drawers nil
2442 "Non-nil means insert state change notes after any drawers in entry.
2443 Only the drawers that *immediately* follow the headline and the
2444 deadline/scheduled line are skipped.
2445 When nil, insert notes right after the heading and perhaps the line
2446 with deadline/scheduling if present.
2448 This variable will have no effect if `org-log-into-drawer' is
2449 set."
2450 :group 'org-todo
2451 :group 'org-progress
2452 :type 'boolean)
2454 (defcustom org-log-states-order-reversed t
2455 "Non-nil means the latest state note will be directly after heading.
2456 When nil, the state change notes will be ordered according to time."
2457 :group 'org-todo
2458 :group 'org-progress
2459 :type 'boolean)
2461 (defcustom org-todo-repeat-to-state nil
2462 "The TODO state to which a repeater should return the repeating task.
2463 By default this is the first task in a TODO sequence, or the previous state
2464 in a TODO_TYP set. But you can specify another task here.
2465 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2466 :group 'org-todo
2467 :type '(choice (const :tag "Head of sequence" nil)
2468 (string :tag "Specific state")))
2470 (defcustom org-log-repeat 'time
2471 "Non-nil means record moving through the DONE state when triggering repeat.
2472 An auto-repeating task is immediately switched back to TODO when
2473 marked DONE. If you are not logging state changes (by adding \"@\"
2474 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2475 record a closing note, there will be no record of the task moving
2476 through DONE. This variable forces taking a note anyway.
2478 nil Don't force a record
2479 time Record a time stamp
2480 note Record a note
2482 This option can also be set with on a per-file-basis with
2484 #+STARTUP: logrepeat
2485 #+STARTUP: lognoterepeat
2486 #+STARTUP: nologrepeat
2488 You can have local logging settings for a subtree by setting the LOGGING
2489 property to one or more of these keywords."
2490 :group 'org-todo
2491 :group 'org-progress
2492 :type '(choice
2493 (const :tag "Don't force a record" nil)
2494 (const :tag "Force recording the DONE state" time)
2495 (const :tag "Force recording a note with the DONE state" note)))
2498 (defgroup org-priorities nil
2499 "Priorities in Org-mode."
2500 :tag "Org Priorities"
2501 :group 'org-todo)
2503 (defcustom org-enable-priority-commands t
2504 "Non-nil means priority commands are active.
2505 When nil, these commands will be disabled, so that you never accidentally
2506 set a priority."
2507 :group 'org-priorities
2508 :type 'boolean)
2510 (defcustom org-highest-priority ?A
2511 "The highest priority of TODO items. A character like ?A, ?B etc.
2512 Must have a smaller ASCII number than `org-lowest-priority'."
2513 :group 'org-priorities
2514 :type 'character)
2516 (defcustom org-lowest-priority ?C
2517 "The lowest priority of TODO items. A character like ?A, ?B etc.
2518 Must have a larger ASCII number than `org-highest-priority'."
2519 :group 'org-priorities
2520 :type 'character)
2522 (defcustom org-default-priority ?B
2523 "The default priority of TODO items.
2524 This is the priority an item gets if no explicit priority is given.
2525 When starting to cycle on an empty priority the first step in the cycle
2526 depends on `org-priority-start-cycle-with-default'. The resulting first
2527 step priority must not exceed the range from `org-highest-priority' to
2528 `org-lowest-priority' which means that `org-default-priority' has to be
2529 in this range exclusive or inclusive the range boundaries. Else the
2530 first step refuses to set the default and the second will fall back
2531 to (depending on the command used) the highest or lowest priority."
2532 :group 'org-priorities
2533 :type 'character)
2535 (defcustom org-priority-start-cycle-with-default t
2536 "Non-nil means start with default priority when starting to cycle.
2537 When this is nil, the first step in the cycle will be (depending on the
2538 command used) one higher or lower than the default priority.
2539 See also `org-default-priority'."
2540 :group 'org-priorities
2541 :type 'boolean)
2543 (defcustom org-get-priority-function nil
2544 "Function to extract the priority from a string.
2545 The string is normally the headline. If this is nil Org computes the
2546 priority from the priority cookie like [#A] in the headline. It returns
2547 an integer, increasing by 1000 for each priority level.
2548 The user can set a different function here, which should take a string
2549 as an argument and return the numeric priority."
2550 :group 'org-priorities
2551 :type 'function)
2553 (defgroup org-time nil
2554 "Options concerning time stamps and deadlines in Org-mode."
2555 :tag "Org Time"
2556 :group 'org)
2558 (defcustom org-insert-labeled-timestamps-at-point nil
2559 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2560 When nil, these labeled time stamps are forces into the second line of an
2561 entry, just after the headline. When scheduling from the global TODO list,
2562 the time stamp will always be forced into the second line."
2563 :group 'org-time
2564 :type 'boolean)
2566 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2567 "Formats for `format-time-string' which are used for time stamps.
2568 It is not recommended to change this constant.")
2570 (defcustom org-time-stamp-rounding-minutes '(0 5)
2571 "Number of minutes to round time stamps to.
2572 These are two values, the first applies when first creating a time stamp.
2573 The second applies when changing it with the commands `S-up' and `S-down'.
2574 When changing the time stamp, this means that it will change in steps
2575 of N minutes, as given by the second value.
2577 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2578 numbers should be factors of 60, so for example 5, 10, 15.
2580 When this is larger than 1, you can still force an exact time stamp by using
2581 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2582 and by using a prefix arg to `S-up/down' to specify the exact number
2583 of minutes to shift."
2584 :group 'org-time
2585 :get #'(lambda (var) ; Make sure both elements are there
2586 (if (integerp (default-value var))
2587 (list (default-value var) 5)
2588 (default-value var)))
2589 :type '(list
2590 (integer :tag "when inserting times")
2591 (integer :tag "when modifying times")))
2593 ;; Normalize old customizations of this variable.
2594 (when (integerp org-time-stamp-rounding-minutes)
2595 (setq org-time-stamp-rounding-minutes
2596 (list org-time-stamp-rounding-minutes
2597 org-time-stamp-rounding-minutes)))
2599 (defcustom org-display-custom-times nil
2600 "Non-nil means overlay custom formats over all time stamps.
2601 The formats are defined through the variable `org-time-stamp-custom-formats'.
2602 To turn this on on a per-file basis, insert anywhere in the file:
2603 #+STARTUP: customtime"
2604 :group 'org-time
2605 :set 'set-default
2606 :type 'sexp)
2607 (make-variable-buffer-local 'org-display-custom-times)
2609 (defcustom org-time-stamp-custom-formats
2610 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2611 "Custom formats for time stamps. See `format-time-string' for the syntax.
2612 These are overlayed over the default ISO format if the variable
2613 `org-display-custom-times' is set. Time like %H:%M should be at the
2614 end of the second format. The custom formats are also honored by export
2615 commands, if custom time display is turned on at the time of export."
2616 :group 'org-time
2617 :type 'sexp)
2619 (defun org-time-stamp-format (&optional long inactive)
2620 "Get the right format for a time string."
2621 (let ((f (if long (cdr org-time-stamp-formats)
2622 (car org-time-stamp-formats))))
2623 (if inactive
2624 (concat "[" (substring f 1 -1) "]")
2625 f)))
2627 (defcustom org-time-clocksum-format "%d:%02d"
2628 "The format string used when creating CLOCKSUM lines.
2629 This is also used when org-mode generates a time duration."
2630 :group 'org-time
2631 :type 'string)
2633 (defcustom org-time-clocksum-use-fractional nil
2634 "If non-nil, \\[org-clock-display] uses fractional times.
2635 org-mode generates a time duration."
2636 :group 'org-time
2637 :type 'boolean)
2639 (defcustom org-time-clocksum-fractional-format "%.2f"
2640 "The format string used when creating CLOCKSUM lines, or when
2641 org-mode generates a time duration."
2642 :group 'org-time
2643 :type 'string)
2645 (defcustom org-deadline-warning-days 14
2646 "No. of days before expiration during which a deadline becomes active.
2647 This variable governs the display in sparse trees and in the agenda.
2648 When 0 or negative, it means use this number (the absolute value of it)
2649 even if a deadline has a different individual lead time specified.
2651 Custom commands can set this variable in the options section."
2652 :group 'org-time
2653 :group 'org-agenda-daily/weekly
2654 :type 'integer)
2656 (defcustom org-read-date-prefer-future t
2657 "Non-nil means assume future for incomplete date input from user.
2658 This affects the following situations:
2659 1. The user gives a month but not a year.
2660 For example, if it is April and you enter \"feb 2\", this will be read
2661 as Feb 2, *next* year. \"May 5\", however, will be this year.
2662 2. The user gives a day, but no month.
2663 For example, if today is the 15th, and you enter \"3\", Org-mode will
2664 read this as the third of *next* month. However, if you enter \"17\",
2665 it will be considered as *this* month.
2667 If you set this variable to the symbol `time', then also the following
2668 will work:
2670 3. If the user gives a time, but no day. If the time is before now,
2671 to will be interpreted as tomorrow.
2673 Currently none of this works for ISO week specifications.
2675 When this option is nil, the current day, month and year will always be
2676 used as defaults.
2678 See also `org-agenda-jump-prefer-future'."
2679 :group 'org-time
2680 :type '(choice
2681 (const :tag "Never" nil)
2682 (const :tag "Check month and day" t)
2683 (const :tag "Check month, day, and time" time)))
2685 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2686 "Should the agenda jump command prefer the future for incomplete dates?
2687 The default is to do the same as configured in `org-read-date-prefer-future'.
2688 But you can also set a deviating value here.
2689 This may t or nil, or the symbol `org-read-date-prefer-future'."
2690 :group 'org-agenda
2691 :group 'org-time
2692 :type '(choice
2693 (const :tag "Use org-read-date-prefer-future"
2694 org-read-date-prefer-future)
2695 (const :tag "Never" nil)
2696 (const :tag "Always" t)))
2698 (defcustom org-read-date-force-compatible-dates t
2699 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2701 Depending on the system Emacs is running on, certain dates cannot
2702 be represented with the type used internally to represent time.
2703 Dates between 1970-1-1 and 2038-1-1 can always be represented
2704 correctly. Some systems allow for earlier dates, some for later,
2705 some for both. One way to find out it to insert any date into an
2706 Org buffer, putting the cursor on the year and hitting S-up and
2707 S-down to test the range.
2709 When this variable is set to t, the date/time prompt will not let
2710 you specify dates outside the 1970-2037 range, so it is certain that
2711 these dates will work in whatever version of Emacs you are
2712 running, and also that you can move a file from one Emacs implementation
2713 to another. WHenever Org is forcing the year for you, it will display
2714 a message and beep.
2716 When this variable is nil, Org will check if the date is
2717 representable in the specific Emacs implementation you are using.
2718 If not, it will force a year, usually the current year, and beep
2719 to remind you. Currently this setting is not recommended because
2720 the likelihood that you will open your Org files in an Emacs that
2721 has limited date range is not negligible.
2723 A workaround for this problem is to use diary sexp dates for time
2724 stamps outside of this range."
2725 :group 'org-time
2726 :type 'boolean)
2728 (defcustom org-read-date-display-live t
2729 "Non-nil means display current interpretation of date prompt live.
2730 This display will be in an overlay, in the minibuffer."
2731 :group 'org-time
2732 :type 'boolean)
2734 (defcustom org-read-date-popup-calendar t
2735 "Non-nil means pop up a calendar when prompting for a date.
2736 In the calendar, the date can be selected with mouse-1. However, the
2737 minibuffer will also be active, and you can simply enter the date as well.
2738 When nil, only the minibuffer will be available."
2739 :group 'org-time
2740 :type 'boolean)
2741 (if (fboundp 'defvaralias)
2742 (defvaralias 'org-popup-calendar-for-date-prompt
2743 'org-read-date-popup-calendar))
2745 (defcustom org-read-date-minibuffer-setup-hook nil
2746 "Hook to be used to set up keys for the date/time interface.
2747 Add key definitions to `minibuffer-local-map', which will be a temporary
2748 copy."
2749 :group 'org-time
2750 :type 'hook)
2752 (defcustom org-extend-today-until 0
2753 "The hour when your day really ends. Must be an integer.
2754 This has influence for the following applications:
2755 - When switching the agenda to \"today\". It it is still earlier than
2756 the time given here, the day recognized as TODAY is actually yesterday.
2757 - When a date is read from the user and it is still before the time given
2758 here, the current date and time will be assumed to be yesterday, 23:59.
2759 Also, timestamps inserted in remember templates follow this rule.
2761 IMPORTANT: This is a feature whose implementation is and likely will
2762 remain incomplete. Really, it is only here because past midnight seems to
2763 be the favorite working time of John Wiegley :-)"
2764 :group 'org-time
2765 :type 'integer)
2767 (defcustom org-use-effective-time nil
2768 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2769 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2770 \"effective time\" of any timestamps between midnight and 8am will be
2771 23:59 of the previous day."
2772 :group 'boolean
2773 :type 'integer)
2775 (defcustom org-edit-timestamp-down-means-later nil
2776 "Non-nil means S-down will increase the time in a time stamp.
2777 When nil, S-up will increase."
2778 :group 'org-time
2779 :type 'boolean)
2781 (defcustom org-calendar-follow-timestamp-change t
2782 "Non-nil means make the calendar window follow timestamp changes.
2783 When a timestamp is modified and the calendar window is visible, it will be
2784 moved to the new date."
2785 :group 'org-time
2786 :type 'boolean)
2788 (defgroup org-tags nil
2789 "Options concerning tags in Org-mode."
2790 :tag "Org Tags"
2791 :group 'org)
2793 (defcustom org-tag-alist nil
2794 "List of tags allowed in Org-mode files.
2795 When this list is nil, Org-mode will base TAG input on what is already in the
2796 buffer.
2797 The value of this variable is an alist, the car of each entry must be a
2798 keyword as a string, the cdr may be a character that is used to select
2799 that tag through the fast-tag-selection interface.
2800 See the manual for details."
2801 :group 'org-tags
2802 :type '(repeat
2803 (choice
2804 (cons (string :tag "Tag name")
2805 (character :tag "Access char"))
2806 (list :tag "Start radio group"
2807 (const :startgroup)
2808 (option (string :tag "Group description")))
2809 (list :tag "End radio group"
2810 (const :endgroup)
2811 (option (string :tag "Group description")))
2812 (const :tag "New line" (:newline)))))
2814 (defcustom org-tag-persistent-alist nil
2815 "List of tags that will always appear in all Org-mode files.
2816 This is in addition to any in buffer settings or customizations
2817 of `org-tag-alist'.
2818 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2819 The value of this variable is an alist, the car of each entry must be a
2820 keyword as a string, the cdr may be a character that is used to select
2821 that tag through the fast-tag-selection interface.
2822 See the manual for details.
2823 To disable these tags on a per-file basis, insert anywhere in the file:
2824 #+STARTUP: noptag"
2825 :group 'org-tags
2826 :type '(repeat
2827 (choice
2828 (cons (string :tag "Tag name")
2829 (character :tag "Access char"))
2830 (const :tag "Start radio group" (:startgroup))
2831 (const :tag "End radio group" (:endgroup))
2832 (const :tag "New line" (:newline)))))
2834 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2835 "If non-nil, always offer completion for all tags of all agenda files.
2836 Instead of customizing this variable directly, you might want to
2837 set it locally for capture buffers, because there no list of
2838 tags in that file can be created dynamically (there are none).
2840 (add-hook 'org-capture-mode-hook
2841 (lambda ()
2842 (set (make-local-variable
2843 'org-complete-tags-always-offer-all-agenda-tags)
2844 t)))"
2845 :group 'org-tags
2846 :type 'boolean)
2848 (defvar org-file-tags nil
2849 "List of tags that can be inherited by all entries in the file.
2850 The tags will be inherited if the variable `org-use-tag-inheritance'
2851 says they should be.
2852 This variable is populated from #+FILETAGS lines.")
2854 (defcustom org-use-fast-tag-selection 'auto
2855 "Non-nil means use fast tag selection scheme.
2856 This is a special interface to select and deselect tags with single keys.
2857 When nil, fast selection is never used.
2858 When the symbol `auto', fast selection is used if and only if selection
2859 characters for tags have been configured, either through the variable
2860 `org-tag-alist' or through a #+TAGS line in the buffer.
2861 When t, fast selection is always used and selection keys are assigned
2862 automatically if necessary."
2863 :group 'org-tags
2864 :type '(choice
2865 (const :tag "Always" t)
2866 (const :tag "Never" nil)
2867 (const :tag "When selection characters are configured" 'auto)))
2869 (defcustom org-fast-tag-selection-single-key nil
2870 "Non-nil means fast tag selection exits after first change.
2871 When nil, you have to press RET to exit it.
2872 During fast tag selection, you can toggle this flag with `C-c'.
2873 This variable can also have the value `expert'. In this case, the window
2874 displaying the tags menu is not even shown, until you press C-c again."
2875 :group 'org-tags
2876 :type '(choice
2877 (const :tag "No" nil)
2878 (const :tag "Yes" t)
2879 (const :tag "Expert" expert)))
2881 (defvar org-fast-tag-selection-include-todo nil
2882 "Non-nil means fast tags selection interface will also offer TODO states.
2883 This is an undocumented feature, you should not rely on it.")
2885 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2886 "The column to which tags should be indented in a headline.
2887 If this number is positive, it specifies the column. If it is negative,
2888 it means that the tags should be flushright to that column. For example,
2889 -80 works well for a normal 80 character screen.
2890 When 0, place tags directly after headline text, with only one space in
2891 between."
2892 :group 'org-tags
2893 :type 'integer)
2895 (defcustom org-auto-align-tags t
2896 "Non-nil keeps tags aligned when modifying headlines.
2897 Some operations (i.e. demoting) change the length of a headline and
2898 therefore shift the tags around. With this option turned on, after
2899 each such operation the tags are again aligned to `org-tags-column'."
2900 :group 'org-tags
2901 :type 'boolean)
2903 (defcustom org-use-tag-inheritance t
2904 "Non-nil means tags in levels apply also for sublevels.
2905 When nil, only the tags directly given in a specific line apply there.
2906 This may also be a list of tags that should be inherited, or a regexp that
2907 matches tags that should be inherited. Additional control is possible
2908 with the variable `org-tags-exclude-from-inheritance' which gives an
2909 explicit list of tags to be excluded from inheritance., even if the value of
2910 `org-use-tag-inheritance' would select it for inheritance.
2912 If this option is t, a match early-on in a tree can lead to a large
2913 number of matches in the subtree when constructing the agenda or creating
2914 a sparse tree. If you only want to see the first match in a tree during
2915 a search, check out the variable `org-tags-match-list-sublevels'."
2916 :group 'org-tags
2917 :type '(choice
2918 (const :tag "Not" nil)
2919 (const :tag "Always" t)
2920 (repeat :tag "Specific tags" (string :tag "Tag"))
2921 (regexp :tag "Tags matched by regexp")))
2923 (defcustom org-tags-exclude-from-inheritance nil
2924 "List of tags that should never be inherited.
2925 This is a way to exclude a few tags from inheritance. For way to do
2926 the opposite, to actively allow inheritance for selected tags,
2927 see the variable `org-use-tag-inheritance'."
2928 :group 'org-tags
2929 :type '(repeat (string :tag "Tag")))
2931 (defun org-tag-inherit-p (tag)
2932 "Check if TAG is one that should be inherited."
2933 (cond
2934 ((member tag org-tags-exclude-from-inheritance) nil)
2935 ((eq org-use-tag-inheritance t) t)
2936 ((not org-use-tag-inheritance) nil)
2937 ((stringp org-use-tag-inheritance)
2938 (string-match org-use-tag-inheritance tag))
2939 ((listp org-use-tag-inheritance)
2940 (member tag org-use-tag-inheritance))
2941 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2943 (defcustom org-tags-match-list-sublevels t
2944 "Non-nil means list also sublevels of headlines matching a search.
2945 This variable applies to tags/property searches, and also to stuck
2946 projects because this search is based on a tags match as well.
2948 When set to the symbol `indented', sublevels are indented with
2949 leading dots.
2951 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2952 the sublevels of a headline matching a tag search often also match
2953 the same search. Listing all of them can create very long lists.
2954 Setting this variable to nil causes subtrees of a match to be skipped.
2956 This variable is semi-obsolete and probably should always be true. It
2957 is better to limit inheritance to certain tags using the variables
2958 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2959 :group 'org-tags
2960 :type '(choice
2961 (const :tag "No, don't list them" nil)
2962 (const :tag "Yes, do list them" t)
2963 (const :tag "List them, indented with leading dots" indented)))
2965 (defcustom org-tags-sort-function nil
2966 "When set, tags are sorted using this function as a comparator."
2967 :group 'org-tags
2968 :type '(choice
2969 (const :tag "No sorting" nil)
2970 (const :tag "Alphabetical" string<)
2971 (const :tag "Reverse alphabetical" string>)
2972 (function :tag "Custom function" nil)))
2974 (defvar org-tags-history nil
2975 "History of minibuffer reads for tags.")
2976 (defvar org-last-tags-completion-table nil
2977 "The last used completion table for tags.")
2978 (defvar org-after-tags-change-hook nil
2979 "Hook that is run after the tags in a line have changed.")
2981 (defgroup org-properties nil
2982 "Options concerning properties in Org-mode."
2983 :tag "Org Properties"
2984 :group 'org)
2986 (defcustom org-property-format "%-10s %s"
2987 "How property key/value pairs should be formatted by `indent-line'.
2988 When `indent-line' hits a property definition, it will format the line
2989 according to this format, mainly to make sure that the values are
2990 lined-up with respect to each other."
2991 :group 'org-properties
2992 :type 'string)
2994 (defcustom org-properties-postprocess-alist nil
2995 "Alist of properties and functions to adjust inserted values.
2996 Elements of this alist must be of the form
2998 ([string] [function])
3000 where [string] must be a property name and [function] must be a
3001 lambda expression: this lambda expression must take one argument,
3002 the value to adjust, and return the new value as a string.
3004 For example, this element will allow the property \"Remaining\"
3005 to be updated wrt the relation between the \"Effort\" property
3006 and the clock summary:
3008 ((\"Remaining\" (lambda(value)
3009 (let ((clocksum (org-clock-sum-current-item))
3010 (effort (org-duration-string-to-minutes
3011 (org-entry-get (point) \"Effort\"))))
3012 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3013 :group 'org-properties
3014 :type 'alist)
3016 (defcustom org-use-property-inheritance nil
3017 "Non-nil means properties apply also for sublevels.
3019 This setting is chiefly used during property searches. Turning it on can
3020 cause significant overhead when doing a search, which is why it is not
3021 on by default.
3023 When nil, only the properties directly given in the current entry count.
3024 When t, every property is inherited. The value may also be a list of
3025 properties that should have inheritance, or a regular expression matching
3026 properties that should be inherited.
3028 However, note that some special properties use inheritance under special
3029 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3030 and the properties ending in \"_ALL\" when they are used as descriptor
3031 for valid values of a property.
3033 Note for programmers:
3034 When querying an entry with `org-entry-get', you can control if inheritance
3035 should be used. By default, `org-entry-get' looks only at the local
3036 properties. You can request inheritance by setting the inherit argument
3037 to t (to force inheritance) or to `selective' (to respect the setting
3038 in this variable)."
3039 :group 'org-properties
3040 :type '(choice
3041 (const :tag "Not" nil)
3042 (const :tag "Always" t)
3043 (repeat :tag "Specific properties" (string :tag "Property"))
3044 (regexp :tag "Properties matched by regexp")))
3046 (defun org-property-inherit-p (property)
3047 "Check if PROPERTY is one that should be inherited."
3048 (cond
3049 ((eq org-use-property-inheritance t) t)
3050 ((not org-use-property-inheritance) nil)
3051 ((stringp org-use-property-inheritance)
3052 (string-match org-use-property-inheritance property))
3053 ((listp org-use-property-inheritance)
3054 (member property org-use-property-inheritance))
3055 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3057 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3058 "The default column format, if no other format has been defined.
3059 This variable can be set on the per-file basis by inserting a line
3061 #+COLUMNS: %25ITEM ....."
3062 :group 'org-properties
3063 :type 'string)
3065 (defcustom org-columns-ellipses ".."
3066 "The ellipses to be used when a field in column view is truncated.
3067 When this is the empty string, as many characters as possible are shown,
3068 but then there will be no visual indication that the field has been truncated.
3069 When this is a string of length N, the last N characters of a truncated
3070 field are replaced by this string. If the column is narrower than the
3071 ellipses string, only part of the ellipses string will be shown."
3072 :group 'org-properties
3073 :type 'string)
3075 (defcustom org-columns-modify-value-for-display-function nil
3076 "Function that modifies values for display in column view.
3077 For example, it can be used to cut out a certain part from a time stamp.
3078 The function must take 2 arguments:
3080 column-title The title of the column (*not* the property name)
3081 value The value that should be modified.
3083 The function should return the value that should be displayed,
3084 or nil if the normal value should be used."
3085 :group 'org-properties
3086 :type 'function)
3088 (defcustom org-effort-property "Effort"
3089 "The property that is being used to keep track of effort estimates.
3090 Effort estimates given in this property need to have the format H:MM."
3091 :group 'org-properties
3092 :group 'org-progress
3093 :type '(string :tag "Property"))
3095 (defconst org-global-properties-fixed
3096 '(("VISIBILITY_ALL" . "folded children content all")
3097 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3098 "List of property/value pairs that can be inherited by any entry.
3100 These are fixed values, for the preset properties. The user variable
3101 that can be used to add to this list is `org-global-properties'.
3103 The entries in this list are cons cells where the car is a property
3104 name and cdr is a string with the value. If the value represents
3105 multiple items like an \"_ALL\" property, separate the items by
3106 spaces.")
3108 (defcustom org-global-properties nil
3109 "List of property/value pairs that can be inherited by any entry.
3111 This list will be combined with the constant `org-global-properties-fixed'.
3113 The entries in this list are cons cells where the car is a property
3114 name and cdr is a string with the value.
3116 You can set buffer-local values for the same purpose in the variable
3117 `org-file-properties' this by adding lines like
3119 #+PROPERTY: NAME VALUE"
3120 :group 'org-properties
3121 :type '(repeat
3122 (cons (string :tag "Property")
3123 (string :tag "Value"))))
3125 (defvar org-file-properties nil
3126 "List of property/value pairs that can be inherited by any entry.
3127 Valid for the current buffer.
3128 This variable is populated from #+PROPERTY lines.")
3129 (make-variable-buffer-local 'org-file-properties)
3131 (defgroup org-agenda nil
3132 "Options concerning agenda views in Org-mode."
3133 :tag "Org Agenda"
3134 :group 'org)
3136 (defvar org-category nil
3137 "Variable used by org files to set a category for agenda display.
3138 Such files should use a file variable to set it, for example
3140 # -*- mode: org; org-category: \"ELisp\"
3142 or contain a special line
3144 #+CATEGORY: ELisp
3146 If the file does not specify a category, then file's base name
3147 is used instead.")
3148 (make-variable-buffer-local 'org-category)
3149 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3151 (defcustom org-agenda-files nil
3152 "The files to be used for agenda display.
3153 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3154 \\[org-remove-file]. You can also use customize to edit the list.
3156 If an entry is a directory, all files in that directory that are matched by
3157 `org-agenda-file-regexp' will be part of the file list.
3159 If the value of the variable is not a list but a single file name, then
3160 the list of agenda files is actually stored and maintained in that file, one
3161 agenda file per line. In this file paths can be given relative to
3162 `org-directory'. Tilde expansion and environment variable substitution
3163 are also made."
3164 :group 'org-agenda
3165 :type '(choice
3166 (repeat :tag "List of files and directories" file)
3167 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3169 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3170 "Regular expression to match files for `org-agenda-files'.
3171 If any element in the list in that variable contains a directory instead
3172 of a normal file, all files in that directory that are matched by this
3173 regular expression will be included."
3174 :group 'org-agenda
3175 :type 'regexp)
3177 (defcustom org-agenda-text-search-extra-files nil
3178 "List of extra files to be searched by text search commands.
3179 These files will be search in addition to the agenda files by the
3180 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3181 Note that these files will only be searched for text search commands,
3182 not for the other agenda views like todo lists, tag searches or the weekly
3183 agenda. This variable is intended to list notes and possibly archive files
3184 that should also be searched by these two commands.
3185 In fact, if the first element in the list is the symbol `agenda-archives',
3186 than all archive files of all agenda files will be added to the search
3187 scope."
3188 :group 'org-agenda
3189 :type '(set :greedy t
3190 (const :tag "Agenda Archives" agenda-archives)
3191 (repeat :inline t (file))))
3193 (if (fboundp 'defvaralias)
3194 (defvaralias 'org-agenda-multi-occur-extra-files
3195 'org-agenda-text-search-extra-files))
3197 (defcustom org-agenda-skip-unavailable-files nil
3198 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3199 A nil value means to remove them, after a query, from the list."
3200 :group 'org-agenda
3201 :type 'boolean)
3203 (defcustom org-calendar-to-agenda-key [?c]
3204 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3205 The command `org-calendar-goto-agenda' will be bound to this key. The
3206 default is the character `c' because then `c' can be used to switch back and
3207 forth between agenda and calendar."
3208 :group 'org-agenda
3209 :type 'sexp)
3211 (defcustom org-calendar-agenda-action-key [?k]
3212 "The key to be installed in `calendar-mode-map' for agenda-action.
3213 The command `org-agenda-action' will be bound to this key. The
3214 default is the character `k' because we use the same key in the agenda."
3215 :group 'org-agenda
3216 :type 'sexp)
3218 (defcustom org-calendar-insert-diary-entry-key [?i]
3219 "The key to be installed in `calendar-mode-map' for adding diary entries.
3220 This option is irrelevant until `org-agenda-diary-file' has been configured
3221 to point to an Org-mode file. When that is the case, the command
3222 `org-agenda-diary-entry' will be bound to the key given here, by default
3223 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3224 if you want to continue doing this, you need to change this to a different
3225 key."
3226 :group 'org-agenda
3227 :type 'sexp)
3229 (defcustom org-agenda-diary-file 'diary-file
3230 "File to which to add new entries with the `i' key in agenda and calendar.
3231 When this is the symbol `diary-file', the functionality in the Emacs
3232 calendar will be used to add entries to the `diary-file'. But when this
3233 points to a file, `org-agenda-diary-entry' will be used instead."
3234 :group 'org-agenda
3235 :type '(choice
3236 (const :tag "The standard Emacs diary file" diary-file)
3237 (file :tag "Special Org file diary entries")))
3239 (eval-after-load "calendar"
3240 '(progn
3241 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3242 'org-calendar-goto-agenda)
3243 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3244 'org-agenda-action)
3245 (add-hook 'calendar-mode-hook
3246 (lambda ()
3247 (unless (eq org-agenda-diary-file 'diary-file)
3248 (define-key calendar-mode-map
3249 org-calendar-insert-diary-entry-key
3250 'org-agenda-diary-entry))))))
3252 (defgroup org-latex nil
3253 "Options for embedding LaTeX code into Org-mode."
3254 :tag "Org LaTeX"
3255 :group 'org)
3257 (defcustom org-format-latex-options
3258 '(:foreground default :background default :scale 1.0
3259 :html-foreground "Black" :html-background "Transparent"
3260 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3261 "Options for creating images from LaTeX fragments.
3262 This is a property list with the following properties:
3263 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3264 `default' means use the foreground of the default face.
3265 :background the background color, or \"Transparent\".
3266 `default' means use the background of the default face.
3267 :scale a scaling factor for the size of the images, to get more pixels
3268 :html-foreground, :html-background, :html-scale
3269 the same numbers for HTML export.
3270 :matchers a list indicating which matchers should be used to
3271 find LaTeX fragments. Valid members of this list are:
3272 \"begin\" find environments
3273 \"$1\" find single characters surrounded by $.$
3274 \"$\" find math expressions surrounded by $...$
3275 \"$$\" find math expressions surrounded by $$....$$
3276 \"\\(\" find math expressions surrounded by \\(...\\)
3277 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3278 :group 'org-latex
3279 :type 'plist)
3281 (defcustom org-format-latex-signal-error t
3282 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3283 When nil, just push out a message."
3284 :group 'org-latex
3285 :type 'boolean)
3287 (defcustom org-format-latex-header "\\documentclass{article}
3288 \\usepackage[usenames]{color}
3289 \\usepackage{amsmath}
3290 \\usepackage[mathscr]{eucal}
3291 \\pagestyle{empty} % do not remove
3292 \[PACKAGES]
3293 \[DEFAULT-PACKAGES]
3294 % The settings below are copied from fullpage.sty
3295 \\setlength{\\textwidth}{\\paperwidth}
3296 \\addtolength{\\textwidth}{-3cm}
3297 \\setlength{\\oddsidemargin}{1.5cm}
3298 \\addtolength{\\oddsidemargin}{-2.54cm}
3299 \\setlength{\\evensidemargin}{\\oddsidemargin}
3300 \\setlength{\\textheight}{\\paperheight}
3301 \\addtolength{\\textheight}{-\\headheight}
3302 \\addtolength{\\textheight}{-\\headsep}
3303 \\addtolength{\\textheight}{-\\footskip}
3304 \\addtolength{\\textheight}{-3cm}
3305 \\setlength{\\topmargin}{1.5cm}
3306 \\addtolength{\\topmargin}{-2.54cm}"
3307 "The document header used for processing LaTeX fragments.
3308 It is imperative that this header make sure that no page number
3309 appears on the page. The package defined in the variables
3310 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3311 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3312 will be appended."
3313 :group 'org-latex
3314 :type 'string)
3316 (defvar org-format-latex-header-extra nil)
3318 (defun org-set-packages-alist (var val)
3319 "Set the packages alist and make sure it has 3 elements per entry."
3320 (set var (mapcar (lambda (x)
3321 (if (and (consp x) (= (length x) 2))
3322 (list (car x) (nth 1 x) t)
3324 val)))
3326 (defun org-get-packages-alist (var)
3328 "Get the packages alist and make sure it has 3 elements per entry."
3329 (mapcar (lambda (x)
3330 (if (and (consp x) (= (length x) 2))
3331 (list (car x) (nth 1 x) t)
3333 (default-value var)))
3335 ;; The following variables are defined here because is it also used
3336 ;; when formatting latex fragments. Originally it was part of the
3337 ;; LaTeX exporter, which is why the name includes "export".
3338 (defcustom org-export-latex-default-packages-alist
3339 '(("AUTO" "inputenc" t)
3340 ("T1" "fontenc" t)
3341 ("" "fixltx2e" nil)
3342 ("" "graphicx" t)
3343 ("" "longtable" nil)
3344 ("" "float" nil)
3345 ("" "wrapfig" nil)
3346 ("" "soul" t)
3347 ("" "textcomp" t)
3348 ("" "marvosym" t)
3349 ("" "wasysym" t)
3350 ("" "latexsym" t)
3351 ("" "amssymb" t)
3352 ("" "hyperref" nil)
3353 "\\tolerance=1000"
3355 "Alist of default packages to be inserted in the header.
3356 Change this only if one of the packages here causes an incompatibility
3357 with another package you are using.
3358 The packages in this list are needed by one part or another of Org-mode
3359 to function properly.
3361 - inputenc, fontenc: for basic font and character selection
3362 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3363 for interpreting the entities in `org-entities'. You can skip some of these
3364 packages if you don't use any of the symbols in it.
3365 - graphicx: for including images
3366 - float, wrapfig: for figure placement
3367 - longtable: for long tables
3368 - hyperref: for cross references
3370 Therefore you should not modify this variable unless you know what you
3371 are doing. The one reason to change it anyway is that you might be loading
3372 some other package that conflicts with one of the default packages.
3373 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3374 If SNIPPET-FLAG is t, the package also needs to be included when
3375 compiling LaTeX snippets into images for inclusion into HTML."
3376 :group 'org-export-latex
3377 :set 'org-set-packages-alist
3378 :get 'org-get-packages-alist
3379 :type '(repeat
3380 (choice
3381 (list :tag "options/package pair"
3382 (string :tag "options")
3383 (string :tag "package")
3384 (boolean :tag "Snippet"))
3385 (string :tag "A line of LaTeX"))))
3387 (defcustom org-export-latex-packages-alist nil
3388 "Alist of packages to be inserted in every LaTeX header.
3389 These will be inserted after `org-export-latex-default-packages-alist'.
3390 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3391 SNIPPET-FLAG, when t, indicates that this package is also needed when
3392 turning LaTeX snippets into images for inclusion into HTML.
3393 Make sure that you only list packages here which:
3394 - you want in every file
3395 - do not conflict with the default packages in
3396 `org-export-latex-default-packages-alist'
3397 - do not conflict with the setup in `org-format-latex-header'."
3398 :group 'org-export-latex
3399 :set 'org-set-packages-alist
3400 :get 'org-get-packages-alist
3401 :type '(repeat
3402 (choice
3403 (list :tag "options/package pair"
3404 (string :tag "options")
3405 (string :tag "package")
3406 (boolean :tag "Snippet"))
3407 (string :tag "A line of LaTeX"))))
3410 (defgroup org-appearance nil
3411 "Settings for Org-mode appearance."
3412 :tag "Org Appearance"
3413 :group 'org)
3415 (defcustom org-level-color-stars-only nil
3416 "Non-nil means fontify only the stars in each headline.
3417 When nil, the entire headline is fontified.
3418 Changing it requires restart of `font-lock-mode' to become effective
3419 also in regions already fontified."
3420 :group 'org-appearance
3421 :type 'boolean)
3423 (defcustom org-hide-leading-stars nil
3424 "Non-nil means hide the first N-1 stars in a headline.
3425 This works by using the face `org-hide' for these stars. This
3426 face is white for a light background, and black for a dark
3427 background. You may have to customize the face `org-hide' to
3428 make this work.
3429 Changing it requires restart of `font-lock-mode' to become effective
3430 also in regions already fontified.
3431 You may also set this on a per-file basis by adding one of the following
3432 lines to the buffer:
3434 #+STARTUP: hidestars
3435 #+STARTUP: showstars"
3436 :group 'org-appearance
3437 :type 'boolean)
3439 (defcustom org-hidden-keywords nil
3440 "List of symbols corresponding to keywords to be hidden the org buffer.
3441 For example, a value '(title) for this list will make the document's title
3442 appear in the buffer without the initial #+TITLE: keyword."
3443 :group 'org-appearance
3444 :type '(set (const :tag "#+AUTHOR" author)
3445 (const :tag "#+DATE" date)
3446 (const :tag "#+EMAIL" email)
3447 (const :tag "#+TITLE" title)))
3449 (defcustom org-fontify-done-headline nil
3450 "Non-nil means change the face of a headline if it is marked DONE.
3451 Normally, only the TODO/DONE keyword indicates the state of a headline.
3452 When this is non-nil, the headline after the keyword is set to the
3453 `org-headline-done' as an additional indication."
3454 :group 'org-appearance
3455 :type 'boolean)
3457 (defcustom org-fontify-emphasized-text t
3458 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3459 Changing this variable requires a restart of Emacs to take effect."
3460 :group 'org-appearance
3461 :type 'boolean)
3463 (defcustom org-fontify-whole-heading-line nil
3464 "Non-nil means fontify the whole line for headings.
3465 This is useful when setting a background color for the
3466 org-level-* faces."
3467 :group 'org-appearance
3468 :type 'boolean)
3470 (defcustom org-highlight-latex-fragments-and-specials nil
3471 "Non-nil means fontify what is treated specially by the exporters."
3472 :group 'org-appearance
3473 :type 'boolean)
3475 (defcustom org-hide-emphasis-markers nil
3476 "Non-nil mean font-lock should hide the emphasis marker characters."
3477 :group 'org-appearance
3478 :type 'boolean)
3480 (defcustom org-pretty-entities nil
3481 "Non-nil means show entities as UTF8 characters.
3482 When nil, the \\name form remains in the buffer."
3483 :group 'org-appearance
3484 :type 'boolean)
3486 (defcustom org-pretty-entities-include-sub-superscripts t
3487 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3488 :group 'org-appearance
3489 :type 'boolean)
3491 (defvar org-emph-re nil
3492 "Regular expression for matching emphasis.
3493 After a match, the match groups contain these elements:
3494 0 The match of the full regular expression, including the characters
3495 before and after the proper match
3496 1 The character before the proper match, or empty at beginning of line
3497 2 The proper match, including the leading and trailing markers
3498 3 The leading marker like * or /, indicating the type of highlighting
3499 4 The text between the emphasis markers, not including the markers
3500 5 The character after the match, empty at the end of a line")
3501 (defvar org-verbatim-re nil
3502 "Regular expression for matching verbatim text.")
3503 (defvar org-emphasis-regexp-components) ; defined just below
3504 (defvar org-emphasis-alist) ; defined just below
3505 (defun org-set-emph-re (var val)
3506 "Set variable and compute the emphasis regular expression."
3507 (set var val)
3508 (when (and (boundp 'org-emphasis-alist)
3509 (boundp 'org-emphasis-regexp-components)
3510 org-emphasis-alist org-emphasis-regexp-components)
3511 (let* ((e org-emphasis-regexp-components)
3512 (pre (car e))
3513 (post (nth 1 e))
3514 (border (nth 2 e))
3515 (body (nth 3 e))
3516 (nl (nth 4 e))
3517 (body1 (concat body "*?"))
3518 (markers (mapconcat 'car org-emphasis-alist ""))
3519 (vmarkers (mapconcat
3520 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3521 org-emphasis-alist "")))
3522 ;; make sure special characters appear at the right position in the class
3523 (if (string-match "\\^" markers)
3524 (setq markers (concat (replace-match "" t t markers) "^")))
3525 (if (string-match "-" markers)
3526 (setq markers (concat (replace-match "" t t markers) "-")))
3527 (if (string-match "\\^" vmarkers)
3528 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3529 (if (string-match "-" vmarkers)
3530 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3531 (if (> nl 0)
3532 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3533 (int-to-string nl) "\\}")))
3534 ;; Make the regexp
3535 (setq org-emph-re
3536 (concat "\\([" pre "]\\|^\\)"
3537 "\\("
3538 "\\([" markers "]\\)"
3539 "\\("
3540 "[^" border "]\\|"
3541 "[^" border "]"
3542 body1
3543 "[^" border "]"
3544 "\\)"
3545 "\\3\\)"
3546 "\\([" post "]\\|$\\)"))
3547 (setq org-verbatim-re
3548 (concat "\\([" pre "]\\|^\\)"
3549 "\\("
3550 "\\([" vmarkers "]\\)"
3551 "\\("
3552 "[^" border "]\\|"
3553 "[^" border "]"
3554 body1
3555 "[^" border "]"
3556 "\\)"
3557 "\\3\\)"
3558 "\\([" post "]\\|$\\)")))))
3560 (defcustom org-emphasis-regexp-components
3561 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3562 "Components used to build the regular expression for emphasis.
3563 This is a list with five entries. Terminology: In an emphasis string
3564 like \" *strong word* \", we call the initial space PREMATCH, the final
3565 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3566 and \"trong wor\" is the body. The different components in this variable
3567 specify what is allowed/forbidden in each part:
3569 pre Chars allowed as prematch. Beginning of line will be allowed too.
3570 post Chars allowed as postmatch. End of line will be allowed too.
3571 border The chars *forbidden* as border characters.
3572 body-regexp A regexp like \".\" to match a body character. Don't use
3573 non-shy groups here, and don't allow newline here.
3574 newline The maximum number of newlines allowed in an emphasis exp.
3576 Use customize to modify this, or restart Emacs after changing it."
3577 :group 'org-appearance
3578 :set 'org-set-emph-re
3579 :type '(list
3580 (sexp :tag "Allowed chars in pre ")
3581 (sexp :tag "Allowed chars in post ")
3582 (sexp :tag "Forbidden chars in border ")
3583 (sexp :tag "Regexp for body ")
3584 (integer :tag "number of newlines allowed")
3585 (option (boolean :tag "Please ignore this button"))))
3587 (defcustom org-emphasis-alist
3588 `(("*" bold "<b>" "</b>")
3589 ("/" italic "<i>" "</i>")
3590 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3591 ("=" org-code "<code>" "</code>" verbatim)
3592 ("~" org-verbatim "<code>" "</code>" verbatim)
3593 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3594 "<del>" "</del>")
3596 "Special syntax for emphasized text.
3597 Text starting and ending with a special character will be emphasized, for
3598 example *bold*, _underlined_ and /italic/. This variable sets the marker
3599 characters, the face to be used by font-lock for highlighting in Org-mode
3600 Emacs buffers, and the HTML tags to be used for this.
3601 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3602 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3603 Use customize to modify this, or restart Emacs after changing it."
3604 :group 'org-appearance
3605 :set 'org-set-emph-re
3606 :type '(repeat
3607 (list
3608 (string :tag "Marker character")
3609 (choice
3610 (face :tag "Font-lock-face")
3611 (plist :tag "Face property list"))
3612 (string :tag "HTML start tag")
3613 (string :tag "HTML end tag")
3614 (option (const verbatim)))))
3616 (defvar org-protecting-blocks
3617 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3618 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3619 This is needed for font-lock setup.")
3621 ;;; Miscellaneous options
3623 (defgroup org-completion nil
3624 "Completion in Org-mode."
3625 :tag "Org Completion"
3626 :group 'org)
3628 (defcustom org-completion-use-ido nil
3629 "Non-nil means use ido completion wherever possible.
3630 Note that `ido-mode' must be active for this variable to be relevant.
3631 If you decide to turn this variable on, you might well want to turn off
3632 `org-outline-path-complete-in-steps'.
3633 See also `org-completion-use-iswitchb'."
3634 :group 'org-completion
3635 :type 'boolean)
3637 (defcustom org-completion-use-iswitchb nil
3638 "Non-nil means use iswitchb completion wherever possible.
3639 Note that `iswitchb-mode' must be active for this variable to be relevant.
3640 If you decide to turn this variable on, you might well want to turn off
3641 `org-outline-path-complete-in-steps'.
3642 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3643 :group 'org-completion
3644 :type 'boolean)
3646 (defcustom org-completion-fallback-command 'hippie-expand
3647 "The expansion command called by \\[pcomplete] in normal context.
3648 Normal means, no org-mode-specific context."
3649 :group 'org-completion
3650 :type 'function)
3652 ;;; Functions and variables from their packages
3653 ;; Declared here to avoid compiler warnings
3655 ;; XEmacs only
3656 (defvar outline-mode-menu-heading)
3657 (defvar outline-mode-menu-show)
3658 (defvar outline-mode-menu-hide)
3659 (defvar zmacs-regions) ; XEmacs regions
3661 ;; Emacs only
3662 (defvar mark-active)
3664 ;; Various packages
3665 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3666 (declare-function calendar-forward-day "cal-move" (arg))
3667 (declare-function calendar-goto-date "cal-move" (date))
3668 (declare-function calendar-goto-today "cal-move" ())
3669 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3670 (defvar calc-embedded-close-formula)
3671 (defvar calc-embedded-open-formula)
3672 (declare-function cdlatex-tab "ext:cdlatex" ())
3673 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3674 (defvar font-lock-unfontify-region-function)
3675 (declare-function iswitchb-read-buffer "iswitchb"
3676 (prompt &optional default require-match start matches-set))
3677 (defvar iswitchb-temp-buflist)
3678 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3679 (defvar org-agenda-tags-todo-honor-ignore-options)
3680 (declare-function org-agenda-skip "org-agenda" ())
3681 (declare-function
3682 org-format-agenda-item "org-agenda"
3683 (extra txt &optional category tags dotime noprefix remove-re habitp))
3684 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3685 (declare-function org-agenda-change-all-lines "org-agenda"
3686 (newhead hdmarker &optional fixface just-this))
3687 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3688 (declare-function org-agenda-maybe-redo "org-agenda" ())
3689 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3690 (beg end))
3691 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3692 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3693 "org-agenda" (&optional end))
3694 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3695 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3696 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3697 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3698 (declare-function org-indent-mode "org-indent" (&optional arg))
3699 (declare-function parse-time-string "parse-time" (string))
3700 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3701 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3702 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3703 (defvar remember-data-file)
3704 (defvar texmathp-why)
3705 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3706 (declare-function table--at-cell-p "table" (position &optional object at-column))
3708 (defvar w3m-current-url)
3709 (defvar w3m-current-title)
3711 (defvar org-latex-regexps)
3713 ;;; Autoload and prepare some org modules
3715 ;; Some table stuff that needs to be defined here, because it is used
3716 ;; by the functions setting up org-mode or checking for table context.
3718 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3719 "Detect an org-type or table-type table.")
3720 (defconst org-table-line-regexp "^[ \t]*|"
3721 "Detect an org-type table line.")
3722 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3723 "Detect an org-type table line.")
3724 (defconst org-table-hline-regexp "^[ \t]*|-"
3725 "Detect an org-type table hline.")
3726 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3727 "Detect a table-type table hline.")
3728 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3729 "Detect the first line outside a table when searching from within it.
3730 This works for both table types.")
3732 ;; Autoload the functions in org-table.el that are needed by functions here.
3734 (eval-and-compile
3735 (org-autoload "org-table"
3736 '(org-table-align org-table-begin org-table-blank-field
3737 org-table-convert org-table-convert-region org-table-copy-down
3738 org-table-copy-region org-table-create
3739 org-table-create-or-convert-from-region
3740 org-table-create-with-table.el org-table-current-dline
3741 org-table-cut-region org-table-delete-column org-table-edit-field
3742 org-table-edit-formulas org-table-end org-table-eval-formula
3743 org-table-export org-table-field-info
3744 org-table-get-stored-formulas org-table-goto-column
3745 org-table-hline-and-move org-table-import org-table-insert-column
3746 org-table-insert-hline org-table-insert-row org-table-iterate
3747 org-table-justify-field-maybe org-table-kill-row
3748 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3749 org-table-move-column org-table-move-column-left
3750 org-table-move-column-right org-table-move-row
3751 org-table-move-row-down org-table-move-row-up
3752 org-table-next-field org-table-next-row org-table-paste-rectangle
3753 org-table-previous-field org-table-recalculate
3754 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3755 org-table-toggle-coordinate-overlays
3756 org-table-toggle-formula-debugger org-table-wrap-region
3757 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3758 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3759 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3761 (defun org-at-table-p (&optional table-type)
3762 "Return t if the cursor is inside an org-type table.
3763 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3764 (if org-enable-table-editor
3765 (save-excursion
3766 (beginning-of-line 1)
3767 (looking-at (if table-type org-table-any-line-regexp
3768 org-table-line-regexp)))
3769 nil))
3770 (defsubst org-table-p () (org-at-table-p))
3772 (defun org-at-table.el-p ()
3773 "Return t if and only if we are at a table.el table."
3774 (and (org-at-table-p 'any)
3775 (save-excursion
3776 (goto-char (org-table-begin 'any))
3777 (looking-at org-table1-hline-regexp))))
3778 (defun org-table-recognize-table.el ()
3779 "If there is a table.el table nearby, recognize it and move into it."
3780 (if org-table-tab-recognizes-table.el
3781 (if (org-at-table.el-p)
3782 (progn
3783 (beginning-of-line 1)
3784 (if (looking-at org-table-dataline-regexp)
3786 (if (looking-at org-table1-hline-regexp)
3787 (progn
3788 (beginning-of-line 2)
3789 (if (looking-at org-table-any-border-regexp)
3790 (beginning-of-line -1)))))
3791 (if (re-search-forward "|" (org-table-end t) t)
3792 (progn
3793 (require 'table)
3794 (if (table--at-cell-p (point))
3796 (message "recognizing table.el table...")
3797 (table-recognize-table)
3798 (message "recognizing table.el table...done")))
3799 (error "This should not happen"))
3801 nil)
3802 nil))
3804 (defun org-at-table-hline-p ()
3805 "Return t if the cursor is inside a hline in a table."
3806 (if org-enable-table-editor
3807 (save-excursion
3808 (beginning-of-line 1)
3809 (looking-at org-table-hline-regexp))
3810 nil))
3812 (defvar org-table-clean-did-remove-column nil)
3814 (defun org-table-map-tables (function &optional quietly)
3815 "Apply FUNCTION to the start of all tables in the buffer."
3816 (save-excursion
3817 (save-restriction
3818 (widen)
3819 (goto-char (point-min))
3820 (while (re-search-forward org-table-any-line-regexp nil t)
3821 (unless quietly
3822 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3823 (beginning-of-line 1)
3824 (when (looking-at org-table-line-regexp)
3825 (save-excursion (funcall function))
3826 (or (looking-at org-table-line-regexp)
3827 (forward-char 1)))
3828 (re-search-forward org-table-any-border-regexp nil 1))))
3829 (unless quietly (message "Mapping tables: done")))
3831 ;; Declare and autoload functions from org-exp.el & Co
3833 (declare-function org-default-export-plist "org-exp")
3834 (declare-function org-infile-export-plist "org-exp")
3835 (declare-function org-get-current-options "org-exp")
3836 (eval-and-compile
3837 (org-autoload "org-exp"
3838 '(org-export org-export-visible
3839 org-insert-export-options-template
3840 org-table-clean-before-export))
3841 (org-autoload "org-ascii"
3842 '(org-export-as-ascii org-export-ascii-preprocess
3843 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3844 org-export-region-as-ascii))
3845 (org-autoload "org-latex"
3846 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3847 org-replace-region-by-latex org-export-region-as-latex
3848 org-export-as-latex org-export-as-pdf
3849 org-export-as-pdf-and-open))
3850 (org-autoload "org-html"
3851 '(org-export-as-html-and-open
3852 org-export-as-html-batch org-export-as-html-to-buffer
3853 org-replace-region-by-html org-export-region-as-html
3854 org-export-as-html))
3855 (org-autoload "org-docbook"
3856 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3857 org-replace-region-by-docbook org-export-region-as-docbook
3858 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3859 org-export-as-docbook))
3860 (org-autoload "org-icalendar"
3861 '(org-export-icalendar-this-file
3862 org-export-icalendar-all-agenda-files
3863 org-export-icalendar-combine-agenda-files))
3864 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3865 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3867 ;; Declare and autoload functions from org-agenda.el
3869 (eval-and-compile
3870 (org-autoload "org-agenda"
3871 '(org-agenda org-agenda-list org-search-view
3872 org-todo-list org-tags-view org-agenda-list-stuck-projects
3873 org-diary org-agenda-to-appt
3874 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3876 ;; Autoload org-remember
3878 (eval-and-compile
3879 (org-autoload "org-remember"
3880 '(org-remember-insinuate org-remember-annotation
3881 org-remember-apply-template org-remember org-remember-handler)))
3883 (eval-and-compile
3884 (org-autoload "org-capture"
3885 '(org-capture org-capture-insert-template-here
3886 org-capture-import-remember-templates)))
3888 ;; Autoload org-clock.el
3890 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3891 (beg end))
3892 (declare-function org-clock-update-mode-line "org-clock" ())
3893 (declare-function org-resolve-clocks "org-clock"
3894 (&optional also-non-dangling-p prompt last-valid))
3895 (defvar org-clock-start-time)
3896 (defvar org-clock-marker (make-marker)
3897 "Marker recording the last clock-in.")
3898 (defvar org-clock-hd-marker (make-marker)
3899 "Marker recording the last clock-in, but the headline position.")
3900 (defvar org-clock-heading ""
3901 "The heading of the current clock entry.")
3902 (defun org-clock-is-active ()
3903 "Return non-nil if clock is currently running.
3904 The return value is actually the clock marker."
3905 (marker-buffer org-clock-marker))
3907 (eval-and-compile
3908 (org-autoload
3909 "org-clock"
3910 '(org-clock-in org-clock-out org-clock-cancel
3911 org-clock-goto org-clock-sum org-clock-display
3912 org-clock-remove-overlays org-clock-report
3913 org-clocktable-shift org-dblock-write:clocktable
3914 org-get-clocktable org-resolve-clocks)))
3916 (defun org-clock-update-time-maybe ()
3917 "If this is a CLOCK line, update it and return t.
3918 Otherwise, return nil."
3919 (interactive)
3920 (save-excursion
3921 (beginning-of-line 1)
3922 (skip-chars-forward " \t")
3923 (when (looking-at org-clock-string)
3924 (let ((re (concat "[ \t]*" org-clock-string
3925 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3926 "\\([ \t]*=>.*\\)?\\)?"))
3927 ts te h m s neg)
3928 (cond
3929 ((not (looking-at re))
3930 nil)
3931 ((not (match-end 2))
3932 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3933 (> org-clock-marker (point))
3934 (<= org-clock-marker (point-at-eol)))
3935 ;; The clock is running here
3936 (setq org-clock-start-time
3937 (apply 'encode-time
3938 (org-parse-time-string (match-string 1))))
3939 (org-clock-update-mode-line)))
3941 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3942 (end-of-line 1)
3943 (setq ts (match-string 1)
3944 te (match-string 3))
3945 (setq s (- (org-float-time
3946 (apply 'encode-time (org-parse-time-string te)))
3947 (org-float-time
3948 (apply 'encode-time (org-parse-time-string ts))))
3949 neg (< s 0)
3950 s (abs s)
3951 h (floor (/ s 3600))
3952 s (- s (* 3600 h))
3953 m (floor (/ s 60))
3954 s (- s (* 60 s)))
3955 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3956 t))))))
3958 (defun org-check-running-clock ()
3959 "Check if the current buffer contains the running clock.
3960 If yes, offer to stop it and to save the buffer with the changes."
3961 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3962 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3963 (buffer-name))))
3964 (org-clock-out)
3965 (when (y-or-n-p "Save changed buffer?")
3966 (save-buffer))))
3968 (defun org-clocktable-try-shift (dir n)
3969 "Check if this line starts a clock table, if yes, shift the time block."
3970 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
3971 (org-clocktable-shift dir n)))
3973 ;; Autoload org-timer.el
3975 (eval-and-compile
3976 (org-autoload
3977 "org-timer"
3978 '(org-timer-start org-timer org-timer-item
3979 org-timer-change-times-in-region
3980 org-timer-set-timer
3981 org-timer-reset-timers
3982 org-timer-show-remaining-time)))
3984 ;; Autoload org-feed.el
3986 (eval-and-compile
3987 (org-autoload
3988 "org-feed"
3989 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3992 ;; Autoload org-indent.el
3994 ;; Define the variable already here, to make sure we have it.
3995 (defvar org-indent-mode nil
3996 "Non-nil if Org-Indent mode is enabled.
3997 Use the command `org-indent-mode' to change this variable.")
3999 (eval-and-compile
4000 (org-autoload
4001 "org-indent"
4002 '(org-indent-mode)))
4004 ;; Autoload org-mobile.el
4006 (eval-and-compile
4007 (org-autoload
4008 "org-mobile"
4009 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4011 ;; Autoload archiving code
4012 ;; The stuff that is needed for cycling and tags has to be defined here.
4014 (defgroup org-archive nil
4015 "Options concerning archiving in Org-mode."
4016 :tag "Org Archive"
4017 :group 'org-structure)
4019 (defcustom org-archive-location "%s_archive::"
4020 "The location where subtrees should be archived.
4022 The value of this variable is a string, consisting of two parts,
4023 separated by a double-colon. The first part is a filename and
4024 the second part is a headline.
4026 When the filename is omitted, archiving happens in the same file.
4027 %s in the filename will be replaced by the current file
4028 name (without the directory part). Archiving to a different file
4029 is useful to keep archived entries from contributing to the
4030 Org-mode Agenda.
4032 The archived entries will be filed as subtrees of the specified
4033 headline. When the headline is omitted, the subtrees are simply
4034 filed away at the end of the file, as top-level entries. Also in
4035 the heading you can use %s to represent the file name, this can be
4036 useful when using the same archive for a number of different files.
4038 Here are a few examples:
4039 \"%s_archive::\"
4040 If the current file is Projects.org, archive in file
4041 Projects.org_archive, as top-level trees. This is the default.
4043 \"::* Archived Tasks\"
4044 Archive in the current file, under the top-level headline
4045 \"* Archived Tasks\".
4047 \"~/org/archive.org::\"
4048 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4050 \"~/org/archive.org::* From %s\"
4051 Archive in file ~/org/archive.org (absolute path), under headlines
4052 \"From FILENAME\" where file name is the current file name.
4054 \"basement::** Finished Tasks\"
4055 Archive in file ./basement (relative path), as level 3 trees
4056 below the level 2 heading \"** Finished Tasks\".
4058 You may set this option on a per-file basis by adding to the buffer a
4059 line like
4061 #+ARCHIVE: basement::** Finished Tasks
4063 You may also define it locally for a subtree by setting an ARCHIVE property
4064 in the entry. If such a property is found in an entry, or anywhere up
4065 the hierarchy, it will be used."
4066 :group 'org-archive
4067 :type 'string)
4069 (defcustom org-archive-tag "ARCHIVE"
4070 "The tag that marks a subtree as archived.
4071 An archived subtree does not open during visibility cycling, and does
4072 not contribute to the agenda listings.
4073 After changing this, font-lock must be restarted in the relevant buffers to
4074 get the proper fontification."
4075 :group 'org-archive
4076 :group 'org-keywords
4077 :type 'string)
4079 (defcustom org-agenda-skip-archived-trees t
4080 "Non-nil means the agenda will skip any items located in archived trees.
4081 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4082 variable is no longer recommended, you should leave it at the value t.
4083 Instead, use the key `v' to cycle the archives-mode in the agenda."
4084 :group 'org-archive
4085 :group 'org-agenda-skip
4086 :type 'boolean)
4088 (defcustom org-columns-skip-archived-trees t
4089 "Non-nil means ignore archived trees when creating column view."
4090 :group 'org-archive
4091 :group 'org-properties
4092 :type 'boolean)
4094 (defcustom org-cycle-open-archived-trees nil
4095 "Non-nil means `org-cycle' will open archived trees.
4096 An archived tree is a tree marked with the tag ARCHIVE.
4097 When nil, archived trees will stay folded. You can still open them with
4098 normal outline commands like `show-all', but not with the cycling commands."
4099 :group 'org-archive
4100 :group 'org-cycle
4101 :type 'boolean)
4103 (defcustom org-sparse-tree-open-archived-trees nil
4104 "Non-nil means sparse tree construction shows matches in archived trees.
4105 When nil, matches in these trees are highlighted, but the trees are kept in
4106 collapsed state."
4107 :group 'org-archive
4108 :group 'org-sparse-trees
4109 :type 'boolean)
4111 (defun org-cycle-hide-archived-subtrees (state)
4112 "Re-hide all archived subtrees after a visibility state change."
4113 (when (and (not org-cycle-open-archived-trees)
4114 (not (memq state '(overview folded))))
4115 (save-excursion
4116 (let* ((globalp (memq state '(contents all)))
4117 (beg (if globalp (point-min) (point)))
4118 (end (if globalp (point-max) (org-end-of-subtree t))))
4119 (org-hide-archived-subtrees beg end)
4120 (goto-char beg)
4121 (if (looking-at (concat ".*:" org-archive-tag ":"))
4122 (message "%s" (substitute-command-keys
4123 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4125 (defun org-force-cycle-archived ()
4126 "Cycle subtree even if it is archived."
4127 (interactive)
4128 (setq this-command 'org-cycle)
4129 (let ((org-cycle-open-archived-trees t))
4130 (call-interactively 'org-cycle)))
4132 (defun org-hide-archived-subtrees (beg end)
4133 "Re-hide all archived subtrees after a visibility state change."
4134 (save-excursion
4135 (let* ((re (concat ":" org-archive-tag ":")))
4136 (goto-char beg)
4137 (while (re-search-forward re end t)
4138 (when (org-on-heading-p)
4139 (org-flag-subtree t)
4140 (org-end-of-subtree t))))))
4142 (defun org-flag-subtree (flag)
4143 (save-excursion
4144 (org-back-to-heading t)
4145 (outline-end-of-heading)
4146 (outline-flag-region (point)
4147 (progn (org-end-of-subtree t) (point))
4148 flag)))
4150 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4152 (eval-and-compile
4153 (org-autoload "org-archive"
4154 '(org-add-archive-files org-archive-subtree
4155 org-archive-to-archive-sibling org-toggle-archive-tag
4156 org-archive-subtree-default
4157 org-archive-subtree-default-with-confirmation)))
4159 ;; Autoload Column View Code
4161 (declare-function org-columns-number-to-string "org-colview")
4162 (declare-function org-columns-get-format-and-top-level "org-colview")
4163 (declare-function org-columns-compute "org-colview")
4165 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4166 '(org-columns-number-to-string org-columns-get-format-and-top-level
4167 org-columns-compute org-agenda-columns org-columns-remove-overlays
4168 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4170 ;; Autoload ID code
4172 (declare-function org-id-store-link "org-id")
4173 (declare-function org-id-locations-load "org-id")
4174 (declare-function org-id-locations-save "org-id")
4175 (defvar org-id-track-globally)
4176 (org-autoload "org-id"
4177 '(org-id-get-create org-id-new org-id-copy org-id-get
4178 org-id-get-with-outline-path-completion
4179 org-id-get-with-outline-drilling org-id-store-link
4180 org-id-goto org-id-find org-id-store-link))
4182 ;; Autoload Plotting Code
4184 (org-autoload "org-plot"
4185 '(org-plot/gnuplot))
4187 ;;; Variables for pre-computed regular expressions, all buffer local
4189 (defvar org-drawer-regexp nil
4190 "Matches first line of a hidden block.")
4191 (make-variable-buffer-local 'org-drawer-regexp)
4192 (defvar org-todo-regexp nil
4193 "Matches any of the TODO state keywords.")
4194 (make-variable-buffer-local 'org-todo-regexp)
4195 (defvar org-not-done-regexp nil
4196 "Matches any of the TODO state keywords except the last one.")
4197 (make-variable-buffer-local 'org-not-done-regexp)
4198 (defvar org-not-done-heading-regexp nil
4199 "Matches a TODO headline that is not done.")
4200 (make-variable-buffer-local 'org-not-done-regexp)
4201 (defvar org-todo-line-regexp nil
4202 "Matches a headline and puts TODO state into group 2 if present.")
4203 (make-variable-buffer-local 'org-todo-line-regexp)
4204 (defvar org-complex-heading-regexp nil
4205 "Matches a headline and puts everything into groups:
4206 group 1: the stars
4207 group 2: The todo keyword, maybe
4208 group 3: Priority cookie
4209 group 4: True headline
4210 group 5: Tags")
4211 (make-variable-buffer-local 'org-complex-heading-regexp)
4212 (defvar org-complex-heading-regexp-format nil
4213 "Printf format to make regexp to match an exact headline.
4214 This regexp will match the headline of any node which hase the exact
4215 headline text that is put into the format, but may have any TODO state,
4216 priority and tags.")
4217 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4218 (defvar org-todo-line-tags-regexp nil
4219 "Matches a headline and puts TODO state into group 2 if present.
4220 Also put tags into group 4 if tags are present.")
4221 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4222 (defvar org-nl-done-regexp nil
4223 "Matches newline followed by a headline with the DONE keyword.")
4224 (make-variable-buffer-local 'org-nl-done-regexp)
4225 (defvar org-looking-at-done-regexp nil
4226 "Matches the DONE keyword a point.")
4227 (make-variable-buffer-local 'org-looking-at-done-regexp)
4228 (defvar org-ds-keyword-length 12
4229 "Maximum length of the Deadline and SCHEDULED keywords.")
4230 (make-variable-buffer-local 'org-ds-keyword-length)
4231 (defvar org-deadline-regexp nil
4232 "Matches the DEADLINE keyword.")
4233 (make-variable-buffer-local 'org-deadline-regexp)
4234 (defvar org-deadline-time-regexp nil
4235 "Matches the DEADLINE keyword together with a time stamp.")
4236 (make-variable-buffer-local 'org-deadline-time-regexp)
4237 (defvar org-deadline-line-regexp nil
4238 "Matches the DEADLINE keyword and the rest of the line.")
4239 (make-variable-buffer-local 'org-deadline-line-regexp)
4240 (defvar org-scheduled-regexp nil
4241 "Matches the SCHEDULED keyword.")
4242 (make-variable-buffer-local 'org-scheduled-regexp)
4243 (defvar org-scheduled-time-regexp nil
4244 "Matches the SCHEDULED keyword together with a time stamp.")
4245 (make-variable-buffer-local 'org-scheduled-time-regexp)
4246 (defvar org-closed-time-regexp nil
4247 "Matches the CLOSED keyword together with a time stamp.")
4248 (make-variable-buffer-local 'org-closed-time-regexp)
4250 (defvar org-keyword-time-regexp nil
4251 "Matches any of the 4 keywords, together with the time stamp.")
4252 (make-variable-buffer-local 'org-keyword-time-regexp)
4253 (defvar org-keyword-time-not-clock-regexp nil
4254 "Matches any of the 3 keywords, together with the time stamp.")
4255 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4256 (defvar org-maybe-keyword-time-regexp nil
4257 "Matches a timestamp, possibly preceded by a keyword.")
4258 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4259 (defvar org-planning-or-clock-line-re nil
4260 "Matches a line with planning or clock info.")
4261 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4262 (defvar org-all-time-keywords nil
4263 "List of time keywords.")
4264 (make-variable-buffer-local 'org-all-time-keywords)
4266 (defconst org-plain-time-of-day-regexp
4267 (concat
4268 "\\(\\<[012]?[0-9]"
4269 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4270 "\\(--?"
4271 "\\(\\<[012]?[0-9]"
4272 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4273 "\\)?")
4274 "Regular expression to match a plain time or time range.
4275 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4276 groups carry important information:
4277 0 the full match
4278 1 the first time, range or not
4279 8 the second time, if it is a range.")
4281 (defconst org-plain-time-extension-regexp
4282 (concat
4283 "\\(\\<[012]?[0-9]"
4284 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4285 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4286 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4287 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4288 groups carry important information:
4289 0 the full match
4290 7 hours of duration
4291 9 minutes of duration")
4293 (defconst org-stamp-time-of-day-regexp
4294 (concat
4295 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4296 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4297 "\\(--?"
4298 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4299 "Regular expression to match a timestamp time or time range.
4300 After a match, the following groups carry important information:
4301 0 the full match
4302 1 date plus weekday, for back referencing to make sure both times are on the same day
4303 2 the first time, range or not
4304 4 the second time, if it is a range.")
4306 (defconst org-startup-options
4307 '(("fold" org-startup-folded t)
4308 ("overview" org-startup-folded t)
4309 ("nofold" org-startup-folded nil)
4310 ("showall" org-startup-folded nil)
4311 ("showeverything" org-startup-folded showeverything)
4312 ("content" org-startup-folded content)
4313 ("indent" org-startup-indented t)
4314 ("noindent" org-startup-indented nil)
4315 ("hidestars" org-hide-leading-stars t)
4316 ("showstars" org-hide-leading-stars nil)
4317 ("odd" org-odd-levels-only t)
4318 ("oddeven" org-odd-levels-only nil)
4319 ("align" org-startup-align-all-tables t)
4320 ("noalign" org-startup-align-all-tables nil)
4321 ("inlineimages" org-startup-with-inline-images t)
4322 ("noinlineimages" org-startup-with-inline-images nil)
4323 ("customtime" org-display-custom-times t)
4324 ("logdone" org-log-done time)
4325 ("lognotedone" org-log-done note)
4326 ("nologdone" org-log-done nil)
4327 ("lognoteclock-out" org-log-note-clock-out t)
4328 ("nolognoteclock-out" org-log-note-clock-out nil)
4329 ("logrepeat" org-log-repeat state)
4330 ("lognoterepeat" org-log-repeat note)
4331 ("nologrepeat" org-log-repeat nil)
4332 ("logreschedule" org-log-reschedule time)
4333 ("lognotereschedule" org-log-reschedule note)
4334 ("nologreschedule" org-log-reschedule nil)
4335 ("logredeadline" org-log-redeadline time)
4336 ("lognoteredeadline" org-log-redeadline note)
4337 ("nologredeadline" org-log-redeadline nil)
4338 ("logrefile" org-log-refile time)
4339 ("lognoterefile" org-log-refile note)
4340 ("nologrefile" org-log-refile nil)
4341 ("fninline" org-footnote-define-inline t)
4342 ("nofninline" org-footnote-define-inline nil)
4343 ("fnlocal" org-footnote-section nil)
4344 ("fnauto" org-footnote-auto-label t)
4345 ("fnprompt" org-footnote-auto-label nil)
4346 ("fnconfirm" org-footnote-auto-label confirm)
4347 ("fnplain" org-footnote-auto-label plain)
4348 ("fnadjust" org-footnote-auto-adjust t)
4349 ("nofnadjust" org-footnote-auto-adjust nil)
4350 ("constcgs" constants-unit-system cgs)
4351 ("constSI" constants-unit-system SI)
4352 ("noptag" org-tag-persistent-alist nil)
4353 ("hideblocks" org-hide-block-startup t)
4354 ("nohideblocks" org-hide-block-startup nil)
4355 ("beamer" org-startup-with-beamer-mode t)
4356 ("entitiespretty" org-pretty-entities t)
4357 ("entitiesplain" org-pretty-entities nil))
4358 "Variable associated with STARTUP options for org-mode.
4359 Each element is a list of three items: The startup options as written
4360 in the #+STARTUP line, the corresponding variable, and the value to
4361 set this variable to if the option is found. An optional forth element PUSH
4362 means to push this value onto the list in the variable.")
4364 (defun org-set-regexps-and-options ()
4365 "Precompute regular expressions for current buffer."
4366 (when (org-mode-p)
4367 (org-set-local 'org-todo-kwd-alist nil)
4368 (org-set-local 'org-todo-key-alist nil)
4369 (org-set-local 'org-todo-key-trigger nil)
4370 (org-set-local 'org-todo-keywords-1 nil)
4371 (org-set-local 'org-done-keywords nil)
4372 (org-set-local 'org-todo-heads nil)
4373 (org-set-local 'org-todo-sets nil)
4374 (org-set-local 'org-todo-log-states nil)
4375 (org-set-local 'org-file-properties nil)
4376 (org-set-local 'org-file-tags nil)
4377 (let ((re (org-make-options-regexp
4378 '("CATEGORY" "TODO" "COLUMNS"
4379 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4380 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4381 "OPTIONS")
4382 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4383 (splitre "[ \t]+")
4384 (scripts org-use-sub-superscripts)
4385 kwds kws0 kwsa key log value cat arch tags const links hw dws
4386 tail sep kws1 prio props ftags drawers beamer-p
4387 ext-setup-or-nil setup-contents (start 0))
4388 (save-excursion
4389 (save-restriction
4390 (widen)
4391 (goto-char (point-min))
4392 (while (or (and ext-setup-or-nil
4393 (string-match re ext-setup-or-nil start)
4394 (setq start (match-end 0)))
4395 (and (setq ext-setup-or-nil nil start 0)
4396 (re-search-forward re nil t)))
4397 (setq key (upcase (match-string 1 ext-setup-or-nil))
4398 value (org-match-string-no-properties 2 ext-setup-or-nil))
4399 (if (stringp value) (setq value (org-trim value)))
4400 (cond
4401 ((equal key "CATEGORY")
4402 (setq cat value))
4403 ((member key '("SEQ_TODO" "TODO"))
4404 (push (cons 'sequence (org-split-string value splitre)) kwds))
4405 ((equal key "TYP_TODO")
4406 (push (cons 'type (org-split-string value splitre)) kwds))
4407 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4408 ;; general TODO-like setup
4409 (push (cons (intern (downcase (match-string 1 key)))
4410 (org-split-string value splitre)) kwds))
4411 ((equal key "TAGS")
4412 (setq tags (append tags (if tags '("\\n") nil)
4413 (org-split-string value splitre))))
4414 ((equal key "COLUMNS")
4415 (org-set-local 'org-columns-default-format value))
4416 ((equal key "LINK")
4417 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4418 (push (cons (match-string 1 value)
4419 (org-trim (match-string 2 value)))
4420 links)))
4421 ((equal key "PRIORITIES")
4422 (setq prio (org-split-string value " +")))
4423 ((equal key "PROPERTY")
4424 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4425 (push (cons (match-string 1 value) (match-string 2 value))
4426 props)))
4427 ((equal key "FILETAGS")
4428 (when (string-match "\\S-" value)
4429 (setq ftags
4430 (append
4431 ftags
4432 (apply 'append
4433 (mapcar (lambda (x) (org-split-string x ":"))
4434 (org-split-string value)))))))
4435 ((equal key "DRAWERS")
4436 (setq drawers (org-split-string value splitre)))
4437 ((equal key "CONSTANTS")
4438 (setq const (append const (org-split-string value splitre))))
4439 ((equal key "STARTUP")
4440 (let ((opts (org-split-string value splitre))
4441 l var val)
4442 (while (setq l (pop opts))
4443 (when (setq l (assoc l org-startup-options))
4444 (setq var (nth 1 l) val (nth 2 l))
4445 (if (not (nth 3 l))
4446 (set (make-local-variable var) val)
4447 (if (not (listp (symbol-value var)))
4448 (set (make-local-variable var) nil))
4449 (set (make-local-variable var) (symbol-value var))
4450 (add-to-list var val))))))
4451 ((equal key "ARCHIVE")
4452 (setq arch value)
4453 (remove-text-properties 0 (length arch)
4454 '(face t fontified t) arch))
4455 ((equal key "LATEX_CLASS")
4456 (setq beamer-p (equal value "beamer")))
4457 ((equal key "OPTIONS")
4458 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4459 (setq scripts (read (match-string 2 value)))))
4460 ((equal key "SETUPFILE")
4461 (setq setup-contents (org-file-contents
4462 (expand-file-name
4463 (org-remove-double-quotes value))
4464 'noerror))
4465 (if (not ext-setup-or-nil)
4466 (setq ext-setup-or-nil setup-contents start 0)
4467 (setq ext-setup-or-nil
4468 (concat (substring ext-setup-or-nil 0 start)
4469 "\n" setup-contents "\n"
4470 (substring ext-setup-or-nil start)))))
4471 ))))
4472 (org-set-local 'org-use-sub-superscripts scripts)
4473 (when cat
4474 (org-set-local 'org-category (intern cat))
4475 (push (cons "CATEGORY" cat) props))
4476 (when prio
4477 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4478 (setq prio (mapcar 'string-to-char prio))
4479 (org-set-local 'org-highest-priority (nth 0 prio))
4480 (org-set-local 'org-lowest-priority (nth 1 prio))
4481 (org-set-local 'org-default-priority (nth 2 prio)))
4482 (and props (org-set-local 'org-file-properties (nreverse props)))
4483 (and ftags (org-set-local 'org-file-tags
4484 (mapcar 'org-add-prop-inherited ftags)))
4485 (and drawers (org-set-local 'org-drawers drawers))
4486 (and arch (org-set-local 'org-archive-location arch))
4487 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4488 ;; Process the TODO keywords
4489 (unless kwds
4490 ;; Use the global values as if they had been given locally.
4491 (setq kwds (default-value 'org-todo-keywords))
4492 (if (stringp (car kwds))
4493 (setq kwds (list (cons org-todo-interpretation
4494 (default-value 'org-todo-keywords)))))
4495 (setq kwds (reverse kwds)))
4496 (setq kwds (nreverse kwds))
4497 (let (inter kws kw)
4498 (while (setq kws (pop kwds))
4499 (let ((kws (or
4500 (run-hook-with-args-until-success
4501 'org-todo-setup-filter-hook kws)
4502 kws)))
4503 (setq inter (pop kws) sep (member "|" kws)
4504 kws0 (delete "|" (copy-sequence kws))
4505 kwsa nil
4506 kws1 (mapcar
4507 (lambda (x)
4508 ;; 1 2
4509 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4510 (progn
4511 (setq kw (match-string 1 x)
4512 key (and (match-end 2) (match-string 2 x))
4513 log (org-extract-log-state-settings x))
4514 (push (cons kw (and key (string-to-char key))) kwsa)
4515 (and log (push log org-todo-log-states))
4517 (error "Invalid TODO keyword %s" x)))
4518 kws0)
4519 kwsa (if kwsa (append '((:startgroup))
4520 (nreverse kwsa)
4521 '((:endgroup))))
4522 hw (car kws1)
4523 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4524 tail (list inter hw (car dws) (org-last dws))))
4525 (add-to-list 'org-todo-heads hw 'append)
4526 (push kws1 org-todo-sets)
4527 (setq org-done-keywords (append org-done-keywords dws nil))
4528 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4529 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4530 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4531 (setq org-todo-sets (nreverse org-todo-sets)
4532 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4533 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4534 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4535 ;; Process the constants
4536 (when const
4537 (let (e cst)
4538 (while (setq e (pop const))
4539 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4540 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4541 (setq org-table-formula-constants-local cst)))
4543 ;; Process the tags.
4544 (when tags
4545 (let (e tgs)
4546 (while (setq e (pop tags))
4547 (cond
4548 ((equal e "{") (push '(:startgroup) tgs))
4549 ((equal e "}") (push '(:endgroup) tgs))
4550 ((equal e "\\n") (push '(:newline) tgs))
4551 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4552 (push (cons (match-string 1 e)
4553 (string-to-char (match-string 2 e)))
4554 tgs))
4555 (t (push (list e) tgs))))
4556 (org-set-local 'org-tag-alist nil)
4557 (while (setq e (pop tgs))
4558 (or (and (stringp (car e))
4559 (assoc (car e) org-tag-alist))
4560 (push e org-tag-alist)))))
4562 ;; Compute the regular expressions and other local variables
4563 (if (not org-done-keywords)
4564 (setq org-done-keywords (and org-todo-keywords-1
4565 (list (org-last org-todo-keywords-1)))))
4566 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4567 (length org-scheduled-string)
4568 (length org-clock-string)
4569 (length org-closed-string)))
4570 org-drawer-regexp
4571 (concat "^[ \t]*:\\("
4572 (mapconcat 'regexp-quote org-drawers "\\|")
4573 "\\):[ \t]*$")
4574 org-not-done-keywords
4575 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4576 org-todo-regexp
4577 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4578 "\\|") "\\)\\>")
4579 org-not-done-regexp
4580 (concat "\\<\\("
4581 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4582 "\\)\\>")
4583 org-not-done-heading-regexp
4584 (concat "^\\(\\*+\\)[ \t]+\\("
4585 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4586 "\\)[ \t]+")
4587 org-todo-line-regexp
4588 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4589 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4590 "\\)[ \t]+\\)?\\(.*\\)")
4591 org-complex-heading-regexp
4592 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4593 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4594 "\\)[ \t]+\\)?"
4595 "\\(?:\\(\\[#.\\]\\)[ \t]+\\)?"
4596 "\\(.*?\\)"
4597 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
4598 org-complex-heading-regexp-format
4599 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4600 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4601 "\\)[ \t]+\\)?"
4602 "\\(?:\\(\\[#.\\]\\)[ \t]+\\)?"
4603 "\\(?:\\(?:\\[[0-9%%/]+\\]\\)[ \t]+\\)?" ; stats cookie
4604 "\\(%s\\)[ \t]*"
4605 "\\(?:\\[[0-9%%/]+\\]\\)?" ; stats cookie
4606 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?[ \t]*$"))
4607 org-nl-done-regexp
4608 (concat "\n\\*+[ \t]+"
4609 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4610 "\\)" "[ \t]+")
4611 org-todo-line-tags-regexp
4612 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4613 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4614 "\\)[ \t]+\\)"
4615 (org-re "\\(.*?\\([ \t]:[[:alnum:]:_@#%]+:[ \t]*\\)?$\\)"))
4616 org-looking-at-done-regexp
4617 (concat "^" "\\(?:"
4618 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4619 "[ \t]+")
4620 org-deadline-regexp (concat "\\<" org-deadline-string)
4621 org-deadline-time-regexp
4622 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4623 org-deadline-line-regexp
4624 (concat "\\<\\(" org-deadline-string "\\).*")
4625 org-scheduled-regexp
4626 (concat "\\<" org-scheduled-string)
4627 org-scheduled-time-regexp
4628 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4629 org-closed-time-regexp
4630 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4631 org-keyword-time-regexp
4632 (concat "\\<\\(" org-scheduled-string
4633 "\\|" org-deadline-string
4634 "\\|" org-closed-string
4635 "\\|" org-clock-string "\\)"
4636 " *[[<]\\([^]>]+\\)[]>]")
4637 org-keyword-time-not-clock-regexp
4638 (concat "\\<\\(" org-scheduled-string
4639 "\\|" org-deadline-string
4640 "\\|" org-closed-string
4641 "\\)"
4642 " *[[<]\\([^]>]+\\)[]>]")
4643 org-maybe-keyword-time-regexp
4644 (concat "\\(\\<\\(" org-scheduled-string
4645 "\\|" org-deadline-string
4646 "\\|" org-closed-string
4647 "\\|" org-clock-string "\\)\\)?"
4648 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4649 org-planning-or-clock-line-re
4650 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4651 "\\|" org-deadline-string
4652 "\\|" org-closed-string "\\|" org-clock-string
4653 "\\)\\>\\)")
4654 org-all-time-keywords
4655 (mapcar (lambda (w) (substring w 0 -1))
4656 (list org-scheduled-string org-deadline-string
4657 org-clock-string org-closed-string))
4659 (org-compute-latex-and-specials-regexp)
4660 (org-set-font-lock-defaults))))
4662 (defun org-file-contents (file &optional noerror)
4663 "Return the contents of FILE, as a string."
4664 (if (or (not file)
4665 (not (file-readable-p file)))
4666 (if noerror
4667 (progn
4668 (message "Cannot read file \"%s\"" file)
4669 (ding) (sit-for 2)
4671 (error "Cannot read file \"%s\"" file))
4672 (with-temp-buffer
4673 (insert-file-contents file)
4674 (buffer-string))))
4676 (defun org-extract-log-state-settings (x)
4677 "Extract the log state setting from a TODO keyword string.
4678 This will extract info from a string like \"WAIT(w@/!)\"."
4679 (let (kw key log1 log2)
4680 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4681 (setq kw (match-string 1 x)
4682 key (and (match-end 2) (match-string 2 x))
4683 log1 (and (match-end 3) (match-string 3 x))
4684 log2 (and (match-end 4) (match-string 4 x)))
4685 (and (or log1 log2)
4686 (list kw
4687 (and log1 (if (equal log1 "!") 'time 'note))
4688 (and log2 (if (equal log2 "!") 'time 'note)))))))
4690 (defun org-remove-keyword-keys (list)
4691 "Remove a pair of parenthesis at the end of each string in LIST."
4692 (mapcar (lambda (x)
4693 (if (string-match "(.*)$" x)
4694 (substring x 0 (match-beginning 0))
4696 list))
4698 (defun org-assign-fast-keys (alist)
4699 "Assign fast keys to a keyword-key alist.
4700 Respect keys that are already there."
4701 (let (new e (alt ?0))
4702 (while (setq e (pop alist))
4703 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4704 (cdr e)) ;; Key already assigned.
4705 (push e new)
4706 (let ((clist (string-to-list (downcase (car e))))
4707 (used (append new alist)))
4708 (when (= (car clist) ?@)
4709 (pop clist))
4710 (while (and clist (rassoc (car clist) used))
4711 (pop clist))
4712 (unless clist
4713 (while (rassoc alt used)
4714 (incf alt)))
4715 (push (cons (car e) (or (car clist) alt)) new))))
4716 (nreverse new)))
4718 ;;; Some variables used in various places
4720 (defvar org-window-configuration nil
4721 "Used in various places to store a window configuration.")
4722 (defvar org-selected-window nil
4723 "Used in various places to store a window configuration.")
4724 (defvar org-finish-function nil
4725 "Function to be called when `C-c C-c' is used.
4726 This is for getting out of special buffers like remember.")
4729 ;; FIXME: Occasionally check by commenting these, to make sure
4730 ;; no other functions uses these, forgetting to let-bind them.
4731 (defvar entry)
4732 (defvar last-state)
4733 (defvar date)
4735 ;; Defined somewhere in this file, but used before definition.
4736 (defvar org-entities) ;; defined in org-entities.el
4737 (defvar org-struct-menu)
4738 (defvar org-org-menu)
4739 (defvar org-tbl-menu)
4741 ;;;; Define the Org-mode
4743 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4744 (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"))
4747 ;; We use a before-change function to check if a table might need
4748 ;; an update.
4749 (defvar org-table-may-need-update t
4750 "Indicates that a table might need an update.
4751 This variable is set by `org-before-change-function'.
4752 `org-table-align' sets it back to nil.")
4753 (defun org-before-change-function (beg end)
4754 "Every change indicates that a table might need an update."
4755 (setq org-table-may-need-update t))
4756 (defvar org-mode-map)
4757 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4758 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4759 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4760 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4761 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4762 (defvar org-table-buffer-is-an nil)
4764 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
4765 ;; some places -- e.g. see the macro org-with-limited-levels.
4767 ;; In Org buffers, the value of `outline-regexp' is that of
4768 ;; `org-outline-regexp'. The only function still directly relying on
4769 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
4770 ;; job when `orgstruct-mode' is active.
4771 (defvar org-outline-regexp "\\*+ "
4772 "Regexp to match Org headlines.")
4773 (defconst org-outline-regexp-bol "^\\*+ "
4774 "Regexp to match Org headlines.
4775 This is similar to `org-outline-regexp' but additionally makes
4776 sure that we are at the beginning of the line.")
4778 ;;;###autoload
4779 (define-derived-mode org-mode outline-mode "Org"
4780 "Outline-based notes management and organizer, alias
4781 \"Carsten's outline-mode for keeping track of everything.\"
4783 Org-mode develops organizational tasks around a NOTES file which
4784 contains information about projects as plain text. Org-mode is
4785 implemented on top of outline-mode, which is ideal to keep the content
4786 of large files well structured. It supports ToDo items, deadlines and
4787 time stamps, which magically appear in the diary listing of the Emacs
4788 calendar. Tables are easily created with a built-in table editor.
4789 Plain text URL-like links connect to websites, emails (VM), Usenet
4790 messages (Gnus), BBDB entries, and any files related to the project.
4791 For printing and sharing of notes, an Org-mode file (or a part of it)
4792 can be exported as a structured ASCII or HTML file.
4794 The following commands are available:
4796 \\{org-mode-map}"
4798 ;; Get rid of Outline menus, they are not needed
4799 ;; Need to do this here because define-derived-mode sets up
4800 ;; the keymap so late. Still, it is a waste to call this each time
4801 ;; we switch another buffer into org-mode.
4802 (if (featurep 'xemacs)
4803 (when (boundp 'outline-mode-menu-heading)
4804 ;; Assume this is Greg's port, it uses easymenu
4805 (easy-menu-remove outline-mode-menu-heading)
4806 (easy-menu-remove outline-mode-menu-show)
4807 (easy-menu-remove outline-mode-menu-hide))
4808 (define-key org-mode-map [menu-bar headings] 'undefined)
4809 (define-key org-mode-map [menu-bar hide] 'undefined)
4810 (define-key org-mode-map [menu-bar show] 'undefined))
4812 (org-load-modules-maybe)
4813 (easy-menu-add org-org-menu)
4814 (easy-menu-add org-tbl-menu)
4815 (org-install-agenda-files-menu)
4816 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4817 (add-to-invisibility-spec '(org-cwidth))
4818 (add-to-invisibility-spec '(org-hide-block . t))
4819 (when (featurep 'xemacs)
4820 (org-set-local 'line-move-ignore-invisible t))
4821 (org-set-local 'outline-regexp org-outline-regexp)
4822 (org-set-local 'outline-level 'org-outline-level)
4823 (setq bidi-paragraph-direction 'left-to-right)
4824 (when (and org-ellipsis
4825 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4826 (fboundp 'make-glyph-code))
4827 (unless org-display-table
4828 (setq org-display-table (make-display-table)))
4829 (set-display-table-slot
4830 org-display-table 4
4831 (vconcat (mapcar
4832 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4833 org-ellipsis)))
4834 (if (stringp org-ellipsis) org-ellipsis "..."))))
4835 (setq buffer-display-table org-display-table))
4836 (org-set-regexps-and-options)
4837 (when (and org-tag-faces (not org-tags-special-faces-re))
4838 ;; tag faces set outside customize.... force initialization.
4839 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4840 ;; Calc embedded
4841 (org-set-local 'calc-embedded-open-mode "# ")
4842 (modify-syntax-entry ?@ "w")
4843 (if org-startup-truncated (setq truncate-lines t))
4844 (org-set-local 'font-lock-unfontify-region-function
4845 'org-unfontify-region)
4846 ;; Activate before-change-function
4847 (org-set-local 'org-table-may-need-update t)
4848 (org-add-hook 'before-change-functions 'org-before-change-function nil
4849 'local)
4850 ;; Check for running clock before killing a buffer
4851 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4852 ;; Paragraphs and auto-filling
4853 (org-set-autofill-regexps)
4854 (setq indent-line-function 'org-indent-line-function)
4855 (org-update-radio-target-regexp)
4856 ;; Beginning/end of defun
4857 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
4858 (org-set-local 'end-of-defun-function 'org-end-of-defun)
4859 ;; Next error for sparse trees
4860 (org-set-local 'next-error-function 'org-occur-next-match)
4861 ;; Make sure dependence stuff works reliably, even for users who set it
4862 ;; too late :-(
4863 (if org-enforce-todo-dependencies
4864 (add-hook 'org-blocker-hook
4865 'org-block-todo-from-children-or-siblings-or-parent)
4866 (remove-hook 'org-blocker-hook
4867 'org-block-todo-from-children-or-siblings-or-parent))
4868 (if org-enforce-todo-checkbox-dependencies
4869 (add-hook 'org-blocker-hook
4870 'org-block-todo-from-checkboxes)
4871 (remove-hook 'org-blocker-hook
4872 'org-block-todo-from-checkboxes))
4874 ;; Comment characters
4875 (org-set-local 'comment-start "#")
4876 (org-set-local 'comment-padding " ")
4878 ;; Align options lines
4879 (org-set-local
4880 'align-mode-rules-list
4881 '((org-in-buffer-settings
4882 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4883 (modes . '(org-mode)))))
4885 ;; Imenu
4886 (org-set-local 'imenu-create-index-function
4887 'org-imenu-get-tree)
4889 ;; Make isearch reveal context
4890 (if (or (featurep 'xemacs)
4891 (not (boundp 'outline-isearch-open-invisible-function)))
4892 ;; Emacs 21 and XEmacs make use of the hook
4893 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4894 ;; Emacs 22 deals with this through a special variable
4895 (org-set-local 'outline-isearch-open-invisible-function
4896 (lambda (&rest ignore) (org-show-context 'isearch))))
4898 ;; Turn on org-beamer-mode?
4899 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4901 ;; Setup the pcomplete hooks
4902 (set (make-local-variable 'pcomplete-command-completion-function)
4903 'org-pcomplete-initial)
4904 (set (make-local-variable 'pcomplete-command-name-function)
4905 'org-command-at-point)
4906 (set (make-local-variable 'pcomplete-default-completion-function)
4907 'ignore)
4908 (set (make-local-variable 'pcomplete-parse-arguments-function)
4909 'org-parse-arguments)
4910 (set (make-local-variable 'pcomplete-termination-string) "")
4911 (set (make-local-variable 'face-remapping-alist)
4912 '((default org-default)))
4914 ;; If empty file that did not turn on org-mode automatically, make it to.
4915 (if (and org-insert-mode-line-in-empty-file
4916 (org-called-interactively-p 'any)
4917 (= (point-min) (point-max)))
4918 (insert "# -*- mode: org -*-\n\n"))
4919 (unless org-inhibit-startup
4920 (when org-startup-align-all-tables
4921 (let ((bmp (buffer-modified-p)))
4922 (org-table-map-tables 'org-table-align 'quietly)
4923 (set-buffer-modified-p bmp)))
4924 (when org-startup-with-inline-images
4925 (org-display-inline-images))
4926 (when org-startup-indented
4927 (require 'org-indent)
4928 (org-indent-mode 1))
4929 (unless org-inhibit-startup-visibility-stuff
4930 (org-set-startup-visibility))))
4932 (when (fboundp 'abbrev-table-put)
4933 (abbrev-table-put org-mode-abbrev-table
4934 :parents (list text-mode-abbrev-table)))
4936 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4938 (defun org-current-time ()
4939 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4940 (if (> (car org-time-stamp-rounding-minutes) 1)
4941 (let ((r (car org-time-stamp-rounding-minutes))
4942 (time (decode-time)))
4943 (apply 'encode-time
4944 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4945 (nthcdr 2 time))))
4946 (current-time)))
4948 (defun org-today ()
4949 "Return today date, considering `org-extend-today-until'."
4950 (time-to-days
4951 (time-subtract (current-time)
4952 (list 0 (* 3600 org-extend-today-until) 0))))
4954 ;;;; Font-Lock stuff, including the activators
4956 (defvar org-mouse-map (make-sparse-keymap))
4957 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
4958 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
4959 (when org-mouse-1-follows-link
4960 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4961 (when org-tab-follows-link
4962 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4963 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4965 (require 'font-lock)
4967 (defconst org-non-link-chars "]\t\n\r<>")
4968 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4969 "shell" "elisp" "doi" "message"))
4970 (defvar org-link-types-re nil
4971 "Matches a link that has a url-like prefix like \"http:\"")
4972 (defvar org-link-re-with-space nil
4973 "Matches a link with spaces, optional angular brackets around it.")
4974 (defvar org-link-re-with-space2 nil
4975 "Matches a link with spaces, optional angular brackets around it.")
4976 (defvar org-link-re-with-space3 nil
4977 "Matches a link with spaces, only for internal part in bracket links.")
4978 (defvar org-angle-link-re nil
4979 "Matches link with angular brackets, spaces are allowed.")
4980 (defvar org-plain-link-re nil
4981 "Matches plain link, without spaces.")
4982 (defvar org-bracket-link-regexp nil
4983 "Matches a link in double brackets.")
4984 (defvar org-bracket-link-analytic-regexp nil
4985 "Regular expression used to analyze links.
4986 Here is what the match groups contain after a match:
4987 1: http:
4988 2: http
4989 3: path
4990 4: [desc]
4991 5: desc")
4992 (defvar org-bracket-link-analytic-regexp++ nil
4993 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
4994 (defvar org-any-link-re nil
4995 "Regular expression matching any link.")
4997 (defcustom org-match-sexp-depth 3
4998 "Number of stacked braces for sub/superscript matching.
4999 This has to be set before loading org.el to be effective."
5000 :group 'org-export-translation ; ??????????????????????????/
5001 :type 'integer)
5003 (defun org-create-multibrace-regexp (left right n)
5004 "Create a regular expression which will match a balanced sexp.
5005 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5006 as single character strings.
5007 The regexp returned will match the entire expression including the
5008 delimiters. It will also define a single group which contains the
5009 match except for the outermost delimiters. The maximum depth of
5010 stacked delimiters is N. Escaping delimiters is not possible."
5011 (let* ((nothing (concat "[^" left right "]*?"))
5012 (or "\\|")
5013 (re nothing)
5014 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5015 (while (> n 1)
5016 (setq n (1- n)
5017 re (concat re or next)
5018 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5019 (concat left "\\(" re "\\)" right)))
5021 (defvar org-match-substring-regexp
5022 (concat
5023 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5024 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5025 "\\|"
5026 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5027 "\\|"
5028 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5029 "The regular expression matching a sub- or superscript.")
5031 (defvar org-match-substring-with-braces-regexp
5032 (concat
5033 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5034 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5035 "\\)")
5036 "The regular expression matching a sub- or superscript, forcing braces.")
5038 (defun org-make-link-regexps ()
5039 "Update the link regular expressions.
5040 This should be called after the variable `org-link-types' has changed."
5041 (setq org-link-types-re
5042 (concat
5043 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5044 org-link-re-with-space
5045 (concat
5046 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5047 "\\([^" org-non-link-chars " ]"
5048 "[^" org-non-link-chars "]*"
5049 "[^" org-non-link-chars " ]\\)>?")
5050 org-link-re-with-space2
5051 (concat
5052 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5053 "\\([^" org-non-link-chars " ]"
5054 "[^\t\n\r]*"
5055 "[^" org-non-link-chars " ]\\)>?")
5056 org-link-re-with-space3
5057 (concat
5058 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5059 "\\([^" org-non-link-chars " ]"
5060 "[^\t\n\r]*\\)")
5061 org-angle-link-re
5062 (concat
5063 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5064 "\\([^" org-non-link-chars " ]"
5065 "[^" org-non-link-chars "]*"
5066 "\\)>")
5067 org-plain-link-re
5068 (concat
5069 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5070 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5071 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5072 org-bracket-link-regexp
5073 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5074 org-bracket-link-analytic-regexp
5075 (concat
5076 "\\[\\["
5077 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5078 "\\([^]]+\\)"
5079 "\\]"
5080 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5081 "\\]")
5082 org-bracket-link-analytic-regexp++
5083 (concat
5084 "\\[\\["
5085 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5086 "\\([^]]+\\)"
5087 "\\]"
5088 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5089 "\\]")
5090 org-any-link-re
5091 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5092 org-angle-link-re "\\)\\|\\("
5093 org-plain-link-re "\\)")))
5095 (org-make-link-regexps)
5097 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5098 "Regular expression for fast time stamp matching.")
5099 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?\\)[]>]"
5100 "Regular expression for fast time stamp matching.")
5101 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5102 "Regular expression matching time strings for analysis.
5103 This one does not require the space after the date, so it can be used
5104 on a string that terminates immediately after the date.")
5105 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5106 "Regular expression matching time strings for analysis.")
5107 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5108 "Regular expression matching time stamps, with groups.")
5109 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5110 "Regular expression matching time stamps (also [..]), with groups.")
5111 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5112 "Regular expression matching a time stamp range.")
5113 (defconst org-tr-regexp-both
5114 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5115 "Regular expression matching a time stamp range.")
5116 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5117 org-ts-regexp "\\)?")
5118 "Regular expression matching a time stamp or time stamp range.")
5119 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5120 org-ts-regexp-both "\\)?")
5121 "Regular expression matching a time stamp or time stamp range.
5122 The time stamps may be either active or inactive.")
5124 (defvar org-emph-face nil)
5126 (defun org-do-emphasis-faces (limit)
5127 "Run through the buffer and add overlays to emphasised strings."
5128 (let (rtn a)
5129 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5130 (if (not (= (char-after (match-beginning 3))
5131 (char-after (match-beginning 4))))
5132 (progn
5133 (setq rtn t)
5134 (setq a (assoc (match-string 3) org-emphasis-alist))
5135 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5136 'face
5137 (nth 1 a))
5138 (and (nth 4 a)
5139 (org-remove-flyspell-overlays-in
5140 (match-beginning 0) (match-end 0)))
5141 (add-text-properties (match-beginning 2) (match-end 2)
5142 '(font-lock-multiline t org-emphasis t))
5143 (when org-hide-emphasis-markers
5144 (add-text-properties (match-end 4) (match-beginning 5)
5145 '(invisible org-link))
5146 (add-text-properties (match-beginning 3) (match-end 3)
5147 '(invisible org-link)))))
5148 (backward-char 1))
5149 rtn))
5151 (defun org-emphasize (&optional char)
5152 "Insert or change an emphasis, i.e. a font like bold or italic.
5153 If there is an active region, change that region to a new emphasis.
5154 If there is no region, just insert the marker characters and position
5155 the cursor between them.
5156 CHAR should be either the marker character, or the first character of the
5157 HTML tag associated with that emphasis. If CHAR is a space, the means
5158 to remove the emphasis of the selected region.
5159 If char is not given (for example in an interactive call) it
5160 will be prompted for."
5161 (interactive)
5162 (let ((eal org-emphasis-alist) e det
5163 (erc org-emphasis-regexp-components)
5164 (prompt "")
5165 (string "") beg end move tag c s)
5166 (if (org-region-active-p)
5167 (setq beg (region-beginning) end (region-end)
5168 string (buffer-substring beg end))
5169 (setq move t))
5171 (while (setq e (pop eal))
5172 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5173 c (aref tag 0))
5174 (push (cons c (string-to-char (car e))) det)
5175 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5176 (substring tag 1)))))
5177 (setq det (nreverse det))
5178 (unless char
5179 (message "%s" (concat "Emphasis marker or tag:" prompt))
5180 (setq char (read-char-exclusive)))
5181 (setq char (or (cdr (assoc char det)) char))
5182 (if (equal char ?\ )
5183 (setq s "" move nil)
5184 (unless (assoc (char-to-string char) org-emphasis-alist)
5185 (error "No such emphasis marker: \"%c\"" char))
5186 (setq s (char-to-string char)))
5187 (while (and (> (length string) 1)
5188 (equal (substring string 0 1) (substring string -1))
5189 (assoc (substring string 0 1) org-emphasis-alist))
5190 (setq string (substring string 1 -1)))
5191 (setq string (concat s string s))
5192 (if beg (delete-region beg end))
5193 (unless (or (bolp)
5194 (string-match (concat "[" (nth 0 erc) "\n]")
5195 (char-to-string (char-before (point)))))
5196 (insert " "))
5197 (unless (or (eobp)
5198 (string-match (concat "[" (nth 1 erc) "\n]")
5199 (char-to-string (char-after (point)))))
5200 (insert " ") (backward-char 1))
5201 (insert string)
5202 (and move (backward-char 1))))
5204 (defconst org-nonsticky-props
5205 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5207 (defsubst org-rear-nonsticky-at (pos)
5208 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5210 (defun org-activate-plain-links (limit)
5211 "Run through the buffer and add overlays to links."
5212 (catch 'exit
5213 (let (f)
5214 (if (re-search-forward org-plain-link-re limit t)
5215 (progn
5216 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5217 (setq f (get-text-property (match-beginning 0) 'face))
5218 (if (or (eq f 'org-tag)
5219 (and (listp f) (memq 'org-tag f)))
5221 (add-text-properties (match-beginning 0) (match-end 0)
5222 (list 'mouse-face 'highlight
5223 'face 'org-link
5224 'keymap org-mouse-map))
5225 (org-rear-nonsticky-at (match-end 0)))
5226 t)))))
5228 (defun org-activate-code (limit)
5229 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5230 (progn
5231 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5232 (remove-text-properties (match-beginning 0) (match-end 0)
5233 '(display t invisible t intangible t))
5234 t)))
5236 (defcustom org-src-fontify-natively nil
5237 "When non-nil, fontify code in code blocks."
5238 :type 'boolean
5239 :group 'org-appearance
5240 :group 'org-babel)
5242 (defun org-fontify-meta-lines-and-blocks (limit)
5243 (condition-case nil
5244 (org-fontify-meta-lines-and-blocks-1 limit)
5245 (error (message "org-mode fontification error"))))
5247 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5248 "Fontify #+ lines and blocks, in the correct ways."
5249 (let ((case-fold-search t))
5250 (if (re-search-forward
5251 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5252 limit t)
5253 (let ((beg (match-beginning 0))
5254 (block-start (match-end 0))
5255 (block-end nil)
5256 (lang (match-string 7))
5257 (beg1 (line-beginning-position 2))
5258 (dc1 (downcase (match-string 2)))
5259 (dc3 (downcase (match-string 3)))
5260 end end1 quoting block-type ovl)
5261 (cond
5262 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5263 ;; a single line of backend-specific content
5264 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5265 (remove-text-properties (match-beginning 0) (match-end 0)
5266 '(display t invisible t intangible t))
5267 (add-text-properties (match-beginning 1) (match-end 3)
5268 '(font-lock-fontified t face org-meta-line))
5269 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5270 '(font-lock-fontified t face org-block))
5271 ; for backend-specific code
5273 ((and (match-end 4) (equal dc3 "begin"))
5274 ;; Truly a block
5275 (setq block-type (downcase (match-string 5))
5276 quoting (member block-type org-protecting-blocks))
5277 (when (re-search-forward
5278 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5279 nil t) ;; on purpose, we look further than LIMIT
5280 (setq end (match-end 0) end1 (1- (match-beginning 0)))
5281 (setq block-end (match-beginning 0))
5282 (when quoting
5283 (remove-text-properties beg end
5284 '(display t invisible t intangible t)))
5285 (add-text-properties
5286 beg end
5287 '(font-lock-fontified t font-lock-multiline t))
5288 (add-text-properties beg beg1 '(face org-meta-line))
5289 (add-text-properties end1 (min (point-max) (1+ end))
5290 '(face org-meta-line)) ; for end_src
5291 (cond
5292 ((and lang (not (string= lang "")) org-src-fontify-natively)
5293 (org-src-font-lock-fontify-block lang block-start block-end)
5294 ;; remove old background overlays
5295 (mapc (lambda (ov)
5296 (if (eq (overlay-get ov 'face) 'org-block-background)
5297 (delete-overlay ov)))
5298 (overlays-at (/ (+ beg1 block-end) 2)))
5299 ;; add a background overlay
5300 (setq ovl (make-overlay beg1 block-end))
5301 (overlay-put ovl 'face 'org-block-background)
5302 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5303 (quoting
5304 (add-text-properties beg1 (min (point-max) (1+ end1))
5305 '(face org-block))) ; end of source block
5306 ((not org-fontify-quote-and-verse-blocks))
5307 ((string= block-type "quote")
5308 (add-text-properties beg1 (1+ end1) '(face org-quote)))
5309 ((string= block-type "verse")
5310 (add-text-properties beg1 (1+ end1) '(face org-verse))))
5311 (add-text-properties beg beg1 '(face org-block-begin-line))
5312 (add-text-properties (1+ end) (1+ end1) '(face org-block-end-line))
5314 ((member dc1 '("title:" "author:" "email:" "date:"))
5315 (add-text-properties
5316 beg (match-end 3)
5317 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5318 '(font-lock-fontified t invisible t)
5319 '(font-lock-fontified t face org-document-info-keyword)))
5320 (add-text-properties
5321 (match-beginning 6) (match-end 6)
5322 (if (string-equal dc1 "title:")
5323 '(font-lock-fontified t face org-document-title)
5324 '(font-lock-fontified t face org-document-info))))
5325 ((not (member (char-after beg) '(?\ ?\t)))
5326 ;; just any other in-buffer setting, but not indented
5327 (add-text-properties
5328 beg (1+ (match-end 0))
5329 '(font-lock-fontified t face org-meta-line))
5331 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5332 "orgtbl:" "tblfm:" "tblname:" "result:"
5333 "results:" "source:" "srcname:" "call:"
5334 "data:" "header:" "headers:"))
5335 (and (match-end 4) (equal dc3 "attr")))
5336 (add-text-properties
5337 beg (match-end 0)
5338 '(font-lock-fontified t face org-meta-line))
5340 ((member dc3 '(" " ""))
5341 (add-text-properties
5342 beg (match-end 0)
5343 '(font-lock-fontified t face font-lock-comment-face)))
5344 (t nil))))))
5346 (defun org-activate-angle-links (limit)
5347 "Run through the buffer and add overlays to links."
5348 (if (re-search-forward org-angle-link-re limit t)
5349 (progn
5350 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5351 (add-text-properties (match-beginning 0) (match-end 0)
5352 (list 'mouse-face 'highlight
5353 'keymap org-mouse-map))
5354 (org-rear-nonsticky-at (match-end 0))
5355 t)))
5357 (defun org-activate-footnote-links (limit)
5358 "Run through the buffer and add overlays to footnotes."
5359 (let ((fn (org-footnote-next-reference-or-definition limit)))
5360 (when fn
5361 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5362 (org-remove-flyspell-overlays-in beg end)
5363 (add-text-properties beg end
5364 (list 'mouse-face 'highlight
5365 'keymap org-mouse-map
5366 'help-echo
5367 (if (= (point-at-bol) beg)
5368 "Footnote definition"
5369 "Footnote reference")
5370 'font-lock-fontified t
5371 'font-lock-multiline t
5372 'face 'org-footnote))))))
5374 (defun org-activate-bracket-links (limit)
5375 "Run through the buffer and add overlays to bracketed links."
5376 (if (re-search-forward org-bracket-link-regexp limit t)
5377 (let* ((help (concat "LINK: "
5378 (org-match-string-no-properties 1)))
5379 ;; FIXME: above we should remove the escapes.
5380 ;; but that requires another match, protecting match data,
5381 ;; a lot of overhead for font-lock.
5382 (ip (org-maybe-intangible
5383 (list 'invisible 'org-link
5384 'keymap org-mouse-map 'mouse-face 'highlight
5385 'font-lock-multiline t 'help-echo help)))
5386 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5387 'font-lock-multiline t 'help-echo help)))
5388 ;; We need to remove the invisible property here. Table narrowing
5389 ;; may have made some of this invisible.
5390 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5391 (remove-text-properties (match-beginning 0) (match-end 0)
5392 '(invisible nil))
5393 (if (match-end 3)
5394 (progn
5395 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5396 (org-rear-nonsticky-at (match-beginning 3))
5397 (add-text-properties (match-beginning 3) (match-end 3) vp)
5398 (org-rear-nonsticky-at (match-end 3))
5399 (add-text-properties (match-end 3) (match-end 0) ip)
5400 (org-rear-nonsticky-at (match-end 0)))
5401 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5402 (org-rear-nonsticky-at (match-beginning 1))
5403 (add-text-properties (match-beginning 1) (match-end 1) vp)
5404 (org-rear-nonsticky-at (match-end 1))
5405 (add-text-properties (match-end 1) (match-end 0) ip)
5406 (org-rear-nonsticky-at (match-end 0)))
5407 t)))
5409 (defun org-activate-dates (limit)
5410 "Run through the buffer and add overlays to dates."
5411 (if (re-search-forward org-tsr-regexp-both limit t)
5412 (progn
5413 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5414 (add-text-properties (match-beginning 0) (match-end 0)
5415 (list 'mouse-face 'highlight
5416 'keymap org-mouse-map))
5417 (org-rear-nonsticky-at (match-end 0))
5418 (when org-display-custom-times
5419 (if (match-end 3)
5420 (org-display-custom-time (match-beginning 3) (match-end 3)))
5421 (org-display-custom-time (match-beginning 1) (match-end 1)))
5422 t)))
5424 (defvar org-target-link-regexp nil
5425 "Regular expression matching radio targets in plain text.")
5426 (make-variable-buffer-local 'org-target-link-regexp)
5427 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5428 "Regular expression matching a link target.")
5429 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5430 "Regular expression matching a radio target.")
5431 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5432 "Regular expression matching any target.")
5434 (defun org-activate-target-links (limit)
5435 "Run through the buffer and add overlays to target matches."
5436 (when org-target-link-regexp
5437 (let ((case-fold-search t))
5438 (if (re-search-forward org-target-link-regexp limit t)
5439 (progn
5440 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5441 (add-text-properties (match-beginning 0) (match-end 0)
5442 (list 'mouse-face 'highlight
5443 'keymap org-mouse-map
5444 'help-echo "Radio target link"
5445 'org-linked-text t))
5446 (org-rear-nonsticky-at (match-end 0))
5447 t)))))
5449 (defun org-update-radio-target-regexp ()
5450 "Find all radio targets in this file and update the regular expression."
5451 (interactive)
5452 (when (memq 'radio org-activate-links)
5453 (setq org-target-link-regexp
5454 (org-make-target-link-regexp (org-all-targets 'radio)))
5455 (org-restart-font-lock)))
5457 (defun org-hide-wide-columns (limit)
5458 (let (s e)
5459 (setq s (text-property-any (point) (or limit (point-max))
5460 'org-cwidth t))
5461 (when s
5462 (setq e (next-single-property-change s 'org-cwidth))
5463 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5464 (goto-char e)
5465 t)))
5467 (defvar org-latex-and-specials-regexp nil
5468 "Regular expression for highlighting export special stuff.")
5469 (defvar org-match-substring-regexp)
5470 (defvar org-match-substring-with-braces-regexp)
5472 ;; This should be with the exporter code, but we also use if for font-locking
5473 (defconst org-export-html-special-string-regexps
5474 '(("\\\\-" . "&shy;")
5475 ("---\\([^-]\\)" . "&mdash;\\1")
5476 ("--\\([^-]\\)" . "&ndash;\\1")
5477 ("\\.\\.\\." . "&hellip;"))
5478 "Regular expressions for special string conversion.")
5481 (defun org-compute-latex-and-specials-regexp ()
5482 "Compute regular expression for stuff treated specially by exporters."
5483 (if (not org-highlight-latex-fragments-and-specials)
5484 (org-set-local 'org-latex-and-specials-regexp nil)
5485 (require 'org-exp)
5486 (let*
5487 ((matchers (plist-get org-format-latex-options :matchers))
5488 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5489 org-latex-regexps)))
5490 (org-export-allow-BIND nil)
5491 (options (org-combine-plists (org-default-export-plist)
5492 (org-infile-export-plist)))
5493 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5494 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5495 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5496 (org-export-html-expand (plist-get options :expand-quoted-html))
5497 (org-export-with-special-strings (plist-get options :special-strings))
5498 (re-sub
5499 (cond
5500 ((equal org-export-with-sub-superscripts '{})
5501 (list org-match-substring-with-braces-regexp))
5502 (org-export-with-sub-superscripts
5503 (list org-match-substring-regexp))
5504 (t nil)))
5505 (re-latex
5506 (if org-export-with-LaTeX-fragments
5507 (mapcar (lambda (x) (nth 1 x)) latexs)))
5508 (re-macros
5509 (if org-export-with-TeX-macros
5510 (list (concat "\\\\"
5511 (regexp-opt
5512 (append
5514 (delq nil
5515 (mapcar 'car-safe
5516 (append org-entities-user
5517 org-entities)))
5518 (if (boundp 'org-latex-entities)
5519 (mapcar (lambda (x)
5520 (or (car-safe x) x))
5521 org-latex-entities)
5522 nil))
5523 'words))) ; FIXME
5525 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5526 (re-special (if org-export-with-special-strings
5527 (mapcar (lambda (x) (car x))
5528 org-export-html-special-string-regexps)))
5529 (re-rest
5530 (delq nil
5531 (list
5532 (if org-export-html-expand "@<[^>\n]+>")
5533 ))))
5534 (org-set-local
5535 'org-latex-and-specials-regexp
5536 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5537 re-rest) "\\|")))))
5539 (defun org-do-latex-and-special-faces (limit)
5540 "Run through the buffer and add overlays to links."
5541 (when org-latex-and-specials-regexp
5542 (let (rtn d)
5543 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5544 limit t))
5545 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5546 'face))
5547 '(org-code org-verbatim underline)))
5548 (progn
5549 (setq rtn t
5550 d (cond ((member (char-after (1+ (match-beginning 0)))
5551 '(?_ ?^)) 1)
5552 (t 0)))
5553 (font-lock-prepend-text-property
5554 (+ d (match-beginning 0)) (match-end 0)
5555 'face 'org-latex-and-export-specials)
5556 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5557 '(font-lock-multiline t)))))
5558 rtn)))
5560 (defun org-restart-font-lock ()
5561 "Restart `font-lock-mode', to force refontification."
5562 (when (and (boundp 'font-lock-mode) font-lock-mode)
5563 (font-lock-mode -1)
5564 (font-lock-mode 1)))
5566 (defun org-all-targets (&optional radio)
5567 "Return a list of all targets in this file.
5568 With optional argument RADIO, only find radio targets."
5569 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5570 rtn)
5571 (save-excursion
5572 (goto-char (point-min))
5573 (while (re-search-forward re nil t)
5574 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5575 rtn)))
5577 (defun org-make-target-link-regexp (targets)
5578 "Make regular expression matching all strings in TARGETS.
5579 The regular expression finds the targets also if there is a line break
5580 between words."
5581 (and targets
5582 (concat
5583 "\\<\\("
5584 (mapconcat
5585 (lambda (x)
5586 (setq x (regexp-quote x))
5587 (while (string-match " +" x)
5588 (setq x (replace-match "\\s-+" t t x)))
5590 targets
5591 "\\|")
5592 "\\)\\>")))
5594 (defun org-activate-tags (limit)
5595 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5596 (progn
5597 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5598 (add-text-properties (match-beginning 1) (match-end 1)
5599 (list 'mouse-face 'highlight
5600 'keymap org-mouse-map))
5601 (org-rear-nonsticky-at (match-end 1))
5602 t)))
5604 (defun org-outline-level ()
5605 "Compute the outline level of the heading at point.
5606 This function assumes that the cursor is at the beginning of a line matched
5607 by `outline-regexp'. Otherwise it returns garbage.
5608 If this is called at a normal headline, the level is the number of stars.
5609 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5610 (save-excursion
5611 (looking-at org-outline-regexp)
5612 (1- (- (match-end 0) (match-beginning 0)))))
5614 (defvar org-font-lock-keywords nil)
5616 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5617 "Regular expression matching a property line.")
5619 (defvar org-font-lock-hook nil
5620 "Functions to be called for special font lock stuff.")
5622 (defvar org-font-lock-set-keywords-hook nil
5623 "Functions that can manipulate `org-font-lock-extra-keywords'.
5624 This is calles after `org-font-lock-extra-keywords' is defined, but before
5625 it is installed to be used by font lock. This can be useful if something
5626 needs to be inserted at a specific position in the font-lock sequence.")
5628 (defun org-font-lock-hook (limit)
5629 (run-hook-with-args 'org-font-lock-hook limit))
5631 (defun org-set-font-lock-defaults ()
5632 (let* ((em org-fontify-emphasized-text)
5633 (lk org-activate-links)
5634 (org-font-lock-extra-keywords
5635 (list
5636 ;; Call the hook
5637 '(org-font-lock-hook)
5638 ;; Headlines
5639 `(,(if org-fontify-whole-heading-line
5640 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5641 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5642 (1 (org-get-level-face 1))
5643 (2 (org-get-level-face 2))
5644 (3 (org-get-level-face 3)))
5645 ;; Table lines
5646 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5647 (1 'org-table t))
5648 ;; Table internals
5649 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5650 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5651 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5652 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5653 ;; Drawers
5654 (list org-drawer-regexp '(0 'org-special-keyword t))
5655 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5656 ;; Properties
5657 (list org-property-re
5658 '(1 'org-special-keyword t)
5659 '(3 'org-property-value t))
5660 ;; Links
5661 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5662 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5663 (if (memq 'plain lk) '(org-activate-plain-links))
5664 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5665 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5666 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5667 (if (memq 'footnote lk) '(org-activate-footnote-links))
5668 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5669 '(org-hide-wide-columns (0 nil append))
5670 ;; TODO lines
5671 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
5672 '(1 (org-get-todo-face 1) t))
5673 ;; DONE
5674 (if org-fontify-done-headline
5675 (list (concat "^[*]+ +\\<\\("
5676 (mapconcat 'regexp-quote org-done-keywords "\\|")
5677 "\\)\\(.*\\)")
5678 '(2 'org-headline-done t))
5679 nil)
5680 ;; Priorities
5681 '(org-font-lock-add-priority-faces)
5682 ;; Tags
5683 '(org-font-lock-add-tag-faces)
5684 ;; Special keywords
5685 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5686 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5687 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5688 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5689 ;; Emphasis
5690 (if em
5691 (if (featurep 'xemacs)
5692 '(org-do-emphasis-faces (0 nil append))
5693 '(org-do-emphasis-faces)))
5694 ;; Checkboxes
5695 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5696 1 'org-checkbox prepend)
5697 (if (cdr (assq 'checkbox org-list-automatic-rules))
5698 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5699 (0 (org-get-checkbox-statistics-face) t)))
5700 ;; Description list items
5701 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5702 1 'bold prepend)
5703 ;; ARCHIVEd headings
5704 (list (concat
5705 org-outline-regexp-bol
5706 "\\(.*:" org-archive-tag ":.*\\)")
5707 '(1 'org-archived prepend))
5708 ;; Specials
5709 '(org-do-latex-and-special-faces)
5710 '(org-fontify-entities)
5711 '(org-raise-scripts)
5712 ;; Code
5713 '(org-activate-code (1 'org-code t))
5714 ;; COMMENT
5715 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5716 "\\|" org-quote-string "\\)\\>")
5717 '(1 'org-special-keyword t))
5718 '("^#.*" (0 'font-lock-comment-face t))
5719 ;; Blocks and meta lines
5720 '(org-fontify-meta-lines-and-blocks)
5722 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5723 (run-hooks 'org-font-lock-set-keywords-hook)
5724 ;; Now set the full font-lock-keywords
5725 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5726 (org-set-local 'font-lock-defaults
5727 '(org-font-lock-keywords t nil nil backward-paragraph))
5728 (kill-local-variable 'font-lock-keywords) nil))
5730 (defun org-toggle-pretty-entities ()
5731 "Toggle the composition display of entities as UTF8 characters."
5732 (interactive)
5733 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5734 (org-restart-font-lock)
5735 (if org-pretty-entities
5736 (message "Entities are displayed as UTF8 characers")
5737 (save-restriction
5738 (widen)
5739 (org-decompose-region (point-min) (point-max))
5740 (message "Entities are displayed plain"))))
5742 (defun org-fontify-entities (limit)
5743 "Find an entity to fontify."
5744 (let (ee)
5745 (when org-pretty-entities
5746 (catch 'match
5747 (while (re-search-forward
5748 "\\\\\\([a-zA-Z][a-zA-Z0-9]*\\)\\($\\|[^[:alnum:]\n]\\)"
5749 limit t)
5750 (if (and (not (org-in-indented-comment-line))
5751 (setq ee (org-entity-get (match-string 1)))
5752 (= (length (nth 6 ee)) 1))
5753 (progn
5754 (add-text-properties
5755 (match-beginning 0) (match-end 1)
5756 (list 'font-lock-fontified t))
5757 (compose-region (match-beginning 0) (match-end 1)
5758 (nth 6 ee) nil)
5759 (backward-char 1)
5760 (throw 'match t))))
5761 nil))))
5763 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5764 "Fontify string S like in Org-mode."
5765 (with-temp-buffer
5766 (insert s)
5767 (let ((org-odd-levels-only odd-levels))
5768 (org-mode)
5769 (font-lock-fontify-buffer)
5770 (buffer-string))))
5772 (defvar org-m nil)
5773 (defvar org-l nil)
5774 (defvar org-f nil)
5775 (defun org-get-level-face (n)
5776 "Get the right face for match N in font-lock matching of headlines."
5777 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5778 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5779 (if org-cycle-level-faces
5780 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5781 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5782 (cond
5783 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5784 ((eq n 2) org-f)
5785 (t (if org-level-color-stars-only nil org-f))))
5788 (defun org-get-todo-face (kwd)
5789 "Get the right face for a TODO keyword KWD.
5790 If KWD is a number, get the corresponding match group."
5791 (if (numberp kwd) (setq kwd (match-string kwd)))
5792 (or (org-face-from-face-or-color
5793 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5794 (and (member kwd org-done-keywords) 'org-done)
5795 'org-todo))
5797 (defun org-face-from-face-or-color (context inherit face-or-color)
5798 "Create a face list that inherits INHERIT, but sets the foreground color.
5799 When FACE-OR-COLOR is not a string, just return it."
5800 (if (stringp face-or-color)
5801 (list :inherit inherit
5802 (cdr (assoc context org-faces-easy-properties))
5803 face-or-color)
5804 face-or-color))
5806 (defun org-font-lock-add-tag-faces (limit)
5807 "Add the special tag faces."
5808 (when (and org-tag-faces org-tags-special-faces-re)
5809 (while (re-search-forward org-tags-special-faces-re limit t)
5810 (add-text-properties (match-beginning 1) (match-end 1)
5811 (list 'face (org-get-tag-face 1)
5812 'font-lock-fontified t))
5813 (backward-char 1))))
5815 (defun org-font-lock-add-priority-faces (limit)
5816 "Add the special priority faces."
5817 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5818 (add-text-properties
5819 (match-beginning 0) (match-end 0)
5820 (list 'face (or (org-face-from-face-or-color
5821 'priority 'org-special-keyword
5822 (cdr (assoc (char-after (match-beginning 1))
5823 org-priority-faces)))
5824 'org-special-keyword)
5825 'font-lock-fontified t))))
5827 (defun org-get-tag-face (kwd)
5828 "Get the right face for a TODO keyword KWD.
5829 If KWD is a number, get the corresponding match group."
5830 (if (numberp kwd) (setq kwd (match-string kwd)))
5831 (or (org-face-from-face-or-color
5832 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5833 'org-tag))
5835 (defun org-unfontify-region (beg end &optional maybe_loudly)
5836 "Remove fontification and activation overlays from links."
5837 (font-lock-default-unfontify-region beg end)
5838 (let* ((buffer-undo-list t)
5839 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5840 (inhibit-modification-hooks t)
5841 deactivate-mark buffer-file-name buffer-file-truename)
5842 (org-decompose-region beg end)
5843 (remove-text-properties beg end
5844 '(mouse-face t keymap t org-linked-text t
5845 invisible t intangible t
5846 org-no-flyspell t org-emphasis t))
5847 (org-remove-font-lock-display-properties beg end)))
5849 (defconst org-script-display '(((raise -0.3) (height 0.7))
5850 ((raise 0.3) (height 0.7))
5851 ((raise -0.5))
5852 ((raise 0.5)))
5853 "Display properties for showing superscripts and subscripts.")
5855 (defun org-remove-font-lock-display-properties (beg end)
5856 "Remove specific display properties that have been added by font lock.
5857 The will remove the raise properties that are used to show superscripts
5858 and subscripts."
5859 (let (next prop)
5860 (while (< beg end)
5861 (setq next (next-single-property-change beg 'display nil end)
5862 prop (get-text-property beg 'display))
5863 (if (member prop org-script-display)
5864 (put-text-property beg next 'display nil))
5865 (setq beg next))))
5867 (defun org-raise-scripts (limit)
5868 "Add raise properties to sub/superscripts."
5869 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
5870 (if (re-search-forward
5871 (if (eq org-use-sub-superscripts t)
5872 org-match-substring-regexp
5873 org-match-substring-with-braces-regexp)
5874 limit t)
5875 (let* ((pos (point)) table-p comment-p
5876 (mpos (match-beginning 3))
5877 (emph-p (get-text-property mpos 'org-emphasis))
5878 (link-p (get-text-property mpos 'mouse-face))
5879 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
5880 (goto-char (point-at-bol))
5881 (setq table-p (org-looking-at-p org-table-dataline-regexp)
5882 comment-p (org-looking-at-p "[ \t]*#"))
5883 (goto-char pos)
5884 ;; FIXME: Should we go back one character here, for a_b^c
5885 ;; (goto-char (1- pos)) ;????????????????????
5886 (if (or comment-p emph-p link-p keyw-p)
5888 (put-text-property (match-beginning 3) (match-end 0)
5889 'display
5890 (if (equal (char-after (match-beginning 2)) ?^)
5891 (nth (if table-p 3 1) org-script-display)
5892 (nth (if table-p 2 0) org-script-display)))
5893 (add-text-properties (match-beginning 2) (match-end 2)
5894 (list 'invisible t
5895 'org-dwidth t 'org-dwidth-n 1))
5896 (if (and (eq (char-after (match-beginning 3)) ?{)
5897 (eq (char-before (match-end 3)) ?}))
5898 (progn
5899 (add-text-properties
5900 (match-beginning 3) (1+ (match-beginning 3))
5901 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
5902 (add-text-properties
5903 (1- (match-end 3)) (match-end 3)
5904 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
5905 t)))))
5907 ;;;; Visibility cycling, including org-goto and indirect buffer
5909 ;;; Cycling
5911 (defvar org-cycle-global-status nil)
5912 (make-variable-buffer-local 'org-cycle-global-status)
5913 (defvar org-cycle-subtree-status nil)
5914 (make-variable-buffer-local 'org-cycle-subtree-status)
5916 ;;;###autoload
5918 (defvar org-inlinetask-min-level)
5920 (defun org-cycle (&optional arg)
5921 "TAB-action and visibility cycling for Org-mode.
5923 This is the command invoked in Org-mode by the TAB key. Its main purpose
5924 is outline visibility cycling, but it also invokes other actions
5925 in special contexts.
5927 - When this function is called with a prefix argument, rotate the entire
5928 buffer through 3 states (global cycling)
5929 1. OVERVIEW: Show only top-level headlines.
5930 2. CONTENTS: Show all headlines of all levels, but no body text.
5931 3. SHOW ALL: Show everything.
5932 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5933 determined by the variable `org-startup-folded', and by any VISIBILITY
5934 properties in the buffer.
5935 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5936 including any drawers.
5938 - When inside a table, re-align the table and move to the next field.
5940 - When point is at the beginning of a headline, rotate the subtree started
5941 by this line through 3 different states (local cycling)
5942 1. FOLDED: Only the main headline is shown.
5943 2. CHILDREN: The main headline and the direct children are shown.
5944 From this state, you can move to one of the children
5945 and zoom in further.
5946 3. SUBTREE: Show the entire subtree, including body text.
5947 If there is no subtree, switch directly from CHILDREN to FOLDED.
5949 - When point is at the beginning of an empty headline and the variable
5950 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5951 of the headline by demoting and promoting it to likely levels. This
5952 speeds up creation document structure by pressing TAB once or several
5953 times right after creating a new headline.
5955 - When there is a numeric prefix, go up to a heading with level ARG, do
5956 a `show-subtree' and return to the previous cursor position. If ARG
5957 is negative, go up that many levels.
5959 - When point is not at the beginning of a headline, execute the global
5960 binding for TAB, which is re-indenting the line. See the option
5961 `org-cycle-emulate-tab' for details.
5963 - Special case: if point is at the beginning of the buffer and there is
5964 no headline in line 1, this function will act as if called with prefix arg
5965 (C-u TAB, same as S-TAB) also when called without prefix arg.
5966 But only if also the variable `org-cycle-global-at-bob' is t."
5967 (interactive "P")
5968 (org-load-modules-maybe)
5969 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5970 (and org-cycle-level-after-item/entry-creation
5971 (or (org-cycle-level)
5972 (org-cycle-item-indentation))))
5973 (let* ((limit-level
5974 (or org-cycle-max-level
5975 (and (boundp 'org-inlinetask-min-level)
5976 org-inlinetask-min-level
5977 (1- org-inlinetask-min-level))))
5978 (nstars (and limit-level
5979 (if org-odd-levels-only
5980 (and limit-level (1- (* limit-level 2)))
5981 limit-level)))
5982 (org-outline-regexp
5983 (if (not (org-mode-p))
5984 outline-regexp
5985 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
5986 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
5987 (not (looking-at org-outline-regexp))))
5988 (org-cycle-hook
5989 (if bob-special
5990 (delq 'org-optimize-window-after-visibility-change
5991 (copy-sequence org-cycle-hook))
5992 org-cycle-hook))
5993 (pos (point)))
5995 (if (or bob-special (equal arg '(4)))
5996 ;; special case: use global cycling
5997 (setq arg t))
5999 (cond
6001 ((equal arg '(16))
6002 (setq last-command 'dummy)
6003 (org-set-startup-visibility)
6004 (message "Startup visibility, plus VISIBILITY properties"))
6006 ((equal arg '(64))
6007 (show-all)
6008 (message "Entire buffer visible, including drawers"))
6010 ;; Table: enter it or move to the next field.
6011 ((org-at-table-p 'any)
6012 (if (org-at-table.el-p)
6013 (message "Use C-c ' to edit table.el tables")
6014 (if arg (org-table-edit-field t)
6015 (org-table-justify-field-maybe)
6016 (call-interactively 'org-table-next-field))))
6018 ((run-hook-with-args-until-success
6019 'org-tab-after-check-for-table-hook))
6021 ;; Global cycling: delegate to `org-cycle-internal-global'.
6022 ((eq arg t) (org-cycle-internal-global))
6024 ;; Drawers: delegate to `org-flag-drawer'.
6025 ((and org-drawers org-drawer-regexp
6026 (save-excursion
6027 (beginning-of-line 1)
6028 (looking-at org-drawer-regexp)))
6029 (org-flag-drawer ; toggle block visibility
6030 (not (get-char-property (match-end 0) 'invisible))))
6032 ;; Show-subtree, ARG levels up from here.
6033 ((integerp arg)
6034 (save-excursion
6035 (org-back-to-heading)
6036 (outline-up-heading (if (< arg 0) (- arg)
6037 (- (funcall outline-level) arg)))
6038 (org-show-subtree)))
6040 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6041 ((and (featurep 'org-inlinetask)
6042 (org-inlinetask-at-task-p)
6043 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6044 (org-inlinetask-toggle-visibility))
6046 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6047 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6048 (save-excursion (beginning-of-line 1)
6049 (looking-at org-outline-regexp)))
6050 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6051 (org-cycle-internal-local))
6053 ;; From there: TAB emulation and template completion.
6054 (buffer-read-only (org-back-to-heading))
6056 ((run-hook-with-args-until-success
6057 'org-tab-after-check-for-cycling-hook))
6059 ((org-try-structure-completion))
6061 ((org-try-cdlatex-tab))
6063 ((run-hook-with-args-until-success
6064 'org-tab-before-tab-emulation-hook))
6066 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6067 (or (not (bolp))
6068 (not (looking-at org-outline-regexp))))
6069 (call-interactively (global-key-binding "\t")))
6071 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6072 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6073 (or (and (eq org-cycle-emulate-tab 'white)
6074 (= (match-end 0) (point-at-eol)))
6075 (and (eq org-cycle-emulate-tab 'whitestart)
6076 (>= (match-end 0) pos))))
6078 (eq org-cycle-emulate-tab t))
6079 (call-interactively (global-key-binding "\t")))
6081 (t (save-excursion
6082 (org-back-to-heading)
6083 (org-cycle)))))))
6085 (defun org-cycle-internal-global ()
6086 "Do the global cycling action."
6087 (cond
6088 ((and (eq last-command this-command)
6089 (eq org-cycle-global-status 'overview))
6090 ;; We just created the overview - now do table of contents
6091 ;; This can be slow in very large buffers, so indicate action
6092 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6093 (message "CONTENTS...")
6094 (org-content)
6095 (message "CONTENTS...done")
6096 (setq org-cycle-global-status 'contents)
6097 (run-hook-with-args 'org-cycle-hook 'contents))
6099 ((and (eq last-command this-command)
6100 (eq org-cycle-global-status 'contents))
6101 ;; We just showed the table of contents - now show everything
6102 (run-hook-with-args 'org-pre-cycle-hook 'all)
6103 (show-all)
6104 (message "SHOW ALL")
6105 (setq org-cycle-global-status 'all)
6106 (run-hook-with-args 'org-cycle-hook 'all))
6109 ;; Default action: go to overview
6110 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6111 (org-overview)
6112 (message "OVERVIEW")
6113 (setq org-cycle-global-status 'overview)
6114 (run-hook-with-args 'org-cycle-hook 'overview))))
6116 (defun org-cycle-internal-local ()
6117 "Do the local cycling action."
6118 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6119 ;; First, determine end of headline (EOH), end of subtree or item
6120 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6121 (save-excursion
6122 (if (org-at-item-p)
6123 (progn
6124 (beginning-of-line)
6125 (setq struct (org-list-struct))
6126 (setq eoh (point-at-eol))
6127 (setq eos (org-list-get-item-end-before-blank (point) struct))
6128 (setq has-children (org-list-has-child-p (point) struct)))
6129 (org-back-to-heading)
6130 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6131 (setq eos (save-excursion
6132 (org-end-of-subtree t)
6133 (unless (eobp)
6134 (skip-chars-forward " \t\n"))
6135 (if (eobp) (point) (1- (point)))))
6136 (setq has-children
6137 (or (save-excursion
6138 (let ((level (funcall outline-level)))
6139 (outline-next-heading)
6140 (and (org-at-heading-p t)
6141 (> (funcall outline-level) level))))
6142 (save-excursion
6143 (org-list-search-forward (org-item-beginning-re) eos t)))))
6144 ;; Determine end invisible part of buffer (EOL)
6145 (beginning-of-line 2)
6146 ;; XEmacs doesn't have `next-single-char-property-change'
6147 (if (featurep 'xemacs)
6148 (while (and (not (eobp)) ;; this is like `next-line'
6149 (get-char-property (1- (point)) 'invisible))
6150 (beginning-of-line 2))
6151 (while (and (not (eobp)) ;; this is like `next-line'
6152 (get-char-property (1- (point)) 'invisible))
6153 (goto-char (next-single-char-property-change (point) 'invisible))
6154 (and (eolp) (beginning-of-line 2))))
6155 (setq eol (point)))
6156 ;; Find out what to do next and set `this-command'
6157 (cond
6158 ((= eos eoh)
6159 ;; Nothing is hidden behind this heading
6160 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6161 (message "EMPTY ENTRY")
6162 (setq org-cycle-subtree-status nil)
6163 (save-excursion
6164 (goto-char eos)
6165 (outline-next-heading)
6166 (if (outline-invisible-p) (org-flag-heading nil))))
6167 ((and (or (>= eol eos)
6168 (not (string-match "\\S-" (buffer-substring eol eos))))
6169 (or has-children
6170 (not (setq children-skipped
6171 org-cycle-skip-children-state-if-no-children))))
6172 ;; Entire subtree is hidden in one line: children view
6173 (run-hook-with-args 'org-pre-cycle-hook 'children)
6174 (if (org-at-item-p)
6175 (org-list-set-item-visibility (point-at-bol) struct 'children)
6176 (org-show-entry)
6177 (show-children)
6178 ;; Fold every list in subtree to top-level items.
6179 (when (eq org-cycle-include-plain-lists 'integrate)
6180 (save-excursion
6181 (org-back-to-heading)
6182 (while (org-list-search-forward (org-item-beginning-re) eos t)
6183 (beginning-of-line 1)
6184 (let* ((struct (org-list-struct))
6185 (prevs (org-list-prevs-alist struct))
6186 (end (org-list-get-bottom-point struct)))
6187 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6188 (org-list-get-all-items (point) struct prevs))
6189 (goto-char end))))))
6190 (message "CHILDREN")
6191 (save-excursion
6192 (goto-char eos)
6193 (outline-next-heading)
6194 (if (outline-invisible-p) (org-flag-heading nil)))
6195 (setq org-cycle-subtree-status 'children)
6196 (run-hook-with-args 'org-cycle-hook 'children))
6197 ((or children-skipped
6198 (and (eq last-command this-command)
6199 (eq org-cycle-subtree-status 'children)))
6200 ;; We just showed the children, or no children are there,
6201 ;; now show everything.
6202 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6203 (outline-flag-region eoh eos nil)
6204 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6205 (setq org-cycle-subtree-status 'subtree)
6206 (run-hook-with-args 'org-cycle-hook 'subtree))
6208 ;; Default action: hide the subtree.
6209 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6210 (outline-flag-region eoh eos t)
6211 (message "FOLDED")
6212 (setq org-cycle-subtree-status 'folded)
6213 (run-hook-with-args 'org-cycle-hook 'folded)))))
6215 ;;;###autoload
6216 (defun org-global-cycle (&optional arg)
6217 "Cycle the global visibility. For details see `org-cycle'.
6218 With \\[universal-argument] prefix arg, switch to startup visibility.
6219 With a numeric prefix, show all headlines up to that level."
6220 (interactive "P")
6221 (let ((org-cycle-include-plain-lists
6222 (if (org-mode-p) org-cycle-include-plain-lists nil)))
6223 (cond
6224 ((integerp arg)
6225 (show-all)
6226 (hide-sublevels arg)
6227 (setq org-cycle-global-status 'contents))
6228 ((equal arg '(4))
6229 (org-set-startup-visibility)
6230 (message "Startup visibility, plus VISIBILITY properties."))
6232 (org-cycle '(4))))))
6234 (defun org-set-startup-visibility ()
6235 "Set the visibility required by startup options and properties."
6236 (cond
6237 ((eq org-startup-folded t)
6238 (org-cycle '(4)))
6239 ((eq org-startup-folded 'content)
6240 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6241 (org-cycle '(4)) (org-cycle '(4)))))
6242 (unless (eq org-startup-folded 'showeverything)
6243 (if org-hide-block-startup (org-hide-block-all))
6244 (org-set-visibility-according-to-property 'no-cleanup)
6245 (org-cycle-hide-archived-subtrees 'all)
6246 (org-cycle-hide-drawers 'all)
6247 (org-cycle-show-empty-lines t)))
6249 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6250 "Switch subtree visibilities according to :VISIBILITY: property."
6251 (interactive)
6252 (let (org-show-entry-below state)
6253 (save-excursion
6254 (goto-char (point-min))
6255 (while (re-search-forward
6256 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6257 nil t)
6258 (setq state (match-string 1))
6259 (save-excursion
6260 (org-back-to-heading t)
6261 (hide-subtree)
6262 (org-reveal)
6263 (cond
6264 ((equal state '("fold" "folded"))
6265 (hide-subtree))
6266 ((equal state "children")
6267 (org-show-hidden-entry)
6268 (show-children))
6269 ((equal state "content")
6270 (save-excursion
6271 (save-restriction
6272 (org-narrow-to-subtree)
6273 (org-content))))
6274 ((member state '("all" "showall"))
6275 (show-subtree)))))
6276 (unless no-cleanup
6277 (org-cycle-hide-archived-subtrees 'all)
6278 (org-cycle-hide-drawers 'all)
6279 (org-cycle-show-empty-lines 'all)))))
6281 ;; This function uses outline-regexp instead of the more fundamental
6282 ;; org-outline-regexp so that org-cycle-global works outside of Org
6283 ;; buffers, where outline-regexp is needed.
6284 (defun org-overview ()
6285 "Switch to overview mode, showing only top-level headlines.
6286 Really, this shows all headlines with level equal or greater than the level
6287 of the first headline in the buffer. This is important, because if the
6288 first headline is not level one, then (hide-sublevels 1) gives confusing
6289 results."
6290 (interactive)
6291 (let ((level (save-excursion
6292 (goto-char (point-min))
6293 (if (re-search-forward (concat "^" outline-regexp) nil t)
6294 (progn
6295 (goto-char (match-beginning 0))
6296 (funcall outline-level))))))
6297 (and level (hide-sublevels level))))
6299 (defun org-content (&optional arg)
6300 "Show all headlines in the buffer, like a table of contents.
6301 With numerical argument N, show content up to level N."
6302 (interactive "P")
6303 (save-excursion
6304 ;; Visit all headings and show their offspring
6305 (and (integerp arg) (org-overview))
6306 (goto-char (point-max))
6307 (catch 'exit
6308 (while (and (progn (condition-case nil
6309 (outline-previous-visible-heading 1)
6310 (error (goto-char (point-min))))
6312 (looking-at org-outline-regexp))
6313 (if (integerp arg)
6314 (show-children (1- arg))
6315 (show-branches))
6316 (if (bobp) (throw 'exit nil))))))
6319 (defun org-optimize-window-after-visibility-change (state)
6320 "Adjust the window after a change in outline visibility.
6321 This function is the default value of the hook `org-cycle-hook'."
6322 (when (get-buffer-window (current-buffer))
6323 (cond
6324 ((eq state 'content) nil)
6325 ((eq state 'all) nil)
6326 ((eq state 'folded) nil)
6327 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6328 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6330 (defun org-remove-empty-overlays-at (pos)
6331 "Remove outline overlays that do not contain non-white stuff."
6332 (mapc
6333 (lambda (o)
6334 (and (eq 'outline (overlay-get o 'invisible))
6335 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6336 (overlay-end o))))
6337 (delete-overlay o)))
6338 (overlays-at pos)))
6340 (defun org-clean-visibility-after-subtree-move ()
6341 "Fix visibility issues after moving a subtree."
6342 ;; First, find a reasonable region to look at:
6343 ;; Start two siblings above, end three below
6344 (let* ((beg (save-excursion
6345 (and (org-get-last-sibling)
6346 (org-get-last-sibling))
6347 (point)))
6348 (end (save-excursion
6349 (and (org-get-next-sibling)
6350 (org-get-next-sibling)
6351 (org-get-next-sibling))
6352 (if (org-at-heading-p)
6353 (point-at-eol)
6354 (point))))
6355 (level (looking-at "\\*+"))
6356 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6357 (save-excursion
6358 (save-restriction
6359 (narrow-to-region beg end)
6360 (when re
6361 ;; Properly fold already folded siblings
6362 (goto-char (point-min))
6363 (while (re-search-forward re nil t)
6364 (if (and (not (outline-invisible-p))
6365 (save-excursion
6366 (goto-char (point-at-eol)) (outline-invisible-p)))
6367 (hide-entry))))
6368 (org-cycle-show-empty-lines 'overview)
6369 (org-cycle-hide-drawers 'overview)))))
6371 (defun org-cycle-show-empty-lines (state)
6372 "Show empty lines above all visible headlines.
6373 The region to be covered depends on STATE when called through
6374 `org-cycle-hook'. Lisp program can use t for STATE to get the
6375 entire buffer covered. Note that an empty line is only shown if there
6376 are at least `org-cycle-separator-lines' empty lines before the headline."
6377 (when (not (= org-cycle-separator-lines 0))
6378 (save-excursion
6379 (let* ((n (abs org-cycle-separator-lines))
6380 (re (cond
6381 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6382 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6383 (t (let ((ns (number-to-string (- n 2))))
6384 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6385 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6386 beg end b e)
6387 (cond
6388 ((memq state '(overview contents t))
6389 (setq beg (point-min) end (point-max)))
6390 ((memq state '(children folded))
6391 (setq beg (point) end (progn (org-end-of-subtree t t)
6392 (beginning-of-line 2)
6393 (point)))))
6394 (when beg
6395 (goto-char beg)
6396 (while (re-search-forward re end t)
6397 (unless (get-char-property (match-end 1) 'invisible)
6398 (setq e (match-end 1))
6399 (if (< org-cycle-separator-lines 0)
6400 (setq b (save-excursion
6401 (goto-char (match-beginning 0))
6402 (org-back-over-empty-lines)
6403 (if (save-excursion
6404 (goto-char (max (point-min) (1- (point))))
6405 (org-on-heading-p))
6406 (1- (point))
6407 (point))))
6408 (setq b (match-beginning 1)))
6409 (outline-flag-region b e nil)))))))
6410 ;; Never hide empty lines at the end of the file.
6411 (save-excursion
6412 (goto-char (point-max))
6413 (outline-previous-heading)
6414 (outline-end-of-heading)
6415 (if (and (looking-at "[ \t\n]+")
6416 (= (match-end 0) (point-max)))
6417 (outline-flag-region (point) (match-end 0) nil))))
6419 (defun org-show-empty-lines-in-parent ()
6420 "Move to the parent and re-show empty lines before visible headlines."
6421 (save-excursion
6422 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6423 (org-cycle-show-empty-lines context))))
6425 (defun org-files-list ()
6426 "Return `org-agenda-files' list, plus all open org-mode files.
6427 This is useful for operations that need to scan all of a user's
6428 open and agenda-wise Org files."
6429 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6430 (dolist (buf (buffer-list))
6431 (with-current-buffer buf
6432 (if (and (org-mode-p) (buffer-file-name))
6433 (let ((file (expand-file-name (buffer-file-name))))
6434 (unless (member file files)
6435 (push file files))))))
6436 files))
6438 (defsubst org-entry-beginning-position ()
6439 "Return the beginning position of the current entry."
6440 (save-excursion (outline-back-to-heading t) (point)))
6442 (defsubst org-entry-end-position ()
6443 "Return the end position of the current entry."
6444 (save-excursion (outline-next-heading) (point)))
6446 (defun org-cycle-hide-drawers (state)
6447 "Re-hide all drawers after a visibility state change."
6448 (when (and (org-mode-p)
6449 (not (memq state '(overview folded contents))))
6450 (save-excursion
6451 (let* ((globalp (memq state '(contents all)))
6452 (beg (if globalp (point-min) (point)))
6453 (end (if globalp (point-max)
6454 (if (eq state 'children)
6455 (save-excursion (outline-next-heading) (point))
6456 (org-end-of-subtree t)))))
6457 (goto-char beg)
6458 (while (re-search-forward org-drawer-regexp end t)
6459 (org-flag-drawer t))))))
6461 (defun org-flag-drawer (flag)
6462 (save-excursion
6463 (beginning-of-line 1)
6464 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6465 (let ((b (match-end 0)))
6466 (if (re-search-forward
6467 "^[ \t]*:END:"
6468 (save-excursion (outline-next-heading) (point)) t)
6469 (outline-flag-region b (point-at-eol) flag)
6470 (error ":END: line missing at position %s" b))))))
6472 (defun org-subtree-end-visible-p ()
6473 "Is the end of the current subtree visible?"
6474 (pos-visible-in-window-p
6475 (save-excursion (org-end-of-subtree t) (point))))
6477 (defun org-first-headline-recenter (&optional N)
6478 "Move cursor to the first headline and recenter the headline.
6479 Optional argument N means put the headline into the Nth line of the window."
6480 (goto-char (point-min))
6481 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6482 (beginning-of-line)
6483 (recenter (prefix-numeric-value N))))
6485 ;;; Saving and restoring visibility
6487 (defun org-outline-overlay-data (&optional use-markers)
6488 "Return a list of the locations of all outline overlays.
6489 These are overlays with the `invisible' property value `outline'.
6490 The return value is a list of cons cells, with start and stop
6491 positions for each overlay.
6492 If USE-MARKERS is set, return the positions as markers."
6493 (let (beg end)
6494 (save-excursion
6495 (save-restriction
6496 (widen)
6497 (delq nil
6498 (mapcar (lambda (o)
6499 (when (eq (overlay-get o 'invisible) 'outline)
6500 (setq beg (overlay-start o)
6501 end (overlay-end o))
6502 (and beg end (> end beg)
6503 (if use-markers
6504 (cons (move-marker (make-marker) beg)
6505 (move-marker (make-marker) end))
6506 (cons beg end)))))
6507 (overlays-in (point-min) (point-max))))))))
6509 (defun org-set-outline-overlay-data (data)
6510 "Create visibility overlays for all positions in DATA.
6511 DATA should have been made by `org-outline-overlay-data'."
6512 (let (o)
6513 (save-excursion
6514 (save-restriction
6515 (widen)
6516 (show-all)
6517 (mapc (lambda (c)
6518 (setq o (make-overlay (car c) (cdr c)))
6519 (overlay-put o 'invisible 'outline))
6520 data)))))
6522 ;;; Folding of blocks
6524 (defconst org-block-regexp
6525 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
6526 "Regular expression for hiding blocks.")
6528 (defvar org-hide-block-overlays nil
6529 "Overlays hiding blocks.")
6530 (make-variable-buffer-local 'org-hide-block-overlays)
6532 (defun org-block-map (function &optional start end)
6533 "Call FUNCTION at the head of all source blocks in the current buffer.
6534 Optional arguments START and END can be used to limit the range."
6535 (let ((start (or start (point-min)))
6536 (end (or end (point-max))))
6537 (save-excursion
6538 (goto-char start)
6539 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6540 (save-excursion
6541 (save-match-data
6542 (goto-char (match-beginning 0))
6543 (funcall function)))))))
6545 (defun org-hide-block-toggle-all ()
6546 "Toggle the visibility of all blocks in the current buffer."
6547 (org-block-map #'org-hide-block-toggle))
6549 (defun org-hide-block-all ()
6550 "Fold all blocks in the current buffer."
6551 (interactive)
6552 (org-show-block-all)
6553 (org-block-map #'org-hide-block-toggle-maybe))
6555 (defun org-show-block-all ()
6556 "Unfold all blocks in the current buffer."
6557 (interactive)
6558 (mapc 'delete-overlay org-hide-block-overlays)
6559 (setq org-hide-block-overlays nil))
6561 (defun org-hide-block-toggle-maybe ()
6562 "Toggle visibility of block at point."
6563 (interactive)
6564 (let ((case-fold-search t))
6565 (if (save-excursion
6566 (beginning-of-line 1)
6567 (looking-at org-block-regexp))
6568 (progn (org-hide-block-toggle)
6569 t) ;; to signal that we took action
6570 nil))) ;; to signal that we did not
6572 (defun org-hide-block-toggle (&optional force)
6573 "Toggle the visibility of the current block."
6574 (interactive)
6575 (save-excursion
6576 (beginning-of-line)
6577 (if (re-search-forward org-block-regexp nil t)
6578 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6579 (end (match-end 0)) ;; end of entire body
6581 (if (memq t (mapcar (lambda (overlay)
6582 (eq (overlay-get overlay 'invisible)
6583 'org-hide-block))
6584 (overlays-at start)))
6585 (if (or (not force) (eq force 'off))
6586 (mapc (lambda (ov)
6587 (when (member ov org-hide-block-overlays)
6588 (setq org-hide-block-overlays
6589 (delq ov org-hide-block-overlays)))
6590 (when (eq (overlay-get ov 'invisible)
6591 'org-hide-block)
6592 (delete-overlay ov)))
6593 (overlays-at start)))
6594 (setq ov (make-overlay start end))
6595 (overlay-put ov 'invisible 'org-hide-block)
6596 ;; make the block accessible to isearch
6597 (overlay-put
6598 ov 'isearch-open-invisible
6599 (lambda (ov)
6600 (when (member ov org-hide-block-overlays)
6601 (setq org-hide-block-overlays
6602 (delq ov org-hide-block-overlays)))
6603 (when (eq (overlay-get ov 'invisible)
6604 'org-hide-block)
6605 (delete-overlay ov))))
6606 (push ov org-hide-block-overlays)))
6607 (error "Not looking at a source block"))))
6609 ;; org-tab-after-check-for-cycling-hook
6610 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6611 ;; Remove overlays when changing major mode
6612 (add-hook 'org-mode-hook
6613 (lambda () (org-add-hook 'change-major-mode-hook
6614 'org-show-block-all 'append 'local)))
6616 ;;; Org-goto
6618 (defvar org-goto-window-configuration nil)
6619 (defvar org-goto-marker nil)
6620 (defvar org-goto-map
6621 (let ((map (make-sparse-keymap)))
6622 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6623 (while (setq cmd (pop cmds))
6624 (substitute-key-definition cmd cmd map global-map)))
6625 (suppress-keymap map)
6626 (org-defkey map "\C-m" 'org-goto-ret)
6627 (org-defkey map [(return)] 'org-goto-ret)
6628 (org-defkey map [(left)] 'org-goto-left)
6629 (org-defkey map [(right)] 'org-goto-right)
6630 (org-defkey map [(control ?g)] 'org-goto-quit)
6631 (org-defkey map "\C-i" 'org-cycle)
6632 (org-defkey map [(tab)] 'org-cycle)
6633 (org-defkey map [(down)] 'outline-next-visible-heading)
6634 (org-defkey map [(up)] 'outline-previous-visible-heading)
6635 (if org-goto-auto-isearch
6636 (if (fboundp 'define-key-after)
6637 (define-key-after map [t] 'org-goto-local-auto-isearch)
6638 nil)
6639 (org-defkey map "q" 'org-goto-quit)
6640 (org-defkey map "n" 'outline-next-visible-heading)
6641 (org-defkey map "p" 'outline-previous-visible-heading)
6642 (org-defkey map "f" 'outline-forward-same-level)
6643 (org-defkey map "b" 'outline-backward-same-level)
6644 (org-defkey map "u" 'outline-up-heading))
6645 (org-defkey map "/" 'org-occur)
6646 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6647 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6648 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6649 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6650 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6651 map))
6653 (defconst org-goto-help
6654 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6655 RET=jump to location [Q]uit and return to previous location
6656 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6658 (defvar org-goto-start-pos) ; dynamically scoped parameter
6660 ;; FIXME: Docstring does not mention both interfaces
6661 (defun org-goto (&optional alternative-interface)
6662 "Look up a different location in the current file, keeping current visibility.
6664 When you want look-up or go to a different location in a document, the
6665 fastest way is often to fold the entire buffer and then dive into the tree.
6666 This method has the disadvantage, that the previous location will be folded,
6667 which may not be what you want.
6669 This command works around this by showing a copy of the current buffer
6670 in an indirect buffer, in overview mode. You can dive into the tree in
6671 that copy, use org-occur and incremental search to find a location.
6672 When pressing RET or `Q', the command returns to the original buffer in
6673 which the visibility is still unchanged. After RET is will also jump to
6674 the location selected in the indirect buffer and expose the headline
6675 hierarchy above."
6676 (interactive "P")
6677 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6678 (org-refile-use-outline-path t)
6679 (org-refile-target-verify-function nil)
6680 (interface
6681 (if (not alternative-interface)
6682 org-goto-interface
6683 (if (eq org-goto-interface 'outline)
6684 'outline-path-completion
6685 'outline)))
6686 (org-goto-start-pos (point))
6687 (selected-point
6688 (if (eq interface 'outline)
6689 (car (org-get-location (current-buffer) org-goto-help))
6690 (let ((pa (org-refile-get-location "Goto")))
6691 (org-refile-check-position pa)
6692 (nth 3 pa)))))
6693 (if selected-point
6694 (progn
6695 (org-mark-ring-push org-goto-start-pos)
6696 (goto-char selected-point)
6697 (if (or (outline-invisible-p) (org-invisible-p2))
6698 (org-show-context 'org-goto)))
6699 (message "Quit"))))
6701 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6702 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6703 (defvar org-goto-local-auto-isearch-map) ; defined below
6705 (defun org-get-location (buf help)
6706 "Let the user select a location in the Org-mode buffer BUF.
6707 This function uses a recursive edit. It returns the selected position
6708 or nil."
6709 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6710 (isearch-hide-immediately nil)
6711 (isearch-search-fun-function
6712 (lambda () 'org-goto-local-search-headings))
6713 (org-goto-selected-point org-goto-exit-command)
6714 (pop-up-frames nil)
6715 (special-display-buffer-names nil)
6716 (special-display-regexps nil)
6717 (special-display-function nil))
6718 (save-excursion
6719 (save-window-excursion
6720 (delete-other-windows)
6721 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6722 (org-pop-to-buffer-same-window
6723 (condition-case nil
6724 (make-indirect-buffer (current-buffer) "*org-goto*")
6725 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6726 (with-output-to-temp-buffer "*Help*"
6727 (princ help))
6728 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6729 (setq buffer-read-only nil)
6730 (let ((org-startup-truncated t)
6731 (org-startup-folded nil)
6732 (org-startup-align-all-tables nil))
6733 (org-mode)
6734 (org-overview))
6735 (setq buffer-read-only t)
6736 (if (and (boundp 'org-goto-start-pos)
6737 (integer-or-marker-p org-goto-start-pos))
6738 (let ((org-show-hierarchy-above t)
6739 (org-show-siblings t)
6740 (org-show-following-heading t))
6741 (goto-char org-goto-start-pos)
6742 (and (outline-invisible-p) (org-show-context)))
6743 (goto-char (point-min)))
6744 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6745 (message "Select location and press RET")
6746 (use-local-map org-goto-map)
6747 (recursive-edit)
6749 (kill-buffer "*org-goto*")
6750 (cons org-goto-selected-point org-goto-exit-command)))
6752 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6753 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6754 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6755 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6757 (defun org-goto-local-search-headings (string bound noerror)
6758 "Search and make sure that any matches are in headlines."
6759 (catch 'return
6760 (while (if isearch-forward
6761 (search-forward string bound noerror)
6762 (search-backward string bound noerror))
6763 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6764 (and (member :headline context)
6765 (not (member :tags context))))
6766 (throw 'return (point))))))
6768 (defun org-goto-local-auto-isearch ()
6769 "Start isearch."
6770 (interactive)
6771 (goto-char (point-min))
6772 (let ((keys (this-command-keys)))
6773 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6774 (isearch-mode t)
6775 (isearch-process-search-char (string-to-char keys)))))
6777 (defun org-goto-ret (&optional arg)
6778 "Finish `org-goto' by going to the new location."
6779 (interactive "P")
6780 (setq org-goto-selected-point (point)
6781 org-goto-exit-command 'return)
6782 (throw 'exit nil))
6784 (defun org-goto-left ()
6785 "Finish `org-goto' by going to the new location."
6786 (interactive)
6787 (if (org-on-heading-p)
6788 (progn
6789 (beginning-of-line 1)
6790 (setq org-goto-selected-point (point)
6791 org-goto-exit-command 'left)
6792 (throw 'exit nil))
6793 (error "Not on a heading")))
6795 (defun org-goto-right ()
6796 "Finish `org-goto' by going to the new location."
6797 (interactive)
6798 (if (org-on-heading-p)
6799 (progn
6800 (setq org-goto-selected-point (point)
6801 org-goto-exit-command 'right)
6802 (throw 'exit nil))
6803 (error "Not on a heading")))
6805 (defun org-goto-quit ()
6806 "Finish `org-goto' without cursor motion."
6807 (interactive)
6808 (setq org-goto-selected-point nil)
6809 (setq org-goto-exit-command 'quit)
6810 (throw 'exit nil))
6812 ;;; Indirect buffer display of subtrees
6814 (defvar org-indirect-dedicated-frame nil
6815 "This is the frame being used for indirect tree display.")
6816 (defvar org-last-indirect-buffer nil)
6818 (defun org-tree-to-indirect-buffer (&optional arg)
6819 "Create indirect buffer and narrow it to current subtree.
6820 With numerical prefix ARG, go up to this level and then take that tree.
6821 If ARG is negative, go up that many levels.
6822 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6823 indirect buffer previously made with this command, to avoid proliferation of
6824 indirect buffers. However, when you call the command with a \
6825 \\[universal-argument] prefix, or
6826 when `org-indirect-buffer-display' is `new-frame', the last buffer
6827 is kept so that you can work with several indirect buffers at the same time.
6828 If `org-indirect-buffer-display' is `dedicated-frame', the \
6829 \\[universal-argument] prefix also
6830 requests that a new frame be made for the new buffer, so that the dedicated
6831 frame is not changed."
6832 (interactive "P")
6833 (let ((cbuf (current-buffer))
6834 (cwin (selected-window))
6835 (pos (point))
6836 beg end level heading ibuf)
6837 (save-excursion
6838 (org-back-to-heading t)
6839 (when (numberp arg)
6840 (setq level (org-outline-level))
6841 (if (< arg 0) (setq arg (+ level arg)))
6842 (while (> (setq level (org-outline-level)) arg)
6843 (outline-up-heading 1 t)))
6844 (setq beg (point)
6845 heading (org-get-heading))
6846 (org-end-of-subtree t t)
6847 (if (org-on-heading-p) (backward-char 1))
6848 (setq end (point)))
6849 (if (and (buffer-live-p org-last-indirect-buffer)
6850 (not (eq org-indirect-buffer-display 'new-frame))
6851 (not arg))
6852 (kill-buffer org-last-indirect-buffer))
6853 (setq ibuf (org-get-indirect-buffer cbuf)
6854 org-last-indirect-buffer ibuf)
6855 (cond
6856 ((or (eq org-indirect-buffer-display 'new-frame)
6857 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6858 (select-frame (make-frame))
6859 (delete-other-windows)
6860 (org-pop-to-buffer-same-window ibuf)
6861 (org-set-frame-title heading))
6862 ((eq org-indirect-buffer-display 'dedicated-frame)
6863 (raise-frame
6864 (select-frame (or (and org-indirect-dedicated-frame
6865 (frame-live-p org-indirect-dedicated-frame)
6866 org-indirect-dedicated-frame)
6867 (setq org-indirect-dedicated-frame (make-frame)))))
6868 (delete-other-windows)
6869 (org-pop-to-buffer-same-window ibuf)
6870 (org-set-frame-title (concat "Indirect: " heading)))
6871 ((eq org-indirect-buffer-display 'current-window)
6872 (org-pop-to-buffer-same-window ibuf))
6873 ((eq org-indirect-buffer-display 'other-window)
6874 (pop-to-buffer ibuf))
6875 (t (error "Invalid value")))
6876 (if (featurep 'xemacs)
6877 (save-excursion (org-mode) (turn-on-font-lock)))
6878 (narrow-to-region beg end)
6879 (show-all)
6880 (goto-char pos)
6881 (run-hook-with-args 'org-cycle-hook 'all)
6882 (and (window-live-p cwin) (select-window cwin))))
6884 (defun org-get-indirect-buffer (&optional buffer)
6885 (setq buffer (or buffer (current-buffer)))
6886 (let ((n 1) (base (buffer-name buffer)) bname)
6887 (while (buffer-live-p
6888 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6889 (setq n (1+ n)))
6890 (condition-case nil
6891 (make-indirect-buffer buffer bname 'clone)
6892 (error (make-indirect-buffer buffer bname)))))
6894 (defun org-set-frame-title (title)
6895 "Set the title of the current frame to the string TITLE."
6896 ;; FIXME: how to name a single frame in XEmacs???
6897 (unless (featurep 'xemacs)
6898 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6900 ;;;; Structure editing
6902 ;;; Inserting headlines
6904 (defun org-previous-line-empty-p ()
6905 (save-excursion
6906 (and (not (bobp))
6907 (or (beginning-of-line 0) t)
6908 (save-match-data
6909 (looking-at "[ \t]*$")))))
6911 (defun org-insert-heading (&optional force-heading invisible-ok)
6912 "Insert a new heading or item with same depth at point.
6913 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6914 If point is at the beginning of a headline, insert a sibling before the
6915 current headline. If point is not at the beginning, split the line,
6916 create the new headline with the text in the current line after point
6917 \(but see also the variable `org-M-RET-may-split-line').
6919 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6920 This is important for non-interactive uses of the command."
6921 (interactive "P")
6922 (if (or (= (buffer-size) 0)
6923 (and (not (save-excursion
6924 (and (ignore-errors (org-back-to-heading invisible-ok))
6925 (org-on-heading-p))))
6926 (or force-heading (not (org-in-item-p)))))
6927 (progn
6928 (insert "\n* ")
6929 (run-hooks 'org-insert-heading-hook))
6930 (when (or force-heading (not (org-insert-item)))
6931 (let* ((empty-line-p nil)
6932 (level nil)
6933 (on-heading (org-on-heading-p))
6934 (head (save-excursion
6935 (condition-case nil
6936 (progn
6937 (org-back-to-heading invisible-ok)
6938 (when (and (not on-heading)
6939 (featurep 'org-inlinetask)
6940 (integerp org-inlinetask-min-level)
6941 (>= (length (match-string 0))
6942 org-inlinetask-min-level))
6943 ;; Find a heading level before the inline task
6944 (while (and (setq level (org-up-heading-safe))
6945 (>= level org-inlinetask-min-level)))
6946 (if (org-on-heading-p)
6947 (org-back-to-heading invisible-ok)
6948 (error "This should not happen")))
6949 (setq empty-line-p (org-previous-line-empty-p))
6950 (match-string 0))
6951 (error "*"))))
6952 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6953 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6954 pos hide-previous previous-pos)
6955 (cond
6956 ((and (org-on-heading-p) (bolp)
6957 (or (bobp)
6958 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
6959 ;; insert before the current line
6960 (open-line (if blank 2 1)))
6961 ((and (bolp)
6962 (not org-insert-heading-respect-content)
6963 (or (bobp)
6964 (save-excursion
6965 (backward-char 1) (not (outline-invisible-p)))))
6966 ;; insert right here
6967 nil)
6969 ;; somewhere in the line
6970 (save-excursion
6971 (setq previous-pos (point-at-bol))
6972 (end-of-line)
6973 (setq hide-previous (outline-invisible-p)))
6974 (and org-insert-heading-respect-content (org-show-subtree))
6975 (let ((split
6976 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6977 (save-excursion
6978 (let ((p (point)))
6979 (goto-char (point-at-bol))
6980 (and (looking-at org-complex-heading-regexp)
6981 (> p (match-beginning 4)))))))
6982 tags pos)
6983 (cond
6984 (org-insert-heading-respect-content
6985 (org-end-of-subtree nil t)
6986 (when (featurep 'org-inlinetask)
6987 (while (and (not (eobp))
6988 (looking-at "\\(\\*+\\)[ \t]+")
6989 (>= (length (match-string 1))
6990 org-inlinetask-min-level))
6991 (org-end-of-subtree nil t)))
6992 (or (bolp) (newline))
6993 (or (org-previous-line-empty-p)
6994 (and blank (newline)))
6995 (open-line 1))
6996 ((org-on-heading-p)
6997 (when hide-previous
6998 (show-children)
6999 (org-show-entry))
7000 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7001 (setq tags (and (match-end 2) (match-string 2)))
7002 (and (match-end 1)
7003 (delete-region (match-beginning 1) (match-end 1)))
7004 (setq pos (point-at-bol))
7005 (or split (end-of-line 1))
7006 (delete-horizontal-space)
7007 (if (string-match "\\`\\*+\\'"
7008 (buffer-substring (point-at-bol) (point)))
7009 (insert " "))
7010 (newline (if blank 2 1))
7011 (when tags
7012 (save-excursion
7013 (goto-char pos)
7014 (end-of-line 1)
7015 (insert " " tags)
7016 (org-set-tags nil 'align))))
7018 (or split (end-of-line 1))
7019 (newline (if blank 2 1)))))))
7020 (insert head) (just-one-space)
7021 (setq pos (point))
7022 (end-of-line 1)
7023 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7024 (when (and org-insert-heading-respect-content hide-previous)
7025 (save-excursion
7026 (goto-char previous-pos)
7027 (hide-subtree)))
7028 (run-hooks 'org-insert-heading-hook)))))
7030 (defun org-get-heading (&optional no-tags no-todo)
7031 "Return the heading of the current entry, without the stars.
7032 When NO-TAGS is non-nil, don't include tags.
7033 When NO-TODO is non-nil, don't include TODO keywords."
7034 (save-excursion
7035 (org-back-to-heading t)
7036 (cond
7037 ((and no-tags no-todo)
7038 (looking-at org-complex-heading-regexp)
7039 (match-string 4))
7040 (no-tags
7041 (looking-at "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@#%]+:[ \t]*\\)?$")
7042 (match-string 1))
7043 (no-todo
7044 (looking-at (concat "\\*+[ \t]+" org-todo-regexp " +"
7045 "\\([^\n\r]*?[ \t]+:[[:alnum:]:_@#%]+:[ \t]*\\)?$"))
7046 (match-string 2))
7047 (t (looking-at "\\*+[ \t]+\\([^\r\n]*\\)")
7048 (match-string 1)))))
7050 (defun org-heading-components ()
7051 "Return the components of the current heading.
7052 This is a list with the following elements:
7053 - the level as an integer
7054 - the reduced level, different if `org-odd-levels-only' is set.
7055 - the TODO keyword, or nil
7056 - the priority character, like ?A, or nil if no priority is given
7057 - the headline text itself, or the tags string if no headline text
7058 - the tags string, or nil."
7059 (save-excursion
7060 (org-back-to-heading t)
7061 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7062 (list (length (match-string 1))
7063 (org-reduced-level (length (match-string 1)))
7064 (org-match-string-no-properties 2)
7065 (and (match-end 3) (aref (match-string 3) 2))
7066 (org-match-string-no-properties 4)
7067 (org-match-string-no-properties 5)))))
7069 (defun org-get-entry ()
7070 "Get the entry text, after heading, entire subtree."
7071 (save-excursion
7072 (org-back-to-heading t)
7073 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7075 (defun org-insert-heading-after-current ()
7076 "Insert a new heading with same level as current, after current subtree."
7077 (interactive)
7078 (org-back-to-heading)
7079 (org-insert-heading)
7080 (org-move-subtree-down)
7081 (end-of-line 1))
7083 (defun org-insert-heading-respect-content ()
7084 (interactive)
7085 (let ((org-insert-heading-respect-content t))
7086 (org-insert-heading t)))
7088 (defun org-insert-todo-heading-respect-content (&optional force-state)
7089 (interactive "P")
7090 (let ((org-insert-heading-respect-content t))
7091 (org-insert-todo-heading force-state t)))
7093 (defun org-insert-todo-heading (arg &optional force-heading)
7094 "Insert a new heading with the same level and TODO state as current heading.
7095 If the heading has no TODO state, or if the state is DONE, use the first
7096 state (TODO by default). Also with prefix arg, force first state."
7097 (interactive "P")
7098 (when (or force-heading (not (org-insert-item 'checkbox)))
7099 (org-insert-heading force-heading)
7100 (save-excursion
7101 (org-back-to-heading)
7102 (outline-previous-heading)
7103 (looking-at org-todo-line-regexp))
7104 (let*
7105 ((new-mark-x
7106 (if (or arg
7107 (not (match-beginning 2))
7108 (member (match-string 2) org-done-keywords))
7109 (car org-todo-keywords-1)
7110 (match-string 2)))
7111 (new-mark
7113 (run-hook-with-args-until-success
7114 'org-todo-get-default-hook new-mark-x nil)
7115 new-mark-x)))
7116 (beginning-of-line 1)
7117 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7118 (if org-treat-insert-todo-heading-as-state-change
7119 (org-todo new-mark)
7120 (insert new-mark " "))))
7121 (when org-provide-todo-statistics
7122 (org-update-parent-todo-statistics))))
7124 (defun org-insert-subheading (arg)
7125 "Insert a new subheading and demote it.
7126 Works for outline headings and for plain lists alike."
7127 (interactive "P")
7128 (org-insert-heading arg)
7129 (cond
7130 ((org-on-heading-p) (org-do-demote))
7131 ((org-at-item-p) (org-indent-item))))
7133 (defun org-insert-todo-subheading (arg)
7134 "Insert a new subheading with TODO keyword or checkbox and demote it.
7135 Works for outline headings and for plain lists alike."
7136 (interactive "P")
7137 (org-insert-todo-heading arg)
7138 (cond
7139 ((org-on-heading-p) (org-do-demote))
7140 ((org-at-item-p) (org-indent-item))))
7142 ;;; Promotion and Demotion
7144 (defvar org-after-demote-entry-hook nil
7145 "Hook run after an entry has been demoted.
7146 The cursor will be at the beginning of the entry.
7147 When a subtree is being demoted, the hook will be called for each node.")
7149 (defvar org-after-promote-entry-hook nil
7150 "Hook run after an entry has been promoted.
7151 The cursor will be at the beginning of the entry.
7152 When a subtree is being promoted, the hook will be called for each node.")
7154 (defun org-promote-subtree ()
7155 "Promote the entire subtree.
7156 See also `org-promote'."
7157 (interactive)
7158 (save-excursion
7159 (org-with-limited-levels (org-map-tree 'org-promote)))
7160 (org-fix-position-after-promote))
7162 (defun org-demote-subtree ()
7163 "Demote the entire subtree. See `org-demote'.
7164 See also `org-promote'."
7165 (interactive)
7166 (save-excursion
7167 (org-with-limited-levels (org-map-tree 'org-demote)))
7168 (org-fix-position-after-promote))
7171 (defun org-do-promote ()
7172 "Promote the current heading higher up the tree.
7173 If the region is active in `transient-mark-mode', promote all headings
7174 in the region."
7175 (interactive)
7176 (save-excursion
7177 (if (org-region-active-p)
7178 (org-map-region 'org-promote (region-beginning) (region-end))
7179 (org-promote)))
7180 (org-fix-position-after-promote))
7182 (defun org-do-demote ()
7183 "Demote the current heading lower down the tree.
7184 If the region is active in `transient-mark-mode', demote all headings
7185 in the region."
7186 (interactive)
7187 (save-excursion
7188 (if (org-region-active-p)
7189 (org-map-region 'org-demote (region-beginning) (region-end))
7190 (org-demote)))
7191 (org-fix-position-after-promote))
7193 (defun org-fix-position-after-promote ()
7194 "Make sure that after pro/demotion cursor position is right."
7195 (let ((pos (point)))
7196 (when (save-excursion
7197 (beginning-of-line 1)
7198 (looking-at org-todo-line-regexp)
7199 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7200 (cond ((eobp) (insert " "))
7201 ((eolp) (insert " "))
7202 ((equal (char-after) ?\ ) (forward-char 1))))))
7204 (defun org-current-level ()
7205 "Return the level of the current entry, or nil if before the first headline.
7206 The level is the number of stars at the beginning of the headline."
7207 (save-excursion
7208 (org-with-limited-levels
7209 (ignore-errors
7210 (org-back-to-heading t)
7211 (funcall outline-level)))))
7213 (defun org-get-previous-line-level ()
7214 "Return the outline depth of the last headline before the current line.
7215 Returns 0 for the first headline in the buffer, and nil if before the
7216 first headline."
7217 (let ((current-level (org-current-level))
7218 (prev-level (when (> (line-number-at-pos) 1)
7219 (save-excursion
7220 (beginning-of-line 0)
7221 (org-current-level)))))
7222 (cond ((null current-level) nil) ; Before first headline
7223 ((null prev-level) 0) ; At first headline
7224 (prev-level))))
7226 (defun org-reduced-level (l)
7227 "Compute the effective level of a heading.
7228 This takes into account the setting of `org-odd-levels-only'."
7229 (cond
7230 ((zerop l) 0)
7231 (org-odd-levels-only (1+ (floor (/ l 2))))
7232 (t l)))
7234 (defun org-level-increment ()
7235 "Return the number of stars that will be added or removed at a
7236 time to headlines when structure editing, based on the value of
7237 `org-odd-levels-only'."
7238 (if org-odd-levels-only 2 1))
7240 (defun org-get-valid-level (level &optional change)
7241 "Rectify a level change under the influence of `org-odd-levels-only'
7242 LEVEL is a current level, CHANGE is by how much the level should be
7243 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7244 even level numbers will become the next higher odd number."
7245 (if org-odd-levels-only
7246 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7247 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7248 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7249 (max 1 (+ level (or change 0)))))
7251 (if (boundp 'define-obsolete-function-alias)
7252 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7253 (define-obsolete-function-alias 'org-get-legal-level
7254 'org-get-valid-level)
7255 (define-obsolete-function-alias 'org-get-legal-level
7256 'org-get-valid-level "23.1")))
7258 (defun org-promote ()
7259 "Promote the current heading higher up the tree.
7260 If the region is active in `transient-mark-mode', promote all headings
7261 in the region."
7262 (org-back-to-heading t)
7263 (let* ((level (save-match-data (funcall outline-level)))
7264 (after-change-functions (remove 'flyspell-after-change-function
7265 after-change-functions))
7266 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7267 (diff (abs (- level (length up-head) -1))))
7268 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7269 (replace-match up-head nil t)
7270 ;; Fixup tag positioning
7271 (and org-auto-align-tags (org-set-tags nil t))
7272 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7273 (run-hooks 'org-after-promote-entry-hook)))
7275 (defun org-demote ()
7276 "Demote the current heading lower down the tree.
7277 If the region is active in `transient-mark-mode', demote all headings
7278 in the region."
7279 (org-back-to-heading t)
7280 (let* ((level (save-match-data (funcall outline-level)))
7281 (after-change-functions (remove 'flyspell-after-change-function
7282 after-change-functions))
7283 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7284 (diff (abs (- level (length down-head) -1))))
7285 (replace-match down-head nil t)
7286 ;; Fixup tag positioning
7287 (and org-auto-align-tags (org-set-tags nil t))
7288 (if org-adapt-indentation (org-fixup-indentation diff))
7289 (run-hooks 'org-after-demote-entry-hook)))
7291 (defun org-cycle-level ()
7292 "Cycle the level of an empty headline through possible states.
7293 This goes first to child, then to parent, level, then up the hierarchy.
7294 After top level, it switches back to sibling level."
7295 (interactive)
7296 (let ((org-adapt-indentation nil))
7297 (when (org-point-at-end-of-empty-headline)
7298 (setq this-command 'org-cycle-level) ; Only needed for caching
7299 (let ((cur-level (org-current-level))
7300 (prev-level (org-get-previous-line-level)))
7301 (cond
7302 ;; If first headline in file, promote to top-level.
7303 ((= prev-level 0)
7304 (loop repeat (/ (- cur-level 1) (org-level-increment))
7305 do (org-do-promote)))
7306 ;; If same level as prev, demote one.
7307 ((= prev-level cur-level)
7308 (org-do-demote))
7309 ;; If parent is top-level, promote to top level if not already.
7310 ((= prev-level 1)
7311 (loop repeat (/ (- cur-level 1) (org-level-increment))
7312 do (org-do-promote)))
7313 ;; If top-level, return to prev-level.
7314 ((= cur-level 1)
7315 (loop repeat (/ (- prev-level 1) (org-level-increment))
7316 do (org-do-demote)))
7317 ;; If less than prev-level, promote one.
7318 ((< cur-level prev-level)
7319 (org-do-promote))
7320 ;; If deeper than prev-level, promote until higher than
7321 ;; prev-level.
7322 ((> cur-level prev-level)
7323 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7324 do (org-do-promote))))
7325 t))))
7327 (defun org-map-tree (fun)
7328 "Call FUN for every heading underneath the current one."
7329 (org-back-to-heading)
7330 (let ((level (funcall outline-level)))
7331 (save-excursion
7332 (funcall fun)
7333 (while (and (progn
7334 (outline-next-heading)
7335 (> (funcall outline-level) level))
7336 (not (eobp)))
7337 (funcall fun)))))
7339 (defun org-map-region (fun beg end)
7340 "Call FUN for every heading between BEG and END."
7341 (let ((org-ignore-region t))
7342 (save-excursion
7343 (setq end (copy-marker end))
7344 (goto-char beg)
7345 (if (and (re-search-forward org-outline-regexp-bol nil t)
7346 (< (point) end))
7347 (funcall fun))
7348 (while (and (progn
7349 (outline-next-heading)
7350 (< (point) end))
7351 (not (eobp)))
7352 (funcall fun)))))
7354 (defvar org-property-end-re) ; silence byte-compiler
7355 (defun org-fixup-indentation (diff)
7356 "Change the indentation in the current entry by DIFF.
7357 However, if any line in the current entry has no indentation, or if it
7358 would end up with no indentation after the change, nothing at all is done."
7359 (save-excursion
7360 (let ((end (save-excursion (outline-next-heading)
7361 (point-marker)))
7362 (prohibit (if (> diff 0)
7363 "^\\S-"
7364 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7365 col)
7366 (unless (save-excursion (end-of-line 1)
7367 (re-search-forward prohibit end t))
7368 (while (and (< (point) end)
7369 (re-search-forward "^[ \t]+" end t))
7370 (goto-char (match-end 0))
7371 (setq col (current-column))
7372 (if (< diff 0) (replace-match ""))
7373 (org-indent-to-column (+ diff col))))
7374 (move-marker end nil))))
7376 (defun org-convert-to-odd-levels ()
7377 "Convert an org-mode file with all levels allowed to one with odd levels.
7378 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7379 level 5 etc."
7380 (interactive)
7381 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7382 (let ((outline-level 'org-outline-level)
7383 (org-odd-levels-only nil) n)
7384 (save-excursion
7385 (goto-char (point-min))
7386 (while (re-search-forward "^\\*\\*+ " nil t)
7387 (setq n (- (length (match-string 0)) 2))
7388 (while (>= (setq n (1- n)) 0)
7389 (org-demote))
7390 (end-of-line 1))))))
7392 (defun org-convert-to-oddeven-levels ()
7393 "Convert an org-mode file with only odd levels to one with odd/even levels.
7394 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7395 file contains a section with an even level, conversion would
7396 destroy the structure of the file. An error is signaled in this
7397 case."
7398 (interactive)
7399 (goto-char (point-min))
7400 ;; First check if there are no even levels
7401 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7402 (org-show-context t)
7403 (error "Not all levels are odd in this file. Conversion not possible"))
7404 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7405 (let ((outline-regexp org-outline-regexp)
7406 (outline-level 'org-outline-level)
7407 (org-odd-levels-only nil) n)
7408 (save-excursion
7409 (goto-char (point-min))
7410 (while (re-search-forward "^\\*\\*+ " nil t)
7411 (setq n (/ (1- (length (match-string 0))) 2))
7412 (while (>= (setq n (1- n)) 0)
7413 (org-promote))
7414 (end-of-line 1))))))
7416 (defun org-tr-level (n)
7417 "Make N odd if required."
7418 (if org-odd-levels-only (1+ (/ n 2)) n))
7420 ;;; Vertical tree motion, cutting and pasting of subtrees
7422 (defun org-move-subtree-up (&optional arg)
7423 "Move the current subtree up past ARG headlines of the same level."
7424 (interactive "p")
7425 (org-move-subtree-down (- (prefix-numeric-value arg))))
7427 (defun org-move-subtree-down (&optional arg)
7428 "Move the current subtree down past ARG headlines of the same level."
7429 (interactive "p")
7430 (setq arg (prefix-numeric-value arg))
7431 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7432 'org-get-last-sibling))
7433 (ins-point (make-marker))
7434 (cnt (abs arg))
7435 (col (current-column))
7436 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7437 ;; Select the tree
7438 (org-back-to-heading)
7439 (setq beg0 (point))
7440 (save-excursion
7441 (setq ne-beg (org-back-over-empty-lines))
7442 (setq beg (point)))
7443 (save-match-data
7444 (save-excursion (outline-end-of-heading)
7445 (setq folded (outline-invisible-p)))
7446 (outline-end-of-subtree))
7447 (outline-next-heading)
7448 (setq ne-end (org-back-over-empty-lines))
7449 (setq end (point))
7450 (goto-char beg0)
7451 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7452 ;; include less whitespace
7453 (save-excursion
7454 (goto-char beg)
7455 (forward-line (- ne-beg ne-end))
7456 (setq beg (point))))
7457 ;; Find insertion point, with error handling
7458 (while (> cnt 0)
7459 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7460 (progn (goto-char beg0)
7461 (error "Cannot move past superior level or buffer limit")))
7462 (setq cnt (1- cnt)))
7463 (if (> arg 0)
7464 ;; Moving forward - still need to move over subtree
7465 (progn (org-end-of-subtree t t)
7466 (save-excursion
7467 (org-back-over-empty-lines)
7468 (or (bolp) (newline)))))
7469 (setq ne-ins (org-back-over-empty-lines))
7470 (move-marker ins-point (point))
7471 (setq txt (buffer-substring beg end))
7472 (org-save-markers-in-region beg end)
7473 (delete-region beg end)
7474 (org-remove-empty-overlays-at beg)
7475 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7476 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7477 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7478 (let ((bbb (point)))
7479 (insert-before-markers txt)
7480 (org-reinstall-markers-in-region bbb)
7481 (move-marker ins-point bbb))
7482 (or (bolp) (insert "\n"))
7483 (setq ins-end (point))
7484 (goto-char ins-point)
7485 (org-skip-whitespace)
7486 (when (and (< arg 0)
7487 (org-first-sibling-p)
7488 (> ne-ins ne-beg))
7489 ;; Move whitespace back to beginning
7490 (save-excursion
7491 (goto-char ins-end)
7492 (let ((kill-whole-line t))
7493 (kill-line (- ne-ins ne-beg)) (point)))
7494 (insert (make-string (- ne-ins ne-beg) ?\n)))
7495 (move-marker ins-point nil)
7496 (if folded
7497 (hide-subtree)
7498 (org-show-entry)
7499 (show-children)
7500 (org-cycle-hide-drawers 'children))
7501 (org-clean-visibility-after-subtree-move)
7502 ;; move back to the initial column we were at
7503 (move-to-column col)))
7505 (defvar org-subtree-clip ""
7506 "Clipboard for cut and paste of subtrees.
7507 This is actually only a copy of the kill, because we use the normal kill
7508 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7510 (defvar org-subtree-clip-folded nil
7511 "Was the last copied subtree folded?
7512 This is used to fold the tree back after pasting.")
7514 (defun org-cut-subtree (&optional n)
7515 "Cut the current subtree into the clipboard.
7516 With prefix arg N, cut this many sequential subtrees.
7517 This is a short-hand for marking the subtree and then cutting it."
7518 (interactive "p")
7519 (org-copy-subtree n 'cut))
7521 (defun org-copy-subtree (&optional n cut force-store-markers)
7522 "Cut the current subtree into the clipboard.
7523 With prefix arg N, cut this many sequential subtrees.
7524 This is a short-hand for marking the subtree and then copying it.
7525 If CUT is non-nil, actually cut the subtree.
7526 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7527 of some markers in the region, even if CUT is non-nil. This is
7528 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7529 (interactive "p")
7530 (let (beg end folded (beg0 (point)))
7531 (if (org-called-interactively-p 'any)
7532 (org-back-to-heading nil) ; take what looks like a subtree
7533 (org-back-to-heading t)) ; take what is really there
7534 (org-back-over-empty-lines)
7535 (setq beg (point))
7536 (skip-chars-forward " \t\r\n")
7537 (save-match-data
7538 (save-excursion (outline-end-of-heading)
7539 (setq folded (outline-invisible-p)))
7540 (condition-case nil
7541 (org-forward-same-level (1- n) t)
7542 (error nil))
7543 (org-end-of-subtree t t))
7544 (org-back-over-empty-lines)
7545 (setq end (point))
7546 (goto-char beg0)
7547 (when (> end beg)
7548 (setq org-subtree-clip-folded folded)
7549 (when (or cut force-store-markers)
7550 (org-save-markers-in-region beg end))
7551 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7552 (setq org-subtree-clip (current-kill 0))
7553 (message "%s: Subtree(s) with %d characters"
7554 (if cut "Cut" "Copied")
7555 (length org-subtree-clip)))))
7557 (defun org-paste-subtree (&optional level tree for-yank)
7558 "Paste the clipboard as a subtree, with modification of headline level.
7559 The entire subtree is promoted or demoted in order to match a new headline
7560 level.
7562 If the cursor is at the beginning of a headline, the same level as
7563 that headline is used to paste the tree
7565 If not, the new level is derived from the *visible* headings
7566 before and after the insertion point, and taken to be the inferior headline
7567 level of the two. So if the previous visible heading is level 3 and the
7568 next is level 4 (or vice versa), level 4 will be used for insertion.
7569 This makes sure that the subtree remains an independent subtree and does
7570 not swallow low level entries.
7572 You can also force a different level, either by using a numeric prefix
7573 argument, or by inserting the heading marker by hand. For example, if the
7574 cursor is after \"*****\", then the tree will be shifted to level 5.
7576 If optional TREE is given, use this text instead of the kill ring.
7578 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7579 move back over whitespace before inserting, and move point to the end of
7580 the inserted text when done."
7581 (interactive "P")
7582 (setq tree (or tree (and kill-ring (current-kill 0))))
7583 (unless (org-kill-is-subtree-p tree)
7584 (error "%s"
7585 (substitute-command-keys
7586 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7587 (org-with-limited-levels
7588 (let* ((visp (not (outline-invisible-p)))
7589 (txt tree)
7590 (^re_ "\\(\\*+\\)[ \t]*")
7591 (old-level (if (string-match org-outline-regexp-bol txt)
7592 (- (match-end 0) (match-beginning 0) 1)
7593 -1))
7594 (force-level (cond (level (prefix-numeric-value level))
7595 ((and (looking-at "[ \t]*$")
7596 (string-match
7597 "^\\*+$" (buffer-substring
7598 (point-at-bol) (point))))
7599 (- (match-end 1) (match-beginning 1)))
7600 ((and (bolp)
7601 (looking-at org-outline-regexp))
7602 (- (match-end 0) (point) 1))
7603 (t nil)))
7604 (previous-level (save-excursion
7605 (condition-case nil
7606 (progn
7607 (outline-previous-visible-heading 1)
7608 (if (looking-at ^re_)
7609 (- (match-end 0) (match-beginning 0) 1)
7611 (error 1))))
7612 (next-level (save-excursion
7613 (condition-case nil
7614 (progn
7615 (or (looking-at org-outline-regexp)
7616 (outline-next-visible-heading 1))
7617 (if (looking-at ^re_)
7618 (- (match-end 0) (match-beginning 0) 1)
7620 (error 1))))
7621 (new-level (or force-level (max previous-level next-level)))
7622 (shift (if (or (= old-level -1)
7623 (= new-level -1)
7624 (= old-level new-level))
7626 (- new-level old-level)))
7627 (delta (if (> shift 0) -1 1))
7628 (func (if (> shift 0) 'org-demote 'org-promote))
7629 (org-odd-levels-only nil)
7630 beg end newend)
7631 ;; Remove the forced level indicator
7632 (if force-level
7633 (delete-region (point-at-bol) (point)))
7634 ;; Paste
7635 (beginning-of-line (if (bolp) 1 2))
7636 (unless for-yank (org-back-over-empty-lines))
7637 (setq beg (point))
7638 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7639 (insert-before-markers txt)
7640 (unless (string-match "\n\\'" txt) (insert "\n"))
7641 (setq newend (point))
7642 (org-reinstall-markers-in-region beg)
7643 (setq end (point))
7644 (goto-char beg)
7645 (skip-chars-forward " \t\n\r")
7646 (setq beg (point))
7647 (if (and (outline-invisible-p) visp)
7648 (save-excursion (outline-show-heading)))
7649 ;; Shift if necessary
7650 (unless (= shift 0)
7651 (save-restriction
7652 (narrow-to-region beg end)
7653 (while (not (= shift 0))
7654 (org-map-region func (point-min) (point-max))
7655 (setq shift (+ delta shift)))
7656 (goto-char (point-min))
7657 (setq newend (point-max))))
7658 (when (or (org-called-interactively-p 'interactive) for-yank)
7659 (message "Clipboard pasted as level %d subtree" new-level))
7660 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7661 kill-ring
7662 (eq org-subtree-clip (current-kill 0))
7663 org-subtree-clip-folded)
7664 ;; The tree was folded before it was killed/copied
7665 (hide-subtree))
7666 (and for-yank (goto-char newend)))))
7668 (defun org-kill-is-subtree-p (&optional txt)
7669 "Check if the current kill is an outline subtree, or a set of trees.
7670 Returns nil if kill does not start with a headline, or if the first
7671 headline level is not the largest headline level in the tree.
7672 So this will actually accept several entries of equal levels as well,
7673 which is OK for `org-paste-subtree'.
7674 If optional TXT is given, check this string instead of the current kill."
7675 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7676 (re (org-get-limited-outline-regexp))
7677 (^re (concat "^" re))
7678 (start-level (and kill
7679 (string-match
7680 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7681 kill)
7682 (- (match-end 2) (match-beginning 2) 1)))
7683 (start (1+ (or (match-beginning 2) -1))))
7684 (if (not start-level)
7685 (progn
7686 nil) ;; does not even start with a heading
7687 (catch 'exit
7688 (while (setq start (string-match ^re kill (1+ start)))
7689 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7690 (throw 'exit nil)))
7691 t))))
7693 (defvar org-markers-to-move nil
7694 "Markers that should be moved with a cut-and-paste operation.
7695 Those markers are stored together with their positions relative to
7696 the start of the region.")
7698 (defun org-save-markers-in-region (beg end)
7699 "Check markers in region.
7700 If these markers are between BEG and END, record their position relative
7701 to BEG, so that after moving the block of text, we can put the markers back
7702 into place.
7703 This function gets called just before an entry or tree gets cut from the
7704 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7705 called immediately, to move the markers with the entries."
7706 (setq org-markers-to-move nil)
7707 (when (featurep 'org-clock)
7708 (org-clock-save-markers-for-cut-and-paste beg end))
7709 (when (featurep 'org-agenda)
7710 (org-agenda-save-markers-for-cut-and-paste beg end)))
7712 (defun org-check-and-save-marker (marker beg end)
7713 "Check if MARKER is between BEG and END.
7714 If yes, remember the marker and the distance to BEG."
7715 (when (and (marker-buffer marker)
7716 (equal (marker-buffer marker) (current-buffer)))
7717 (if (and (>= marker beg) (< marker end))
7718 (push (cons marker (- marker beg)) org-markers-to-move))))
7720 (defun org-reinstall-markers-in-region (beg)
7721 "Move all remembered markers to their position relative to BEG."
7722 (mapc (lambda (x)
7723 (move-marker (car x) (+ beg (cdr x))))
7724 org-markers-to-move)
7725 (setq org-markers-to-move nil))
7727 (defun org-narrow-to-subtree ()
7728 "Narrow buffer to the current subtree."
7729 (interactive)
7730 (save-excursion
7731 (save-match-data
7732 (org-with-limited-levels
7733 (narrow-to-region
7734 (progn (org-back-to-heading t) (point))
7735 (progn (org-end-of-subtree t t)
7736 (if (and (org-on-heading-p) (not (eobp))) (backward-char 1))
7737 (point)))))))
7739 (defun org-narrow-to-block ()
7740 "Narrow buffer to the current block."
7741 (interactive)
7742 (let* ((case-fold-search t)
7743 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7744 "^[ \t]*#\\+end_.*")))
7745 (if blockp
7746 (narrow-to-region (car blockp) (cdr blockp))
7747 (error "Not in a block"))))
7749 (eval-when-compile
7750 (defvar org-property-drawer-re))
7752 (defvar org-property-start-re) ;; defined below
7753 (defun org-clone-subtree-with-time-shift (n &optional shift)
7754 "Clone the task (subtree) at point N times.
7755 The clones will be inserted as siblings.
7757 In interactive use, the user will be prompted for the number of
7758 clones to be produced, and for a time SHIFT, which may be a
7759 repeater as used in time stamps, for example `+3d'.
7761 When a valid repeater is given and the entry contains any time
7762 stamps, the clones will become a sequence in time, with time
7763 stamps in the subtree shifted for each clone produced. If SHIFT
7764 is nil or the empty string, time stamps will be left alone. The
7765 ID property of the original subtree is removed.
7767 If the original subtree did contain time stamps with a repeater,
7768 the following will happen:
7769 - the repeater will be removed in each clone
7770 - an additional clone will be produced, with the current, unshifted
7771 date(s) in the entry.
7772 - the original entry will be placed *after* all the clones, with
7773 repeater intact.
7774 - the start days in the repeater in the original entry will be shifted
7775 to past the last clone.
7776 I this way you can spell out a number of instances of a repeating task,
7777 and still retain the repeater to cover future instances of the task."
7778 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7779 (let (beg end template task idprop
7780 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7781 (if (not (and (integerp n) (> n 0)))
7782 (error "Invalid number of replications %s" n))
7783 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7784 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7785 shift)))
7786 (error "Invalid shift specification %s" shift))
7787 (when doshift
7788 (setq shift-n (string-to-number (match-string 1 shift))
7789 shift-what (cdr (assoc (match-string 2 shift)
7790 '(("d" . day) ("w" . week)
7791 ("m" . month) ("y" . year))))))
7792 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7793 (setq nmin 1 nmax n)
7794 (org-back-to-heading t)
7795 (setq beg (point))
7796 (setq idprop (org-entry-get nil "ID"))
7797 (org-end-of-subtree t t)
7798 (or (bolp) (insert "\n"))
7799 (setq end (point))
7800 (setq template (buffer-substring beg end))
7801 ;; Remove clocks and empty drawers
7802 (with-temp-buffer
7803 (insert template)
7804 (goto-char (point-min))
7805 (while (re-search-forward
7806 "^[ \t]*CLOCK:.*$" (save-excursion (org-end-of-subtree t t)) t)
7807 (replace-match "")
7808 (kill-whole-line))
7809 (goto-char (point-min))
7810 (while (re-search-forward
7811 (concat "^[ \t]*:" (regexp-opt org-drawers) ":[ \t]*$") nil t)
7812 (mapc (lambda(d) (org-remove-empty-drawer-at d (point))) org-drawers))
7813 (setq template (buffer-substring (point-min) (point-max))))
7814 (when (and doshift
7815 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7816 (delete-region beg end)
7817 (setq end beg)
7818 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7819 (goto-char end)
7820 (loop for n from nmin to nmax do
7821 ;; prepare clone
7822 (with-temp-buffer
7823 (insert template)
7824 (org-mode)
7825 (goto-char (point-min))
7826 (and idprop (if org-clone-delete-id
7827 (org-entry-delete nil "ID")
7828 (org-id-get-create t)))
7829 (while (re-search-forward org-property-start-re nil t)
7830 (org-remove-empty-drawer-at "PROPERTIES" (point)))
7831 (goto-char (point-min))
7832 (when doshift
7833 (while (re-search-forward org-ts-regexp-both nil t)
7834 (org-timestamp-change (* n shift-n) shift-what))
7835 (unless (= n n-no-remove)
7836 (goto-char (point-min))
7837 (while (re-search-forward org-ts-regexp nil t)
7838 (save-excursion
7839 (goto-char (match-beginning 0))
7840 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7841 (delete-region (match-beginning 1) (match-end 1)))))))
7842 (setq task (buffer-string)))
7843 (insert task))
7844 (goto-char beg)))
7846 ;;; Outline Sorting
7848 (defun org-sort (with-case)
7849 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
7850 Optional argument WITH-CASE means sort case-sensitively.
7851 With a double prefix argument, also remove duplicate entries."
7852 (interactive "P")
7853 (cond
7854 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
7855 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
7857 (org-call-with-arg 'org-sort-entries with-case))))
7859 (defun org-sort-remove-invisible (s)
7860 (remove-text-properties 0 (length s) org-rm-props s)
7861 (while (string-match org-bracket-link-regexp s)
7862 (setq s (replace-match (if (match-end 2)
7863 (match-string 3 s)
7864 (match-string 1 s)) t t s)))
7867 (defvar org-priority-regexp) ; defined later in the file
7869 (defvar org-after-sorting-entries-or-items-hook nil
7870 "Hook that is run after a bunch of entries or items have been sorted.
7871 When children are sorted, the cursor is in the parent line when this
7872 hook gets called. When a region or a plain list is sorted, the cursor
7873 will be in the first entry of the sorted region/list.")
7875 (defun org-sort-entries
7876 (&optional with-case sorting-type getkey-func compare-func property)
7877 "Sort entries on a certain level of an outline tree.
7878 If there is an active region, the entries in the region are sorted.
7879 Else, if the cursor is before the first entry, sort the top-level items.
7880 Else, the children of the entry at point are sorted.
7882 Sorting can be alphabetically, numerically, by date/time as given by
7883 a time stamp, by a property or by priority.
7885 The command prompts for the sorting type unless it has been given to the
7886 function through the SORTING-TYPE argument, which needs to be a character,
7887 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7888 precise meaning of each character:
7890 n Numerically, by converting the beginning of the entry/item to a number.
7891 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7892 t By date/time, either the first active time stamp in the entry, or, if
7893 none exist, by the first inactive one.
7894 s By the scheduled date/time.
7895 d By deadline date/time.
7896 c By creation time, which is assumed to be the first inactive time stamp
7897 at the beginning of a line.
7898 p By priority according to the cookie.
7899 r By the value of a property.
7901 Capital letters will reverse the sort order.
7903 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7904 called with point at the beginning of the record. It must return either
7905 a string or a number that should serve as the sorting key for that record.
7907 Comparing entries ignores case by default. However, with an optional argument
7908 WITH-CASE, the sorting considers case as well."
7909 (interactive "P")
7910 (let ((case-func (if with-case 'identity 'downcase))
7911 start beg end stars re re2
7912 txt what tmp)
7913 ;; Find beginning and end of region to sort
7914 (cond
7915 ((org-region-active-p)
7916 ;; we will sort the region
7917 (setq end (region-end)
7918 what "region")
7919 (goto-char (region-beginning))
7920 (if (not (org-on-heading-p)) (outline-next-heading))
7921 (setq start (point)))
7922 ((or (org-on-heading-p)
7923 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7924 ;; we will sort the children of the current headline
7925 (org-back-to-heading)
7926 (setq start (point)
7927 end (progn (org-end-of-subtree t t)
7928 (or (bolp) (insert "\n"))
7929 (org-back-over-empty-lines)
7930 (point))
7931 what "children")
7932 (goto-char start)
7933 (show-subtree)
7934 (outline-next-heading))
7936 ;; we will sort the top-level entries in this file
7937 (goto-char (point-min))
7938 (or (org-on-heading-p) (outline-next-heading))
7939 (setq start (point))
7940 (goto-char (point-max))
7941 (beginning-of-line 1)
7942 (when (looking-at ".*?\\S-")
7943 ;; File ends in a non-white line
7944 (end-of-line 1)
7945 (insert "\n"))
7946 (setq end (point-max))
7947 (setq what "top-level")
7948 (goto-char start)
7949 (show-all)))
7951 (setq beg (point))
7952 (if (>= beg end) (error "Nothing to sort"))
7954 (looking-at "\\(\\*+\\)")
7955 (setq stars (match-string 1)
7956 re (concat "^" (regexp-quote stars) " +")
7957 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
7958 txt (buffer-substring beg end))
7959 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7960 (if (and (not (equal stars "*")) (string-match re2 txt))
7961 (error "Region to sort contains a level above the first entry"))
7963 (unless sorting-type
7964 (message
7965 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7966 [t]ime [s]cheduled [d]eadline [c]reated
7967 A/N/T/S/D/C/P/O/F means reversed:"
7968 what)
7969 (setq sorting-type (read-char-exclusive))
7971 (and (= (downcase sorting-type) ?f)
7972 (setq getkey-func
7973 (org-icompleting-read "Sort using function: "
7974 obarray 'fboundp t nil nil))
7975 (setq getkey-func (intern getkey-func)))
7977 (and (= (downcase sorting-type) ?r)
7978 (setq property
7979 (org-icompleting-read "Property: "
7980 (mapcar 'list (org-buffer-property-keys t))
7981 nil t))))
7983 (message "Sorting entries...")
7985 (save-restriction
7986 (narrow-to-region start end)
7987 (let ((dcst (downcase sorting-type))
7988 (case-fold-search nil)
7989 (now (current-time)))
7990 (sort-subr
7991 (/= dcst sorting-type)
7992 ;; This function moves to the beginning character of the "record" to
7993 ;; be sorted.
7994 (lambda nil
7995 (if (re-search-forward re nil t)
7996 (goto-char (match-beginning 0))
7997 (goto-char (point-max))))
7998 ;; This function moves to the last character of the "record" being
7999 ;; sorted.
8000 (lambda nil
8001 (save-match-data
8002 (condition-case nil
8003 (outline-forward-same-level 1)
8004 (error
8005 (goto-char (point-max))))))
8006 ;; This function returns the value that gets sorted against.
8007 (lambda nil
8008 (cond
8009 ((= dcst ?n)
8010 (if (looking-at org-complex-heading-regexp)
8011 (string-to-number (match-string 4))
8012 nil))
8013 ((= dcst ?a)
8014 (if (looking-at org-complex-heading-regexp)
8015 (funcall case-func (match-string 4))
8016 nil))
8017 ((= dcst ?t)
8018 (let ((end (save-excursion (outline-next-heading) (point))))
8019 (if (or (re-search-forward org-ts-regexp end t)
8020 (re-search-forward org-ts-regexp-both end t))
8021 (org-time-string-to-seconds (match-string 0))
8022 (org-float-time now))))
8023 ((= dcst ?c)
8024 (let ((end (save-excursion (outline-next-heading) (point))))
8025 (if (re-search-forward
8026 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8027 end t)
8028 (org-time-string-to-seconds (match-string 0))
8029 (org-float-time now))))
8030 ((= dcst ?s)
8031 (let ((end (save-excursion (outline-next-heading) (point))))
8032 (if (re-search-forward org-scheduled-time-regexp end t)
8033 (org-time-string-to-seconds (match-string 1))
8034 (org-float-time now))))
8035 ((= dcst ?d)
8036 (let ((end (save-excursion (outline-next-heading) (point))))
8037 (if (re-search-forward org-deadline-time-regexp end t)
8038 (org-time-string-to-seconds (match-string 1))
8039 (org-float-time now))))
8040 ((= dcst ?p)
8041 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8042 (string-to-char (match-string 2))
8043 org-default-priority))
8044 ((= dcst ?r)
8045 (or (org-entry-get nil property) ""))
8046 ((= dcst ?o)
8047 (if (looking-at org-complex-heading-regexp)
8048 (- 9999 (length (member (match-string 2)
8049 org-todo-keywords-1)))))
8050 ((= dcst ?f)
8051 (if getkey-func
8052 (progn
8053 (setq tmp (funcall getkey-func))
8054 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8055 tmp)
8056 (error "Invalid key function `%s'" getkey-func)))
8057 (t (error "Invalid sorting type `%c'" sorting-type))))
8059 (cond
8060 ((= dcst ?a) 'string<)
8061 ((= dcst ?f) compare-func)
8062 ((member dcst '(?p ?t ?s ?d ?c)) '<)
8063 (t nil)))))
8064 (run-hooks 'org-after-sorting-entries-or-items-hook)
8065 (message "Sorting entries...done")))
8067 (defun org-do-sort (table what &optional with-case sorting-type)
8068 "Sort TABLE of WHAT according to SORTING-TYPE.
8069 The user will be prompted for the SORTING-TYPE if the call to this
8070 function does not specify it. WHAT is only for the prompt, to indicate
8071 what is being sorted. The sorting key will be extracted from
8072 the car of the elements of the table.
8073 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8074 (unless sorting-type
8075 (message
8076 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8077 what)
8078 (setq sorting-type (read-char-exclusive)))
8079 (let ((dcst (downcase sorting-type))
8080 extractfun comparefun)
8081 ;; Define the appropriate functions
8082 (cond
8083 ((= dcst ?n)
8084 (setq extractfun 'string-to-number
8085 comparefun (if (= dcst sorting-type) '< '>)))
8086 ((= dcst ?a)
8087 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8088 (lambda(x) (downcase (org-sort-remove-invisible x))))
8089 comparefun (if (= dcst sorting-type)
8090 'string<
8091 (lambda (a b) (and (not (string< a b))
8092 (not (string= a b)))))))
8093 ((= dcst ?t)
8094 (setq extractfun
8095 (lambda (x)
8096 (if (or (string-match org-ts-regexp x)
8097 (string-match org-ts-regexp-both x))
8098 (org-float-time
8099 (org-time-string-to-time (match-string 0 x)))
8101 comparefun (if (= dcst sorting-type) '< '>)))
8102 (t (error "Invalid sorting type `%c'" sorting-type)))
8104 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8105 table)
8106 (lambda (a b) (funcall comparefun (car a) (car b))))))
8109 ;;; The orgstruct minor mode
8111 ;; Define a minor mode which can be used in other modes in order to
8112 ;; integrate the org-mode structure editing commands.
8114 ;; This is really a hack, because the org-mode structure commands use
8115 ;; keys which normally belong to the major mode. Here is how it
8116 ;; works: The minor mode defines all the keys necessary to operate the
8117 ;; structure commands, but wraps the commands into a function which
8118 ;; tests if the cursor is currently at a headline or a plain list
8119 ;; item. If that is the case, the structure command is used,
8120 ;; temporarily setting many Org-mode variables like regular
8121 ;; expressions for filling etc. However, when any of those keys is
8122 ;; used at a different location, function uses `key-binding' to look
8123 ;; up if the key has an associated command in another currently active
8124 ;; keymap (minor modes, major mode, global), and executes that
8125 ;; command. There might be problems if any of the keys is otherwise
8126 ;; used as a prefix key.
8128 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8129 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8130 ;; addresses this by checking explicitly for both bindings.
8132 (defvar orgstruct-mode-map (make-sparse-keymap)
8133 "Keymap for the minor `orgstruct-mode'.")
8135 (defvar org-local-vars nil
8136 "List of local variables, for use by `orgstruct-mode'.")
8138 ;;;###autoload
8139 (define-minor-mode orgstruct-mode
8140 "Toggle the minor mode `orgstruct-mode'.
8141 This mode is for using Org-mode structure commands in other
8142 modes. The following keys behave as if Org-mode were active, if
8143 the cursor is on a headline, or on a plain list item (both as
8144 defined by Org-mode).
8146 M-up Move entry/item up
8147 M-down Move entry/item down
8148 M-left Promote
8149 M-right Demote
8150 M-S-up Move entry/item up
8151 M-S-down Move entry/item down
8152 M-S-left Promote subtree
8153 M-S-right Demote subtree
8154 M-q Fill paragraph and items like in Org-mode
8155 C-c ^ Sort entries
8156 C-c - Cycle list bullet
8157 TAB Cycle item visibility
8158 M-RET Insert new heading/item
8159 S-M-RET Insert new TODO heading / Checkbox item
8160 C-c C-c Set tags / toggle checkbox"
8161 nil " OrgStruct" nil
8162 (org-load-modules-maybe)
8163 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8165 ;;;###autoload
8166 (defun turn-on-orgstruct ()
8167 "Unconditionally turn on `orgstruct-mode'."
8168 (orgstruct-mode 1))
8170 (defun orgstruct++-mode (&optional arg)
8171 "Toggle `orgstruct-mode', the enhanced version of it.
8172 In addition to setting orgstruct-mode, this also exports all indentation
8173 and autofilling variables from org-mode into the buffer. It will also
8174 recognize item context in multiline items.
8175 Note that turning off orgstruct-mode will *not* remove the
8176 indentation/paragraph settings. This can only be done by refreshing the
8177 major mode, for example with \\[normal-mode]."
8178 (interactive "P")
8179 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8180 (if (< arg 1)
8181 (orgstruct-mode -1)
8182 (orgstruct-mode 1)
8183 (let (var val)
8184 (mapc
8185 (lambda (x)
8186 (when (string-match
8187 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8188 (symbol-name (car x)))
8189 (setq var (car x) val (nth 1 x))
8190 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8191 org-local-vars)
8192 (org-set-local 'orgstruct-is-++ t))))
8194 (defvar orgstruct-is-++ nil
8195 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8196 (make-variable-buffer-local 'orgstruct-is-++)
8198 ;;;###autoload
8199 (defun turn-on-orgstruct++ ()
8200 "Unconditionally turn on `orgstruct++-mode'."
8201 (orgstruct++-mode 1))
8203 (defun orgstruct-error ()
8204 "Error when there is no default binding for a structure key."
8205 (interactive)
8206 (error "This key has no function outside structure elements"))
8208 (defun orgstruct-setup ()
8209 "Setup orgstruct keymaps."
8210 (let ((nfunc 0)
8211 (bindings
8212 (list
8213 '([(meta up)] org-metaup)
8214 '([(meta down)] org-metadown)
8215 '([(meta left)] org-metaleft)
8216 '([(meta right)] org-metaright)
8217 '([(meta shift up)] org-shiftmetaup)
8218 '([(meta shift down)] org-shiftmetadown)
8219 '([(meta shift left)] org-shiftmetaleft)
8220 '([(meta shift right)] org-shiftmetaright)
8221 '([?\e (up)] org-metaup)
8222 '([?\e (down)] org-metadown)
8223 '([?\e (left)] org-metaleft)
8224 '([?\e (right)] org-metaright)
8225 '([?\e (shift up)] org-shiftmetaup)
8226 '([?\e (shift down)] org-shiftmetadown)
8227 '([?\e (shift left)] org-shiftmetaleft)
8228 '([?\e (shift right)] org-shiftmetaright)
8229 '([(shift up)] org-shiftup)
8230 '([(shift down)] org-shiftdown)
8231 '([(shift left)] org-shiftleft)
8232 '([(shift right)] org-shiftright)
8233 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8234 '("\M-q" fill-paragraph)
8235 '("\C-c^" org-sort)
8236 '("\C-c-" org-cycle-list-bullet)))
8237 elt key fun cmd)
8238 (while (setq elt (pop bindings))
8239 (setq nfunc (1+ nfunc))
8240 (setq key (org-key (car elt))
8241 fun (nth 1 elt)
8242 cmd (orgstruct-make-binding fun nfunc key))
8243 (org-defkey orgstruct-mode-map key cmd))
8245 ;; Special treatment needed for TAB and RET
8246 (org-defkey orgstruct-mode-map [(tab)]
8247 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8248 (org-defkey orgstruct-mode-map "\C-i"
8249 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8251 (org-defkey orgstruct-mode-map "\M-\C-m"
8252 (orgstruct-make-binding 'org-insert-heading 105
8253 "\M-\C-m" [(meta return)]))
8254 (org-defkey orgstruct-mode-map [(meta return)]
8255 (orgstruct-make-binding 'org-insert-heading 106
8256 [(meta return)] "\M-\C-m"))
8258 (org-defkey orgstruct-mode-map [(shift meta return)]
8259 (orgstruct-make-binding 'org-insert-todo-heading 107
8260 [(meta return)] "\M-\C-m"))
8262 (org-defkey orgstruct-mode-map "\e\C-m"
8263 (orgstruct-make-binding 'org-insert-heading 108
8264 "\e\C-m" [?\e (return)]))
8265 (org-defkey orgstruct-mode-map [?\e (return)]
8266 (orgstruct-make-binding 'org-insert-heading 109
8267 [?\e (return)] "\e\C-m"))
8268 (org-defkey orgstruct-mode-map [?\e (shift return)]
8269 (orgstruct-make-binding 'org-insert-todo-heading 110
8270 [?\e (return)] "\e\C-m"))
8272 (unless org-local-vars
8273 (setq org-local-vars (org-get-local-variables)))
8277 (defun orgstruct-make-binding (fun n &rest keys)
8278 "Create a function for binding in the structure minor mode.
8279 FUN is the command to call inside a table. N is used to create a unique
8280 command name. KEYS are keys that should be checked in for a command
8281 to execute outside of tables."
8282 (eval
8283 (list 'defun
8284 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8285 '(arg)
8286 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8287 "Outside of structure, run the binding of `"
8288 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8289 "'.")
8290 '(interactive "p")
8291 (list 'if
8292 `(org-context-p 'headline 'item
8293 (and orgstruct-is-++
8294 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8295 'item-body))
8296 (list 'org-run-like-in-org-mode (list 'quote fun))
8297 (list 'let '(orgstruct-mode)
8298 (list 'call-interactively
8299 (append '(or)
8300 (mapcar (lambda (k)
8301 (list 'key-binding k))
8302 keys)
8303 '('orgstruct-error))))))))
8305 (defun org-context-p (&rest contexts)
8306 "Check if local context is any of CONTEXTS.
8307 Possible values in the list of contexts are `table', `headline', and `item'."
8308 (let ((pos (point)))
8309 (goto-char (point-at-bol))
8310 (prog1 (or (and (memq 'table contexts)
8311 (looking-at "[ \t]*|"))
8312 (and (memq 'headline contexts)
8313 (looking-at org-outline-regexp))
8314 (and (memq 'item contexts)
8315 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8316 (and (memq 'item-body contexts)
8317 (org-in-item-p)))
8318 (goto-char pos))))
8320 (defun org-get-local-variables ()
8321 "Return a list of all local variables in an org-mode buffer."
8322 (let (varlist)
8323 (with-current-buffer (get-buffer-create "*Org tmp*")
8324 (erase-buffer)
8325 (org-mode)
8326 (setq varlist (buffer-local-variables)))
8327 (kill-buffer "*Org tmp*")
8328 (delq nil
8329 (mapcar
8330 (lambda (x)
8331 (setq x
8332 (if (symbolp x)
8333 (list x)
8334 (list (car x) (list 'quote (cdr x)))))
8335 (if (string-match
8336 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8337 (symbol-name (car x)))
8338 x nil))
8339 varlist))))
8341 (defun org-clone-local-variables (from-buffer &optional regexp)
8342 "Clone local variables from FROM-BUFFER.
8343 Optional argument REGEXP selects variables to clone."
8344 (mapc
8345 (lambda (pair)
8346 (and (symbolp (car pair))
8347 (or (null regexp)
8348 (string-match regexp (symbol-name (car pair))))
8349 (set (make-local-variable (car pair))
8350 (cdr pair))))
8351 (buffer-local-variables from-buffer)))
8353 ;;;###autoload
8354 (defun org-run-like-in-org-mode (cmd)
8355 "Run a command, pretending that the current buffer is in Org-mode.
8356 This will temporarily bind local variables that are typically bound in
8357 Org-mode to the values they have in Org-mode, and then interactively
8358 call CMD."
8359 (org-load-modules-maybe)
8360 (unless org-local-vars
8361 (setq org-local-vars (org-get-local-variables)))
8362 (eval (list 'let org-local-vars
8363 (list 'call-interactively (list 'quote cmd)))))
8365 ;;;; Archiving
8367 (defun org-get-category (&optional pos force-refresh)
8368 "Get the category applying to position POS."
8369 (if force-refresh (org-refresh-category-properties))
8370 (let ((pos (or pos (point))))
8371 (or (get-text-property pos 'org-category)
8372 (progn (org-refresh-category-properties)
8373 (get-text-property pos 'org-category)))))
8375 (defun org-refresh-category-properties ()
8376 "Refresh category text properties in the buffer."
8377 (let ((def-cat (cond
8378 ((null org-category)
8379 (if buffer-file-name
8380 (file-name-sans-extension
8381 (file-name-nondirectory buffer-file-name))
8382 "???"))
8383 ((symbolp org-category) (symbol-name org-category))
8384 (t org-category)))
8385 beg end cat pos optionp)
8386 (org-unmodified
8387 (save-excursion
8388 (save-restriction
8389 (widen)
8390 (goto-char (point-min))
8391 (put-text-property (point) (point-max) 'org-category def-cat)
8392 (while (re-search-forward
8393 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8394 (setq pos (match-end 0)
8395 optionp (equal (char-after (match-beginning 0)) ?#)
8396 cat (org-trim (match-string 2)))
8397 (if optionp
8398 (setq beg (point-at-bol) end (point-max))
8399 (org-back-to-heading t)
8400 (setq beg (point) end (org-end-of-subtree t t)))
8401 (put-text-property beg end 'org-category cat)
8402 (put-text-property beg end 'org-category-position beg)
8403 (goto-char pos)))))))
8406 ;;;; Link Stuff
8408 ;;; Link abbreviations
8410 (defun org-link-expand-abbrev (link)
8411 "Apply replacements as defined in `org-link-abbrev-alist."
8412 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8413 (let* ((key (match-string 1 link))
8414 (as (or (assoc key org-link-abbrev-alist-local)
8415 (assoc key org-link-abbrev-alist)))
8416 (tag (and (match-end 2) (match-string 3 link)))
8417 rpl)
8418 (if (not as)
8419 link
8420 (setq rpl (cdr as))
8421 (cond
8422 ((symbolp rpl) (funcall rpl tag))
8423 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8424 ((string-match "%h" rpl)
8425 (replace-match (url-hexify-string (or tag "")) t t rpl))
8426 (t (concat rpl tag)))))
8427 link))
8429 ;;; Storing and inserting links
8431 (defvar org-insert-link-history nil
8432 "Minibuffer history for links inserted with `org-insert-link'.")
8434 (defvar org-stored-links nil
8435 "Contains the links stored with `org-store-link'.")
8437 (defvar org-store-link-plist nil
8438 "Plist with info about the most recently link created with `org-store-link'.")
8440 (defvar org-link-protocols nil
8441 "Link protocols added to Org-mode using `org-add-link-type'.")
8443 (defvar org-store-link-functions nil
8444 "List of functions that are called to create and store a link.
8445 Each function will be called in turn until one returns a non-nil
8446 value. Each function should check if it is responsible for creating
8447 this link (for example by looking at the major mode).
8448 If not, it must exit and return nil.
8449 If yes, it should return a non-nil value after a calling
8450 `org-store-link-props' with a list of properties and values.
8451 Special properties are:
8453 :type The link prefix, like \"http\". This must be given.
8454 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8455 This is obligatory as well.
8456 :description Optional default description for the second pair
8457 of brackets in an Org-mode link. The user can still change
8458 this when inserting this link into an Org-mode buffer.
8460 In addition to these, any additional properties can be specified
8461 and then used in remember templates.")
8463 (defun org-add-link-type (type &optional follow export)
8464 "Add TYPE to the list of `org-link-types'.
8465 Re-compute all regular expressions depending on `org-link-types'
8467 FOLLOW and EXPORT are two functions.
8469 FOLLOW should take the link path as the single argument and do whatever
8470 is necessary to follow the link, for example find a file or display
8471 a mail message.
8473 EXPORT should format the link path for export to one of the export formats.
8474 It should be a function accepting three arguments:
8476 path the path of the link, the text after the prefix (like \"http:\")
8477 desc the description of the link, if any, or a description added by
8478 org-export-normalize-links if there is none
8479 format the export format, a symbol like `html' or `latex' or `ascii'..
8481 The function may use the FORMAT information to return different values
8482 depending on the format. The return value will be put literally into
8483 the exported file. If the return value is nil, this means Org should
8484 do what it normally does with links which do not have EXPORT defined.
8486 Org-mode has a built-in default for exporting links. If you are happy with
8487 this default, there is no need to define an export function for the link
8488 type. For a simple example of an export function, see `org-bbdb.el'."
8489 (add-to-list 'org-link-types type t)
8490 (org-make-link-regexps)
8491 (if (assoc type org-link-protocols)
8492 (setcdr (assoc type org-link-protocols) (list follow export))
8493 (push (list type follow export) org-link-protocols)))
8495 (defvar org-agenda-buffer-name)
8497 ;;;###autoload
8498 (defun org-store-link (arg)
8499 "\\<org-mode-map>Store an org-link to the current location.
8500 This link is added to `org-stored-links' and can later be inserted
8501 into an org-buffer with \\[org-insert-link].
8503 For some link types, a prefix arg is interpreted:
8504 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8505 For file links, arg negates `org-context-in-file-links'."
8506 (interactive "P")
8507 (org-load-modules-maybe)
8508 (setq org-store-link-plist nil) ; reset
8509 (org-with-limited-levels
8510 (let (link cpltxt desc description search txt custom-id agenda-link)
8511 (cond
8513 ((run-hook-with-args-until-success 'org-store-link-functions)
8514 (setq link (plist-get org-store-link-plist :link)
8515 desc (or (plist-get org-store-link-plist :description) link)))
8517 ((equal (buffer-name) "*Org Edit Src Example*")
8518 (let (label gc)
8519 (while (or (not label)
8520 (save-excursion
8521 (save-restriction
8522 (widen)
8523 (goto-char (point-min))
8524 (re-search-forward
8525 (regexp-quote (format org-coderef-label-format label))
8526 nil t))))
8527 (when label (message "Label exists already") (sit-for 2))
8528 (setq label (read-string "Code line label: " label)))
8529 (end-of-line 1)
8530 (setq link (format org-coderef-label-format label))
8531 (setq gc (- 79 (length link)))
8532 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8533 (insert link)
8534 (setq link (concat "(" label ")") desc nil)))
8536 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8537 ;; We are in the agenda, link to referenced location
8538 (let ((m (or (get-text-property (point) 'org-hd-marker)
8539 (get-text-property (point) 'org-marker))))
8540 (when m
8541 (org-with-point-at m
8542 (setq agenda-link
8543 (if (org-called-interactively-p 'any)
8544 (call-interactively 'org-store-link)
8545 (org-store-link nil)))))))
8547 ((eq major-mode 'calendar-mode)
8548 (let ((cd (calendar-cursor-to-date)))
8549 (setq link
8550 (format-time-string
8551 (car org-time-stamp-formats)
8552 (apply 'encode-time
8553 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8554 nil nil nil))))
8555 (org-store-link-props :type "calendar" :date cd)))
8557 ((eq major-mode 'w3-mode)
8558 (setq cpltxt (if (and (buffer-name)
8559 (not (string-match "Untitled" (buffer-name))))
8560 (buffer-name)
8561 (url-view-url t))
8562 link (org-make-link (url-view-url t)))
8563 (org-store-link-props :type "w3" :url (url-view-url t)))
8565 ((eq major-mode 'w3m-mode)
8566 (setq cpltxt (or w3m-current-title w3m-current-url)
8567 link (org-make-link w3m-current-url))
8568 (org-store-link-props :type "w3m" :url (url-view-url t)))
8570 ((setq search (run-hook-with-args-until-success
8571 'org-create-file-search-functions))
8572 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8573 "::" search))
8574 (setq cpltxt (or description link)))
8576 ((eq major-mode 'image-mode)
8577 (setq cpltxt (concat "file:"
8578 (abbreviate-file-name buffer-file-name))
8579 link (org-make-link cpltxt))
8580 (org-store-link-props :type "image" :file buffer-file-name))
8582 ((eq major-mode 'dired-mode)
8583 ;; link to the file in the current line
8584 (let ((file (dired-get-filename nil t)))
8585 (setq file (if file
8586 (abbreviate-file-name
8587 (expand-file-name (dired-get-filename nil t)))
8588 ;; otherwise, no file so use current directory.
8589 default-directory))
8590 (setq cpltxt (concat "file:" file)
8591 link (org-make-link cpltxt))))
8593 ((and (buffer-file-name (buffer-base-buffer)) (org-mode-p))
8594 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8595 (cond
8596 ((org-in-regexp "<<\\(.*?\\)>>")
8597 (setq cpltxt
8598 (concat "file:"
8599 (abbreviate-file-name
8600 (buffer-file-name (buffer-base-buffer)))
8601 "::" (match-string 1))
8602 link (org-make-link cpltxt)))
8603 ((and (featurep 'org-id)
8604 (or (eq org-link-to-org-use-id t)
8605 (and (eq org-link-to-org-use-id 'create-if-interactive)
8606 (org-called-interactively-p 'any))
8607 (and (eq org-link-to-org-use-id
8608 'create-if-interactive-and-no-custom-id)
8609 (org-called-interactively-p 'any)
8610 (not custom-id))
8611 (and org-link-to-org-use-id
8612 (org-entry-get nil "ID"))))
8613 ;; We can make a link using the ID.
8614 (setq link (condition-case nil
8615 (prog1 (org-id-store-link)
8616 (setq desc (plist-get org-store-link-plist
8617 :description)))
8618 (error
8619 ;; probably before first headline, link to file only
8620 (concat "file:"
8621 (abbreviate-file-name
8622 (buffer-file-name (buffer-base-buffer))))))))
8624 ;; Just link to current headline
8625 (setq cpltxt (concat "file:"
8626 (abbreviate-file-name
8627 (buffer-file-name (buffer-base-buffer)))))
8628 ;; Add a context search string
8629 (when (org-xor org-context-in-file-links arg)
8630 (setq txt (cond
8631 ((org-on-heading-p) nil)
8632 ((org-region-active-p)
8633 (buffer-substring (region-beginning) (region-end)))
8634 (t nil)))
8635 (when (or (null txt) (string-match "\\S-" txt))
8636 (setq cpltxt
8637 (concat cpltxt "::"
8638 (condition-case nil
8639 (org-make-org-heading-search-string txt)
8640 (error "")))
8641 desc (or (nth 4 (ignore-errors
8642 (org-heading-components))) "NONE"))))
8643 (if (string-match "::\\'" cpltxt)
8644 (setq cpltxt (substring cpltxt 0 -2)))
8645 (setq link (org-make-link cpltxt)))))
8647 ((buffer-file-name (buffer-base-buffer))
8648 ;; Just link to this file here.
8649 (setq cpltxt (concat "file:"
8650 (abbreviate-file-name
8651 (buffer-file-name (buffer-base-buffer)))))
8652 ;; Add a context string
8653 (when (org-xor org-context-in-file-links arg)
8654 (setq txt (if (org-region-active-p)
8655 (buffer-substring (region-beginning) (region-end))
8656 (buffer-substring (point-at-bol) (point-at-eol))))
8657 ;; Only use search option if there is some text.
8658 (when (string-match "\\S-" txt)
8659 (setq cpltxt
8660 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8661 desc "NONE")))
8662 (setq link (org-make-link cpltxt)))
8664 ((org-called-interactively-p 'interactive)
8665 (error "Cannot link to a buffer which is not visiting a file"))
8667 (t (setq link nil)))
8669 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8670 (setq link (or link cpltxt)
8671 desc (or desc cpltxt))
8672 (if (equal desc "NONE") (setq desc nil))
8674 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8675 (progn
8676 (setq org-stored-links
8677 (cons (list link desc) org-stored-links))
8678 (message "Stored: %s" (or desc link))
8679 (when custom-id
8680 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8681 "::#" custom-id))
8682 (setq org-stored-links
8683 (cons (list link desc) org-stored-links))))
8684 (or agenda-link (and link (org-make-link-string link desc)))))))
8686 (defun org-store-link-props (&rest plist)
8687 "Store link properties, extract names and addresses."
8688 (let (x adr)
8689 (when (setq x (plist-get plist :from))
8690 (setq adr (mail-extract-address-components x))
8691 (setq plist (plist-put plist :fromname (car adr)))
8692 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8693 (when (setq x (plist-get plist :to))
8694 (setq adr (mail-extract-address-components x))
8695 (setq plist (plist-put plist :toname (car adr)))
8696 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8697 (let ((from (plist-get plist :from))
8698 (to (plist-get plist :to)))
8699 (when (and from to org-from-is-user-regexp)
8700 (setq plist
8701 (plist-put plist :fromto
8702 (if (string-match org-from-is-user-regexp from)
8703 (concat "to %t")
8704 (concat "from %f"))))))
8705 (setq org-store-link-plist plist))
8707 (defun org-add-link-props (&rest plist)
8708 "Add these properties to the link property list."
8709 (let (key value)
8710 (while plist
8711 (setq key (pop plist) value (pop plist))
8712 (setq org-store-link-plist
8713 (plist-put org-store-link-plist key value)))))
8715 (defun org-email-link-description (&optional fmt)
8716 "Return the description part of an email link.
8717 This takes information from `org-store-link-plist' and formats it
8718 according to FMT (default from `org-email-link-description-format')."
8719 (setq fmt (or fmt org-email-link-description-format))
8720 (let* ((p org-store-link-plist)
8721 (to (plist-get p :toaddress))
8722 (from (plist-get p :fromaddress))
8723 (table
8724 (list
8725 (cons "%c" (plist-get p :fromto))
8726 (cons "%F" (plist-get p :from))
8727 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8728 (cons "%T" (plist-get p :to))
8729 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8730 (cons "%s" (plist-get p :subject))
8731 (cons "%d" (plist-get p :date))
8732 (cons "%m" (plist-get p :message-id)))))
8733 (when (string-match "%c" fmt)
8734 ;; Check if the user wrote this message
8735 (if (and org-from-is-user-regexp from to
8736 (save-match-data (string-match org-from-is-user-regexp from)))
8737 (setq fmt (replace-match "to %t" t t fmt))
8738 (setq fmt (replace-match "from %f" t t fmt))))
8739 (org-replace-escapes fmt table)))
8741 (defun org-make-org-heading-search-string (&optional string heading)
8742 "Make search string for STRING or current headline."
8743 (interactive)
8744 (let ((s (or string (org-get-heading)))
8745 (lines org-context-in-file-links))
8746 (unless (and string (not heading))
8747 ;; We are using a headline, clean up garbage in there.
8748 (if (string-match org-todo-regexp s)
8749 (setq s (replace-match "" t t s)))
8750 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8751 (setq s (replace-match "" t t s)))
8752 (setq s (org-trim s))
8753 (if (string-match (concat "^\\(" org-quote-string "\\|"
8754 org-comment-string "\\)") s)
8755 (setq s (replace-match "" t t s)))
8756 (while (string-match org-ts-regexp s)
8757 (setq s (replace-match "" t t s))))
8758 (or string (setq s (concat "*" s))) ; Add * for headlines
8759 (when (and string (integerp lines) (> lines 0))
8760 (let ((slines (org-split-string s "\n")))
8761 (when (< lines (length slines))
8762 (setq s (mapconcat
8763 'identity
8764 (reverse (nthcdr (- (length slines) lines)
8765 (reverse slines))) "\n")))))
8766 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8768 (defun org-make-link (&rest strings)
8769 "Concatenate STRINGS."
8770 (apply 'concat strings))
8772 (defun org-make-link-string (link &optional description)
8773 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8774 (unless (string-match "\\S-" link)
8775 (error "Empty link"))
8776 (when (and description
8777 (stringp description)
8778 (not (string-match "\\S-" description)))
8779 (setq description nil))
8780 (when (stringp description)
8781 ;; Remove brackets from the description, they are fatal.
8782 (while (string-match "\\[" description)
8783 (setq description (replace-match "{" t t description)))
8784 (while (string-match "\\]" description)
8785 (setq description (replace-match "}" t t description))))
8786 (when (equal link description)
8787 ;; No description needed, it is identical
8788 (setq description nil))
8789 (when (and (not description)
8790 (not (string-match (org-image-file-name-regexp) link))
8791 (not (equal link (org-link-escape link))))
8792 (setq description (org-extract-attributes link)))
8793 (setq link
8794 (cond ((string-match (org-image-file-name-regexp) link) link)
8795 ((string-match org-link-types-re link)
8796 (concat (match-string 1 link)
8797 (org-link-escape (substring link (match-end 1)))))
8798 (t (org-link-escape link))))
8799 (concat "[[" link "]"
8800 (if description (concat "[" description "]") "")
8801 "]"))
8803 (defconst org-link-escape-chars
8804 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8805 "List of characters that should be escaped in link.
8806 This is the list that is used for internal purposes.")
8808 (defvar org-url-encoding-use-url-hexify nil)
8810 (defconst org-link-escape-chars-browser
8811 '(?\ )
8812 "List of escapes for characters that are problematic in links.
8813 This is the list that is used before handing over to the browser.")
8815 (defun org-link-escape (text &optional table merge)
8816 "Return percent escaped representation of TEXT.
8817 TEXT is a string with the text to escape.
8818 Optional argument TABLE is a list with characters that should be
8819 escaped. When nil, `org-link-escape-chars' is used.
8820 If optional argument MERGE is set, merge TABLE into
8821 `org-link-escape-chars'."
8822 (if (and org-url-encoding-use-url-hexify (not table))
8823 (url-hexify-string text)
8824 (cond
8825 ((and table merge)
8826 (mapc (lambda (defchr)
8827 (unless (member defchr table)
8828 (setq table (cons defchr table)))) org-link-escape-chars))
8829 ((null table)
8830 (setq table org-link-escape-chars)))
8831 (mapconcat
8832 (lambda (char)
8833 (if (or (member char table)
8834 (< char 32) (= char 37) (> char 126))
8835 (mapconcat (lambda (sequence-element)
8836 (format "%%%.2X" sequence-element))
8837 (or (encode-coding-char char 'utf-8)
8838 (error "Unable to percent escape character: %s"
8839 (char-to-string char))) "")
8840 (char-to-string char))) text "")))
8842 (defun org-link-unescape (str)
8843 "Unhex hexified unicode strings as returned from the JavaScript function
8844 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
8845 (unless (and (null str) (string= "" str))
8846 (let ((pos 0) (case-fold-search t) unhexed)
8847 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
8848 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
8849 (setq str (replace-match unhexed t t str))
8850 (setq pos (+ pos (length unhexed))))))
8851 str)
8853 (defun org-link-unescape-compound (hex)
8854 "Unhexify unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
8855 Note: this function also decodes single byte encodings like
8856 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
8857 (save-match-data
8858 (let* ((bytes (cdr (split-string hex "%")))
8859 (ret "")
8860 (eat 0)
8861 (sum 0))
8862 (while bytes
8863 (let* ((val (string-to-number (pop bytes) 16))
8864 (shift-xor
8865 (if (= 0 eat)
8866 (cond
8867 ((>= val 252) (cons 6 252))
8868 ((>= val 248) (cons 5 248))
8869 ((>= val 240) (cons 4 240))
8870 ((>= val 224) (cons 3 224))
8871 ((>= val 192) (cons 2 192))
8872 (t (cons 0 0)))
8873 (cons 6 128))))
8874 (if (>= val 192) (setq eat (car shift-xor)))
8875 (setq val (logxor val (cdr shift-xor)))
8876 (setq sum (+ (lsh sum (car shift-xor)) val))
8877 (if (> eat 0) (setq eat (- eat 1)))
8878 (cond
8879 ((= 0 eat) ;multi byte
8880 (setq ret (concat ret (org-char-to-string sum)))
8881 (setq sum 0))
8882 ((not bytes) ; single byte(s)
8883 (setq ret (org-link-unescape-single-byte-sequence hex))))
8884 )) ;; end (while bytes
8885 ret )))
8887 (defun org-link-unescape-single-byte-sequence (hex)
8888 "Unhexify hex-encoded single byte character sequences."
8889 (mapconcat (lambda (byte)
8890 (char-to-string (string-to-number byte 16)))
8891 (cdr (split-string hex "%")) ""))
8893 (defun org-xor (a b)
8894 "Exclusive or."
8895 (if a (not b) b))
8897 (defun org-fixup-message-id-for-http (s)
8898 "Replace special characters in a message id, so it can be used in an http query."
8899 (when (string-match "%" s)
8900 (setq s (mapconcat (lambda (c)
8901 (if (eq c ?%)
8902 "%25"
8903 (char-to-string c)))
8904 s "")))
8905 (while (string-match "<" s)
8906 (setq s (replace-match "%3C" t t s)))
8907 (while (string-match ">" s)
8908 (setq s (replace-match "%3E" t t s)))
8909 (while (string-match "@" s)
8910 (setq s (replace-match "%40" t t s)))
8913 ;;;###autoload
8914 (defun org-insert-link-global ()
8915 "Insert a link like Org-mode does.
8916 This command can be called in any mode to insert a link in Org-mode syntax."
8917 (interactive)
8918 (org-load-modules-maybe)
8919 (org-run-like-in-org-mode 'org-insert-link))
8921 (defun org-insert-link (&optional complete-file link-location)
8922 "Insert a link. At the prompt, enter the link.
8924 Completion can be used to insert any of the link protocol prefixes like
8925 http or ftp in use.
8927 The history can be used to select a link previously stored with
8928 `org-store-link'. When the empty string is entered (i.e. if you just
8929 press RET at the prompt), the link defaults to the most recently
8930 stored link. As SPC triggers completion in the minibuffer, you need to
8931 use M-SPC or C-q SPC to force the insertion of a space character.
8933 You will also be prompted for a description, and if one is given, it will
8934 be displayed in the buffer instead of the link.
8936 If there is already a link at point, this command will allow you to edit link
8937 and description parts.
8939 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
8940 be selected using completion. The path to the file will be relative to the
8941 current directory if the file is in the current directory or a subdirectory.
8942 Otherwise, the link will be the absolute path as completed in the minibuffer
8943 \(i.e. normally ~/path/to/file). You can configure this behavior using the
8944 option `org-link-file-path-type'.
8946 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
8947 the current directory or below.
8949 With three \\[universal-argument] prefixes, negate the meaning of
8950 `org-keep-stored-link-after-insertion'.
8952 If `org-make-link-description-function' is non-nil, this function will be
8953 called with the link target, and the result will be the default
8954 link description.
8956 If the LINK-LOCATION parameter is non-nil, this value will be
8957 used as the link location instead of reading one interactively."
8958 (interactive "P")
8959 (let* ((wcf (current-window-configuration))
8960 (region (if (org-region-active-p)
8961 (buffer-substring (region-beginning) (region-end))))
8962 (remove (and region (list (region-beginning) (region-end))))
8963 (desc region)
8964 tmphist ; byte-compile incorrectly complains about this
8965 (link link-location)
8966 entry file all-prefixes)
8967 (cond
8968 (link-location) ; specified by arg, just use it.
8969 ((org-in-regexp org-bracket-link-regexp 1)
8970 ;; We do have a link at point, and we are going to edit it.
8971 (setq remove (list (match-beginning 0) (match-end 0)))
8972 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8973 (setq link (read-string "Link: "
8974 (org-link-unescape
8975 (org-match-string-no-properties 1)))))
8976 ((or (org-in-regexp org-angle-link-re)
8977 (org-in-regexp org-plain-link-re))
8978 ;; Convert to bracket link
8979 (setq remove (list (match-beginning 0) (match-end 0))
8980 link (read-string "Link: "
8981 (org-remove-angle-brackets (match-string 0)))))
8982 ((member complete-file '((4) (16)))
8983 ;; Completing read for file names.
8984 (setq link (org-file-complete-link complete-file)))
8986 ;; Read link, with completion for stored links.
8987 (with-output-to-temp-buffer "*Org Links*"
8988 (princ "Insert a link.
8989 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8990 (when org-stored-links
8991 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8992 (princ (mapconcat
8993 (lambda (x)
8994 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8995 (reverse org-stored-links) "\n"))))
8996 (let ((cw (selected-window)))
8997 (select-window (get-buffer-window "*Org Links*" 'visible))
8998 (with-current-buffer "*Org Links*" (setq truncate-lines t))
8999 (unless (pos-visible-in-window-p (point-max))
9000 (org-fit-window-to-buffer))
9001 (and (window-live-p cw) (select-window cw)))
9002 ;; Fake a link history, containing the stored links.
9003 (setq tmphist (append (mapcar 'car org-stored-links)
9004 org-insert-link-history))
9005 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
9006 (mapcar 'car org-link-abbrev-alist)
9007 org-link-types))
9008 (unwind-protect
9009 (progn
9010 (setq link
9011 (let ((org-completion-use-ido nil)
9012 (org-completion-use-iswitchb nil))
9013 (org-completing-read
9014 "Link: "
9015 (append
9016 (mapcar (lambda (x) (list (concat x ":")))
9017 all-prefixes)
9018 (mapcar 'car org-stored-links))
9019 nil nil nil
9020 'tmphist
9021 (car (car org-stored-links)))))
9022 (if (not (string-match "\\S-" link))
9023 (error "No link selected"))
9024 (if (or (member link all-prefixes)
9025 (and (equal ":" (substring link -1))
9026 (member (substring link 0 -1) all-prefixes)
9027 (setq link (substring link 0 -1))))
9028 (setq link (org-link-try-special-completion link))))
9029 (set-window-configuration wcf)
9030 (kill-buffer "*Org Links*"))
9031 (setq entry (assoc link org-stored-links))
9032 (or entry (push link org-insert-link-history))
9033 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9034 (not org-keep-stored-link-after-insertion))
9035 (setq org-stored-links (delq (assoc link org-stored-links)
9036 org-stored-links)))
9037 (setq desc (or desc (nth 1 entry)))))
9039 (if (string-match org-plain-link-re link)
9040 ;; URL-like link, normalize the use of angular brackets.
9041 (setq link (org-make-link (org-remove-angle-brackets link))))
9043 ;; Check if we are linking to the current file with a search option
9044 ;; If yes, simplify the link by using only the search option.
9045 (when (and buffer-file-name
9046 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9047 (let* ((path (match-string 1 link))
9048 (case-fold-search nil)
9049 (search (match-string 2 link)))
9050 (save-match-data
9051 (if (equal (file-truename buffer-file-name) (file-truename path))
9052 ;; We are linking to this same file, with a search option
9053 (setq link search)))))
9055 ;; Check if we can/should use a relative path. If yes, simplify the link
9056 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9057 (let* ((type (match-string 1 link))
9058 (path (match-string 2 link))
9059 (origpath path)
9060 (case-fold-search nil))
9061 (cond
9062 ((or (eq org-link-file-path-type 'absolute)
9063 (equal complete-file '(16)))
9064 (setq path (abbreviate-file-name (expand-file-name path))))
9065 ((eq org-link-file-path-type 'noabbrev)
9066 (setq path (expand-file-name path)))
9067 ((eq org-link-file-path-type 'relative)
9068 (setq path (file-relative-name path)))
9070 (save-match-data
9071 (if (string-match (concat "^" (regexp-quote
9072 (expand-file-name
9073 (file-name-as-directory
9074 default-directory))))
9075 (expand-file-name path))
9076 ;; We are linking a file with relative path name.
9077 (setq path (substring (expand-file-name path)
9078 (match-end 0)))
9079 (setq path (abbreviate-file-name (expand-file-name path)))))))
9080 (setq link (concat type path))
9081 (if (equal desc origpath)
9082 (setq desc path))))
9084 (if org-make-link-description-function
9085 (setq desc (funcall org-make-link-description-function link desc)))
9087 (setq desc (read-string "Description: " desc))
9088 (unless (string-match "\\S-" desc) (setq desc nil))
9089 (if remove (apply 'delete-region remove))
9090 (insert (org-make-link-string link desc))))
9092 (defun org-link-try-special-completion (type)
9093 "If there is completion support for link type TYPE, offer it."
9094 (let ((fun (intern (concat "org-" type "-complete-link"))))
9095 (if (functionp fun)
9096 (funcall fun)
9097 (read-string "Link (no completion support): " (concat type ":")))))
9099 (defun org-file-complete-link (&optional arg)
9100 "Create a file link using completion."
9101 (let (file link)
9102 (setq file (read-file-name "File: "))
9103 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9104 (pwd1 (file-name-as-directory (abbreviate-file-name
9105 (expand-file-name ".")))))
9106 (cond
9107 ((equal arg '(16))
9108 (setq link (org-make-link
9109 "file:"
9110 (abbreviate-file-name (expand-file-name file)))))
9111 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9112 (setq link (org-make-link "file:" (match-string 1 file))))
9113 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9114 (expand-file-name file))
9115 (setq link (org-make-link
9116 "file:" (match-string 1 (expand-file-name file)))))
9117 (t (setq link (org-make-link "file:" file)))))
9118 link))
9120 (defun org-completing-read (&rest args)
9121 "Completing-read with SPACE being a normal character."
9122 (let ((minibuffer-local-completion-map
9123 (copy-keymap minibuffer-local-completion-map)))
9124 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9125 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9126 (apply 'org-icompleting-read args)))
9128 (defun org-completing-read-no-i (&rest args)
9129 (let (org-completion-use-ido org-completion-use-iswitchb)
9130 (apply 'org-completing-read args)))
9132 (defun org-iswitchb-completing-read (prompt choices &rest args)
9133 "Use iswitch as a completing-read replacement to choose from choices.
9134 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9135 from."
9136 (let* ((iswitchb-use-virtual-buffers nil)
9137 (iswitchb-make-buflist-hook
9138 (lambda ()
9139 (setq iswitchb-temp-buflist choices))))
9140 (iswitchb-read-buffer prompt)))
9142 (defun org-icompleting-read (&rest args)
9143 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9144 (org-without-partial-completion
9145 (if (and org-completion-use-ido
9146 (fboundp 'ido-completing-read)
9147 (boundp 'ido-mode) ido-mode
9148 (listp (second args)))
9149 (let ((ido-enter-matching-directory nil))
9150 (apply 'ido-completing-read (concat (car args))
9151 (if (consp (car (nth 1 args)))
9152 (mapcar 'car (nth 1 args))
9153 (nth 1 args))
9154 (cddr args)))
9155 (if (and org-completion-use-iswitchb
9156 (boundp 'iswitchb-mode) iswitchb-mode
9157 (listp (second args)))
9158 (apply 'org-iswitchb-completing-read (concat (car args))
9159 (if (consp (car (nth 1 args)))
9160 (mapcar 'car (nth 1 args))
9161 (nth 1 args))
9162 (cddr args))
9163 (apply 'completing-read args)))))
9165 (defun org-extract-attributes (s)
9166 "Extract the attributes cookie from a string and set as text property."
9167 (let (a attr (start 0) key value)
9168 (save-match-data
9169 (when (string-match "{{\\([^}]+\\)}}$" s)
9170 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9171 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9172 (setq key (match-string 1 a) value (match-string 2 a)
9173 start (match-end 0)
9174 attr (plist-put attr (intern key) value))))
9175 (org-add-props s nil 'org-attr attr))
9178 (defun org-extract-attributes-from-string (tag)
9179 (let (key value attr)
9180 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9181 (setq key (match-string 1 tag) value (match-string 2 tag)
9182 tag (replace-match "" t t tag)
9183 attr (plist-put attr (intern key) value)))
9184 (cons tag attr)))
9186 (defun org-attributes-to-string (plist)
9187 "Format a property list into an HTML attribute list."
9188 (let ((s "") key value)
9189 (while plist
9190 (setq key (pop plist) value (pop plist))
9191 (and value
9192 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9195 ;;; Opening/following a link
9197 (defvar org-link-search-failed nil)
9199 (defvar org-open-link-functions nil
9200 "Hook for functions finding a plain text link.
9201 These functions must take a single argument, the link content.
9202 They will be called for links that look like [[link text][description]]
9203 when LINK TEXT does not have a protocol like \"http:\" and does not look
9204 like a filename (e.g. \"./blue.png\").
9206 These functions will be called *before* Org attempts to resolve the
9207 link by doing text searches in the current buffer - so if you want a
9208 link \"[[target]]\" to still find \"<<target>>\", your function should
9209 handle this as a special case.
9211 When the function does handle the link, it must return a non-nil value.
9212 If it decides that it is not responsible for this link, it must return
9213 nil to indicate that that Org-mode can continue with other options
9214 like exact and fuzzy text search.")
9216 (defun org-next-link ()
9217 "Move forward to the next link.
9218 If the link is in hidden text, expose it."
9219 (interactive)
9220 (when (and org-link-search-failed (eq this-command last-command))
9221 (goto-char (point-min))
9222 (message "Link search wrapped back to beginning of buffer"))
9223 (setq org-link-search-failed nil)
9224 (let* ((pos (point))
9225 (ct (org-context))
9226 (a (assoc :link ct)))
9227 (if a (goto-char (nth 2 a)))
9228 (if (re-search-forward org-any-link-re nil t)
9229 (progn
9230 (goto-char (match-beginning 0))
9231 (if (outline-invisible-p) (org-show-context)))
9232 (goto-char pos)
9233 (setq org-link-search-failed t)
9234 (error "No further link found"))))
9236 (defun org-previous-link ()
9237 "Move backward to the previous link.
9238 If the link is in hidden text, expose it."
9239 (interactive)
9240 (when (and org-link-search-failed (eq this-command last-command))
9241 (goto-char (point-max))
9242 (message "Link search wrapped back to end of buffer"))
9243 (setq org-link-search-failed nil)
9244 (let* ((pos (point))
9245 (ct (org-context))
9246 (a (assoc :link ct)))
9247 (if a (goto-char (nth 1 a)))
9248 (if (re-search-backward org-any-link-re nil t)
9249 (progn
9250 (goto-char (match-beginning 0))
9251 (if (outline-invisible-p) (org-show-context)))
9252 (goto-char pos)
9253 (setq org-link-search-failed t)
9254 (error "No further link found"))))
9256 (defun org-translate-link (s)
9257 "Translate a link string if a translation function has been defined."
9258 (if (and org-link-translation-function
9259 (fboundp org-link-translation-function)
9260 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9261 (progn
9262 (setq s (funcall org-link-translation-function
9263 (match-string 1) (match-string 2)))
9264 (concat (car s) ":" (cdr s)))
9267 (defun org-translate-link-from-planner (type path)
9268 "Translate a link from Emacs Planner syntax so that Org can follow it.
9269 This is still an experimental function, your mileage may vary."
9270 (cond
9271 ((member type '("http" "https" "news" "ftp"))
9272 ;; standard Internet links are the same.
9273 nil)
9274 ((and (equal type "irc") (string-match "^//" path))
9275 ;; Planner has two / at the beginning of an irc link, we have 1.
9276 ;; We should have zero, actually....
9277 (setq path (substring path 1)))
9278 ((and (equal type "lisp") (string-match "^/" path))
9279 ;; Planner has a slash, we do not.
9280 (setq type "elisp" path (substring path 1)))
9281 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9282 ;; A typical message link. Planner has the id after the final slash,
9283 ;; we separate it with a hash mark
9284 (setq path (concat (match-string 1 path) "#"
9285 (org-remove-angle-brackets (match-string 2 path)))))
9287 (cons type path))
9289 (defun org-find-file-at-mouse (ev)
9290 "Open file link or URL at mouse."
9291 (interactive "e")
9292 (mouse-set-point ev)
9293 (org-open-at-point 'in-emacs))
9295 (defun org-open-at-mouse (ev)
9296 "Open file link or URL at mouse.
9297 See the docstring of `org-open-file' for details."
9298 (interactive "e")
9299 (mouse-set-point ev)
9300 (if (eq major-mode 'org-agenda-mode)
9301 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9302 (org-open-at-point))
9304 (defvar org-window-config-before-follow-link nil
9305 "The window configuration before following a link.
9306 This is saved in case the need arises to restore it.")
9308 (defvar org-open-link-marker (make-marker)
9309 "Marker pointing to the location where `org-open-at-point; was called.")
9311 ;;;###autoload
9312 (defun org-open-at-point-global ()
9313 "Follow a link like Org-mode does.
9314 This command can be called in any mode to follow a link that has
9315 Org-mode syntax."
9316 (interactive)
9317 (org-run-like-in-org-mode 'org-open-at-point))
9319 ;;;###autoload
9320 (defun org-open-link-from-string (s &optional arg reference-buffer)
9321 "Open a link in the string S, as if it was in Org-mode."
9322 (interactive "sLink: \nP")
9323 (let ((reference-buffer (or reference-buffer (current-buffer))))
9324 (with-temp-buffer
9325 (let ((org-inhibit-startup t))
9326 (org-mode)
9327 (insert s)
9328 (goto-char (point-min))
9329 (when reference-buffer
9330 (setq org-link-abbrev-alist-local
9331 (with-current-buffer reference-buffer
9332 org-link-abbrev-alist-local)))
9333 (org-open-at-point arg reference-buffer)))))
9335 (defvar org-open-at-point-functions nil
9336 "Hook that is run when following a link at point.
9338 Functions in this hook must return t if they identify and follow
9339 a link at point. If they don't find anything interesting at point,
9340 they must return nil.")
9342 (defun org-open-at-point (&optional arg reference-buffer)
9343 "Open link at or after point.
9344 If there is no link at point, this function will search forward up to
9345 the end of the current line.
9346 Normally, files will be opened by an appropriate application. If the
9347 optional prefix argument ARG is non-nil, Emacs will visit the file.
9348 With a double prefix argument, try to open outside of Emacs, in the
9349 application the system uses for this file type."
9350 (interactive "P")
9351 ;; if in a code block, then open the block's results
9352 (unless (call-interactively #'org-babel-open-src-block-result)
9353 (org-load-modules-maybe)
9354 (move-marker org-open-link-marker (point))
9355 (setq org-window-config-before-follow-link (current-window-configuration))
9356 (org-remove-occur-highlights nil nil t)
9357 (cond
9358 ((and (org-on-heading-p)
9359 (not (org-in-regexp
9360 (concat org-plain-link-re "\\|"
9361 org-bracket-link-regexp "\\|"
9362 org-angle-link-re "\\|"
9363 "[ \t]:[^ \t\n]+:[ \t]*$")))
9364 (not (get-text-property (point) 'org-linked-text)))
9365 (or (org-offer-links-in-entry arg)
9366 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9367 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9368 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9369 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9370 (not (org-in-regexp org-bracket-link-regexp)))
9371 (org-footnote-action))
9373 (let (type path link line search (pos (point)))
9374 (catch 'match
9375 (save-excursion
9376 (skip-chars-forward "^]\n\r")
9377 (when (org-in-regexp org-bracket-link-regexp 1)
9378 (setq link (org-extract-attributes
9379 (org-link-unescape (org-match-string-no-properties 1))))
9380 (while (string-match " *\n *" link)
9381 (setq link (replace-match " " t t link)))
9382 (setq link (org-link-expand-abbrev link))
9383 (cond
9384 ((or (file-name-absolute-p link)
9385 (string-match "^\\.\\.?/" link))
9386 (setq type "file" path link))
9387 ((string-match org-link-re-with-space3 link)
9388 (setq type (match-string 1 link) path (match-string 2 link)))
9389 (t (setq type "thisfile" path link)))
9390 (throw 'match t)))
9392 (when (get-text-property (point) 'org-linked-text)
9393 (setq type "thisfile"
9394 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9395 (1+ (point)) (point))
9396 path (buffer-substring
9397 (or (previous-single-property-change pos 'org-linked-text)
9398 (point-min))
9399 (or (next-single-property-change pos 'org-linked-text)
9400 (point-max))))
9401 (throw 'match t))
9403 (save-excursion
9404 (when (or (org-in-regexp org-angle-link-re)
9405 (org-in-regexp org-plain-link-re))
9406 (setq type (match-string 1)
9407 path (org-link-unescape (match-string 2)))
9408 (throw 'match t)))
9409 (save-excursion
9410 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9411 (setq type "tags"
9412 path (match-string 1))
9413 (while (string-match ":" path)
9414 (setq path (replace-match "+" t t path)))
9415 (throw 'match t)))
9416 (when (org-in-regexp "<\\([^><\n]+\\)>")
9417 (setq type "tree-match"
9418 path (match-string 1))
9419 (throw 'match t)))
9420 (unless path
9421 (error "No link found"))
9423 ;; switch back to reference buffer
9424 ;; needed when if called in a temporary buffer through
9425 ;; org-open-link-from-string
9426 (with-current-buffer (or reference-buffer (current-buffer))
9428 ;; Remove any trailing spaces in path
9429 (if (string-match " +\\'" path)
9430 (setq path (replace-match "" t t path)))
9431 (if (and org-link-translation-function
9432 (fboundp org-link-translation-function))
9433 ;; Check if we need to translate the link
9434 (let ((tmp (funcall org-link-translation-function type path)))
9435 (setq type (car tmp) path (cdr tmp))))
9437 (cond
9439 ((assoc type org-link-protocols)
9440 (funcall (nth 1 (assoc type org-link-protocols)) path))
9442 ((equal type "mailto")
9443 (let ((cmd (car org-link-mailto-program))
9444 (args (cdr org-link-mailto-program)) args1
9445 (address path) (subject "") a)
9446 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9447 (setq address (match-string 1 path)
9448 subject (org-link-escape (match-string 2 path))))
9449 (while args
9450 (cond
9451 ((not (stringp (car args))) (push (pop args) args1))
9452 (t (setq a (pop args))
9453 (if (string-match "%a" a)
9454 (setq a (replace-match address t t a)))
9455 (if (string-match "%s" a)
9456 (setq a (replace-match subject t t a)))
9457 (push a args1))))
9458 (apply cmd (nreverse args1))))
9460 ((member type '("http" "https" "ftp" "news"))
9461 (browse-url (concat type ":" (org-link-escape
9462 path org-link-escape-chars-browser))))
9464 ((string= type "doi")
9465 (browse-url (concat "http://dx.doi.org/"
9466 (org-link-escape
9467 path org-link-escape-chars-browser))))
9469 ((member type '("message"))
9470 (browse-url (concat type ":" path)))
9472 ((string= type "tags")
9473 (org-tags-view arg path))
9475 ((string= type "tree-match")
9476 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9478 ((string= type "file")
9479 (if (string-match "::\\([0-9]+\\)\\'" path)
9480 (setq line (string-to-number (match-string 1 path))
9481 path (substring path 0 (match-beginning 0)))
9482 (if (string-match "::\\(.+\\)\\'" path)
9483 (setq search (match-string 1 path)
9484 path (substring path 0 (match-beginning 0)))))
9485 (if (string-match "[*?{]" (file-name-nondirectory path))
9486 (dired path)
9487 (org-open-file path arg line search)))
9489 ((string= type "shell")
9490 (let ((cmd path))
9491 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9492 (string-match org-confirm-shell-link-not-regexp cmd))
9493 (not org-confirm-shell-link-function)
9494 (funcall org-confirm-shell-link-function
9495 (format "Execute \"%s\" in shell? "
9496 (org-add-props cmd nil
9497 'face 'org-warning))))
9498 (progn
9499 (message "Executing %s" cmd)
9500 (shell-command cmd))
9501 (error "Abort"))))
9503 ((string= type "elisp")
9504 (let ((cmd path))
9505 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9506 (string-match org-confirm-elisp-link-not-regexp cmd))
9507 (not org-confirm-elisp-link-function)
9508 (funcall org-confirm-elisp-link-function
9509 (format "Execute \"%s\" as elisp? "
9510 (org-add-props cmd nil
9511 'face 'org-warning))))
9512 (message "%s => %s" cmd
9513 (if (equal (string-to-char cmd) ?\()
9514 (eval (read cmd))
9515 (call-interactively (read cmd))))
9516 (error "Abort"))))
9518 ((and (string= type "thisfile")
9519 (run-hook-with-args-until-success
9520 'org-open-link-functions path)))
9522 ((string= type "thisfile")
9523 (if arg
9524 (switch-to-buffer-other-window
9525 (org-get-buffer-for-internal-link (current-buffer)))
9526 (org-mark-ring-push))
9527 (let ((cmd `(org-link-search
9528 ,path
9529 ,(cond ((equal arg '(4)) ''occur)
9530 ((equal arg '(16)) ''org-occur)
9531 (t nil))
9532 ,pos)))
9533 (condition-case nil (let ((org-link-search-inhibit-query t))
9534 (eval cmd))
9535 (error (progn (widen) (eval cmd))))))
9538 (browse-url-at-point)))))))
9539 (move-marker org-open-link-marker nil)
9540 (run-hook-with-args 'org-follow-link-hook)))
9542 (defun org-offer-links-in-entry (&optional nth zero)
9543 "Offer links in the current entry and follow the selected link.
9544 If there is only one link, follow it immediately as well.
9545 If NTH is an integer, immediately pick the NTH link found.
9546 If ZERO is a string, check also this string for a link, and if
9547 there is one, offer it as link number zero."
9548 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9549 "\\(" org-angle-link-re "\\)\\|"
9550 "\\(" org-plain-link-re "\\)"))
9551 (cnt ?0)
9552 (in-emacs (if (integerp nth) nil nth))
9553 have-zero end links link c)
9554 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9555 (push (match-string 0 zero) links)
9556 (setq cnt (1- cnt) have-zero t))
9557 (save-excursion
9558 (org-back-to-heading t)
9559 (setq end (save-excursion (outline-next-heading) (point)))
9560 (while (re-search-forward re end t)
9561 (push (match-string 0) links))
9562 (setq links (org-uniquify (reverse links))))
9564 (cond
9565 ((null links)
9566 (message "No links"))
9567 ((equal (length links) 1)
9568 (setq link (list (car links))))
9569 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9570 (setq link (nth (if have-zero nth (1- nth)) links)))
9571 (t ; we have to select a link
9572 (save-excursion
9573 (save-window-excursion
9574 (delete-other-windows)
9575 (with-output-to-temp-buffer "*Select Link*"
9576 (mapc (lambda (l)
9577 (if (not (string-match org-bracket-link-regexp l))
9578 (princ (format "[%c] %s\n" (incf cnt)
9579 (org-remove-angle-brackets l)))
9580 (if (match-end 3)
9581 (princ (format "[%c] %s (%s)\n" (incf cnt)
9582 (match-string 3 l) (match-string 1 l)))
9583 (princ (format "[%c] %s\n" (incf cnt)
9584 (match-string 1 l))))))
9585 links))
9586 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9587 (message "Select link to open, RET to open all:")
9588 (setq c (read-char-exclusive))
9589 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9590 (when (equal c ?q) (error "Abort"))
9591 (if (equal c ?\C-m)
9592 (setq link links)
9593 (setq nth (- c ?0))
9594 (if have-zero (setq nth (1+ nth)))
9595 (unless (and (integerp nth) (>= (length links) nth))
9596 (error "Invalid link selection"))
9597 (setq link (list (nth (1- nth) links))))))
9598 (if link
9599 (let ((buf (current-buffer)))
9600 (dolist (l link)
9601 (org-open-link-from-string l in-emacs buf))
9603 nil)))
9605 ;; Add special file links that specify the way of opening
9607 (org-add-link-type "file+sys" 'org-open-file-with-system)
9608 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9609 (defun org-open-file-with-system (path)
9610 "Open file at PATH using the system way of opening it."
9611 (org-open-file path 'system))
9612 (defun org-open-file-with-emacs (path)
9613 "Open file at PATH in Emacs."
9614 (org-open-file path 'emacs))
9615 (defun org-remove-file-link-modifiers ()
9616 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9617 (goto-char (point-min))
9618 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9619 (org-if-unprotected
9620 (replace-match "file:" t t))))
9621 (eval-after-load "org-exp"
9622 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9623 'org-remove-file-link-modifiers))
9625 ;;;; Time estimates
9627 (defun org-get-effort (&optional pom)
9628 "Get the effort estimate for the current entry."
9629 (org-entry-get pom org-effort-property))
9631 ;;; File search
9633 (defvar org-create-file-search-functions nil
9634 "List of functions to construct the right search string for a file link.
9635 These functions are called in turn with point at the location to
9636 which the link should point.
9638 A function in the hook should first test if it would like to
9639 handle this file type, for example by checking the `major-mode'
9640 or the file extension. If it decides not to handle this file, it
9641 should just return nil to give other functions a chance. If it
9642 does handle the file, it must return the search string to be used
9643 when following the link. The search string will be part of the
9644 file link, given after a double colon, and `org-open-at-point'
9645 will automatically search for it. If special measures must be
9646 taken to make the search successful, another function should be
9647 added to the companion hook `org-execute-file-search-functions',
9648 which see.
9650 A function in this hook may also use `setq' to set the variable
9651 `description' to provide a suggestion for the descriptive text to
9652 be used for this link when it gets inserted into an Org-mode
9653 buffer with \\[org-insert-link].")
9655 (defvar org-execute-file-search-functions nil
9656 "List of functions to execute a file search triggered by a link.
9658 Functions added to this hook must accept a single argument, the
9659 search string that was part of the file link, the part after the
9660 double colon. The function must first check if it would like to
9661 handle this search, for example by checking the `major-mode' or
9662 the file extension. If it decides not to handle this search, it
9663 should just return nil to give other functions a chance. If it
9664 does handle the search, it must return a non-nil value to keep
9665 other functions from trying.
9667 Each function can access the current prefix argument through the
9668 variable `current-prefix-argument'. Note that a single prefix is
9669 used to force opening a link in Emacs, so it may be good to only
9670 use a numeric or double prefix to guide the search function.
9672 In case this is needed, a function in this hook can also restore
9673 the window configuration before `org-open-at-point' was called using:
9675 (set-window-configuration org-window-config-before-follow-link)")
9677 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9678 (defun org-link-search (s &optional type avoid-pos)
9679 "Search for a link search option.
9680 If S is surrounded by forward slashes, it is interpreted as a
9681 regular expression. In org-mode files, this will create an `org-occur'
9682 sparse tree. In ordinary files, `occur' will be used to list matches.
9683 If the current buffer is in `dired-mode', grep will be used to search
9684 in all files. If AVOID-POS is given, ignore matches near that position."
9685 (let ((case-fold-search t)
9686 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9687 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9688 (append '(("") (" ") ("\t") ("\n"))
9689 org-emphasis-alist)
9690 "\\|") "\\)"))
9691 (pos (point))
9692 (pre nil) (post nil)
9693 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9694 (cond
9695 ;; First check if there are any special search functions
9696 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9697 ;; Now try the builtin stuff
9698 ((and (equal (string-to-char s0) ?#)
9699 (> (length s0) 1)
9700 (save-excursion
9701 (goto-char (point-min))
9702 (and
9703 (re-search-forward
9704 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9705 (setq type 'dedicated
9706 pos (match-beginning 0))))
9707 ;; There is an exact target for this
9708 (goto-char pos)
9709 (org-back-to-heading t)))
9710 ((save-excursion
9711 (goto-char (point-min))
9712 (and
9713 (re-search-forward
9714 (concat "<<" (regexp-quote s0) ">>") nil t)
9715 (setq type 'dedicated
9716 pos (match-beginning 0))))
9717 ;; There is an exact target for this
9718 (goto-char pos))
9719 ((and (string-match "^(\\(.*\\))$" s0)
9720 (save-excursion
9721 (goto-char (point-min))
9722 (and
9723 (re-search-forward
9724 (concat "[^[]" (regexp-quote
9725 (format org-coderef-label-format
9726 (match-string 1 s0))))
9727 nil t)
9728 (setq type 'dedicated
9729 pos (1+ (match-beginning 0))))))
9730 ;; There is a coderef target for this
9731 (goto-char pos))
9732 ((string-match "^/\\(.*\\)/$" s)
9733 ;; A regular expression
9734 (cond
9735 ((org-mode-p)
9736 (org-occur (match-string 1 s)))
9737 ;;((eq major-mode 'dired-mode)
9738 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9739 (t (org-do-occur (match-string 1 s)))))
9740 ((and (org-mode-p) org-link-search-must-match-exact-headline)
9741 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9742 (goto-char (point-min))
9743 (cond
9744 ((let (case-fold-search)
9745 (re-search-forward (format org-complex-heading-regexp-format
9746 (regexp-quote s))
9747 nil t))
9748 ;; OK, found a match
9749 (setq type 'dedicated)
9750 (goto-char (match-beginning 0)))
9751 ((and (not org-link-search-inhibit-query)
9752 (eq org-link-search-must-match-exact-headline 'query-to-create)
9753 (y-or-n-p "No match - create this as a new heading? "))
9754 (goto-char (point-max))
9755 (or (bolp) (newline))
9756 (insert "* " s "\n")
9757 (beginning-of-line 0))
9759 (goto-char pos)
9760 (error "No match"))))
9762 ;; A normal search string
9763 (when (equal (string-to-char s) ?*)
9764 ;; Anchor on headlines, post may include tags.
9765 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9766 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9767 s (substring s 1)))
9768 (remove-text-properties
9769 0 (length s)
9770 '(face nil mouse-face nil keymap nil fontified nil) s)
9771 ;; Make a series of regular expressions to find a match
9772 (setq words (org-split-string s "[ \n\r\t]+")
9774 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9775 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9776 "\\)" markers)
9777 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9778 re2a (concat "[ \t\r\n]" re2a_)
9779 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9780 re4 (concat "[^a-zA-Z_]" re4_)
9782 re1 (concat pre re2 post)
9783 re3 (concat pre (if pre re4_ re4) post)
9784 re5 (concat pre ".*" re4)
9785 re2 (concat pre re2)
9786 re2a (concat pre (if pre re2a_ re2a))
9787 re4 (concat pre (if pre re4_ re4))
9788 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9789 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9790 re5 "\\)"
9792 (cond
9793 ((eq type 'org-occur) (org-occur reall))
9794 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9795 (t (goto-char (point-min))
9796 (setq type 'fuzzy)
9797 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9798 (org-search-not-self 1 re1 nil t)
9799 (org-search-not-self 1 re2 nil t)
9800 (org-search-not-self 1 re2a nil t)
9801 (org-search-not-self 1 re3 nil t)
9802 (org-search-not-self 1 re4 nil t)
9803 (org-search-not-self 1 re5 nil t)
9805 (goto-char (match-beginning 1))
9806 (goto-char pos)
9807 (error "No match"))))))
9808 (and (org-mode-p) (org-show-context 'link-search))
9809 type))
9811 (defun org-search-not-self (group &rest args)
9812 "Execute `re-search-forward', but only accept matches that do not
9813 enclose the position of `org-open-link-marker'."
9814 (let ((m org-open-link-marker))
9815 (catch 'exit
9816 (while (apply 're-search-forward args)
9817 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9818 (goto-char (match-end group))
9819 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9820 (> (match-beginning 0) (marker-position m))
9821 (< (match-end 0) (marker-position m)))
9822 (save-match-data
9823 (or (not (org-in-regexp
9824 org-bracket-link-analytic-regexp 1))
9825 (not (match-end 4)) ; no description
9826 (and (<= (match-beginning 4) (point))
9827 (>= (match-end 4) (point))))))
9828 (throw 'exit (point))))))))
9830 (defun org-get-buffer-for-internal-link (buffer)
9831 "Return a buffer to be used for displaying the link target of internal links."
9832 (cond
9833 ((not org-display-internal-link-with-indirect-buffer)
9834 buffer)
9835 ((string-match "(Clone)$" (buffer-name buffer))
9836 (message "Buffer is already a clone, not making another one")
9837 ;; we also do not modify visibility in this case
9838 buffer)
9839 (t ; make a new indirect buffer for displaying the link
9840 (let* ((bn (buffer-name buffer))
9841 (ibn (concat bn "(Clone)"))
9842 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9843 (with-current-buffer ib (org-overview))
9844 ib))))
9846 (defun org-do-occur (regexp &optional cleanup)
9847 "Call the Emacs command `occur'.
9848 If CLEANUP is non-nil, remove the printout of the regular expression
9849 in the *Occur* buffer. This is useful if the regex is long and not useful
9850 to read."
9851 (occur regexp)
9852 (when cleanup
9853 (let ((cwin (selected-window)) win beg end)
9854 (when (setq win (get-buffer-window "*Occur*"))
9855 (select-window win))
9856 (goto-char (point-min))
9857 (when (re-search-forward "match[a-z]+" nil t)
9858 (setq beg (match-end 0))
9859 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9860 (setq end (1- (match-beginning 0)))))
9861 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9862 (goto-char (point-min))
9863 (select-window cwin))))
9865 ;;; The mark ring for links jumps
9867 (defvar org-mark-ring nil
9868 "Mark ring for positions before jumps in Org-mode.")
9869 (defvar org-mark-ring-last-goto nil
9870 "Last position in the mark ring used to go back.")
9871 ;; Fill and close the ring
9872 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9873 (loop for i from 1 to org-mark-ring-length do
9874 (push (make-marker) org-mark-ring))
9875 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9876 org-mark-ring)
9878 (defun org-mark-ring-push (&optional pos buffer)
9879 "Put the current position or POS into the mark ring and rotate it."
9880 (interactive)
9881 (setq pos (or pos (point)))
9882 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9883 (move-marker (car org-mark-ring)
9884 (or pos (point))
9885 (or buffer (current-buffer)))
9886 (message "%s"
9887 (substitute-command-keys
9888 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9890 (defun org-mark-ring-goto (&optional n)
9891 "Jump to the previous position in the mark ring.
9892 With prefix arg N, jump back that many stored positions. When
9893 called several times in succession, walk through the entire ring.
9894 Org-mode commands jumping to a different position in the current file,
9895 or to another Org-mode file, automatically push the old position
9896 onto the ring."
9897 (interactive "p")
9898 (let (p m)
9899 (if (eq last-command this-command)
9900 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9901 (setq p org-mark-ring))
9902 (setq org-mark-ring-last-goto p)
9903 (setq m (car p))
9904 (org-pop-to-buffer-same-window (marker-buffer m))
9905 (goto-char m)
9906 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9908 (defun org-remove-angle-brackets (s)
9909 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9910 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9912 (defun org-add-angle-brackets (s)
9913 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9914 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9916 (defun org-remove-double-quotes (s)
9917 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9918 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
9921 ;;; Following specific links
9923 (defun org-follow-timestamp-link ()
9924 (cond
9925 ((org-at-date-range-p t)
9926 (let ((org-agenda-start-on-weekday)
9927 (t1 (match-string 1))
9928 (t2 (match-string 2)))
9929 (setq t1 (time-to-days (org-time-string-to-time t1))
9930 t2 (time-to-days (org-time-string-to-time t2)))
9931 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9932 ((org-at-timestamp-p t)
9933 (org-agenda-list nil (time-to-days (org-time-string-to-time
9934 (substring (match-string 1) 0 10)))
9936 (t (error "This should not happen"))))
9939 ;;; Following file links
9940 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
9941 (declare-function mailcap-extension-to-mime "mailcap" (extn))
9942 (declare-function mailcap-mime-info
9943 "mailcap" (string &optional request no-decode))
9944 (defvar org-wait nil)
9945 (defun org-open-file (path &optional in-emacs line search)
9946 "Open the file at PATH.
9947 First, this expands any special file name abbreviations. Then the
9948 configuration variable `org-file-apps' is checked if it contains an
9949 entry for this file type, and if yes, the corresponding command is launched.
9951 If no application is found, Emacs simply visits the file.
9953 With optional prefix argument IN-EMACS, Emacs will visit the file.
9954 With a double \\[universal-argument] \\[universal-argument] \
9955 prefix arg, Org tries to avoid opening in Emacs
9956 and to use an external application to visit the file.
9958 Optional LINE specifies a line to go to, optional SEARCH a string
9959 to search for. If LINE or SEARCH is given, the file will be
9960 opened in Emacs, unless an entry from org-file-apps that makes
9961 use of groups in a regexp matches.
9963 If you want to change the way frames are used when following a
9964 link, please customize `org-link-frame-setup'.
9966 If the file does not exist, an error is thrown."
9967 (let* ((file (if (equal path "")
9968 buffer-file-name
9969 (substitute-in-file-name (expand-file-name path))))
9970 (file-apps (append org-file-apps (org-default-apps)))
9971 (apps (org-remove-if
9972 'org-file-apps-entry-match-against-dlink-p file-apps))
9973 (apps-dlink (org-remove-if-not
9974 'org-file-apps-entry-match-against-dlink-p file-apps))
9975 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9976 (dirp (if remp nil (file-directory-p file)))
9977 (file (if (and dirp org-open-directory-means-index-dot-org)
9978 (concat (file-name-as-directory file) "index.org")
9979 file))
9980 (a-m-a-p (assq 'auto-mode apps))
9981 (dfile (downcase file))
9982 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
9983 (link (cond ((and (eq line nil)
9984 (eq search nil))
9985 file)
9986 (line
9987 (concat file "::" (number-to-string line)))
9988 (search
9989 (concat file "::" search))))
9990 (dlink (downcase link))
9991 (old-buffer (current-buffer))
9992 (old-pos (point))
9993 (old-mode major-mode)
9994 ext cmd link-match-data)
9995 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9996 (setq ext (match-string 1 dfile))
9997 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9998 (setq ext (match-string 1 dfile))))
9999 (cond
10000 ((member in-emacs '((16) system))
10001 (setq cmd (cdr (assoc 'system apps))))
10002 (in-emacs (setq cmd 'emacs))
10004 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10005 (and dirp (cdr (assoc 'directory apps)))
10006 ; first, try matching against apps-dlink
10007 ; if we get a match here, store the match data for later
10008 (let ((match (assoc-default dlink apps-dlink
10009 'string-match)))
10010 (if match
10011 (progn (setq link-match-data (match-data))
10012 match)
10013 (progn (setq in-emacs (or in-emacs line search))
10014 nil))) ; if we have no match in apps-dlink,
10015 ; always open the file in emacs if line or search
10016 ; is given (for backwards compatibility)
10017 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10018 'string-match)
10019 (cdr (assoc ext apps))
10020 (cdr (assoc t apps))))))
10021 (when (eq cmd 'system)
10022 (setq cmd (cdr (assoc 'system apps))))
10023 (when (eq cmd 'default)
10024 (setq cmd (cdr (assoc t apps))))
10025 (when (eq cmd 'mailcap)
10026 (require 'mailcap)
10027 (mailcap-parse-mailcaps)
10028 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10029 (command (mailcap-mime-info mime-type)))
10030 (if (stringp command)
10031 (setq cmd command)
10032 (setq cmd 'emacs))))
10033 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10034 (not (file-exists-p file))
10035 (not org-open-non-existing-files))
10036 (error "No such file: %s" file))
10037 (cond
10038 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10039 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10040 (while (string-match "['\"]%s['\"]" cmd)
10041 (setq cmd (replace-match "%s" t t cmd)))
10042 (while (string-match "%s" cmd)
10043 (setq cmd (replace-match
10044 (save-match-data
10045 (shell-quote-argument
10046 (convert-standard-filename file)))
10047 t t cmd)))
10049 ;; Replace "%1", "%2" etc. in command with group matches from regex
10050 (save-match-data
10051 (let ((match-index 1)
10052 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10053 (set-match-data link-match-data)
10054 (while (<= match-index number-of-groups)
10055 (let ((regex (concat "%" (number-to-string match-index)))
10056 (replace-with (match-string match-index dlink)))
10057 (while (string-match regex cmd)
10058 (setq cmd (replace-match replace-with t t cmd))))
10059 (setq match-index (+ match-index 1)))))
10061 (save-window-excursion
10062 (start-process-shell-command cmd nil cmd)
10063 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10065 ((or (stringp cmd)
10066 (eq cmd 'emacs))
10067 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10068 (widen)
10069 (if line (org-goto-line line)
10070 (if search (org-link-search search))))
10071 ((consp cmd)
10072 (let ((file (convert-standard-filename file)))
10073 (save-match-data
10074 (set-match-data link-match-data)
10075 (eval cmd))))
10076 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10077 (and (org-mode-p) (eq old-mode 'org-mode)
10078 (or (not (equal old-buffer (current-buffer)))
10079 (not (equal old-pos (point))))
10080 (org-mark-ring-push old-pos old-buffer))))
10082 (defun org-file-apps-entry-match-against-dlink-p (entry)
10083 "This function returns non-nil if `entry' uses a regular
10084 expression which should be matched against the whole link by
10085 org-open-file.
10087 It assumes that is the case when the entry uses a regular
10088 expression which has at least one grouping construct and the
10089 action is either a lisp form or a command string containing
10090 '%1', i.e. using at least one subexpression match as a
10091 parameter."
10092 (let ((selector (car entry))
10093 (action (cdr entry)))
10094 (if (stringp selector)
10095 (and (> (regexp-opt-depth selector) 0)
10096 (or (and (stringp action)
10097 (string-match "%[0-9]" action))
10098 (consp action)))
10099 nil)))
10101 (defun org-default-apps ()
10102 "Return the default applications for this operating system."
10103 (cond
10104 ((eq system-type 'darwin)
10105 org-file-apps-defaults-macosx)
10106 ((eq system-type 'windows-nt)
10107 org-file-apps-defaults-windowsnt)
10108 (t org-file-apps-defaults-gnu)))
10110 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10111 "Convert extensions to regular expressions in the cars of LIST.
10112 Also, weed out any non-string entries, because the return value is used
10113 only for regexp matching.
10114 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10115 point to the symbol `emacs', indicating that the file should
10116 be opened in Emacs."
10117 (append
10118 (delq nil
10119 (mapcar (lambda (x)
10120 (if (not (stringp (car x)))
10122 (if (string-match "\\W" (car x))
10124 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10125 list))
10126 (if add-auto-mode
10127 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10129 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10130 (defun org-file-remote-p (file)
10131 "Test whether FILE specifies a location on a remote system.
10132 Return non-nil if the location is indeed remote.
10134 For example, the filename \"/user@host:/foo\" specifies a location
10135 on the system \"/user@host:\"."
10136 (cond ((fboundp 'file-remote-p)
10137 (file-remote-p file))
10138 ((fboundp 'tramp-handle-file-remote-p)
10139 (tramp-handle-file-remote-p file))
10140 ((and (boundp 'ange-ftp-name-format)
10141 (string-match (car ange-ftp-name-format) file))
10143 (t nil)))
10146 ;;;; Refiling
10148 (defun org-get-org-file ()
10149 "Read a filename, with default directory `org-directory'."
10150 (let ((default (or org-default-notes-file remember-data-file)))
10151 (read-file-name (format "File name [%s]: " default)
10152 (file-name-as-directory org-directory)
10153 default)))
10155 (defun org-notes-order-reversed-p ()
10156 "Check if the current file should receive notes in reversed order."
10157 (cond
10158 ((not org-reverse-note-order) nil)
10159 ((eq t org-reverse-note-order) t)
10160 ((not (listp org-reverse-note-order)) nil)
10161 (t (catch 'exit
10162 (let ((all org-reverse-note-order)
10163 entry)
10164 (while (setq entry (pop all))
10165 (if (string-match (car entry) buffer-file-name)
10166 (throw 'exit (cdr entry))))
10167 nil)))))
10169 (defvar org-refile-target-table nil
10170 "The list of refile targets, created by `org-refile'.")
10172 (defvar org-agenda-new-buffers nil
10173 "Buffers created to visit agenda files.")
10175 (defvar org-refile-cache nil
10176 "Cache for refile targets.")
10178 (defvar org-refile-markers nil
10179 "All the markers used for caching refile locations.")
10181 (defun org-refile-marker (pos)
10182 "Get a new refile marker, but only if caching is in use."
10183 (if (not org-refile-use-cache)
10185 (let ((m (make-marker)))
10186 (move-marker m pos)
10187 (push m org-refile-markers)
10188 m)))
10190 (defun org-refile-cache-clear ()
10191 "Clear the refile cache and disable all the markers."
10192 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10193 (setq org-refile-markers nil)
10194 (setq org-refile-cache nil)
10195 (message "Refile cache has been cleared"))
10197 (defun org-refile-cache-check-set (set)
10198 "Check if all the markers in the cache still have live buffers."
10199 (let (marker)
10200 (catch 'exit
10201 (while (and set (setq marker (nth 3 (pop set))))
10202 ;; if org-refile-use-outline-path is 'file, marker may be nil
10203 (when (and marker (null (marker-buffer marker)))
10204 (message "not found") (sit-for 3)
10205 (throw 'exit nil)))
10206 t)))
10208 (defun org-refile-cache-put (set &rest identifiers)
10209 "Push the refile targets SET into the cache, under IDENTIFIERS."
10210 (let* ((key (sha1 (prin1-to-string identifiers)))
10211 (entry (assoc key org-refile-cache)))
10212 (if entry
10213 (setcdr entry set)
10214 (push (cons key set) org-refile-cache))))
10216 (defun org-refile-cache-get (&rest identifiers)
10217 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10218 (cond
10219 ((not org-refile-cache) nil)
10220 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10222 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10223 org-refile-cache))))
10224 (and set (org-refile-cache-check-set set) set)))))
10226 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10227 "Produce a table with refile targets."
10228 (let ((case-fold-search nil)
10229 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10230 (entries (or org-refile-targets '((nil . (:level . 1)))))
10231 targets tgs txt re files f desc descre fast-path-p level pos0)
10232 (message "Getting targets...")
10233 (with-current-buffer (or default-buffer (current-buffer))
10234 (while (setq entry (pop entries))
10235 (setq files (car entry) desc (cdr entry))
10236 (setq fast-path-p nil)
10237 (cond
10238 ((null files) (setq files (list (current-buffer))))
10239 ((eq files 'org-agenda-files)
10240 (setq files (org-agenda-files 'unrestricted)))
10241 ((and (symbolp files) (fboundp files))
10242 (setq files (funcall files)))
10243 ((and (symbolp files) (boundp files))
10244 (setq files (symbol-value files))))
10245 (if (stringp files) (setq files (list files)))
10246 (cond
10247 ((eq (car desc) :tag)
10248 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10249 ((eq (car desc) :todo)
10250 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10251 ((eq (car desc) :regexp)
10252 (setq descre (cdr desc)))
10253 ((eq (car desc) :level)
10254 (setq descre (concat "^\\*\\{" (number-to-string
10255 (if org-odd-levels-only
10256 (1- (* 2 (cdr desc)))
10257 (cdr desc)))
10258 "\\}[ \t]")))
10259 ((eq (car desc) :maxlevel)
10260 (setq fast-path-p t)
10261 (setq descre (concat "^\\*\\{1," (number-to-string
10262 (if org-odd-levels-only
10263 (1- (* 2 (cdr desc)))
10264 (cdr desc)))
10265 "\\}[ \t]")))
10266 (t (error "Bad refiling target description %s" desc)))
10267 (while (setq f (pop files))
10268 (with-current-buffer
10269 (if (bufferp f) f (org-get-agenda-file-buffer f))
10271 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10272 (progn
10273 (if (bufferp f) (setq f (buffer-file-name
10274 (buffer-base-buffer f))))
10275 (setq f (and f (expand-file-name f)))
10276 (if (eq org-refile-use-outline-path 'file)
10277 (push (list (file-name-nondirectory f) f nil nil) tgs))
10278 (save-excursion
10279 (save-restriction
10280 (widen)
10281 (goto-char (point-min))
10282 (while (re-search-forward descre nil t)
10283 (goto-char (setq pos0 (point-at-bol)))
10284 (catch 'next
10285 (when org-refile-target-verify-function
10286 (save-match-data
10287 (or (funcall org-refile-target-verify-function)
10288 (throw 'next t))))
10289 (when (and (looking-at org-complex-heading-regexp)
10290 (not (member (match-string 4) excluded-entries)))
10291 (setq level (org-reduced-level
10292 (- (match-end 1) (match-beginning 1)))
10293 txt (org-link-display-format (match-string 4))
10294 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10295 re (format org-complex-heading-regexp-format
10296 (regexp-quote (match-string 4))))
10297 (when org-refile-use-outline-path
10298 (setq txt (mapconcat
10299 'org-protect-slash
10300 (append
10301 (if (eq org-refile-use-outline-path
10302 'file)
10303 (list (file-name-nondirectory
10304 (buffer-file-name
10305 (buffer-base-buffer))))
10306 (if (eq org-refile-use-outline-path
10307 'full-file-path)
10308 (list (buffer-file-name
10309 (buffer-base-buffer)))))
10310 (org-get-outline-path fast-path-p
10311 level txt)
10312 (list txt))
10313 "/")))
10314 (push (list txt f re (org-refile-marker (point)))
10315 tgs)))
10316 (when (= (point) pos0)
10317 ;; verification function has not moved point
10318 (goto-char (point-at-eol))))))))
10319 (when org-refile-use-cache
10320 (org-refile-cache-put tgs (buffer-file-name) descre))
10321 (setq targets (append tgs targets))
10322 ))))
10323 (message "Getting targets...done")
10324 (nreverse targets)))
10326 (defun org-protect-slash (s)
10327 (while (string-match "/" s)
10328 (setq s (replace-match "\\" t t s)))
10331 (defvar org-olpa (make-vector 20 nil))
10333 (defun org-get-outline-path (&optional fastp level heading)
10334 "Return the outline path to the current entry, as a list.
10336 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10337 routine which makes outline path derivations for an entire file,
10338 avoiding backtracing. Refile target collection makes use of that."
10339 (if fastp
10340 (progn
10341 (if (> level 19)
10342 (error "Outline path failure, more than 19 levels"))
10343 (loop for i from level upto 19 do
10344 (aset org-olpa i nil))
10345 (prog1
10346 (delq nil (append org-olpa nil))
10347 (aset org-olpa level heading)))
10348 (let (rtn case-fold-search)
10349 (save-excursion
10350 (save-restriction
10351 (widen)
10352 (while (org-up-heading-safe)
10353 (when (looking-at org-complex-heading-regexp)
10354 (push (org-match-string-no-properties 4) rtn)))
10355 rtn)))))
10357 (defun org-format-outline-path (path &optional width prefix)
10358 "Format the outline path PATH for display.
10359 Width is the maximum number of characters that is available.
10360 Prefix is a prefix to be included in the returned string,
10361 such as the file name."
10362 (setq width (or width 79))
10363 (if prefix (setq width (- width (length prefix))))
10364 (if (not path)
10365 (or prefix "")
10366 (let* ((nsteps (length path))
10367 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10368 (maxwidth (if (<= total-width width)
10369 10000 ;; everything fits
10370 ;; we need to shorten the level headings
10371 (/ (- width nsteps) nsteps)))
10372 (org-odd-levels-only nil)
10373 (n 0)
10374 (total (1+ (length prefix))))
10375 (setq maxwidth (max maxwidth 10))
10376 (concat prefix
10377 (mapconcat
10378 (lambda (h)
10379 (setq n (1+ n))
10380 (if (and (= n nsteps) (< maxwidth 10000))
10381 (setq maxwidth (- total-width total)))
10382 (if (< (length h) maxwidth)
10383 (progn (setq total (+ total (length h) 1)) h)
10384 (setq h (substring h 0 (- maxwidth 2))
10385 total (+ total maxwidth 1))
10386 (if (string-match "[ \t]+\\'" h)
10387 (setq h (substring h 0 (match-beginning 0))))
10388 (setq h (concat h "..")))
10389 (org-add-props h nil 'face
10390 (nth (% (1- n) org-n-level-faces)
10391 org-level-faces))
10393 path "/")))))
10395 (defun org-display-outline-path (&optional file current)
10396 "Display the current outline path in the echo area."
10397 (interactive "P")
10398 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10399 (case-fold-search nil)
10400 (path (and (org-mode-p) (org-get-outline-path))))
10401 (if current (setq path (append path
10402 (save-excursion
10403 (org-back-to-heading t)
10404 (if (looking-at org-complex-heading-regexp)
10405 (list (match-string 4)))))))
10406 (message "%s"
10407 (org-format-outline-path
10408 path
10409 (1- (frame-width))
10410 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10412 (defvar org-refile-history nil
10413 "History for refiling operations.")
10415 (defvar org-after-refile-insert-hook nil
10416 "Hook run after `org-refile' has inserted its stuff at the new location.
10417 Note that this is still *before* the stuff will be removed from
10418 the *old* location.")
10420 (defvar org-capture-last-stored-marker)
10421 (defun org-refile (&optional goto default-buffer rfloc)
10422 "Move the entry or entries at point to another heading.
10423 The list of target headings is compiled using the information in
10424 `org-refile-targets', which see.
10426 At the target location, the entry is filed as a subitem of the target
10427 heading. Depending on `org-reverse-note-order', the new subitem will
10428 either be the first or the last subitem.
10430 If there is an active region, all entries in that region will be moved.
10431 However, the region must fulfill the requirement that the first heading
10432 is the first one sets the top-level of the moved text - at most siblings
10433 below it are allowed.
10435 With prefix arg GOTO, the command will only visit the target location
10436 and not actually move anything.
10438 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10439 go to the location where the last refiling operation has put the subtree.
10440 With a prefix argument of `2', refile to the running clock.
10442 RFLOC can be a refile location obtained in a different way.
10444 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10446 If you are using target caching (see `org-refile-use-cache'),
10447 You have to clear the target cache in order to find new targets.
10448 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10449 prefix argument (`C-u C-u C-u C-c C-w')."
10451 (interactive "P")
10452 (if (member goto '(0 (64)))
10453 (org-refile-cache-clear)
10454 (let* ((cbuf (current-buffer))
10455 (regionp (org-region-active-p))
10456 (region-start (and regionp (region-beginning)))
10457 (region-end (and regionp (region-end)))
10458 (region-length (and regionp (- region-end region-start)))
10459 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10460 pos it nbuf file re level reversed)
10461 (setq last-command nil)
10462 (when regionp
10463 (goto-char region-start)
10464 (or (bolp) (goto-char (point-at-bol)))
10465 (setq region-start (point))
10466 (unless (or (org-kill-is-subtree-p
10467 (buffer-substring region-start region-end))
10468 (prog1 org-refile-active-region-within-subtree
10469 (org-toggle-heading)))
10470 (error "The region is not a (sequence of) subtree(s)")))
10471 (if (equal goto '(16))
10472 (org-refile-goto-last-stored)
10473 (when (or
10474 (and (equal goto 2)
10475 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10476 (prog1
10477 (setq it (list (or org-clock-heading "running clock")
10478 (buffer-file-name
10479 (marker-buffer org-clock-hd-marker))
10481 (marker-position org-clock-hd-marker)))
10482 (setq goto nil)))
10483 (setq it (or rfloc
10484 (save-excursion
10485 (unless goto (org-back-to-heading t))
10486 (org-refile-get-location
10487 (cond (goto "Goto")
10488 (regionp "Refile region to")
10489 (t "Refile subtree to")) default-buffer
10490 org-refile-allow-creating-parent-nodes
10491 goto)))))
10492 (setq file (nth 1 it)
10493 re (nth 2 it)
10494 pos (nth 3 it))
10495 (if (and (not goto)
10497 (equal (buffer-file-name) file)
10498 (if regionp
10499 (and (>= pos region-start)
10500 (<= pos region-end))
10501 (and (>= pos (point))
10502 (< pos (save-excursion
10503 (org-end-of-subtree t t))))))
10504 (error "Cannot refile to position inside the tree or region"))
10506 (setq nbuf (or (find-buffer-visiting file)
10507 (find-file-noselect file)))
10508 (if goto
10509 (progn
10510 (org-pop-to-buffer-same-window nbuf)
10511 (goto-char pos)
10512 (org-show-context 'org-goto))
10513 (if regionp
10514 (progn
10515 (org-kill-new (buffer-substring region-start region-end))
10516 (org-save-markers-in-region region-start region-end))
10517 (org-copy-subtree 1 nil t))
10518 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10519 (find-file-noselect file)))
10520 (setq reversed (org-notes-order-reversed-p))
10521 (save-excursion
10522 (save-restriction
10523 (widen)
10524 (if pos
10525 (progn
10526 (goto-char pos)
10527 (looking-at org-outline-regexp)
10528 (setq level (org-get-valid-level (funcall outline-level) 1))
10529 (goto-char
10530 (if reversed
10531 (or (outline-next-heading) (point-max))
10532 (or (save-excursion (org-get-next-sibling))
10533 (org-end-of-subtree t t)
10534 (point-max)))))
10535 (setq level 1)
10536 (if (not reversed)
10537 (goto-char (point-max))
10538 (goto-char (point-min))
10539 (or (outline-next-heading) (goto-char (point-max)))))
10540 (if (not (bolp)) (newline))
10541 (org-paste-subtree level)
10542 (when org-log-refile
10543 (org-add-log-setup 'refile nil nil 'findpos
10544 org-log-refile)
10545 (unless (eq org-log-refile 'note)
10546 (save-excursion (org-add-log-note))))
10547 (and org-auto-align-tags (org-set-tags nil t))
10548 (bookmark-set "org-refile-last-stored")
10549 ;; If we are refiling for capture, make sure that the
10550 ;; last-capture pointers point here
10551 (when (org-bound-and-true-p org-refile-for-capture)
10552 (bookmark-set "org-capture-last-stored-marker")
10553 (move-marker org-capture-last-stored-marker (point)))
10554 (if (fboundp 'deactivate-mark) (deactivate-mark))
10555 (run-hooks 'org-after-refile-insert-hook))))
10556 (if regionp
10557 (delete-region (point) (+ (point) region-length))
10558 (org-cut-subtree))
10559 (when (featurep 'org-inlinetask)
10560 (org-inlinetask-remove-END-maybe))
10561 (setq org-markers-to-move nil)
10562 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10564 (defun org-refile-goto-last-stored ()
10565 "Go to the location where the last refile was stored."
10566 (interactive)
10567 (bookmark-jump "org-refile-last-stored")
10568 (message "This is the location of the last refile"))
10570 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10571 no-exclude)
10572 "Prompt the user for a refile location, using PROMPT.
10573 PROMPT should not be suffixed with a colon and a space, because
10574 this function appends the default value from
10575 `org-refile-history' automatically, if that is not empty.
10576 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10577 this is used for the GOTO interface."
10578 (let ((org-refile-targets org-refile-targets)
10579 (org-refile-use-outline-path org-refile-use-outline-path)
10580 excluded-entries)
10581 (when (and (eq major-mode 'org-mode)
10582 (not org-refile-use-cache)
10583 (not no-exclude))
10584 (org-map-tree
10585 (lambda()
10586 (setq excluded-entries
10587 (append excluded-entries (list (org-get-heading t t)))))))
10588 (setq org-refile-target-table
10589 (org-refile-get-targets default-buffer excluded-entries)))
10590 (unless org-refile-target-table
10591 (error "No refile targets"))
10592 (let* ((prompt (concat prompt
10593 (and (car org-refile-history)
10594 (concat " (default " (car org-refile-history) ")"))
10595 ": "))
10596 (cbuf (current-buffer))
10597 (partial-completion-mode nil)
10598 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10599 (cfunc (if (and org-refile-use-outline-path
10600 org-outline-path-complete-in-steps)
10601 'org-olpath-completing-read
10602 'org-icompleting-read))
10603 (extra (if org-refile-use-outline-path "/" ""))
10604 (filename (and cfn (expand-file-name cfn)))
10605 (tbl (mapcar
10606 (lambda (x)
10607 (if (and (not (member org-refile-use-outline-path
10608 '(file full-file-path)))
10609 (not (equal filename (nth 1 x))))
10610 (cons (concat (car x) extra " ("
10611 (file-name-nondirectory (nth 1 x)) ")")
10612 (cdr x))
10613 (cons (concat (car x) extra) (cdr x))))
10614 org-refile-target-table))
10615 (completion-ignore-case t)
10616 pa answ parent-target child parent old-hist)
10617 (setq old-hist org-refile-history)
10618 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10619 nil 'org-refile-history (car org-refile-history)))
10620 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10621 (org-refile-check-position pa)
10622 (if pa
10623 (progn
10624 (when (or (not org-refile-history)
10625 (not (eq old-hist org-refile-history))
10626 (not (equal (car pa) (car org-refile-history))))
10627 (setq org-refile-history
10628 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10629 org-refile-history
10630 (cdr org-refile-history))))
10631 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10632 (pop org-refile-history)))
10634 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10635 (progn
10636 (setq parent (match-string 1 answ)
10637 child (match-string 2 answ))
10638 (setq parent-target (or (assoc parent tbl)
10639 (assoc (concat parent "/") tbl)))
10640 (when (and parent-target
10641 (or (eq new-nodes t)
10642 (and (eq new-nodes 'confirm)
10643 (y-or-n-p (format "Create new node \"%s\"? "
10644 child)))))
10645 (org-refile-new-child parent-target child)))
10646 (error "Invalid target location")))))
10648 (defun org-refile-check-position (refile-pointer)
10649 "Check if the refile pointer matches the readline to which it points."
10650 (let* ((file (nth 1 refile-pointer))
10651 (re (nth 2 refile-pointer))
10652 (pos (nth 3 refile-pointer))
10653 buffer)
10654 (when (org-string-nw-p re)
10655 (setq buffer (if (markerp pos)
10656 (marker-buffer pos)
10657 (or (find-buffer-visiting file)
10658 (find-file-noselect file))))
10659 (with-current-buffer buffer
10660 (save-excursion
10661 (save-restriction
10662 (widen)
10663 (goto-char pos)
10664 (beginning-of-line 1)
10665 (unless (org-looking-at-p re)
10666 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10668 (defun org-refile-new-child (parent-target child)
10669 "Use refile target PARENT-TARGET to add new CHILD below it."
10670 (unless parent-target
10671 (error "Cannot find parent for new node"))
10672 (let ((file (nth 1 parent-target))
10673 (pos (nth 3 parent-target))
10674 level)
10675 (with-current-buffer (or (find-buffer-visiting file)
10676 (find-file-noselect file))
10677 (save-excursion
10678 (save-restriction
10679 (widen)
10680 (if pos
10681 (goto-char pos)
10682 (goto-char (point-max))
10683 (if (not (bolp)) (newline)))
10684 (when (looking-at org-outline-regexp)
10685 (setq level (funcall outline-level))
10686 (org-end-of-subtree t t))
10687 (org-back-over-empty-lines)
10688 (insert "\n" (make-string
10689 (if pos (org-get-valid-level level 1) 1) ?*)
10690 " " child "\n")
10691 (beginning-of-line 0)
10692 (list (concat (car parent-target) "/" child) file "" (point)))))))
10694 (defun org-olpath-completing-read (prompt collection &rest args)
10695 "Read an outline path like a file name."
10696 (let ((thetable collection)
10697 (org-completion-use-ido nil) ; does not work with ido.
10698 (org-completion-use-iswitchb nil)) ; or iswitchb
10699 (apply
10700 'org-icompleting-read prompt
10701 (lambda (string predicate &optional flag)
10702 (let (rtn r f (l (length string)))
10703 (cond
10704 ((eq flag nil)
10705 ;; try completion
10706 (try-completion string thetable))
10707 ((eq flag t)
10708 ;; all-completions
10709 (setq rtn (all-completions string thetable predicate))
10710 (mapcar
10711 (lambda (x)
10712 (setq r (substring x l))
10713 (if (string-match " ([^)]*)$" x)
10714 (setq f (match-string 0 x))
10715 (setq f ""))
10716 (if (string-match "/" r)
10717 (concat string (substring r 0 (match-end 0)) f)
10719 rtn))
10720 ((eq flag 'lambda)
10721 ;; exact match?
10722 (assoc string thetable)))
10724 args)))
10726 ;;;; Dynamic blocks
10728 (defun org-find-dblock (name)
10729 "Find the first dynamic block with name NAME in the buffer.
10730 If not found, stay at current position and return nil."
10731 (let (pos)
10732 (save-excursion
10733 (goto-char (point-min))
10734 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10735 nil t)
10736 (match-beginning 0))))
10737 (if pos (goto-char pos))
10738 pos))
10740 (defconst org-dblock-start-re
10741 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10742 "Matches the start line of a dynamic block, with parameters.")
10744 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10745 "Matches the end of a dynamic block.")
10747 (defun org-create-dblock (plist)
10748 "Create a dynamic block section, with parameters taken from PLIST.
10749 PLIST must contain a :name entry which is used as name of the block."
10750 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10751 (end-of-line 1)
10752 (newline))
10753 (let ((col (current-column))
10754 (name (plist-get plist :name)))
10755 (insert "#+BEGIN: " name)
10756 (while plist
10757 (if (eq (car plist) :name)
10758 (setq plist (cddr plist))
10759 (insert " " (prin1-to-string (pop plist)))))
10760 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10761 (beginning-of-line -2)))
10763 (defun org-prepare-dblock ()
10764 "Prepare dynamic block for refresh.
10765 This empties the block, puts the cursor at the insert position and returns
10766 the property list including an extra property :name with the block name."
10767 (unless (looking-at org-dblock-start-re)
10768 (error "Not at a dynamic block"))
10769 (let* ((begdel (1+ (match-end 0)))
10770 (name (org-no-properties (match-string 1)))
10771 (params (append (list :name name)
10772 (read (concat "(" (match-string 3) ")")))))
10773 (save-excursion
10774 (beginning-of-line 1)
10775 (skip-chars-forward " \t")
10776 (setq params (plist-put params :indentation-column (current-column))))
10777 (unless (re-search-forward org-dblock-end-re nil t)
10778 (error "Dynamic block not terminated"))
10779 (setq params
10780 (append params
10781 (list :content (buffer-substring
10782 begdel (match-beginning 0)))))
10783 (delete-region begdel (match-beginning 0))
10784 (goto-char begdel)
10785 (open-line 1)
10786 params))
10788 (defun org-map-dblocks (&optional command)
10789 "Apply COMMAND to all dynamic blocks in the current buffer.
10790 If COMMAND is not given, use `org-update-dblock'."
10791 (let ((cmd (or command 'org-update-dblock)))
10792 (save-excursion
10793 (goto-char (point-min))
10794 (while (re-search-forward org-dblock-start-re nil t)
10795 (goto-char (match-beginning 0))
10796 (save-excursion
10797 (condition-case nil
10798 (funcall cmd)
10799 (error (message "Error during update of dynamic block"))))
10800 (unless (re-search-forward org-dblock-end-re nil t)
10801 (error "Dynamic block not terminated"))))))
10803 (defun org-dblock-update (&optional arg)
10804 "User command for updating dynamic blocks.
10805 Update the dynamic block at point. With prefix ARG, update all dynamic
10806 blocks in the buffer."
10807 (interactive "P")
10808 (if arg
10809 (org-update-all-dblocks)
10810 (or (looking-at org-dblock-start-re)
10811 (org-beginning-of-dblock))
10812 (org-update-dblock)))
10814 (defun org-update-dblock ()
10815 "Update the dynamic block at point.
10816 This means to empty the block, parse for parameters and then call
10817 the correct writing function."
10818 (interactive)
10819 (save-window-excursion
10820 (let* ((pos (point))
10821 (line (org-current-line))
10822 (params (org-prepare-dblock))
10823 (name (plist-get params :name))
10824 (indent (plist-get params :indentation-column))
10825 (cmd (intern (concat "org-dblock-write:" name))))
10826 (message "Updating dynamic block `%s' at line %d..." name line)
10827 (funcall cmd params)
10828 (message "Updating dynamic block `%s' at line %d...done" name line)
10829 (goto-char pos)
10830 (when (and indent (> indent 0))
10831 (setq indent (make-string indent ?\ ))
10832 (save-excursion
10833 (org-beginning-of-dblock)
10834 (forward-line 1)
10835 (while (not (looking-at org-dblock-end-re))
10836 (insert indent)
10837 (beginning-of-line 2))
10838 (when (looking-at org-dblock-end-re)
10839 (and (looking-at "[ \t]+")
10840 (replace-match ""))
10841 (insert indent)))))))
10843 (defun org-beginning-of-dblock ()
10844 "Find the beginning of the dynamic block at point.
10845 Error if there is no such block at point."
10846 (let ((pos (point))
10847 beg)
10848 (end-of-line 1)
10849 (if (and (re-search-backward org-dblock-start-re nil t)
10850 (setq beg (match-beginning 0))
10851 (re-search-forward org-dblock-end-re nil t)
10852 (> (match-end 0) pos))
10853 (goto-char beg)
10854 (goto-char pos)
10855 (error "Not in a dynamic block"))))
10857 (defun org-update-all-dblocks ()
10858 "Update all dynamic blocks in the buffer.
10859 This function can be used in a hook."
10860 (interactive)
10861 (when (org-mode-p)
10862 (org-map-dblocks 'org-update-dblock)))
10865 ;;;; Completion
10867 (defconst org-additional-option-like-keywords
10868 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
10869 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
10870 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
10871 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
10872 "BEGIN:" "END:"
10873 "ORGTBL" "TBLFM:" "TBLNAME:"
10874 "BEGIN_EXAMPLE" "END_EXAMPLE"
10875 "BEGIN_QUOTE" "END_QUOTE"
10876 "BEGIN_VERSE" "END_VERSE"
10877 "BEGIN_CENTER" "END_CENTER"
10878 "BEGIN_SRC" "END_SRC"
10879 "BEGIN_RESULT" "END_RESULT"
10880 "SOURCE:" "SRCNAME:" "FUNCTION:"
10881 "RESULTS:" "DATA:"
10882 "HEADER:" "HEADERS:"
10883 "BABEL:"
10884 "CATEGORY:" "COLUMNS:" "PROPERTY:"
10885 "CAPTION:" "LABEL:"
10886 "SETUPFILE:"
10887 "INCLUDE:"
10888 "BIND:"
10889 "MACRO:"))
10891 (defcustom org-structure-template-alist
10893 ("s" "#+begin_src ?\n\n#+end_src"
10894 "<src lang=\"?\">\n\n</src>")
10895 ("e" "#+begin_example\n?\n#+end_example"
10896 "<example>\n?\n</example>")
10897 ("q" "#+begin_quote\n?\n#+end_quote"
10898 "<quote>\n?\n</quote>")
10899 ("v" "#+begin_verse\n?\n#+end_verse"
10900 "<verse>\n?\n/verse>")
10901 ("c" "#+begin_center\n?\n#+end_center"
10902 "<center>\n?\n/center>")
10903 ("l" "#+begin_latex\n?\n#+end_latex"
10904 "<literal style=\"latex\">\n?\n</literal>")
10905 ("L" "#+latex: "
10906 "<literal style=\"latex\">?</literal>")
10907 ("h" "#+begin_html\n?\n#+end_html"
10908 "<literal style=\"html\">\n?\n</literal>")
10909 ("H" "#+html: "
10910 "<literal style=\"html\">?</literal>")
10911 ("a" "#+begin_ascii\n?\n#+end_ascii")
10912 ("A" "#+ascii: ")
10913 ("i" "#+index: ?"
10914 "#+index: ?")
10915 ("I" "#+include %file ?"
10916 "<include file=%file markup=\"?\">")
10918 "Structure completion elements.
10919 This is a list of abbreviation keys and values. The value gets inserted
10920 if you type `<' followed by the key and then press the completion key,
10921 usually `M-TAB'. %file will be replaced by a file name after prompting
10922 for the file using completion. The cursor will be placed at the position
10923 of the `?` in the template.
10924 There are two templates for each key, the first uses the original Org syntax,
10925 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
10926 the default when the /org-mtags.el/ module has been loaded. See also the
10927 variable `org-mtags-prefer-muse-templates'.
10928 This is an experimental feature, it is undecided if it is going to stay in."
10929 :group 'org-completion
10930 :type '(repeat
10931 (string :tag "Key")
10932 (string :tag "Template")
10933 (string :tag "Muse Template")))
10935 (defun org-try-structure-completion ()
10936 "Try to complete a structure template before point.
10937 This looks for strings like \"<e\" on an otherwise empty line and
10938 expands them."
10939 (let ((l (buffer-substring (point-at-bol) (point)))
10941 (when (and (looking-at "[ \t]*$")
10942 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
10943 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
10944 (org-complete-expand-structure-template (+ -1 (point-at-bol)
10945 (match-beginning 1)) a)
10946 t)))
10948 (defun org-complete-expand-structure-template (start cell)
10949 "Expand a structure template."
10950 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
10951 (rpl (nth (if musep 2 1) cell))
10952 (ind ""))
10953 (delete-region start (point))
10954 (when (string-match "\\`#\\+" rpl)
10955 (cond
10956 ((bolp))
10957 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
10958 (setq ind (buffer-substring (point-at-bol) (point))))
10959 (t (newline))))
10960 (setq start (point))
10961 (if (string-match "%file" rpl)
10962 (setq rpl (replace-match
10963 (concat
10964 "\""
10965 (save-match-data
10966 (abbreviate-file-name (read-file-name "Include file: ")))
10967 "\"")
10968 t t rpl)))
10969 (setq rpl (mapconcat 'identity (split-string rpl "\n")
10970 (concat "\n" ind)))
10971 (insert rpl)
10972 (if (re-search-backward "\\?" start t) (delete-char 1))))
10974 ;;;; TODO, DEADLINE, Comments
10976 (defun org-toggle-comment ()
10977 "Change the COMMENT state of an entry."
10978 (interactive)
10979 (save-excursion
10980 (org-back-to-heading)
10981 (let (case-fold-search)
10982 (if (looking-at (concat org-outline-regexp
10983 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10984 (replace-match "" t t nil 1)
10985 (if (looking-at org-outline-regexp)
10986 (progn
10987 (goto-char (match-end 0))
10988 (insert org-comment-string " ")))))))
10990 (defvar org-last-todo-state-is-todo nil
10991 "This is non-nil when the last TODO state change led to a TODO state.
10992 If the last change removed the TODO tag or switched to DONE, then
10993 this is nil.")
10995 (defvar org-setting-tags nil) ; dynamically skipped
10997 (defvar org-todo-setup-filter-hook nil
10998 "Hook for functions that pre-filter todo specs.
10999 Each function takes a todo spec and returns either nil or the spec
11000 transformed into canonical form." )
11002 (defvar org-todo-get-default-hook nil
11003 "Hook for functions that get a default item for todo.
11004 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11005 nil or a string to be used for the todo mark." )
11007 (defvar org-agenda-headline-snapshot-before-repeat)
11009 (defun org-current-effective-time ()
11010 "Return current time adjusted for `org-extend-today-until' variable"
11011 (let* ((ct (org-current-time))
11012 (dct (decode-time ct))
11013 (ct1
11014 (if (and org-use-effective-time
11015 (< (nth 2 dct) org-extend-today-until))
11016 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11017 ct)))
11018 ct1))
11020 (defun org-todo-yesterday (&optional arg)
11021 "Like `org-todo' but the time of change will be 23:59 of yesterday"
11022 (interactive "P")
11023 (let* ((hour (third (decode-time
11024 (org-current-time))))
11025 (org-extend-today-until (1+ hour)))
11026 (org-todo arg)))
11028 (defun org-todo (&optional arg)
11029 "Change the TODO state of an item.
11030 The state of an item is given by a keyword at the start of the heading,
11031 like
11032 *** TODO Write paper
11033 *** DONE Call mom
11035 The different keywords are specified in the variable `org-todo-keywords'.
11036 By default the available states are \"TODO\" and \"DONE\".
11037 So for this example: when the item starts with TODO, it is changed to DONE.
11038 When it starts with DONE, the DONE is removed. And when neither TODO nor
11039 DONE are present, add TODO at the beginning of the heading.
11041 With \\[universal-argument] prefix arg, use completion to determine the new \
11042 state.
11043 With numeric prefix arg, switch to that state.
11044 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11045 keywords (nextset).
11046 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11048 For calling through lisp, arg is also interpreted in the following way:
11049 'none -> empty state
11050 \"\"(empty string) -> switch to empty state
11051 'done -> switch to DONE
11052 'nextset -> switch to the next set of keywords
11053 'previousset -> switch to the previous set of keywords
11054 \"WAITING\" -> switch to the specified keyword, but only if it
11055 really is a member of `org-todo-keywords'."
11056 (interactive "P")
11057 (if (equal arg '(16)) (setq arg 'nextset))
11058 (let ((org-blocker-hook org-blocker-hook)
11059 (case-fold-search nil))
11060 (when (equal arg '(64))
11061 (setq arg nil org-blocker-hook nil))
11062 (when (and org-blocker-hook
11063 (or org-inhibit-blocking
11064 (org-entry-get nil "NOBLOCKING")))
11065 (setq org-blocker-hook nil))
11066 (save-excursion
11067 (catch 'exit
11068 (org-back-to-heading t)
11069 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11070 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
11071 (looking-at " *"))
11072 (let* ((match-data (match-data))
11073 (startpos (point-at-bol))
11074 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11075 (org-log-done org-log-done)
11076 (org-log-repeat org-log-repeat)
11077 (org-todo-log-states org-todo-log-states)
11078 (this (match-string 1))
11079 (hl-pos (match-beginning 0))
11080 (head (org-get-todo-sequence-head this))
11081 (ass (assoc head org-todo-kwd-alist))
11082 (interpret (nth 1 ass))
11083 (done-word (nth 3 ass))
11084 (final-done-word (nth 4 ass))
11085 (last-state (or this ""))
11086 (completion-ignore-case t)
11087 (member (member this org-todo-keywords-1))
11088 (tail (cdr member))
11089 (state (cond
11090 ((and org-todo-key-trigger
11091 (or (and (equal arg '(4))
11092 (eq org-use-fast-todo-selection 'prefix))
11093 (and (not arg) org-use-fast-todo-selection
11094 (not (eq org-use-fast-todo-selection
11095 'prefix)))))
11096 ;; Use fast selection
11097 (org-fast-todo-selection))
11098 ((and (equal arg '(4))
11099 (or (not org-use-fast-todo-selection)
11100 (not org-todo-key-trigger)))
11101 ;; Read a state with completion
11102 (org-icompleting-read
11103 "State: " (mapcar (lambda(x) (list x))
11104 org-todo-keywords-1)
11105 nil t))
11106 ((eq arg 'right)
11107 (if this
11108 (if tail (car tail) nil)
11109 (car org-todo-keywords-1)))
11110 ((eq arg 'left)
11111 (if (equal member org-todo-keywords-1)
11113 (if this
11114 (nth (- (length org-todo-keywords-1)
11115 (length tail) 2)
11116 org-todo-keywords-1)
11117 (org-last org-todo-keywords-1))))
11118 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11119 (setq arg nil))) ; hack to fall back to cycling
11120 (arg
11121 ;; user or caller requests a specific state
11122 (cond
11123 ((equal arg "") nil)
11124 ((eq arg 'none) nil)
11125 ((eq arg 'done) (or done-word (car org-done-keywords)))
11126 ((eq arg 'nextset)
11127 (or (car (cdr (member head org-todo-heads)))
11128 (car org-todo-heads)))
11129 ((eq arg 'previousset)
11130 (let ((org-todo-heads (reverse org-todo-heads)))
11131 (or (car (cdr (member head org-todo-heads)))
11132 (car org-todo-heads))))
11133 ((car (member arg org-todo-keywords-1)))
11134 ((stringp arg)
11135 (error "State `%s' not valid in this file" arg))
11136 ((nth (1- (prefix-numeric-value arg))
11137 org-todo-keywords-1))))
11138 ((null member) (or head (car org-todo-keywords-1)))
11139 ((equal this final-done-word) nil) ;; -> make empty
11140 ((null tail) nil) ;; -> first entry
11141 ((memq interpret '(type priority))
11142 (if (eq this-command last-command)
11143 (car tail)
11144 (if (> (length tail) 0)
11145 (or done-word (car org-done-keywords))
11146 nil)))
11148 (car tail))))
11149 (state (or
11150 (run-hook-with-args-until-success
11151 'org-todo-get-default-hook state last-state)
11152 state))
11153 (next (if state (concat " " state " ") " "))
11154 (change-plist (list :type 'todo-state-change :from this :to state
11155 :position startpos))
11156 dolog now-done-p)
11157 (when org-blocker-hook
11158 (setq org-last-todo-state-is-todo
11159 (not (member this org-done-keywords)))
11160 (unless (save-excursion
11161 (save-match-data
11162 (org-with-wide-buffer
11163 (run-hook-with-args-until-failure
11164 'org-blocker-hook change-plist))))
11165 (if (org-called-interactively-p 'interactive)
11166 (error "TODO state change from %s to %s blocked" this state)
11167 ;; fail silently
11168 (message "TODO state change from %s to %s blocked" this state)
11169 (throw 'exit nil))))
11170 (store-match-data match-data)
11171 (replace-match next t t)
11172 (unless (pos-visible-in-window-p hl-pos)
11173 (message "TODO state changed to %s" (org-trim next)))
11174 (unless head
11175 (setq head (org-get-todo-sequence-head state)
11176 ass (assoc head org-todo-kwd-alist)
11177 interpret (nth 1 ass)
11178 done-word (nth 3 ass)
11179 final-done-word (nth 4 ass)))
11180 (when (memq arg '(nextset previousset))
11181 (message "Keyword-Set %d/%d: %s"
11182 (- (length org-todo-sets) -1
11183 (length (memq (assoc state org-todo-sets) org-todo-sets)))
11184 (length org-todo-sets)
11185 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11186 (setq org-last-todo-state-is-todo
11187 (not (member state org-done-keywords)))
11188 (setq now-done-p (and (member state org-done-keywords)
11189 (not (member this org-done-keywords))))
11190 (and logging (org-local-logging logging))
11191 (when (and (or org-todo-log-states org-log-done)
11192 (not (eq org-inhibit-logging t))
11193 (not (memq arg '(nextset previousset))))
11194 ;; we need to look at recording a time and note
11195 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
11196 (nth 2 (assoc this org-todo-log-states))))
11197 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11198 (setq dolog 'time))
11199 (when (and state
11200 (member state org-not-done-keywords)
11201 (not (member this org-not-done-keywords)))
11202 ;; This is now a todo state and was not one before
11203 ;; If there was a CLOSED time stamp, get rid of it.
11204 (org-add-planning-info nil nil 'closed))
11205 (when (and now-done-p org-log-done)
11206 ;; It is now done, and it was not done before
11207 (org-add-planning-info 'closed (org-current-effective-time))
11208 (if (and (not dolog) (eq 'note org-log-done))
11209 (org-add-log-setup 'done state this 'findpos 'note)))
11210 (when (and state dolog)
11211 ;; This is a non-nil state, and we need to log it
11212 (org-add-log-setup 'state state this 'findpos dolog)))
11213 ;; Fixup tag positioning
11214 (org-todo-trigger-tag-changes state)
11215 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11216 (when org-provide-todo-statistics
11217 (org-update-parent-todo-statistics))
11218 (run-hooks 'org-after-todo-state-change-hook)
11219 (if (and arg (not (member state org-done-keywords)))
11220 (setq head (org-get-todo-sequence-head state)))
11221 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11222 ;; Do we need to trigger a repeat?
11223 (when now-done-p
11224 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11225 ;; This is for the agenda, take a snapshot of the headline.
11226 (save-match-data
11227 (setq org-agenda-headline-snapshot-before-repeat
11228 (org-get-heading))))
11229 (org-auto-repeat-maybe state))
11230 ;; Fixup cursor location if close to the keyword
11231 (if (and (outline-on-heading-p)
11232 (not (bolp))
11233 (save-excursion (beginning-of-line 1)
11234 (looking-at org-todo-line-regexp))
11235 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11236 (progn
11237 (goto-char (or (match-end 2) (match-end 1)))
11238 (and (looking-at " ") (just-one-space))))
11239 (when org-trigger-hook
11240 (save-excursion
11241 (run-hook-with-args 'org-trigger-hook change-plist))))))))
11243 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11244 "Block turning an entry into a TODO, using the hierarchy.
11245 This checks whether the current task should be blocked from state
11246 changes. Such blocking occurs when:
11248 1. The task has children which are not all in a completed state.
11250 2. A task has a parent with the property :ORDERED:, and there
11251 are siblings prior to the current task with incomplete
11252 status.
11254 3. The parent of the task is blocked because it has siblings that should
11255 be done first, or is child of a block grandparent TODO entry."
11257 (if (not org-enforce-todo-dependencies)
11258 t ; if locally turned off don't block
11259 (catch 'dont-block
11260 ;; If this is not a todo state change, or if this entry is already DONE,
11261 ;; do not block
11262 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11263 (member (plist-get change-plist :from)
11264 (cons 'done org-done-keywords))
11265 (member (plist-get change-plist :to)
11266 (cons 'todo org-not-done-keywords))
11267 (not (plist-get change-plist :to)))
11268 (throw 'dont-block t))
11269 ;; If this task has children, and any are undone, it's blocked
11270 (save-excursion
11271 (org-back-to-heading t)
11272 (let ((this-level (funcall outline-level)))
11273 (outline-next-heading)
11274 (let ((child-level (funcall outline-level)))
11275 (while (and (not (eobp))
11276 (> child-level this-level))
11277 ;; this todo has children, check whether they are all
11278 ;; completed
11279 (if (and (not (org-entry-is-done-p))
11280 (org-entry-is-todo-p))
11281 (throw 'dont-block nil))
11282 (outline-next-heading)
11283 (setq child-level (funcall outline-level))))))
11284 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11285 ;; any previous siblings are undone, it's blocked
11286 (save-excursion
11287 (org-back-to-heading t)
11288 (let* ((pos (point))
11289 (parent-pos (and (org-up-heading-safe) (point))))
11290 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11291 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11292 (forward-line 1)
11293 (re-search-forward org-not-done-heading-regexp pos t))
11294 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11295 ;; Search further up the hierarchy, to see if an anchestor is blocked
11296 (while t
11297 (goto-char parent-pos)
11298 (if (not (looking-at org-not-done-heading-regexp))
11299 (throw 'dont-block t)) ; do not block, parent is not a TODO
11300 (setq pos (point))
11301 (setq parent-pos (and (org-up-heading-safe) (point)))
11302 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11303 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11304 (forward-line 1)
11305 (re-search-forward org-not-done-heading-regexp pos t))
11306 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11308 (defcustom org-track-ordered-property-with-tag nil
11309 "Should the ORDERED property also be shown as a tag?
11310 The ORDERED property decides if an entry should require subtasks to be
11311 completed in sequence. Since a property is not very visible, setting
11312 this option means that toggling the ORDERED property with the command
11313 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11314 not relevant for the behavior, but it makes things more visible.
11316 Note that toggling the tag with tags commands will not change the property
11317 and therefore not influence behavior!
11319 This can be t, meaning the tag ORDERED should be used, It can also be a
11320 string to select a different tag for this task."
11321 :group 'org-todo
11322 :type '(choice
11323 (const :tag "No tracking" nil)
11324 (const :tag "Track with ORDERED tag" t)
11325 (string :tag "Use other tag")))
11327 (defun org-toggle-ordered-property ()
11328 "Toggle the ORDERED property of the current entry.
11329 For better visibility, you can track the value of this property with a tag.
11330 See variable `org-track-ordered-property-with-tag'."
11331 (interactive)
11332 (let* ((t1 org-track-ordered-property-with-tag)
11333 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11334 (save-excursion
11335 (org-back-to-heading)
11336 (if (org-entry-get nil "ORDERED")
11337 (progn
11338 (org-delete-property "ORDERED")
11339 (and tag (org-toggle-tag tag 'off))
11340 (message "Subtasks can be completed in arbitrary order"))
11341 (org-entry-put nil "ORDERED" "t")
11342 (and tag (org-toggle-tag tag 'on))
11343 (message "Subtasks must be completed in sequence")))))
11345 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11346 (defun org-block-todo-from-checkboxes (change-plist)
11347 "Block turning an entry into a TODO, using checkboxes.
11348 This checks whether the current task should be blocked from state
11349 changes because there are unchecked boxes in this entry."
11350 (if (not org-enforce-todo-checkbox-dependencies)
11351 t ; if locally turned off don't block
11352 (catch 'dont-block
11353 ;; If this is not a todo state change, or if this entry is already DONE,
11354 ;; do not block
11355 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11356 (member (plist-get change-plist :from)
11357 (cons 'done org-done-keywords))
11358 (member (plist-get change-plist :to)
11359 (cons 'todo org-not-done-keywords))
11360 (not (plist-get change-plist :to)))
11361 (throw 'dont-block t))
11362 ;; If this task has checkboxes that are not checked, it's blocked
11363 (save-excursion
11364 (org-back-to-heading t)
11365 (let ((beg (point)) end)
11366 (outline-next-heading)
11367 (setq end (point))
11368 (goto-char beg)
11369 (if (org-list-search-forward
11370 (concat (org-item-beginning-re)
11371 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11372 "\\[[- ]\\]")
11373 end t)
11374 (progn
11375 (if (boundp 'org-blocked-by-checkboxes)
11376 (setq org-blocked-by-checkboxes t))
11377 (throw 'dont-block nil)))))
11378 t))) ; do not block
11380 (defun org-entry-blocked-p ()
11381 "Is the current entry blocked?"
11382 (if (org-entry-get nil "NOBLOCKING")
11383 nil ;; Never block this entry
11384 (not
11385 (run-hook-with-args-until-failure
11386 'org-blocker-hook
11387 (list :type 'todo-state-change
11388 :position (point)
11389 :from 'todo
11390 :to 'done)))))
11392 (defun org-update-statistics-cookies (all)
11393 "Update the statistics cookie, either from TODO or from checkboxes.
11394 This should be called with the cursor in a line with a statistics cookie."
11395 (interactive "P")
11396 (if all
11397 (progn
11398 (org-update-checkbox-count 'all)
11399 (org-map-entries 'org-update-parent-todo-statistics))
11400 (if (not (org-on-heading-p))
11401 (org-update-checkbox-count)
11402 (let ((pos (move-marker (make-marker) (point)))
11403 end l1 l2)
11404 (ignore-errors (org-back-to-heading t))
11405 (if (not (org-on-heading-p))
11406 (org-update-checkbox-count)
11407 (setq l1 (org-outline-level))
11408 (setq end (save-excursion
11409 (outline-next-heading)
11410 (if (org-on-heading-p) (setq l2 (org-outline-level)))
11411 (point)))
11412 (if (and (save-excursion
11413 (re-search-forward
11414 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11415 (not (save-excursion (re-search-forward
11416 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11417 (org-update-checkbox-count)
11418 (if (and l2 (> l2 l1))
11419 (progn
11420 (goto-char end)
11421 (org-update-parent-todo-statistics))
11422 (goto-char pos)
11423 (beginning-of-line 1)
11424 (while (re-search-forward
11425 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11426 (point-at-eol) t)
11427 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11428 (goto-char pos)
11429 (move-marker pos nil)))))
11431 (defvar org-entry-property-inherited-from) ;; defined below
11432 (defun org-update-parent-todo-statistics ()
11433 "Update any statistics cookie in the parent of the current headline.
11434 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11435 the entire subtree and this will travel up the hierarchy and update
11436 statistics everywhere."
11437 (let* ((prop (save-excursion (org-up-heading-safe)
11438 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11439 (recursive (or (not org-hierarchical-todo-statistics)
11440 (and prop (string-match "\\<recursive\\>" prop))))
11441 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11443 (first t)
11444 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11445 level ltoggle l1 new ndel
11446 (cnt-all 0) (cnt-done 0) is-percent kwd
11447 checkbox-beg ov ovs ove cookie-present)
11448 (catch 'exit
11449 (save-excursion
11450 (beginning-of-line 1)
11451 (setq ltoggle (funcall outline-level))
11452 ;; Three situations are to consider:
11454 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11455 ;; to the top-level ancestor on the headline;
11457 ;; 2. If parent has "recursive" property, repeat up to the
11458 ;; headline setting that property, taking inheritance into
11459 ;; account;
11461 ;; 3. Else, move up to direct parent and proceed only once.
11462 (while (and (setq level (org-up-heading-safe))
11463 (or recursive first)
11464 (>= (point) lim))
11465 (setq first nil cookie-present nil)
11466 (unless (and level
11467 (not (string-match
11468 "\\<checkbox\\>"
11469 (downcase (or (org-entry-get nil "COOKIE_DATA")
11470 "")))))
11471 (throw 'exit nil))
11472 (while (re-search-forward box-re (point-at-eol) t)
11473 (setq cnt-all 0 cnt-done 0 cookie-present t)
11474 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11475 (save-match-data
11476 (unless (outline-next-heading) (throw 'exit nil))
11477 (while (and (looking-at org-complex-heading-regexp)
11478 (> (setq l1 (length (match-string 1))) level))
11479 (setq kwd (and (or recursive (= l1 ltoggle))
11480 (match-string 2)))
11481 (if (or (eq org-provide-todo-statistics 'all-headlines)
11482 (and (listp org-provide-todo-statistics)
11483 (or (member kwd org-provide-todo-statistics)
11484 (member kwd org-done-keywords))))
11485 (setq cnt-all (1+ cnt-all))
11486 (if (eq org-provide-todo-statistics t)
11487 (and kwd (setq cnt-all (1+ cnt-all)))))
11488 (and (member kwd org-done-keywords)
11489 (setq cnt-done (1+ cnt-done)))
11490 (outline-next-heading)))
11491 (setq new
11492 (if is-percent
11493 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11494 (format "[%d/%d]" cnt-done cnt-all))
11495 ndel (- (match-end 0) checkbox-beg))
11496 ;; handle overlays when updating cookie from column view
11497 (when (setq ov (car (overlays-at checkbox-beg)))
11498 (setq ovs (overlay-start ov) ove (overlay-end ov))
11499 (delete-overlay ov))
11500 (goto-char checkbox-beg)
11501 (insert new)
11502 (delete-region (point) (+ (point) ndel))
11503 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11504 (when ov (move-overlay ov ovs ove)))
11505 (when cookie-present
11506 (run-hook-with-args 'org-after-todo-statistics-hook
11507 cnt-done (- cnt-all cnt-done))))))
11508 (run-hooks 'org-todo-statistics-hook)))
11510 (defvar org-after-todo-statistics-hook nil
11511 "Hook that is called after a TODO statistics cookie has been updated.
11512 Each function is called with two arguments: the number of not-done entries
11513 and the number of done entries.
11515 For example, the following function, when added to this hook, will switch
11516 an entry to DONE when all children are done, and back to TODO when new
11517 entries are set to a TODO status. Note that this hook is only called
11518 when there is a statistics cookie in the headline!
11520 (defun org-summary-todo (n-done n-not-done)
11521 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11522 (let (org-log-done org-log-states) ; turn off logging
11523 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11526 (defvar org-todo-statistics-hook nil
11527 "Hook that is run whenever Org thinks TODO statistics should be updated.
11528 This hook runs even if there is no statistics cookie present, in which case
11529 `org-after-todo-statistics-hook' would not run.")
11531 (defun org-todo-trigger-tag-changes (state)
11532 "Apply the changes defined in `org-todo-state-tags-triggers'."
11533 (let ((l org-todo-state-tags-triggers)
11534 changes)
11535 (when (or (not state) (equal state ""))
11536 (setq changes (append changes (cdr (assoc "" l)))))
11537 (when (and (stringp state) (> (length state) 0))
11538 (setq changes (append changes (cdr (assoc state l)))))
11539 (when (member state org-not-done-keywords)
11540 (setq changes (append changes (cdr (assoc 'todo l)))))
11541 (when (member state org-done-keywords)
11542 (setq changes (append changes (cdr (assoc 'done l)))))
11543 (dolist (c changes)
11544 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11546 (defun org-local-logging (value)
11547 "Get logging settings from a property VALUE."
11548 (let* (words w a)
11549 ;; directly set the variables, they are already local.
11550 (setq org-log-done nil
11551 org-log-repeat nil
11552 org-todo-log-states nil)
11553 (setq words (org-split-string value))
11554 (while (setq w (pop words))
11555 (cond
11556 ((setq a (assoc w org-startup-options))
11557 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11558 (set (nth 1 a) (nth 2 a))))
11559 ((setq a (org-extract-log-state-settings w))
11560 (and (member (car a) org-todo-keywords-1)
11561 (push a org-todo-log-states)))))))
11563 (defun org-get-todo-sequence-head (kwd)
11564 "Return the head of the TODO sequence to which KWD belongs.
11565 If KWD is not set, check if there is a text property remembering the
11566 right sequence."
11567 (let (p)
11568 (cond
11569 ((not kwd)
11570 (or (get-text-property (point-at-bol) 'org-todo-head)
11571 (progn
11572 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11573 nil (point-at-eol)))
11574 (get-text-property p 'org-todo-head))))
11575 ((not (member kwd org-todo-keywords-1))
11576 (car org-todo-keywords-1))
11577 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11579 (defun org-fast-todo-selection ()
11580 "Fast TODO keyword selection with single keys.
11581 Returns the new TODO keyword, or nil if no state change should occur."
11582 (let* ((fulltable org-todo-key-alist)
11583 (done-keywords org-done-keywords) ;; needed for the faces.
11584 (maxlen (apply 'max (mapcar
11585 (lambda (x)
11586 (if (stringp (car x)) (string-width (car x)) 0))
11587 fulltable)))
11588 (expert nil)
11589 (fwidth (+ maxlen 3 1 3))
11590 (ncol (/ (- (window-width) 4) fwidth))
11591 tg cnt e c tbl
11592 groups ingroup)
11593 (save-excursion
11594 (save-window-excursion
11595 (if expert
11596 (set-buffer (get-buffer-create " *Org todo*"))
11597 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11598 (erase-buffer)
11599 (org-set-local 'org-done-keywords done-keywords)
11600 (setq tbl fulltable cnt 0)
11601 (while (setq e (pop tbl))
11602 (cond
11603 ((equal e '(:startgroup))
11604 (push '() groups) (setq ingroup t)
11605 (when (not (= cnt 0))
11606 (setq cnt 0)
11607 (insert "\n"))
11608 (insert "{ "))
11609 ((equal e '(:endgroup))
11610 (setq ingroup nil cnt 0)
11611 (insert "}\n"))
11612 ((equal e '(:newline))
11613 (when (not (= cnt 0))
11614 (setq cnt 0)
11615 (insert "\n")
11616 (setq e (car tbl))
11617 (while (equal (car tbl) '(:newline))
11618 (insert "\n")
11619 (setq tbl (cdr tbl)))))
11621 (setq tg (car e) c (cdr e))
11622 (if ingroup (push tg (car groups)))
11623 (setq tg (org-add-props tg nil 'face
11624 (org-get-todo-face tg)))
11625 (if (and (= cnt 0) (not ingroup)) (insert " "))
11626 (insert "[" c "] " tg (make-string
11627 (- fwidth 4 (length tg)) ?\ ))
11628 (when (= (setq cnt (1+ cnt)) ncol)
11629 (insert "\n")
11630 (if ingroup (insert " "))
11631 (setq cnt 0)))))
11632 (insert "\n")
11633 (goto-char (point-min))
11634 (if (not expert) (org-fit-window-to-buffer))
11635 (message "[a-z..]:Set [SPC]:clear")
11636 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11637 (cond
11638 ((or (= c ?\C-g)
11639 (and (= c ?q) (not (rassoc c fulltable))))
11640 (setq quit-flag t))
11641 ((= c ?\ ) nil)
11642 ((setq e (rassoc c fulltable) tg (car e))
11644 (t (setq quit-flag t)))))))
11646 (defun org-entry-is-todo-p ()
11647 (member (org-get-todo-state) org-not-done-keywords))
11649 (defun org-entry-is-done-p ()
11650 (member (org-get-todo-state) org-done-keywords))
11652 (defun org-get-todo-state ()
11653 (save-excursion
11654 (org-back-to-heading t)
11655 (and (looking-at org-todo-line-regexp)
11656 (match-end 2)
11657 (match-string 2))))
11659 (defun org-at-date-range-p (&optional inactive-ok)
11660 "Is the cursor inside a date range?"
11661 (interactive)
11662 (save-excursion
11663 (catch 'exit
11664 (let ((pos (point)))
11665 (skip-chars-backward "^[<\r\n")
11666 (skip-chars-backward "<[")
11667 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11668 (>= (match-end 0) pos)
11669 (throw 'exit t))
11670 (skip-chars-backward "^<[\r\n")
11671 (skip-chars-backward "<[")
11672 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11673 (>= (match-end 0) pos)
11674 (throw 'exit t)))
11675 nil)))
11677 (defun org-get-repeat (&optional tagline)
11678 "Check if there is a deadline/schedule with repeater in this entry."
11679 (save-match-data
11680 (save-excursion
11681 (org-back-to-heading t)
11682 (and (re-search-forward (if tagline
11683 (concat tagline "\\s-*" org-repeat-re)
11684 org-repeat-re)
11685 (org-entry-end-position) t)
11686 (match-string-no-properties 1)))))
11688 (defvar org-last-changed-timestamp)
11689 (defvar org-last-inserted-timestamp)
11690 (defvar org-log-post-message)
11691 (defvar org-log-note-purpose)
11692 (defvar org-log-note-how)
11693 (defvar org-log-note-extra)
11694 (defun org-auto-repeat-maybe (done-word)
11695 "Check if the current headline contains a repeated deadline/schedule.
11696 If yes, set TODO state back to what it was and change the base date
11697 of repeating deadline/scheduled time stamps to new date.
11698 This function is run automatically after each state change to a DONE state."
11699 ;; last-state is dynamically scoped into this function
11700 (let* ((repeat (org-get-repeat))
11701 (aa (assoc last-state org-todo-kwd-alist))
11702 (interpret (nth 1 aa))
11703 (head (nth 2 aa))
11704 (whata '(("d" . day) ("m" . month) ("y" . year)))
11705 (msg "Entry repeats: ")
11706 (org-log-done nil)
11707 (org-todo-log-states nil)
11708 re type n what ts time to-state)
11709 (when repeat
11710 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11711 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11712 org-todo-repeat-to-state))
11713 (unless (and to-state (member to-state org-todo-keywords-1))
11714 (setq to-state (if (eq interpret 'type) last-state head)))
11715 (org-todo to-state)
11716 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11717 (org-entry-put nil "LAST_REPEAT" (format-time-string
11718 (org-time-stamp-format t t))))
11719 (when org-log-repeat
11720 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11721 (memq 'org-add-log-note post-command-hook))
11722 ;; OK, we are already setup for some record
11723 (if (eq org-log-repeat 'note)
11724 ;; make sure we take a note, not only a time stamp
11725 (setq org-log-note-how 'note))
11726 ;; Set up for taking a record
11727 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11728 last-state
11729 'findpos org-log-repeat)))
11730 (org-back-to-heading t)
11731 (org-add-planning-info nil nil 'closed)
11732 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11733 org-deadline-time-regexp "\\)\\|\\("
11734 org-ts-regexp "\\)"))
11735 (while (re-search-forward
11736 re (save-excursion (outline-next-heading) (point)) t)
11737 (setq type (if (match-end 1) org-scheduled-string
11738 (if (match-end 3) org-deadline-string "Plain:"))
11739 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11740 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11741 (setq n (string-to-number (match-string 2 ts))
11742 what (match-string 3 ts))
11743 (if (equal what "w") (setq n (* n 7) what "d"))
11744 ;; Preparation, see if we need to modify the start date for the change
11745 (when (match-end 1)
11746 (setq time (save-match-data (org-time-string-to-time ts)))
11747 (cond
11748 ((equal (match-string 1 ts) ".")
11749 ;; Shift starting date to today
11750 (org-timestamp-change
11751 (- (org-today) (time-to-days time))
11752 'day))
11753 ((equal (match-string 1 ts) "+")
11754 (let ((nshiftmax 10) (nshift 0))
11755 (while (or (= nshift 0)
11756 (<= (time-to-days time)
11757 (time-to-days (current-time))))
11758 (when (= (incf nshift) nshiftmax)
11759 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11760 (error "Abort")))
11761 (org-timestamp-change n (cdr (assoc what whata)))
11762 (org-at-timestamp-p t)
11763 (setq ts (match-string 1))
11764 (setq time (save-match-data (org-time-string-to-time ts)))))
11765 (org-timestamp-change (- n) (cdr (assoc what whata)))
11766 ;; rematch, so that we have everything in place for the real shift
11767 (org-at-timestamp-p t)
11768 (setq ts (match-string 1))
11769 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11770 (org-timestamp-change n (cdr (assoc what whata)))
11771 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11772 (setq org-log-post-message msg)
11773 (message "%s" msg))))
11775 (defun org-show-todo-tree (arg)
11776 "Make a compact tree which shows all headlines marked with TODO.
11777 The tree will show the lines where the regexp matches, and all higher
11778 headlines above the match.
11779 With a \\[universal-argument] prefix, prompt for a regexp to match.
11780 With a numeric prefix N, construct a sparse tree for the Nth element
11781 of `org-todo-keywords-1'."
11782 (interactive "P")
11783 (let ((case-fold-search nil)
11784 (kwd-re
11785 (cond ((null arg) org-not-done-regexp)
11786 ((equal arg '(4))
11787 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11788 (mapcar 'list org-todo-keywords-1))))
11789 (concat "\\("
11790 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11791 "\\)\\>")))
11792 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11793 (regexp-quote (nth (1- (prefix-numeric-value arg))
11794 org-todo-keywords-1)))
11795 (t (error "Invalid prefix argument: %s" arg)))))
11796 (message "%d TODO entries found"
11797 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
11799 (defun org-deadline (&optional remove time)
11800 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11801 With argument REMOVE, remove any deadline from the item.
11802 With argument TIME, set the deadline at the corresponding date. TIME
11803 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
11804 (interactive "P")
11805 (let* ((old-date (org-entry-get nil "DEADLINE"))
11806 (repeater (and old-date
11807 (string-match
11808 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11809 old-date)
11810 (match-string 1 old-date))))
11811 (if remove
11812 (progn
11813 (when (and old-date org-log-redeadline)
11814 (org-add-log-setup 'deldeadline nil old-date 'findpos
11815 org-log-redeadline))
11816 (org-remove-timestamp-with-keyword org-deadline-string)
11817 (message "Item no longer has a deadline."))
11818 (org-add-planning-info 'deadline time 'closed)
11819 (when (and old-date org-log-redeadline
11820 (not (equal old-date
11821 (substring org-last-inserted-timestamp 1 -1))))
11822 (org-add-log-setup 'redeadline nil old-date 'findpos
11823 org-log-redeadline))
11824 (when repeater
11825 (save-excursion
11826 (org-back-to-heading t)
11827 (when (re-search-forward (concat org-deadline-string " "
11828 org-last-inserted-timestamp)
11829 (save-excursion
11830 (outline-next-heading) (point)) t)
11831 (goto-char (1- (match-end 0)))
11832 (insert " " repeater)
11833 (setq org-last-inserted-timestamp
11834 (concat (substring org-last-inserted-timestamp 0 -1)
11835 " " repeater
11836 (substring org-last-inserted-timestamp -1))))))
11837 (message "Deadline on %s" org-last-inserted-timestamp))))
11839 (defun org-schedule (&optional remove time)
11840 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11841 With argument REMOVE, remove any scheduling date from the item.
11842 With argument TIME, scheduled at the corresponding date. TIME can
11843 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
11844 (interactive "P")
11845 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11846 (repeater (and old-date
11847 (string-match
11848 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11849 old-date)
11850 (match-string 1 old-date))))
11851 (if remove
11852 (progn
11853 (when (and old-date org-log-reschedule)
11854 (org-add-log-setup 'delschedule nil old-date 'findpos
11855 org-log-reschedule))
11856 (org-remove-timestamp-with-keyword org-scheduled-string)
11857 (message "Item is no longer scheduled."))
11858 (org-add-planning-info 'scheduled time 'closed)
11859 (when (and old-date org-log-reschedule
11860 (not (equal old-date
11861 (substring org-last-inserted-timestamp 1 -1))))
11862 (org-add-log-setup 'reschedule nil old-date 'findpos
11863 org-log-reschedule))
11864 (when repeater
11865 (save-excursion
11866 (org-back-to-heading t)
11867 (when (re-search-forward (concat org-scheduled-string " "
11868 org-last-inserted-timestamp)
11869 (save-excursion
11870 (outline-next-heading) (point)) t)
11871 (goto-char (1- (match-end 0)))
11872 (insert " " repeater)
11873 (setq org-last-inserted-timestamp
11874 (concat (substring org-last-inserted-timestamp 0 -1)
11875 " " repeater
11876 (substring org-last-inserted-timestamp -1))))))
11877 (message "Scheduled to %s" org-last-inserted-timestamp))))
11879 (defun org-get-scheduled-time (pom &optional inherit)
11880 "Get the scheduled time as a time tuple, of a format suitable
11881 for calling org-schedule with, or if there is no scheduling,
11882 returns nil."
11883 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
11884 (when time
11885 (apply 'encode-time (org-parse-time-string time)))))
11887 (defun org-get-deadline-time (pom &optional inherit)
11888 "Get the deadline as a time tuple, of a format suitable for
11889 calling org-deadline with, or if there is no scheduling, returns
11890 nil."
11891 (let ((time (org-entry-get pom "DEADLINE" inherit)))
11892 (when time
11893 (apply 'encode-time (org-parse-time-string time)))))
11895 (defun org-remove-timestamp-with-keyword (keyword)
11896 "Remove all time stamps with KEYWORD in the current entry."
11897 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
11898 beg)
11899 (save-excursion
11900 (org-back-to-heading t)
11901 (setq beg (point))
11902 (outline-next-heading)
11903 (while (re-search-backward re beg t)
11904 (replace-match "")
11905 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
11906 (equal (char-before) ?\ ))
11907 (backward-delete-char 1)
11908 (if (string-match "^[ \t]*$" (buffer-substring
11909 (point-at-bol) (point-at-eol)))
11910 (delete-region (point-at-bol)
11911 (min (point-max) (1+ (point-at-eol))))))))))
11913 (defun org-add-planning-info (what &optional time &rest remove)
11914 "Insert new timestamp with keyword in the line directly after the headline.
11915 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
11916 If non is given, the user is prompted for a date.
11917 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11918 be removed."
11919 (interactive)
11920 (let (org-time-was-given org-end-time-was-given ts
11921 end default-time default-input)
11923 (catch 'exit
11924 (when (and (memq what '(scheduled deadline))
11925 (or (not time)
11926 (and (stringp time)
11927 (string-match "^[-+]+[0-9]" time))))
11928 ;; Try to get a default date/time from existing timestamp
11929 (save-excursion
11930 (org-back-to-heading t)
11931 (setq end (save-excursion (outline-next-heading) (point)))
11932 (when (re-search-forward (if (eq what 'scheduled)
11933 org-scheduled-time-regexp
11934 org-deadline-time-regexp)
11935 end t)
11936 (setq ts (match-string 1)
11937 default-time
11938 (apply 'encode-time (org-parse-time-string ts))
11939 default-input (and ts (org-get-compact-tod ts))))))
11940 (when what
11941 (setq time
11942 (if (and (stringp time)
11943 (string-match "^[-+]+[0-9]" time))
11944 ;; This is a relative time, set the proper date
11945 (apply 'encode-time
11946 (org-read-date-analyze
11947 time default-time (decode-time default-time)))
11948 ;; If necessary, get the time from the user
11949 (or time (org-read-date nil 'to-time nil nil
11950 default-time default-input)))))
11952 (when (and org-insert-labeled-timestamps-at-point
11953 (member what '(scheduled deadline)))
11954 (insert
11955 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11956 (org-insert-time-stamp time org-time-was-given
11957 nil nil nil (list org-end-time-was-given))
11958 (setq what nil))
11959 (save-excursion
11960 (save-restriction
11961 (let (col list elt ts buffer-invisibility-spec)
11962 (org-back-to-heading t)
11963 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
11964 (goto-char (match-end 1))
11965 (setq col (current-column))
11966 (goto-char (match-end 0))
11967 (if (eobp) (insert "\n") (forward-char 1))
11968 (when (and (not what)
11969 (not (looking-at
11970 (concat "[ \t]*"
11971 org-keyword-time-not-clock-regexp))))
11972 ;; Nothing to add, nothing to remove...... :-)
11973 (throw 'exit nil))
11974 (if (and (not (looking-at org-outline-regexp))
11975 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11976 "[^\r\n]*"))
11977 (not (equal (match-string 1) org-clock-string)))
11978 (narrow-to-region (match-beginning 0) (match-end 0))
11979 (insert-before-markers "\n")
11980 (backward-char 1)
11981 (narrow-to-region (point) (point))
11982 (and org-adapt-indentation (org-indent-to-column col)))
11983 ;; Check if we have to remove something.
11984 (setq list (cons what remove))
11985 (while list
11986 (setq elt (pop list))
11987 (when (or (and (eq elt 'scheduled)
11988 (re-search-forward org-scheduled-time-regexp nil t))
11989 (and (eq elt 'deadline)
11990 (re-search-forward org-deadline-time-regexp nil t))
11991 (and (eq elt 'closed)
11992 (re-search-forward org-closed-time-regexp nil t)))
11993 (replace-match "")
11994 (if (looking-at "--+<[^>]+>") (replace-match ""))))
11995 (and (looking-at "[ \t]+") (replace-match ""))
11996 (and org-adapt-indentation (bolp) (org-indent-to-column col))
11997 (when what
11998 (insert
11999 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12000 (cond ((eq what 'scheduled) org-scheduled-string)
12001 ((eq what 'deadline) org-deadline-string)
12002 ((eq what 'closed) org-closed-string))
12003 " ")
12004 (setq ts (org-insert-time-stamp
12005 time
12006 (or org-time-was-given
12007 (and (eq what 'closed) org-log-done-with-time))
12008 (eq what 'closed)
12009 nil nil (list org-end-time-was-given)))
12010 (insert
12011 (if (not (or (bolp) (eq (char-before) ?\ )
12012 (memq (char-after) '(32 10))
12013 (eobp))) " " ""))
12014 (end-of-line 1))
12015 (goto-char (point-min))
12016 (widen)
12017 (if (and (looking-at "[ \t]*\n")
12018 (equal (char-before) ?\n))
12019 (delete-region (1- (point)) (point-at-eol)))
12020 ts))))))
12022 (defvar org-log-note-marker (make-marker))
12023 (defvar org-log-note-purpose nil)
12024 (defvar org-log-note-state nil)
12025 (defvar org-log-note-previous-state nil)
12026 (defvar org-log-note-how nil)
12027 (defvar org-log-note-extra nil)
12028 (defvar org-log-note-window-configuration nil)
12029 (defvar org-log-note-return-to (make-marker))
12030 (defvar org-log-note-effective-time nil
12031 "Remembered current time so that dynamically scoped
12032 `org-extend-today-until' affects tha timestamps in state change
12033 log")
12035 (defvar org-log-post-message nil
12036 "Message to be displayed after a log note has been stored.
12037 The auto-repeater uses this.")
12039 (defun org-add-note ()
12040 "Add a note to the current entry.
12041 This is done in the same way as adding a state change note."
12042 (interactive)
12043 (org-add-log-setup 'note nil nil 'findpos nil))
12045 (defvar org-property-end-re)
12046 (defun org-add-log-setup (&optional purpose state prev-state
12047 findpos how extra)
12048 "Set up the post command hook to take a note.
12049 If this is about to TODO state change, the new state is expected in STATE.
12050 When FINDPOS is non-nil, find the correct position for the note in
12051 the current entry. If not, assume that it can be inserted at point.
12052 HOW is an indicator what kind of note should be created.
12053 EXTRA is additional text that will be inserted into the notes buffer."
12054 (let* ((org-log-into-drawer (org-log-into-drawer))
12055 (drawer (cond ((stringp org-log-into-drawer)
12056 org-log-into-drawer)
12057 (org-log-into-drawer "LOGBOOK")
12058 (t nil))))
12059 (save-restriction
12060 (save-excursion
12061 (when findpos
12062 (org-back-to-heading t)
12063 (narrow-to-region (point) (save-excursion
12064 (outline-next-heading) (point)))
12065 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12066 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12067 "[^\r\n]*\\)?"))
12068 (goto-char (match-end 0))
12069 (cond
12070 (drawer
12071 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12072 nil t)
12073 (progn
12074 (goto-char (match-end 0))
12075 (or org-log-states-order-reversed
12076 (and (re-search-forward org-property-end-re nil t)
12077 (goto-char (1- (match-beginning 0))))))
12078 (insert "\n:" drawer ":\n:END:")
12079 (beginning-of-line 0)
12080 (org-indent-line-function)
12081 (beginning-of-line 2)
12082 (org-indent-line-function)
12083 (end-of-line 0)))
12084 ((and org-log-state-notes-insert-after-drawers
12085 (save-excursion
12086 (forward-line) (looking-at org-drawer-regexp)))
12087 (forward-line)
12088 (while (looking-at org-drawer-regexp)
12089 (goto-char (match-end 0))
12090 (re-search-forward org-property-end-re (point-max) t)
12091 (forward-line))
12092 (forward-line -1)))
12093 (unless org-log-states-order-reversed
12094 (and (= (char-after) ?\n) (forward-char 1))
12095 (org-skip-over-state-notes)
12096 (skip-chars-backward " \t\n\r")))
12097 (move-marker org-log-note-marker (point))
12098 (setq org-log-note-purpose purpose
12099 org-log-note-state state
12100 org-log-note-previous-state prev-state
12101 org-log-note-how how
12102 org-log-note-extra extra
12103 org-log-note-effective-time (org-current-effective-time))
12104 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12106 (defun org-skip-over-state-notes ()
12107 "Skip past the list of State notes in an entry."
12108 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12109 (when (ignore-errors (goto-char (org-in-item-p)))
12110 (let* ((struct (org-list-struct))
12111 (prevs (org-list-prevs-alist struct)))
12112 (while (looking-at "[ \t]*- State")
12113 (goto-char (or (org-list-get-next-item (point) struct prevs)
12114 (org-list-get-item-end (point) struct)))))))
12116 (defun org-add-log-note (&optional purpose)
12117 "Pop up a window for taking a note, and add this note later at point."
12118 (remove-hook 'post-command-hook 'org-add-log-note)
12119 (setq org-log-note-window-configuration (current-window-configuration))
12120 (delete-other-windows)
12121 (move-marker org-log-note-return-to (point))
12122 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12123 (goto-char org-log-note-marker)
12124 (org-switch-to-buffer-other-window "*Org Note*")
12125 (erase-buffer)
12126 (if (memq org-log-note-how '(time state))
12127 (let (current-prefix-arg) (org-store-log-note))
12128 (let ((org-inhibit-startup t)) (org-mode))
12129 (insert (format "# Insert note for %s.
12130 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12131 (cond
12132 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12133 ((eq org-log-note-purpose 'done) "closed todo item")
12134 ((eq org-log-note-purpose 'state)
12135 (format "state change from \"%s\" to \"%s\""
12136 (or org-log-note-previous-state "")
12137 (or org-log-note-state "")))
12138 ((eq org-log-note-purpose 'reschedule)
12139 "rescheduling")
12140 ((eq org-log-note-purpose 'delschedule)
12141 "no longer scheduled")
12142 ((eq org-log-note-purpose 'redeadline)
12143 "changing deadline")
12144 ((eq org-log-note-purpose 'deldeadline)
12145 "removing deadline")
12146 ((eq org-log-note-purpose 'refile)
12147 "refiling")
12148 ((eq org-log-note-purpose 'note)
12149 "this entry")
12150 (t (error "This should not happen")))))
12151 (if org-log-note-extra (insert org-log-note-extra))
12152 (org-set-local 'org-finish-function 'org-store-log-note)
12153 (run-hooks 'org-log-buffer-setup-hook)))
12155 (defvar org-note-abort nil) ; dynamically scoped
12156 (defun org-store-log-note ()
12157 "Finish taking a log note, and insert it to where it belongs."
12158 (let ((txt (buffer-string))
12159 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12160 lines ind bul)
12161 (kill-buffer (current-buffer))
12162 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12163 (setq txt (replace-match "" t t txt)))
12164 (if (string-match "\\s-+\\'" txt)
12165 (setq txt (replace-match "" t t txt)))
12166 (setq lines (org-split-string txt "\n"))
12167 (when (and note (string-match "\\S-" note))
12168 (setq note
12169 (org-replace-escapes
12170 note
12171 (list (cons "%u" (user-login-name))
12172 (cons "%U" user-full-name)
12173 (cons "%t" (format-time-string
12174 (org-time-stamp-format 'long 'inactive)
12175 org-log-note-effective-time))
12176 (cons "%T" (format-time-string
12177 (org-time-stamp-format 'long nil)
12178 org-log-note-effective-time))
12179 (cons "%d" (format-time-string
12180 (org-time-stamp-format nil 'inactive)
12181 org-log-note-effective-time))
12182 (cons "%D" (format-time-string
12183 (org-time-stamp-format nil nil)
12184 org-log-note-effective-time))
12185 (cons "%s" (if org-log-note-state
12186 (concat "\"" org-log-note-state "\"")
12187 ""))
12188 (cons "%S" (if org-log-note-previous-state
12189 (concat "\"" org-log-note-previous-state "\"")
12190 "\"\"")))))
12191 (if lines (setq note (concat note " \\\\")))
12192 (push note lines))
12193 (when (or current-prefix-arg org-note-abort)
12194 (when org-log-into-drawer
12195 (org-remove-empty-drawer-at
12196 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12197 org-log-note-marker))
12198 (setq lines nil))
12199 (when lines
12200 (with-current-buffer (marker-buffer org-log-note-marker)
12201 (save-excursion
12202 (goto-char org-log-note-marker)
12203 (move-marker org-log-note-marker nil)
12204 (end-of-line 1)
12205 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12206 (setq ind (save-excursion
12207 (if (ignore-errors (goto-char (org-in-item-p)))
12208 (let ((struct (org-list-struct)))
12209 (org-list-get-ind
12210 (org-list-get-top-point struct) struct))
12211 (skip-chars-backward " \r\t\n")
12212 (cond
12213 ((and (org-at-heading-p)
12214 org-adapt-indentation)
12215 (1+ (org-current-level)))
12216 ((org-at-heading-p) 0)
12217 (t (org-get-indentation))))))
12218 (setq bul (org-list-bullet-string "-"))
12219 (org-indent-line-to ind)
12220 (insert bul (pop lines))
12221 (let ((ind-body (+ (length bul) ind)))
12222 (while lines
12223 (insert "\n")
12224 (org-indent-line-to ind-body)
12225 (insert (pop lines))))
12226 (message "Note stored")
12227 (org-back-to-heading t)
12228 (org-cycle-hide-drawers 'children)))))
12229 (set-window-configuration org-log-note-window-configuration)
12230 (with-current-buffer (marker-buffer org-log-note-return-to)
12231 (goto-char org-log-note-return-to))
12232 (move-marker org-log-note-return-to nil)
12233 (and org-log-post-message (message "%s" org-log-post-message)))
12235 (defun org-remove-empty-drawer-at (drawer pos)
12236 "Remove an empty drawer DRAWER at position POS.
12237 POS may also be a marker."
12238 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12239 (save-excursion
12240 (save-restriction
12241 (widen)
12242 (goto-char pos)
12243 (if (org-in-regexp
12244 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12245 (replace-match ""))))))
12247 (defun org-sparse-tree (&optional arg)
12248 "Create a sparse tree, prompt for the details.
12249 This command can create sparse trees. You first need to select the type
12250 of match used to create the tree:
12252 t Show all TODO entries.
12253 T Show entries with a specific TODO keyword.
12254 m Show entries selected by a tags/property match.
12255 p Enter a property name and its value (both with completion on existing
12256 names/values) and show entries with that property.
12257 r Show entries matching a regular expression (`/' can be used as well)
12258 d Show deadlines due within `org-deadline-warning-days'.
12259 b Show deadlines and scheduled items before a date.
12260 a Show deadlines and scheduled items after a date."
12261 (interactive "P")
12262 (let (ans kwd value)
12263 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date")
12264 (setq ans (read-char-exclusive))
12265 (cond
12266 ((equal ans ?d)
12267 (call-interactively 'org-check-deadlines))
12268 ((equal ans ?b)
12269 (call-interactively 'org-check-before-date))
12270 ((equal ans ?a)
12271 (call-interactively 'org-check-after-date))
12272 ((equal ans ?t)
12273 (org-show-todo-tree nil))
12274 ((equal ans ?T)
12275 (org-show-todo-tree '(4)))
12276 ((member ans '(?T ?m))
12277 (call-interactively 'org-match-sparse-tree))
12278 ((member ans '(?p ?P))
12279 (setq kwd (org-icompleting-read "Property: "
12280 (mapcar 'list (org-buffer-property-keys))))
12281 (setq value (org-icompleting-read "Value: "
12282 (mapcar 'list (org-property-values kwd))))
12283 (unless (string-match "\\`{.*}\\'" value)
12284 (setq value (concat "\"" value "\"")))
12285 (org-match-sparse-tree arg (concat kwd "=" value)))
12286 ((member ans '(?r ?R ?/))
12287 (call-interactively 'org-occur))
12288 (t (error "No such sparse tree command \"%c\"" ans)))))
12290 (defvar org-occur-highlights nil
12291 "List of overlays used for occur matches.")
12292 (make-variable-buffer-local 'org-occur-highlights)
12293 (defvar org-occur-parameters nil
12294 "Parameters of the active org-occur calls.
12295 This is a list, each call to org-occur pushes as cons cell,
12296 containing the regular expression and the callback, onto the list.
12297 The list can contain several entries if `org-occur' has been called
12298 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12299 will only contain one set of parameters. When the highlights are
12300 removed (for example with `C-c C-c', or with the next edit (depending
12301 on `org-remove-highlights-with-change'), this variable is emptied
12302 as well.")
12303 (make-variable-buffer-local 'org-occur-parameters)
12305 (defun org-occur (regexp &optional keep-previous callback)
12306 "Make a compact tree which shows all matches of REGEXP.
12307 The tree will show the lines where the regexp matches, and all higher
12308 headlines above the match. It will also show the heading after the match,
12309 to make sure editing the matching entry is easy.
12310 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12311 call to `org-occur' will be kept, to allow stacking of calls to this
12312 command.
12313 If CALLBACK is non-nil, it is a function which is called to confirm
12314 that the match should indeed be shown."
12315 (interactive "sRegexp: \nP")
12316 (when (equal regexp "")
12317 (error "Regexp cannot be empty"))
12318 (unless keep-previous
12319 (org-remove-occur-highlights nil nil t))
12320 (push (cons regexp callback) org-occur-parameters)
12321 (let ((cnt 0))
12322 (save-excursion
12323 (goto-char (point-min))
12324 (if (or (not keep-previous) ; do not want to keep
12325 (not org-occur-highlights)) ; no previous matches
12326 ;; hide everything
12327 (org-overview))
12328 (while (re-search-forward regexp nil t)
12329 (when (or (not callback)
12330 (save-match-data (funcall callback)))
12331 (setq cnt (1+ cnt))
12332 (when org-highlight-sparse-tree-matches
12333 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12334 (org-show-context 'occur-tree))))
12335 (when org-remove-highlights-with-change
12336 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12337 nil 'local))
12338 (unless org-sparse-tree-open-archived-trees
12339 (org-hide-archived-subtrees (point-min) (point-max)))
12340 (run-hooks 'org-occur-hook)
12341 (if (org-called-interactively-p 'interactive)
12342 (message "%d match(es) for regexp %s" cnt regexp))
12343 cnt))
12345 (defun org-occur-next-match (&optional n reset)
12346 "Function for `next-error-function' to find sparse tree matches.
12347 N is the number of matches to move, when negative move backwards.
12348 RESET is entirely ignored - this function always goes back to the
12349 starting point when no match is found."
12350 (let* ((limit (if (< n 0) (point-min) (point-max)))
12351 (search-func (if (< n 0)
12352 'previous-single-char-property-change
12353 'next-single-char-property-change))
12354 (n (abs n))
12355 (pos (point))
12357 (catch 'exit
12358 (while (setq p1 (funcall search-func (point) 'org-type))
12359 (when (equal p1 limit)
12360 (goto-char pos)
12361 (error "No more matches"))
12362 (when (equal (get-char-property p1 'org-type) 'org-occur)
12363 (setq n (1- n))
12364 (when (= n 0)
12365 (goto-char p1)
12366 (throw 'exit (point))))
12367 (goto-char p1))
12368 (goto-char p1)
12369 (error "No more matches"))))
12371 (defun org-show-context (&optional key)
12372 "Make sure point and context are visible.
12373 How much context is shown depends upon the variables
12374 `org-show-hierarchy-above', `org-show-following-heading'. and
12375 `org-show-siblings'."
12376 (let ((heading-p (org-on-heading-p t))
12377 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12378 (following-p (org-get-alist-option org-show-following-heading key))
12379 (entry-p (org-get-alist-option org-show-entry-below key))
12380 (siblings-p (org-get-alist-option org-show-siblings key)))
12381 (catch 'exit
12382 ;; Show heading or entry text
12383 (if (and heading-p (not entry-p))
12384 (org-flag-heading nil) ; only show the heading
12385 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12386 (org-show-hidden-entry))) ; show entire entry
12387 (when following-p
12388 ;; Show next sibling, or heading below text
12389 (save-excursion
12390 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12391 (org-flag-heading nil))))
12392 (when siblings-p (org-show-siblings))
12393 (when hierarchy-p
12394 ;; show all higher headings, possibly with siblings
12395 (save-excursion
12396 (while (and (condition-case nil
12397 (progn (org-up-heading-all 1) t)
12398 (error nil))
12399 (not (bobp)))
12400 (org-flag-heading nil)
12401 (when siblings-p (org-show-siblings))))))))
12403 (defvar org-reveal-start-hook nil
12404 "Hook run before revealing a location.")
12406 (defun org-reveal (&optional siblings)
12407 "Show current entry, hierarchy above it, and the following headline.
12408 This can be used to show a consistent set of context around locations
12409 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12410 not t for the search context.
12412 With optional argument SIBLINGS, on each level of the hierarchy all
12413 siblings are shown. This repairs the tree structure to what it would
12414 look like when opened with hierarchical calls to `org-cycle'.
12415 With double optional argument \\[universal-argument] \\[universal-argument], \
12416 go to the parent and show the
12417 entire tree."
12418 (interactive "P")
12419 (run-hooks 'org-reveal-start-hook)
12420 (let ((org-show-hierarchy-above t)
12421 (org-show-following-heading t)
12422 (org-show-siblings (if siblings t org-show-siblings)))
12423 (org-show-context nil))
12424 (when (equal siblings '(16))
12425 (save-excursion
12426 (when (org-up-heading-safe)
12427 (org-show-subtree)
12428 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12430 (defun org-highlight-new-match (beg end)
12431 "Highlight from BEG to END and mark the highlight is an occur headline."
12432 (let ((ov (make-overlay beg end)))
12433 (overlay-put ov 'face 'secondary-selection)
12434 (overlay-put ov 'org-type 'org-occur)
12435 (push ov org-occur-highlights)))
12437 (defun org-remove-occur-highlights (&optional beg end noremove)
12438 "Remove the occur highlights from the buffer.
12439 BEG and END are ignored. If NOREMOVE is nil, remove this function
12440 from the `before-change-functions' in the current buffer."
12441 (interactive)
12442 (unless org-inhibit-highlight-removal
12443 (mapc 'delete-overlay org-occur-highlights)
12444 (setq org-occur-highlights nil)
12445 (setq org-occur-parameters nil)
12446 (unless noremove
12447 (remove-hook 'before-change-functions
12448 'org-remove-occur-highlights 'local))))
12450 ;;;; Priorities
12452 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12453 "Regular expression matching the priority indicator.")
12455 (defvar org-remove-priority-next-time nil)
12457 (defun org-priority-up ()
12458 "Increase the priority of the current item."
12459 (interactive)
12460 (org-priority 'up))
12462 (defun org-priority-down ()
12463 "Decrease the priority of the current item."
12464 (interactive)
12465 (org-priority 'down))
12467 (defun org-priority (&optional action)
12468 "Change the priority of an item by ARG.
12469 ACTION can be `set', `up', `down', or a character."
12470 (interactive)
12471 (unless org-enable-priority-commands
12472 (error "Priority commands are disabled"))
12473 (setq action (or action 'set))
12474 (let (current new news have remove)
12475 (save-excursion
12476 (org-back-to-heading t)
12477 (if (looking-at org-priority-regexp)
12478 (setq current (string-to-char (match-string 2))
12479 have t))
12480 (cond
12481 ((eq action 'remove)
12482 (setq remove t new ?\ ))
12483 ((or (eq action 'set)
12484 (if (featurep 'xemacs) (characterp action) (integerp action)))
12485 (if (not (eq action 'set))
12486 (setq new action)
12487 (message "Priority %c-%c, SPC to remove: "
12488 org-highest-priority org-lowest-priority)
12489 (save-match-data
12490 (setq new (read-char-exclusive))))
12491 (if (and (= (upcase org-highest-priority) org-highest-priority)
12492 (= (upcase org-lowest-priority) org-lowest-priority))
12493 (setq new (upcase new)))
12494 (cond ((equal new ?\ ) (setq remove t))
12495 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12496 (error "Priority must be between `%c' and `%c'"
12497 org-highest-priority org-lowest-priority))))
12498 ((eq action 'up)
12499 (setq new (if have
12500 (1- current) ; normal cycling
12501 ;; last priority was empty
12502 (if (eq last-command this-command)
12503 org-lowest-priority ; wrap around empty to lowest
12504 ;; default
12505 (if org-priority-start-cycle-with-default
12506 org-default-priority
12507 (1- org-default-priority))))))
12508 ((eq action 'down)
12509 (setq new (if have
12510 (1+ current) ; normal cycling
12511 ;; last priority was empty
12512 (if (eq last-command this-command)
12513 org-highest-priority ; wrap around empty to highest
12514 ;; default
12515 (if org-priority-start-cycle-with-default
12516 org-default-priority
12517 (1+ org-default-priority))))))
12518 (t (error "Invalid action")))
12519 (if (or (< (upcase new) org-highest-priority)
12520 (> (upcase new) org-lowest-priority))
12521 (if (and (memq action '(up down))
12522 (not have) (not (eq last-command this-command)))
12523 ;; `new' is from default priority
12524 (error
12525 "The default can not be set, see `org-default-priority' why")
12526 ;; normal cycling: `new' is beyond highest/lowest priority
12527 ;; and is wrapped around to the empty priority
12528 (setq remove t)))
12529 (setq news (format "%c" new))
12530 (if have
12531 (if remove
12532 (replace-match "" t t nil 1)
12533 (replace-match news t t nil 2))
12534 (if remove
12535 (error "No priority cookie found in line")
12536 (let ((case-fold-search nil))
12537 (looking-at org-todo-line-regexp))
12538 (if (match-end 2)
12539 (progn
12540 (goto-char (match-end 2))
12541 (insert " [#" news "]"))
12542 (goto-char (match-beginning 3))
12543 (insert "[#" news "] "))))
12544 (org-preserve-lc (org-set-tags nil 'align)))
12545 (if remove
12546 (message "Priority removed")
12547 (message "Priority of current item set to %s" news))))
12549 (defun org-get-priority (s)
12550 "Find priority cookie and return priority."
12551 (if (functionp org-get-priority-function)
12552 (funcall org-get-priority-function)
12553 (save-match-data
12554 (if (not (string-match org-priority-regexp s))
12555 (* 1000 (- org-lowest-priority org-default-priority))
12556 (* 1000 (- org-lowest-priority
12557 (string-to-char (match-string 2 s))))))))
12559 ;;;; Tags
12561 (defvar org-agenda-archives-mode)
12562 (defvar org-map-continue-from nil
12563 "Position from where mapping should continue.
12564 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
12566 (defvar org-scanner-tags nil
12567 "The current tag list while the tags scanner is running.")
12568 (defvar org-trust-scanner-tags nil
12569 "Should `org-get-tags-at' use the tags for the scanner.
12570 This is for internal dynamical scoping only.
12571 When this is non-nil, the function `org-get-tags-at' will return the value
12572 of `org-scanner-tags' instead of building the list by itself. This
12573 can lead to large speed-ups when the tags scanner is used in a file with
12574 many entries, and when the list of tags is retrieved, for example to
12575 obtain a list of properties. Building the tags list for each entry in such
12576 a file becomes an N^2 operation - but with this variable set, it scales
12577 as N.")
12579 (defun org-scan-tags (action matcher &optional todo-only)
12580 "Scan headline tags with inheritance and produce output ACTION.
12582 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12583 or `agenda' to produce an entry list for an agenda view. It can also be
12584 a Lisp form or a function that should be called at each matched headline, in
12585 this case the return value is a list of all return values from these calls.
12587 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12588 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12589 only lines with a TODO keyword are included in the output."
12590 (require 'org-agenda)
12591 (let* ((re (concat "^" org-outline-regexp " *\\(\\<\\("
12592 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12593 (org-re
12594 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12595 (props (list 'face 'default
12596 'done-face 'org-agenda-done
12597 'undone-face 'default
12598 'mouse-face 'highlight
12599 'org-not-done-regexp org-not-done-regexp
12600 'org-todo-regexp org-todo-regexp
12601 'help-echo
12602 (format "mouse-2 or RET jump to org file %s"
12603 (abbreviate-file-name
12604 (or (buffer-file-name (buffer-base-buffer))
12605 (buffer-name (buffer-base-buffer)))))))
12606 (case-fold-search nil)
12607 (org-map-continue-from nil)
12608 lspos tags tags-list
12609 (tags-alist (list (cons 0 org-file-tags)))
12610 (llast 0) rtn rtn1 level category i txt
12611 todo marker entry priority)
12612 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12613 (setq action (list 'lambda nil action)))
12614 (save-excursion
12615 (goto-char (point-min))
12616 (when (eq action 'sparse-tree)
12617 (org-overview)
12618 (org-remove-occur-highlights))
12619 (while (re-search-forward re nil t)
12620 (catch :skip
12621 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12622 tags (if (match-end 4) (org-match-string-no-properties 4)))
12623 (goto-char (setq lspos (match-beginning 0)))
12624 (setq level (org-reduced-level (funcall outline-level))
12625 category (org-get-category))
12626 (setq i llast llast level)
12627 ;; remove tag lists from same and sublevels
12628 (while (>= i level)
12629 (when (setq entry (assoc i tags-alist))
12630 (setq tags-alist (delete entry tags-alist)))
12631 (setq i (1- i)))
12632 ;; add the next tags
12633 (when tags
12634 (setq tags (org-split-string tags ":")
12635 tags-alist
12636 (cons (cons level tags) tags-alist)))
12637 ;; compile tags for current headline
12638 (setq tags-list
12639 (if org-use-tag-inheritance
12640 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12641 tags)
12642 org-scanner-tags tags-list)
12643 (when org-use-tag-inheritance
12644 (setcdr (car tags-alist)
12645 (mapcar (lambda (x)
12646 (setq x (copy-sequence x))
12647 (org-add-prop-inherited x))
12648 (cdar tags-alist))))
12649 (when (and tags org-use-tag-inheritance
12650 (or (not (eq t org-use-tag-inheritance))
12651 org-tags-exclude-from-inheritance))
12652 ;; selective inheritance, remove uninherited ones
12653 (setcdr (car tags-alist)
12654 (org-remove-uninherited-tags (cdar tags-alist))))
12655 (when (and
12657 ;; eval matcher only when the todo condition is OK
12658 (and (or (not todo-only) (member todo org-not-done-keywords))
12659 (let ((case-fold-search t)) (eval matcher)))
12661 ;; Call the skipper, but return t if it does not skip,
12662 ;; so that the `and' form continues evaluating
12663 (progn
12664 (unless (eq action 'sparse-tree) (org-agenda-skip))
12667 ;; Check if timestamps are deselecting this entry
12668 (or (not todo-only)
12669 (and (member todo org-not-done-keywords)
12670 (or (not org-agenda-tags-todo-honor-ignore-options)
12671 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12673 ;; Extra check for the archive tag
12674 ;; FIXME: Does the skipper already do this????
12676 (not (member org-archive-tag tags-list))
12677 ;; we have an archive tag, should we use this anyway?
12678 (or (not org-agenda-skip-archived-trees)
12679 (and (eq action 'agenda) org-agenda-archives-mode))))
12681 ;; select this headline
12683 (cond
12684 ((eq action 'sparse-tree)
12685 (and org-highlight-sparse-tree-matches
12686 (org-get-heading) (match-end 0)
12687 (org-highlight-new-match
12688 (match-beginning 0) (match-beginning 1)))
12689 (org-show-context 'tags-tree))
12690 ((eq action 'agenda)
12691 (setq txt (org-format-agenda-item
12693 (concat
12694 (if (eq org-tags-match-list-sublevels 'indented)
12695 (make-string (1- level) ?.) "")
12696 (org-get-heading))
12697 category
12698 tags-list
12700 priority (org-get-priority txt))
12701 (goto-char lspos)
12702 (setq marker (org-agenda-new-marker))
12703 (org-add-props txt props
12704 'org-marker marker 'org-hd-marker marker 'org-category category
12705 'todo-state todo
12706 'priority priority 'type "tagsmatch")
12707 (push txt rtn))
12708 ((functionp action)
12709 (setq org-map-continue-from nil)
12710 (save-excursion
12711 (setq rtn1 (funcall action))
12712 (push rtn1 rtn)))
12713 (t (error "Invalid action")))
12715 ;; if we are to skip sublevels, jump to end of subtree
12716 (unless org-tags-match-list-sublevels
12717 (org-end-of-subtree t)
12718 (backward-char 1))))
12719 ;; Get the correct position from where to continue
12720 (if org-map-continue-from
12721 (goto-char org-map-continue-from)
12722 (and (= (point) lspos) (end-of-line 1)))))
12723 (when (and (eq action 'sparse-tree)
12724 (not org-sparse-tree-open-archived-trees))
12725 (org-hide-archived-subtrees (point-min) (point-max)))
12726 (nreverse rtn)))
12728 (defun org-remove-uninherited-tags (tags)
12729 "Remove all tags that are not inherited from the list TAGS."
12730 (cond
12731 ((eq org-use-tag-inheritance t)
12732 (if org-tags-exclude-from-inheritance
12733 (org-delete-all org-tags-exclude-from-inheritance tags)
12734 tags))
12735 ((not org-use-tag-inheritance) nil)
12736 ((stringp org-use-tag-inheritance)
12737 (delq nil (mapcar
12738 (lambda (x)
12739 (if (and (string-match org-use-tag-inheritance x)
12740 (not (member x org-tags-exclude-from-inheritance)))
12741 x nil))
12742 tags)))
12743 ((listp org-use-tag-inheritance)
12744 (delq nil (mapcar
12745 (lambda (x)
12746 (if (member x org-use-tag-inheritance) x nil))
12747 tags)))))
12749 (defvar todo-only) ;; dynamically scoped
12751 (defun org-match-sparse-tree (&optional todo-only match)
12752 "Create a sparse tree according to tags string MATCH.
12753 MATCH can contain positive and negative selection of tags, like
12754 \"+WORK+URGENT-WITHBOSS\".
12755 If optional argument TODO-ONLY is non-nil, only select lines that are
12756 also TODO lines."
12757 (interactive "P")
12758 (org-prepare-agenda-buffers (list (current-buffer)))
12759 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12761 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12763 (defvar org-cached-props nil)
12764 (defun org-cached-entry-get (pom property)
12765 (if (or (eq t org-use-property-inheritance)
12766 (and (stringp org-use-property-inheritance)
12767 (string-match org-use-property-inheritance property))
12768 (and (listp org-use-property-inheritance)
12769 (member property org-use-property-inheritance)))
12770 ;; Caching is not possible, check it directly
12771 (org-entry-get pom property 'inherit)
12772 ;; Get all properties, so that we can do complicated checks easily
12773 (cdr (assoc property (or org-cached-props
12774 (setq org-cached-props
12775 (org-entry-properties pom)))))))
12777 (defun org-global-tags-completion-table (&optional files)
12778 "Return the list of all tags in all agenda buffer/files.
12779 Optional FILES argument is a list of files to which can be used
12780 instead of the agenda files."
12781 (save-excursion
12782 (org-uniquify
12783 (delq nil
12784 (apply 'append
12785 (mapcar
12786 (lambda (file)
12787 (set-buffer (find-file-noselect file))
12788 (append (org-get-buffer-tags)
12789 (mapcar (lambda (x) (if (stringp (car-safe x))
12790 (list (car-safe x)) nil))
12791 org-tag-alist)))
12792 (if (and files (car files))
12793 files
12794 (org-agenda-files))))))))
12796 (defun org-make-tags-matcher (match)
12797 "Create the TAGS/TODO matcher form for the selection string MATCH."
12798 ;; todo-only is scoped dynamically into this function, and the function
12799 ;; may change it if the matcher asks for it.
12800 (unless match
12801 ;; Get a new match request, with completion
12802 (let ((org-last-tags-completion-table
12803 (org-global-tags-completion-table)))
12804 (setq match (org-completing-read-no-i
12805 "Match: " 'org-tags-completion-function nil nil nil
12806 'org-tags-history))))
12808 ;; Parse the string and create a lisp form
12809 (let ((match0 match)
12810 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
12811 minus tag mm
12812 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12813 orterms term orlist re-p str-p level-p level-op time-p
12814 prop-p pn pv po gv rest)
12815 (if (string-match "/+" match)
12816 ;; match contains also a todo-matching request
12817 (progn
12818 (setq tagsmatch (substring match 0 (match-beginning 0))
12819 todomatch (substring match (match-end 0)))
12820 (if (string-match "^!" todomatch)
12821 (setq todo-only t todomatch (substring todomatch 1)))
12822 (if (string-match "^\\s-*$" todomatch)
12823 (setq todomatch nil)))
12824 ;; only matching tags
12825 (setq tagsmatch match todomatch nil))
12827 ;; Make the tags matcher
12828 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12829 (setq tagsmatcher t)
12830 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12831 (while (setq term (pop orterms))
12832 (while (and (equal (substring term -1) "\\") orterms)
12833 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12834 (while (string-match re term)
12835 (setq rest (substring term (match-end 0))
12836 minus (and (match-end 1)
12837 (equal (match-string 1 term) "-"))
12838 tag (save-match-data (replace-regexp-in-string
12839 "\\\\-" "-"
12840 (match-string 2 term)))
12841 re-p (equal (string-to-char tag) ?{)
12842 level-p (match-end 4)
12843 prop-p (match-end 5)
12844 mm (cond
12845 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12846 (level-p
12847 (setq level-op (org-op-to-function (match-string 3 term)))
12848 `(,level-op level ,(string-to-number
12849 (match-string 4 term))))
12850 (prop-p
12851 (setq pn (match-string 5 term)
12852 po (match-string 6 term)
12853 pv (match-string 7 term)
12854 re-p (equal (string-to-char pv) ?{)
12855 str-p (equal (string-to-char pv) ?\")
12856 time-p (save-match-data
12857 (string-match "^\"[[<].*[]>]\"$" pv))
12858 pv (if (or re-p str-p) (substring pv 1 -1) pv))
12859 (if time-p (setq pv (org-matcher-time pv)))
12860 (setq po (org-op-to-function po (if time-p 'time str-p)))
12861 (cond
12862 ((equal pn "CATEGORY")
12863 (setq gv '(get-text-property (point) 'org-category)))
12864 ((equal pn "TODO")
12865 (setq gv 'todo))
12867 (setq gv `(org-cached-entry-get nil ,pn))))
12868 (if re-p
12869 (if (eq po 'org<>)
12870 `(not (string-match ,pv (or ,gv "")))
12871 `(string-match ,pv (or ,gv "")))
12872 (if str-p
12873 `(,po (or ,gv "") ,pv)
12874 `(,po (string-to-number (or ,gv ""))
12875 ,(string-to-number pv) ))))
12876 (t `(member ,tag tags-list)))
12877 mm (if minus (list 'not mm) mm)
12878 term rest)
12879 (push mm tagsmatcher))
12880 (push (if (> (length tagsmatcher) 1)
12881 (cons 'and tagsmatcher)
12882 (car tagsmatcher))
12883 orlist)
12884 (setq tagsmatcher nil))
12885 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
12886 (setq tagsmatcher
12887 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
12888 ;; Make the todo matcher
12889 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
12890 (setq todomatcher t)
12891 (setq orterms (org-split-string todomatch "|") orlist nil)
12892 (while (setq term (pop orterms))
12893 (while (string-match re term)
12894 (setq minus (and (match-end 1)
12895 (equal (match-string 1 term) "-"))
12896 kwd (match-string 2 term)
12897 re-p (equal (string-to-char kwd) ?{)
12898 term (substring term (match-end 0))
12899 mm (if re-p
12900 `(string-match ,(substring kwd 1 -1) todo)
12901 (list 'equal 'todo kwd))
12902 mm (if minus (list 'not mm) mm))
12903 (push mm todomatcher))
12904 (push (if (> (length todomatcher) 1)
12905 (cons 'and todomatcher)
12906 (car todomatcher))
12907 orlist)
12908 (setq todomatcher nil))
12909 (setq todomatcher (if (> (length orlist) 1)
12910 (cons 'or orlist) (car orlist))))
12912 ;; Return the string and lisp forms of the matcher
12913 (setq matcher (if todomatcher
12914 (list 'and tagsmatcher todomatcher)
12915 tagsmatcher))
12916 (cons match0 matcher)))
12918 (defun org-op-to-function (op &optional stringp)
12919 "Turn an operator into the appropriate function."
12920 (setq op
12921 (cond
12922 ((equal op "<" ) '(< string< org-time<))
12923 ((equal op ">" ) '(> org-string> org-time>))
12924 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
12925 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
12926 ((member op '("=" "==")) '(= string= org-time=))
12927 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
12928 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
12930 (defun org<> (a b) (not (= a b)))
12931 (defun org-string<= (a b) (or (string= a b) (string< a b)))
12932 (defun org-string>= (a b) (not (string< a b)))
12933 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
12934 (defun org-string<> (a b) (not (string= a b)))
12935 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
12936 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
12937 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
12938 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
12939 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
12940 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
12941 (defun org-2ft (s)
12942 "Convert S to a floating point time.
12943 If S is already a number, just return it. If it is a string, parse
12944 it as a time string and apply `float-time' to it. If S is nil, just return 0."
12945 (cond
12946 ((numberp s) s)
12947 ((stringp s)
12948 (condition-case nil
12949 (float-time (apply 'encode-time (org-parse-time-string s)))
12950 (error 0.)))
12951 (t 0.)))
12953 (defun org-time-today ()
12954 "Time in seconds today at 0:00.
12955 Returns the float number of seconds since the beginning of the
12956 epoch to the beginning of today (00:00)."
12957 (float-time (apply 'encode-time
12958 (append '(0 0 0) (nthcdr 3 (decode-time))))))
12960 (defun org-matcher-time (s)
12961 "Interpret a time comparison value."
12962 (save-match-data
12963 (cond
12964 ((string= s "<now>") (float-time))
12965 ((string= s "<today>") (org-time-today))
12966 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
12967 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
12968 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
12969 (+ (org-time-today)
12970 (* (string-to-number (match-string 1 s))
12971 (cdr (assoc (match-string 2 s)
12972 '(("d" . 86400.0) ("w" . 604800.0)
12973 ("m" . 2678400.0) ("y" . 31557600.0)))))))
12974 (t (org-2ft s)))))
12976 (defun org-match-any-p (re list)
12977 "Does re match any element of list?"
12978 (setq list (mapcar (lambda (x) (string-match re x)) list))
12979 (delq nil list))
12981 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
12982 (defvar org-tags-overlay (make-overlay 1 1))
12983 (org-detach-overlay org-tags-overlay)
12985 (defun org-get-local-tags-at (&optional pos)
12986 "Get a list of tags defined in the current headline."
12987 (org-get-tags-at pos 'local))
12989 (defun org-get-local-tags ()
12990 "Get a list of tags defined in the current headline."
12991 (org-get-tags-at nil 'local))
12993 (defun org-get-tags-at (&optional pos local)
12994 "Get a list of all headline tags applicable at POS.
12995 POS defaults to point. If tags are inherited, the list contains
12996 the targets in the same sequence as the headlines appear, i.e.
12997 the tags of the current headline come last.
12998 When LOCAL is non-nil, only return tags from the current headline,
12999 ignore inherited ones."
13000 (interactive)
13001 (if (and org-trust-scanner-tags
13002 (or (not pos) (equal pos (point)))
13003 (not local))
13004 org-scanner-tags
13005 (let (tags ltags lastpos parent)
13006 (save-excursion
13007 (save-restriction
13008 (widen)
13009 (goto-char (or pos (point)))
13010 (save-match-data
13011 (catch 'done
13012 (condition-case nil
13013 (progn
13014 (org-back-to-heading t)
13015 (while (not (equal lastpos (point)))
13016 (setq lastpos (point))
13017 (when (looking-at
13018 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13019 (setq ltags (org-split-string
13020 (org-match-string-no-properties 1) ":"))
13021 (when parent
13022 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13023 (setq tags (append
13024 (if parent
13025 (org-remove-uninherited-tags ltags)
13026 ltags)
13027 tags)))
13028 (or org-use-tag-inheritance (throw 'done t))
13029 (if local (throw 'done t))
13030 (or (org-up-heading-safe) (error nil))
13031 (setq parent t)))
13032 (error nil)))))
13033 (if local
13034 tags
13035 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13037 (defun org-add-prop-inherited (s)
13038 (add-text-properties 0 (length s) '(inherited t) s)
13041 (defun org-toggle-tag (tag &optional onoff)
13042 "Toggle the tag TAG for the current line.
13043 If ONOFF is `on' or `off', don't toggle but set to this state."
13044 (let (res current)
13045 (save-excursion
13046 (org-back-to-heading t)
13047 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13048 (point-at-eol) t)
13049 (progn
13050 (setq current (match-string 1))
13051 (replace-match ""))
13052 (setq current ""))
13053 (setq current (nreverse (org-split-string current ":")))
13054 (cond
13055 ((eq onoff 'on)
13056 (setq res t)
13057 (or (member tag current) (push tag current)))
13058 ((eq onoff 'off)
13059 (or (not (member tag current)) (setq current (delete tag current))))
13060 (t (if (member tag current)
13061 (setq current (delete tag current))
13062 (setq res t)
13063 (push tag current))))
13064 (end-of-line 1)
13065 (if current
13066 (progn
13067 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13068 (org-set-tags nil t))
13069 (delete-horizontal-space))
13070 (run-hooks 'org-after-tags-change-hook))
13071 res))
13073 (defun org-align-tags-here (to-col)
13074 ;; Assumes that this is a headline
13075 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13076 (beginning-of-line 1)
13077 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13078 (< pos (match-beginning 2)))
13079 (progn
13080 (setq tags-l (- (match-end 2) (match-beginning 2)))
13081 (goto-char (match-beginning 1))
13082 (insert " ")
13083 (delete-region (point) (1+ (match-beginning 2)))
13084 (setq ncol (max (current-column)
13085 (1+ col)
13086 (if (> to-col 0)
13087 to-col
13088 (- (abs to-col) tags-l))))
13089 (setq p (point))
13090 (insert (make-string (- ncol (current-column)) ?\ ))
13091 (setq ncol (current-column))
13092 (when indent-tabs-mode (tabify p (point-at-eol)))
13093 (org-move-to-column (min ncol col) t))
13094 (goto-char pos))))
13096 (defun org-set-tags-command (&optional arg just-align)
13097 "Call the set-tags command for the current entry."
13098 (interactive "P")
13099 (if (org-on-heading-p)
13100 (org-set-tags arg just-align)
13101 (save-excursion
13102 (org-back-to-heading t)
13103 (org-set-tags arg just-align))))
13105 (defun org-set-tags-to (data)
13106 "Set the tags of the current entry to DATA, replacing the current tags.
13107 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13108 If DATA is nil or the empty string, any tags will be removed."
13109 (interactive "sTags: ")
13110 (setq data
13111 (cond
13112 ((eq data nil) "")
13113 ((equal data "") "")
13114 ((stringp data)
13115 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13116 ":"))
13117 ((listp data)
13118 (concat ":" (mapconcat 'identity data ":") ":"))
13119 (t nil)))
13120 (when data
13121 (save-excursion
13122 (org-back-to-heading t)
13123 (when (looking-at org-complex-heading-regexp)
13124 (if (match-end 5)
13125 (progn
13126 (goto-char (match-beginning 5))
13127 (insert data)
13128 (delete-region (point) (point-at-eol))
13129 (org-set-tags nil 'align))
13130 (goto-char (point-at-eol))
13131 (insert " " data)
13132 (org-set-tags nil 'align)))
13133 (beginning-of-line 1)
13134 (if (looking-at ".*?\\([ \t]+\\)$")
13135 (delete-region (match-beginning 1) (match-end 1))))))
13137 (defun org-align-all-tags ()
13138 "Align the tags i all headings."
13139 (interactive)
13140 (save-excursion
13141 (or (ignore-errors (org-back-to-heading t))
13142 (outline-next-heading))
13143 (if (org-on-heading-p)
13144 (org-set-tags t)
13145 (message "No headings"))))
13147 (defvar org-indent-indentation-per-level)
13148 (defun org-set-tags (&optional arg just-align)
13149 "Set the tags for the current headline.
13150 With prefix ARG, realign all tags in headings in the current buffer."
13151 (interactive "P")
13152 (let* ((re org-outline-regexp-bol)
13153 (current (org-get-tags-string))
13154 (col (current-column))
13155 (org-setting-tags t)
13156 table current-tags inherited-tags ; computed below when needed
13157 tags p0 c0 c1 rpl di tc level)
13158 (if arg
13159 (save-excursion
13160 (goto-char (point-min))
13161 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13162 (while (re-search-forward re nil t)
13163 (org-set-tags nil t)
13164 (end-of-line 1)))
13165 (message "All tags realigned to column %d" org-tags-column))
13166 (if just-align
13167 (setq tags current)
13168 ;; Get a new set of tags from the user
13169 (save-excursion
13170 (setq table (append org-tag-persistent-alist
13171 (or org-tag-alist (org-get-buffer-tags))
13172 (and
13173 org-complete-tags-always-offer-all-agenda-tags
13174 (org-global-tags-completion-table
13175 (org-agenda-files))))
13176 org-last-tags-completion-table table
13177 current-tags (org-split-string current ":")
13178 inherited-tags (nreverse
13179 (nthcdr (length current-tags)
13180 (nreverse (org-get-tags-at))))
13181 tags
13182 (if (or (eq t org-use-fast-tag-selection)
13183 (and org-use-fast-tag-selection
13184 (delq nil (mapcar 'cdr table))))
13185 (org-fast-tag-selection
13186 current-tags inherited-tags table
13187 (if org-fast-tag-selection-include-todo
13188 org-todo-key-alist))
13189 (let ((org-add-colon-after-tag-completion t))
13190 (org-trim
13191 (org-icompleting-read "Tags: "
13192 'org-tags-completion-function
13193 nil nil current 'org-tags-history))))))
13194 (while (string-match "[-+&]+" tags)
13195 ;; No boolean logic, just a list
13196 (setq tags (replace-match ":" t t tags))))
13198 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13200 (if org-tags-sort-function
13201 (setq tags (mapconcat 'identity
13202 (sort (org-split-string
13203 tags (org-re "[^[:alnum:]_@#%]+"))
13204 org-tags-sort-function) ":")))
13206 (if (string-match "\\`[\t ]*\\'" tags)
13207 (setq tags "")
13208 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13209 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13211 ;; Insert new tags at the correct column
13212 (beginning-of-line 1)
13213 (setq level (or (and (looking-at org-outline-regexp)
13214 (- (match-end 0) (point) 1))
13216 (cond
13217 ((and (equal current "") (equal tags "")))
13218 ((re-search-forward
13219 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13220 (point-at-eol) t)
13221 (if (equal tags "")
13222 (setq rpl "")
13223 (goto-char (match-beginning 0))
13224 (setq c0 (current-column)
13225 ;; compute offset for the case of org-indent-mode active
13226 di (if org-indent-mode
13227 (* (1- org-indent-indentation-per-level) (1- level))
13229 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13230 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13231 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13232 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13233 (replace-match rpl t t)
13234 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13235 tags)
13236 (t (error "Tags alignment failed")))
13237 (org-move-to-column col)
13238 (unless just-align
13239 (run-hooks 'org-after-tags-change-hook)))))
13241 (defun org-change-tag-in-region (beg end tag off)
13242 "Add or remove TAG for each entry in the region.
13243 This works in the agenda, and also in an org-mode buffer."
13244 (interactive
13245 (list (region-beginning) (region-end)
13246 (let ((org-last-tags-completion-table
13247 (if (org-mode-p)
13248 (org-get-buffer-tags)
13249 (org-global-tags-completion-table))))
13250 (org-icompleting-read
13251 "Tag: " 'org-tags-completion-function nil nil nil
13252 'org-tags-history))
13253 (progn
13254 (message "[s]et or [r]emove? ")
13255 (equal (read-char-exclusive) ?r))))
13256 (if (fboundp 'deactivate-mark) (deactivate-mark))
13257 (let ((agendap (equal major-mode 'org-agenda-mode))
13258 l1 l2 m buf pos newhead (cnt 0))
13259 (goto-char end)
13260 (setq l2 (1- (org-current-line)))
13261 (goto-char beg)
13262 (setq l1 (org-current-line))
13263 (loop for l from l1 to l2 do
13264 (org-goto-line l)
13265 (setq m (get-text-property (point) 'org-hd-marker))
13266 (when (or (and (org-mode-p) (org-on-heading-p))
13267 (and agendap m))
13268 (setq buf (if agendap (marker-buffer m) (current-buffer))
13269 pos (if agendap m (point)))
13270 (with-current-buffer buf
13271 (save-excursion
13272 (save-restriction
13273 (goto-char pos)
13274 (setq cnt (1+ cnt))
13275 (org-toggle-tag tag (if off 'off 'on))
13276 (setq newhead (org-get-heading)))))
13277 (and agendap (org-agenda-change-all-lines newhead m))))
13278 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13280 (defun org-tags-completion-function (string predicate &optional flag)
13281 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13282 (confirm (lambda (x) (stringp (car x)))))
13283 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13284 (setq s1 (match-string 1 string)
13285 s2 (match-string 2 string))
13286 (setq s1 "" s2 string))
13287 (cond
13288 ((eq flag nil)
13289 ;; try completion
13290 (setq rtn (try-completion s2 ctable confirm))
13291 (if (stringp rtn)
13292 (setq rtn
13293 (concat s1 s2 (substring rtn (length s2))
13294 (if (and org-add-colon-after-tag-completion
13295 (assoc rtn ctable))
13296 ":" ""))))
13297 rtn)
13298 ((eq flag t)
13299 ;; all-completions
13300 (all-completions s2 ctable confirm)
13302 ((eq flag 'lambda)
13303 ;; exact match?
13304 (assoc s2 ctable)))
13307 (defun org-fast-tag-insert (kwd tags face &optional end)
13308 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13309 (insert (format "%-12s" (concat kwd ":"))
13310 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13311 (or end "")))
13313 (defun org-fast-tag-show-exit (flag)
13314 (save-excursion
13315 (org-goto-line 3)
13316 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13317 (replace-match ""))
13318 (when flag
13319 (end-of-line 1)
13320 (org-move-to-column (- (window-width) 19) t)
13321 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13323 (defun org-set-current-tags-overlay (current prefix)
13324 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13325 (if (featurep 'xemacs)
13326 (org-overlay-display org-tags-overlay (concat prefix s)
13327 'secondary-selection)
13328 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13329 (org-overlay-display org-tags-overlay (concat prefix s)))))
13331 (defvar org-last-tag-selection-key nil)
13332 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13333 "Fast tag selection with single keys.
13334 CURRENT is the current list of tags in the headline, INHERITED is the
13335 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13336 possibly with grouping information. TODO-TABLE is a similar table with
13337 TODO keywords, should these have keys assigned to them.
13338 If the keys are nil, a-z are automatically assigned.
13339 Returns the new tags string, or nil to not change the current settings."
13340 (let* ((fulltable (append table todo-table))
13341 (maxlen (apply 'max (mapcar
13342 (lambda (x)
13343 (if (stringp (car x)) (string-width (car x)) 0))
13344 fulltable)))
13345 (buf (current-buffer))
13346 (expert (eq org-fast-tag-selection-single-key 'expert))
13347 (buffer-tags nil)
13348 (fwidth (+ maxlen 3 1 3))
13349 (ncol (/ (- (window-width) 4) fwidth))
13350 (i-face 'org-done)
13351 (c-face 'org-todo)
13352 tg cnt e c char c1 c2 ntable tbl rtn
13353 ov-start ov-end ov-prefix
13354 (exit-after-next org-fast-tag-selection-single-key)
13355 (done-keywords org-done-keywords)
13356 groups ingroup)
13357 (save-excursion
13358 (beginning-of-line 1)
13359 (if (looking-at
13360 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13361 (setq ov-start (match-beginning 1)
13362 ov-end (match-end 1)
13363 ov-prefix "")
13364 (setq ov-start (1- (point-at-eol))
13365 ov-end (1+ ov-start))
13366 (skip-chars-forward "^\n\r")
13367 (setq ov-prefix
13368 (concat
13369 (buffer-substring (1- (point)) (point))
13370 (if (> (current-column) org-tags-column)
13372 (make-string (- org-tags-column (current-column)) ?\ ))))))
13373 (move-overlay org-tags-overlay ov-start ov-end)
13374 (save-window-excursion
13375 (if expert
13376 (set-buffer (get-buffer-create " *Org tags*"))
13377 (delete-other-windows)
13378 (split-window-vertically)
13379 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13380 (erase-buffer)
13381 (org-set-local 'org-done-keywords done-keywords)
13382 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13383 (org-fast-tag-insert "Current" current c-face "\n\n")
13384 (org-fast-tag-show-exit exit-after-next)
13385 (org-set-current-tags-overlay current ov-prefix)
13386 (setq tbl fulltable char ?a cnt 0)
13387 (while (setq e (pop tbl))
13388 (cond
13389 ((equal (car e) :startgroup)
13390 (push '() groups) (setq ingroup t)
13391 (when (not (= cnt 0))
13392 (setq cnt 0)
13393 (insert "\n"))
13394 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13395 ((equal (car e) :endgroup)
13396 (setq ingroup nil cnt 0)
13397 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13398 ((equal e '(:newline))
13399 (when (not (= cnt 0))
13400 (setq cnt 0)
13401 (insert "\n")
13402 (setq e (car tbl))
13403 (while (equal (car tbl) '(:newline))
13404 (insert "\n")
13405 (setq tbl (cdr tbl)))))
13407 (setq tg (copy-sequence (car e)) c2 nil)
13408 (if (cdr e)
13409 (setq c (cdr e))
13410 ;; automatically assign a character.
13411 (setq c1 (string-to-char
13412 (downcase (substring
13413 tg (if (= (string-to-char tg) ?@) 1 0)))))
13414 (if (or (rassoc c1 ntable) (rassoc c1 table))
13415 (while (or (rassoc char ntable) (rassoc char table))
13416 (setq char (1+ char)))
13417 (setq c2 c1))
13418 (setq c (or c2 char)))
13419 (if ingroup (push tg (car groups)))
13420 (setq tg (org-add-props tg nil 'face
13421 (cond
13422 ((not (assoc tg table))
13423 (org-get-todo-face tg))
13424 ((member tg current) c-face)
13425 ((member tg inherited) i-face)
13426 (t nil))))
13427 (if (and (= cnt 0) (not ingroup)) (insert " "))
13428 (insert "[" c "] " tg (make-string
13429 (- fwidth 4 (length tg)) ?\ ))
13430 (push (cons tg c) ntable)
13431 (when (= (setq cnt (1+ cnt)) ncol)
13432 (insert "\n")
13433 (if ingroup (insert " "))
13434 (setq cnt 0)))))
13435 (setq ntable (nreverse ntable))
13436 (insert "\n")
13437 (goto-char (point-min))
13438 (if (not expert) (org-fit-window-to-buffer))
13439 (setq rtn
13440 (catch 'exit
13441 (while t
13442 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13443 (if (not groups) "no " "")
13444 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13445 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13446 (setq org-last-tag-selection-key c)
13447 (cond
13448 ((= c ?\r) (throw 'exit t))
13449 ((= c ?!)
13450 (setq groups (not groups))
13451 (goto-char (point-min))
13452 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13453 ((= c ?\C-c)
13454 (if (not expert)
13455 (org-fast-tag-show-exit
13456 (setq exit-after-next (not exit-after-next)))
13457 (setq expert nil)
13458 (delete-other-windows)
13459 (set-window-buffer (split-window-vertically) " *Org tags*")
13460 (org-switch-to-buffer-other-window " *Org tags*")
13461 (org-fit-window-to-buffer)))
13462 ((or (= c ?\C-g)
13463 (and (= c ?q) (not (rassoc c ntable))))
13464 (org-detach-overlay org-tags-overlay)
13465 (setq quit-flag t))
13466 ((= c ?\ )
13467 (setq current nil)
13468 (if exit-after-next (setq exit-after-next 'now)))
13469 ((= c ?\t)
13470 (condition-case nil
13471 (setq tg (org-icompleting-read
13472 "Tag: "
13473 (or buffer-tags
13474 (with-current-buffer buf
13475 (org-get-buffer-tags)))))
13476 (quit (setq tg "")))
13477 (when (string-match "\\S-" tg)
13478 (add-to-list 'buffer-tags (list tg))
13479 (if (member tg current)
13480 (setq current (delete tg current))
13481 (push tg current)))
13482 (if exit-after-next (setq exit-after-next 'now)))
13483 ((setq e (rassoc c todo-table) tg (car e))
13484 (with-current-buffer buf
13485 (save-excursion (org-todo tg)))
13486 (if exit-after-next (setq exit-after-next 'now)))
13487 ((setq e (rassoc c ntable) tg (car e))
13488 (if (member tg current)
13489 (setq current (delete tg current))
13490 (loop for g in groups do
13491 (if (member tg g)
13492 (mapc (lambda (x)
13493 (setq current (delete x current)))
13494 g)))
13495 (push tg current))
13496 (if exit-after-next (setq exit-after-next 'now))))
13498 ;; Create a sorted list
13499 (setq current
13500 (sort current
13501 (lambda (a b)
13502 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13503 (if (eq exit-after-next 'now) (throw 'exit t))
13504 (goto-char (point-min))
13505 (beginning-of-line 2)
13506 (delete-region (point) (point-at-eol))
13507 (org-fast-tag-insert "Current" current c-face)
13508 (org-set-current-tags-overlay current ov-prefix)
13509 (while (re-search-forward
13510 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13511 (setq tg (match-string 1))
13512 (add-text-properties
13513 (match-beginning 1) (match-end 1)
13514 (list 'face
13515 (cond
13516 ((member tg current) c-face)
13517 ((member tg inherited) i-face)
13518 (t (get-text-property (match-beginning 1) 'face))))))
13519 (goto-char (point-min)))))
13520 (org-detach-overlay org-tags-overlay)
13521 (if rtn
13522 (mapconcat 'identity current ":")
13523 nil))))
13525 (defun org-get-tags-string ()
13526 "Get the TAGS string in the current headline."
13527 (unless (org-on-heading-p t)
13528 (error "Not on a heading"))
13529 (save-excursion
13530 (beginning-of-line 1)
13531 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13532 (org-match-string-no-properties 1)
13533 "")))
13535 (defun org-get-tags ()
13536 "Get the list of tags specified in the current headline."
13537 (org-split-string (org-get-tags-string) ":"))
13539 (defun org-get-buffer-tags ()
13540 "Get a table of all tags used in the buffer, for completion."
13541 (let (tags)
13542 (save-excursion
13543 (goto-char (point-min))
13544 (while (re-search-forward
13545 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13546 (when (equal (char-after (point-at-bol 0)) ?*)
13547 (mapc (lambda (x) (add-to-list 'tags x))
13548 (org-split-string (org-match-string-no-properties 1) ":")))))
13549 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13550 (mapcar 'list tags)))
13552 ;;;; The mapping API
13554 ;;;###autoload
13555 (defun org-map-entries (func &optional match scope &rest skip)
13556 "Call FUNC at each headline selected by MATCH in SCOPE.
13558 FUNC is a function or a lisp form. The function will be called without
13559 arguments, with the cursor positioned at the beginning of the headline.
13560 The return values of all calls to the function will be collected and
13561 returned as a list.
13563 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13564 does not need to preserve point. After evaluation, the cursor will be
13565 moved to the end of the line (presumably of the headline of the
13566 processed entry) and search continues from there. Under some
13567 circumstances, this may not produce the wanted results. For example,
13568 if you have removed (e.g. archived) the current (sub)tree it could
13569 mean that the next entry will be skipped entirely. In such cases, you
13570 can specify the position from where search should continue by making
13571 FUNC set the variable `org-map-continue-from' to the desired buffer
13572 position.
13574 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13575 Only headlines that are matched by this query will be considered during
13576 the iteration. When MATCH is nil or t, all headlines will be
13577 visited by the iteration.
13579 SCOPE determines the scope of this command. It can be any of:
13581 nil The current buffer, respecting the restriction if any
13582 tree The subtree started with the entry at point
13583 region The entries within the active region, if any
13584 file The current buffer, without restriction
13585 file-with-archives
13586 The current buffer, and any archives associated with it
13587 agenda All agenda files
13588 agenda-with-archives
13589 All agenda files with any archive files associated with them
13590 \(file1 file2 ...)
13591 If this is a list, all files in the list will be scanned
13593 The remaining args are treated as settings for the skipping facilities of
13594 the scanner. The following items can be given here:
13596 archive skip trees with the archive tag.
13597 comment skip trees with the COMMENT keyword
13598 function or Emacs Lisp form:
13599 will be used as value for `org-agenda-skip-function', so whenever
13600 the function returns t, FUNC will not be called for that
13601 entry and search will continue from the point where the
13602 function leaves it.
13604 If your function needs to retrieve the tags including inherited tags
13605 at the *current* entry, you can use the value of the variable
13606 `org-scanner-tags' which will be much faster than getting the value
13607 with `org-get-tags-at'. If your function gets properties with
13608 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13609 to t around the call to `org-entry-properties' to get the same speedup.
13610 Note that if your function moves around to retrieve tags and properties at
13611 a *different* entry, you cannot use these techniques."
13612 (let* ((org-agenda-archives-mode nil) ; just to make sure
13613 (org-agenda-skip-archived-trees (memq 'archive skip))
13614 (org-agenda-skip-comment-trees (memq 'comment skip))
13615 (org-agenda-skip-function
13616 (car (org-delete-all '(comment archive) skip)))
13617 (org-tags-match-list-sublevels t)
13618 matcher file res
13619 org-todo-keywords-for-agenda
13620 org-done-keywords-for-agenda
13621 org-todo-keyword-alist-for-agenda
13622 org-drawers-for-agenda
13623 org-tag-alist-for-agenda)
13625 (cond
13626 ((eq match t) (setq matcher t))
13627 ((eq match nil) (setq matcher t))
13628 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13630 (save-excursion
13631 (save-restriction
13632 (cond ((eq scope 'tree)
13633 (org-back-to-heading t)
13634 (org-narrow-to-subtree)
13635 (setq scope nil))
13636 ((and (eq scope 'region) (org-region-active-p))
13637 (narrow-to-region (region-beginning) (region-end))
13638 (setq scope nil)))
13640 (if (not scope)
13641 (progn
13642 (org-prepare-agenda-buffers
13643 (list (buffer-file-name (current-buffer))))
13644 (setq res (org-scan-tags func matcher)))
13645 ;; Get the right scope
13646 (cond
13647 ((and scope (listp scope) (symbolp (car scope)))
13648 (setq scope (eval scope)))
13649 ((eq scope 'agenda)
13650 (setq scope (org-agenda-files t)))
13651 ((eq scope 'agenda-with-archives)
13652 (setq scope (org-agenda-files t))
13653 (setq scope (org-add-archive-files scope)))
13654 ((eq scope 'file)
13655 (setq scope (list (buffer-file-name))))
13656 ((eq scope 'file-with-archives)
13657 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13658 (org-prepare-agenda-buffers scope)
13659 (while (setq file (pop scope))
13660 (with-current-buffer (org-find-base-buffer-visiting file)
13661 (save-excursion
13662 (save-restriction
13663 (widen)
13664 (goto-char (point-min))
13665 (setq res (append res (org-scan-tags func matcher))))))))))
13666 res))
13668 ;;;; Properties
13670 ;;; Setting and retrieving properties
13672 (defconst org-special-properties
13673 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13674 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13675 "The special properties valid in Org-mode.
13677 These are properties that are not defined in the property drawer,
13678 but in some other way.")
13680 (defconst org-default-properties
13681 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13682 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13683 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13684 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13685 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13686 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13687 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13688 "Some properties that are used by Org-mode for various purposes.
13689 Being in this list makes sure that they are offered for completion.")
13691 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13692 "Regular expression matching the first line of a property drawer.")
13694 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13695 "Regular expression matching the last line of a property drawer.")
13697 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13698 "Regular expression matching the first line of a property drawer.")
13700 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13701 "Regular expression matching the first line of a property drawer.")
13703 (defconst org-property-drawer-re
13704 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13705 org-property-end-re "\\)\n?")
13706 "Matches an entire property drawer.")
13708 (defconst org-clock-drawer-re
13709 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13710 org-property-end-re "\\)\n?")
13711 "Matches an entire clock drawer.")
13713 (defsubst org-re-property (property)
13714 "Return a regexp matching PROPERTY.
13715 Match group 1 will be set to the value "
13716 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
13718 (defun org-property-action ()
13719 "Do an action on properties."
13720 (interactive)
13721 (let (c)
13722 (org-at-property-p)
13723 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13724 (setq c (read-char-exclusive))
13725 (cond
13726 ((equal c ?s)
13727 (call-interactively 'org-set-property))
13728 ((equal c ?d)
13729 (call-interactively 'org-delete-property))
13730 ((equal c ?D)
13731 (call-interactively 'org-delete-property-globally))
13732 ((equal c ?c)
13733 (call-interactively 'org-compute-property-at-point))
13734 (t (error "No such property action %c" c)))))
13736 (defun org-set-effort (&optional value)
13737 "Set the effort property of the current entry.
13738 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13739 allowed value."
13740 (interactive "P")
13741 (if (equal value 0) (setq value 10))
13742 (let* ((completion-ignore-case t)
13743 (prop org-effort-property)
13744 (cur (org-entry-get nil prop))
13745 (allowed (org-property-get-allowed-values nil prop 'table))
13746 (existing (mapcar 'list (org-property-values prop)))
13748 (val (cond
13749 ((stringp value) value)
13750 ((and allowed (integerp value))
13751 (or (car (nth (1- value) allowed))
13752 (car (org-last allowed))))
13753 (allowed
13754 (message "Select 1-9,0, [RET%s]: %s"
13755 (if cur (concat "=" cur) "")
13756 (mapconcat 'car allowed " "))
13757 (setq rpl (read-char-exclusive))
13758 (if (equal rpl ?\r)
13760 (setq rpl (- rpl ?0))
13761 (if (equal rpl 0) (setq rpl 10))
13762 (if (and (> rpl 0) (<= rpl (length allowed)))
13763 (car (nth (1- rpl) allowed))
13764 (org-completing-read "Effort: " allowed nil))))
13766 (let (org-completion-use-ido org-completion-use-iswitchb)
13767 (org-completing-read
13768 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13769 (concat "[" cur "]") "")
13770 ": ")
13771 existing nil nil "" nil cur))))))
13772 (unless (equal (org-entry-get nil prop) val)
13773 (org-entry-put nil prop val))
13774 (message "%s is now %s" prop val)))
13776 (defun org-at-property-p ()
13777 "Is cursor inside a property drawer?"
13778 (save-excursion
13779 (beginning-of-line 1)
13780 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13781 (save-match-data ;; Used by calling procedures
13782 (let ((p (point))
13783 (range (unless (org-before-first-heading-p)
13784 (org-get-property-block))))
13785 (and range (<= (car range) p) (< p (cdr range))))))))
13787 (defun org-get-property-block (&optional beg end force)
13788 "Return the (beg . end) range of the body of the property drawer.
13789 BEG and END can be beginning and end of subtree, if not given
13790 they will be found.
13791 If the drawer does not exist and FORCE is non-nil, create the drawer."
13792 (catch 'exit
13793 (save-excursion
13794 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13795 (end (or end (progn (outline-next-heading) (point)))))
13796 (goto-char beg)
13797 (if (re-search-forward org-property-start-re end t)
13798 (setq beg (1+ (match-end 0)))
13799 (if force
13800 (save-excursion
13801 (org-insert-property-drawer)
13802 (setq end (progn (outline-next-heading) (point))))
13803 (throw 'exit nil))
13804 (goto-char beg)
13805 (if (re-search-forward org-property-start-re end t)
13806 (setq beg (1+ (match-end 0)))))
13807 (if (re-search-forward org-property-end-re end t)
13808 (setq end (match-beginning 0))
13809 (or force (throw 'exit nil))
13810 (goto-char beg)
13811 (setq end beg)
13812 (org-indent-line-function)
13813 (insert ":END:\n"))
13814 (cons beg end)))))
13816 (defun org-entry-properties (&optional pom which specific)
13817 "Get all properties of the entry at point-or-marker POM.
13818 This includes the TODO keyword, the tags, time strings for deadline,
13819 scheduled, and clocking, and any additional properties defined in the
13820 entry. The return value is an alist, keys may occur multiple times
13821 if the property key was used several times.
13822 POM may also be nil, in which case the current entry is used.
13823 If WHICH is nil or `all', get all properties. If WHICH is
13824 `special' or `standard', only get that subclass. If WHICH
13825 is a string only get exactly this property. SPECIFIC can be a string, the
13826 specific property we are interested in. Specifying it can speed
13827 things up because then unnecessary parsing is avoided."
13828 (setq which (or which 'all))
13829 (org-with-point-at pom
13830 (let ((clockstr (substring org-clock-string 0 -1))
13831 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13832 (case-fold-search nil)
13833 beg end range props sum-props key key1 value string clocksum)
13834 (save-excursion
13835 (when (condition-case nil
13836 (and (org-mode-p) (org-back-to-heading t))
13837 (error nil))
13838 (setq beg (point))
13839 (setq sum-props (get-text-property (point) 'org-summaries))
13840 (setq clocksum (get-text-property (point) :org-clock-minutes))
13841 (outline-next-heading)
13842 (setq end (point))
13843 (when (memq which '(all special))
13844 ;; Get the special properties, like TODO and tags
13845 (goto-char beg)
13846 (when (and (or (not specific) (string= specific "TODO"))
13847 (looking-at org-todo-line-regexp) (match-end 2))
13848 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13849 (when (and (or (not specific) (string= specific "PRIORITY"))
13850 (looking-at org-priority-regexp))
13851 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13852 (when (or (not specific) (string= specific "FILE"))
13853 (push (cons "FILE" buffer-file-name) props))
13854 (when (and (or (not specific) (string= specific "TAGS"))
13855 (setq value (org-get-tags-string))
13856 (string-match "\\S-" value))
13857 (push (cons "TAGS" value) props))
13858 (when (and (or (not specific) (string= specific "ALLTAGS"))
13859 (setq value (org-get-tags-at)))
13860 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
13861 ":"))
13862 props))
13863 (when (or (not specific) (string= specific "BLOCKED"))
13864 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
13865 (when (or (not specific)
13866 (member specific
13867 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
13868 "TIMESTAMP" "TIMESTAMP_IA")))
13869 (catch 'match
13870 (while (re-search-forward org-maybe-keyword-time-regexp end t)
13871 (setq key (if (match-end 1)
13872 (substring (org-match-string-no-properties 1)
13873 0 -1))
13874 string (if (equal key clockstr)
13875 (org-no-properties
13876 (org-trim
13877 (buffer-substring
13878 (match-beginning 3) (goto-char
13879 (point-at-eol)))))
13880 (substring (org-match-string-no-properties 3)
13881 1 -1)))
13882 ;; Get the correct property name from the key. This is
13883 ;; necessary if the user has configured time keywords.
13884 (setq key1 (concat key ":"))
13885 (cond
13886 ((not key)
13887 (setq key
13888 (if (= (char-after (match-beginning 3)) ?\[)
13889 "TIMESTAMP_IA" "TIMESTAMP")))
13890 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
13891 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
13892 ((equal key1 org-closed-string) (setq key "CLOSED"))
13893 ((equal key1 org-clock-string) (setq key "CLOCK")))
13894 (if (and specific (equal key specific) (not (equal key "CLOCK")))
13895 (progn
13896 (push (cons key string) props)
13897 ;; no need to search further if match is found
13898 (throw 'match t))
13899 (when (or (equal key "CLOCK") (not (assoc key props)))
13900 (push (cons key string) props))))))
13903 (when (memq which '(all standard))
13904 ;; Get the standard properties, like :PROP: ...
13905 (setq range (org-get-property-block beg end))
13906 (when range
13907 (goto-char (car range))
13908 (while (re-search-forward
13909 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
13910 (cdr range) t)
13911 (setq key (org-match-string-no-properties 1)
13912 value (org-trim (or (org-match-string-no-properties 2) "")))
13913 (unless (member key excluded)
13914 (push (cons key (or value "")) props)))))
13915 (if clocksum
13916 (push (cons "CLOCKSUM"
13917 (org-columns-number-to-string (/ (float clocksum) 60.)
13918 'add_times))
13919 props))
13920 (unless (assoc "CATEGORY" props)
13921 (push (cons "CATEGORY" (org-get-category)) props))
13922 (append sum-props (nreverse props)))))))
13924 (defun org-entry-get (pom property &optional inherit literal-nil)
13925 "Get value of PROPERTY for entry at point-or-marker POM.
13926 If INHERIT is non-nil and the entry does not have the property,
13927 then also check higher levels of the hierarchy.
13928 If INHERIT is the symbol `selective', use inheritance only if the setting
13929 in `org-use-property-inheritance' selects PROPERTY for inheritance.
13930 If the property is present but empty, the return value is the empty string.
13931 If the property is not present at all, nil is returned.
13933 If LITERAL-NIL is set, return the string value \"nil\" as a string,
13934 do not interpret it as the list atom nil. This is used for inheritance
13935 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
13936 (org-with-point-at pom
13937 (if (and inherit (if (eq inherit 'selective)
13938 (org-property-inherit-p property)
13940 (org-entry-get-with-inheritance property literal-nil)
13941 (if (member property org-special-properties)
13942 ;; We need a special property. Use `org-entry-properties' to
13943 ;; retrieve it, but specify the wanted property
13944 (cdr (assoc property (org-entry-properties nil 'special property)))
13945 (let ((range (unless (org-before-first-heading-p)
13946 (org-get-property-block))))
13947 (if (and range
13948 (goto-char (car range))
13949 (re-search-forward
13950 (org-re-property property)
13951 (cdr range) t))
13952 ;; Found the property, return it.
13953 (if (match-end 1)
13954 (if literal-nil
13955 (org-match-string-no-properties 1)
13956 (org-not-nil (org-match-string-no-properties 1)))
13957 "")))))))
13959 (defun org-property-or-variable-value (var &optional inherit)
13960 "Check if there is a property fixing the value of VAR.
13961 If yes, return this value. If not, return the current value of the variable."
13962 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13963 (if (and prop (stringp prop) (string-match "\\S-" prop))
13964 (read prop)
13965 (symbol-value var))))
13967 (defun org-entry-delete (pom property)
13968 "Delete the property PROPERTY from entry at point-or-marker POM."
13969 (org-with-point-at pom
13970 (if (member property org-special-properties)
13971 nil ; cannot delete these properties.
13972 (let ((range (org-get-property-block)))
13973 (if (and range
13974 (goto-char (car range))
13975 (re-search-forward
13976 (org-re-property property)
13977 (cdr range) t))
13978 (progn
13979 (delete-region (match-beginning 0) (1+ (point-at-eol)))
13981 nil)))))
13983 ;; Multi-values properties are properties that contain multiple values
13984 ;; These values are assumed to be single words, separated by whitespace.
13985 (defun org-entry-add-to-multivalued-property (pom property value)
13986 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
13987 (let* ((old (org-entry-get pom property))
13988 (values (and old (org-split-string old "[ \t]"))))
13989 (setq value (org-entry-protect-space value))
13990 (unless (member value values)
13991 (setq values (cons value values))
13992 (org-entry-put pom property
13993 (mapconcat 'identity values " ")))))
13995 (defun org-entry-remove-from-multivalued-property (pom property value)
13996 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
13997 (let* ((old (org-entry-get pom property))
13998 (values (and old (org-split-string old "[ \t]"))))
13999 (setq value (org-entry-protect-space value))
14000 (when (member value values)
14001 (setq values (delete value values))
14002 (org-entry-put pom property
14003 (mapconcat 'identity values " ")))))
14005 (defun org-entry-member-in-multivalued-property (pom property value)
14006 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14007 (let* ((old (org-entry-get pom property))
14008 (values (and old (org-split-string old "[ \t]"))))
14009 (setq value (org-entry-protect-space value))
14010 (member value values)))
14012 (defun org-entry-get-multivalued-property (pom property)
14013 "Return a list of values in a multivalued property."
14014 (let* ((value (org-entry-get pom property))
14015 (values (and value (org-split-string value "[ \t]"))))
14016 (mapcar 'org-entry-restore-space values)))
14018 (defun org-entry-put-multivalued-property (pom property &rest values)
14019 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14020 VALUES should be a list of strings. Spaces will be protected."
14021 (org-entry-put pom property
14022 (mapconcat 'org-entry-protect-space values " "))
14023 (let* ((value (org-entry-get pom property))
14024 (values (and value (org-split-string value "[ \t]"))))
14025 (mapcar 'org-entry-restore-space values)))
14027 (defun org-entry-protect-space (s)
14028 "Protect spaces and newline in string S."
14029 (while (string-match " " s)
14030 (setq s (replace-match "%20" t t s)))
14031 (while (string-match "\n" s)
14032 (setq s (replace-match "%0A" t t s)))
14035 (defun org-entry-restore-space (s)
14036 "Restore spaces and newline in string S."
14037 (while (string-match "%20" s)
14038 (setq s (replace-match " " t t s)))
14039 (while (string-match "%0A" s)
14040 (setq s (replace-match "\n" t t s)))
14043 (defvar org-entry-property-inherited-from (make-marker)
14044 "Marker pointing to the entry from where a property was inherited.
14045 Each call to `org-entry-get-with-inheritance' will set this marker to the
14046 location of the entry where the inheritance search matched. If there was
14047 no match, the marker will point nowhere.
14048 Note that also `org-entry-get' calls this function, if the INHERIT flag
14049 is set.")
14051 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14052 "Get entry property, and search higher levels if not present.
14053 The search will stop at the first ancestor which has the property defined.
14054 If the value found is \"nil\", return nil to show that the property
14055 should be considered as undefined (this is the meaning of nil here).
14056 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14057 (move-marker org-entry-property-inherited-from nil)
14058 (let (tmp)
14059 (unless (org-before-first-heading-p)
14060 (save-excursion
14061 (save-restriction
14062 (widen)
14063 (catch 'ex
14064 (while t
14065 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14066 (org-back-to-heading t)
14067 (move-marker org-entry-property-inherited-from (point))
14068 (throw 'ex tmp))
14069 (or (org-up-heading-safe) (throw 'ex nil)))))))
14070 (setq tmp (or tmp
14071 (cdr (assoc property org-file-properties))
14072 (cdr (assoc property org-global-properties))
14073 (cdr (assoc property org-global-properties-fixed))))
14074 (if literal-nil tmp (org-not-nil tmp))))
14076 (defvar org-property-changed-functions nil
14077 "Hook called when the value of a property has changed.
14078 Each hook function should accept two arguments, the name of the property
14079 and the new value.")
14081 (defun org-entry-put (pom property value)
14082 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14083 (org-with-point-at pom
14084 (org-back-to-heading t)
14085 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14086 range)
14087 (cond
14088 ((equal property "TODO")
14089 (when (and (stringp value) (string-match "\\S-" value)
14090 (not (member value org-todo-keywords-1)))
14091 (error "\"%s\" is not a valid TODO state" value))
14092 (if (or (not value)
14093 (not (string-match "\\S-" value)))
14094 (setq value 'none))
14095 (org-todo value)
14096 (org-set-tags nil 'align))
14097 ((equal property "PRIORITY")
14098 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14099 (string-to-char value) ?\ ))
14100 (org-set-tags nil 'align))
14101 ((equal property "SCHEDULED")
14102 (if (re-search-forward org-scheduled-time-regexp end t)
14103 (cond
14104 ((eq value 'earlier) (org-timestamp-change -1 'day))
14105 ((eq value 'later) (org-timestamp-change 1 'day))
14106 (t (call-interactively 'org-schedule)))
14107 (call-interactively 'org-schedule)))
14108 ((equal property "DEADLINE")
14109 (if (re-search-forward org-deadline-time-regexp end t)
14110 (cond
14111 ((eq value 'earlier) (org-timestamp-change -1 'day))
14112 ((eq value 'later) (org-timestamp-change 1 'day))
14113 (t (call-interactively 'org-deadline)))
14114 (call-interactively 'org-deadline)))
14115 ((member property org-special-properties)
14116 (error "The %s property can not yet be set with `org-entry-put'"
14117 property))
14118 (t ; a non-special property
14119 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14120 (setq range (org-get-property-block beg end 'force))
14121 (goto-char (car range))
14122 (if (re-search-forward
14123 (org-re-property property) (cdr range) t)
14124 (progn
14125 (delete-region (match-beginning 0) (match-end 0))
14126 (goto-char (match-beginning 0)))
14127 (goto-char (cdr range))
14128 (insert "\n")
14129 (backward-char 1)
14130 (org-indent-line-function))
14131 (insert ":" property ":")
14132 (and value (insert " " value))
14133 (org-indent-line-function)))))
14134 (run-hook-with-args 'org-property-changed-functions property value)))
14136 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14137 "Get all property keys in the current buffer.
14138 With INCLUDE-SPECIALS, also list the special properties that reflect things
14139 like tags and TODO state.
14140 With INCLUDE-DEFAULTS, also include properties that has special meaning
14141 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14142 and others.
14143 With INCLUDE-COLUMNS, also include property names given in COLUMN
14144 formats in the current buffer."
14145 (let (rtn range cfmt s p)
14146 (save-excursion
14147 (save-restriction
14148 (widen)
14149 (goto-char (point-min))
14150 (while (re-search-forward org-property-start-re nil t)
14151 (setq range (org-get-property-block))
14152 (goto-char (car range))
14153 (while (re-search-forward
14154 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14155 (cdr range) t)
14156 (add-to-list 'rtn (org-match-string-no-properties 1)))
14157 (outline-next-heading))))
14159 (when include-specials
14160 (setq rtn (append org-special-properties rtn)))
14162 (when include-defaults
14163 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14164 (add-to-list 'rtn org-effort-property))
14166 (when include-columns
14167 (save-excursion
14168 (save-restriction
14169 (widen)
14170 (goto-char (point-min))
14171 (while (re-search-forward
14172 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14173 nil t)
14174 (setq cfmt (match-string 2) s 0)
14175 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14176 cfmt s)
14177 (setq s (match-end 0)
14178 p (match-string 1 cfmt))
14179 (unless (or (equal p "ITEM")
14180 (member p org-special-properties))
14181 (add-to-list 'rtn (match-string 1 cfmt))))))))
14183 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14185 (defun org-property-values (key)
14186 "Return a list of all values of property KEY in the current buffer."
14187 (save-excursion
14188 (save-restriction
14189 (widen)
14190 (goto-char (point-min))
14191 (let ((re (org-re-property key))
14192 values)
14193 (while (re-search-forward re nil t)
14194 (add-to-list 'values (org-trim (match-string 1))))
14195 (delete "" values)))))
14197 (defun org-insert-property-drawer ()
14198 "Insert a property drawer into the current entry."
14199 (interactive)
14200 (org-back-to-heading t)
14201 (looking-at org-outline-regexp)
14202 (let ((indent (if org-adapt-indentation
14203 (- (match-end 0)(match-beginning 0))
14205 (beg (point))
14206 (re (concat "^[ \t]*" org-keyword-time-regexp))
14207 end hiddenp)
14208 (outline-next-heading)
14209 (setq end (point))
14210 (goto-char beg)
14211 (while (re-search-forward re end t))
14212 (setq hiddenp (outline-invisible-p))
14213 (end-of-line 1)
14214 (and (equal (char-after) ?\n) (forward-char 1))
14215 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14216 (if (member (match-string 1) '("CLOCK:" ":END:"))
14217 ;; just skip this line
14218 (beginning-of-line 2)
14219 ;; Drawer start, find the end
14220 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14221 (beginning-of-line 1)))
14222 (org-skip-over-state-notes)
14223 (skip-chars-backward " \t\n\r")
14224 (if (eq (char-before) ?*) (forward-char 1))
14225 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14226 (beginning-of-line 0)
14227 (org-indent-to-column indent)
14228 (beginning-of-line 2)
14229 (org-indent-to-column indent)
14230 (beginning-of-line 0)
14231 (if hiddenp
14232 (save-excursion
14233 (org-back-to-heading t)
14234 (hide-entry))
14235 (org-flag-drawer t))))
14237 (defvar org-property-set-functions-alist nil
14238 "Property set function alist.
14239 Each entry should have the following format:
14241 (PROPERTY . READ-FUNCTION)
14243 The read function will be called with the same argument as
14244 `org-completing-read'.")
14246 (defun org-set-property-function (property)
14247 "Get the function that should be used to set PROPERTY.
14248 This is computed according to `org-property-set-functions-alist'."
14249 (or (cdr (assoc property org-property-set-functions-alist))
14250 'org-completing-read))
14252 (defun org-read-property-value (property)
14253 "Read PROPERTY value from user."
14254 (let* ((completion-ignore-case t)
14255 (allowed (org-property-get-allowed-values nil property 'table))
14256 (cur (org-entry-get nil property))
14257 (prompt (concat property " value"
14258 (if (and cur (string-match "\\S-" cur))
14259 (concat " [" cur "]") "") ": "))
14260 (set-function (org-set-property-function property))
14261 (val (if allowed
14262 (funcall set-function prompt allowed nil
14263 (not (get-text-property 0 'org-unrestricted
14264 (caar allowed))))
14265 (let (org-completion-use-ido org-completion-use-iswitchb)
14266 (funcall set-function prompt
14267 (mapcar 'list (org-property-values property))
14268 nil nil "" nil cur)))))
14269 (if (equal val "")
14271 val)))
14273 (defvar org-last-set-property nil)
14274 (defun org-read-property-name ()
14275 "Read a property name."
14276 (let* ((completion-ignore-case t)
14277 (keys (org-buffer-property-keys nil t t))
14278 (default-prop (or (save-excursion
14279 (save-match-data
14280 (beginning-of-line)
14281 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14282 (null (string= (match-string 1) "END"))
14283 (match-string 1))))
14284 org-last-set-property))
14285 (property (org-icompleting-read
14286 (concat "Property"
14287 (if default-prop (concat " [" default-prop "]") "")
14288 ": ")
14289 (mapcar 'list keys)
14290 nil nil nil nil
14291 default-prop
14293 (if (member property keys)
14294 property
14295 (or (cdr (assoc (downcase property)
14296 (mapcar (lambda (x) (cons (downcase x) x))
14297 keys)))
14298 property))))
14300 (defun org-set-property (property value)
14301 "In the current entry, set PROPERTY to VALUE.
14302 When called interactively, this will prompt for a property name, offering
14303 completion on existing and default properties. And then it will prompt
14304 for a value, offering completion either on allowed values (via an inherited
14305 xxx_ALL property) or on existing values in other instances of this property
14306 in the current file."
14307 (interactive (list nil nil))
14308 (let* ((property (or property (org-read-property-name)))
14309 (value (or value (org-read-property-value property)))
14310 (fn (assoc property org-properties-postprocess-alist)))
14311 (setq org-last-set-property property)
14312 ;; Possibly postprocess the inserted value:
14313 (when fn (setq value (funcall (cadr fn) value)))
14314 (unless (equal (org-entry-get nil property) value)
14315 (org-entry-put nil property value))))
14317 (defun org-delete-property (property)
14318 "In the current entry, delete PROPERTY."
14319 (interactive
14320 (let* ((completion-ignore-case t)
14321 (prop (org-icompleting-read "Property: "
14322 (org-entry-properties nil 'standard))))
14323 (list prop)))
14324 (message "Property %s %s" property
14325 (if (org-entry-delete nil property)
14326 "deleted"
14327 "was not present in the entry")))
14329 (defun org-delete-property-globally (property)
14330 "Remove PROPERTY globally, from all entries."
14331 (interactive
14332 (let* ((completion-ignore-case t)
14333 (prop (org-icompleting-read
14334 "Globally remove property: "
14335 (mapcar 'list (org-buffer-property-keys)))))
14336 (list prop)))
14337 (save-excursion
14338 (save-restriction
14339 (widen)
14340 (goto-char (point-min))
14341 (let ((cnt 0))
14342 (while (re-search-forward
14343 (org-re-property property)
14344 nil t)
14345 (setq cnt (1+ cnt))
14346 (replace-match ""))
14347 (message "Property \"%s\" removed from %d entries" property cnt)))))
14349 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14351 (defun org-compute-property-at-point ()
14352 "Compute the property at point.
14353 This looks for an enclosing column format, extracts the operator and
14354 then applies it to the property in the column format's scope."
14355 (interactive)
14356 (unless (org-at-property-p)
14357 (error "Not at a property"))
14358 (let ((prop (org-match-string-no-properties 2)))
14359 (org-columns-get-format-and-top-level)
14360 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14361 (error "No operator defined for property %s" prop))
14362 (org-columns-compute prop)))
14364 (defvar org-property-allowed-value-functions nil
14365 "Hook for functions supplying allowed values for a specific property.
14366 The functions must take a single argument, the name of the property, and
14367 return a flat list of allowed values. If \":ETC\" is one of
14368 the values, this means that these values are intended as defaults for
14369 completion, but that other values should be allowed too.
14370 The functions must return nil if they are not responsible for this
14371 property.")
14373 (defun org-property-get-allowed-values (pom property &optional table)
14374 "Get allowed values for the property PROPERTY.
14375 When TABLE is non-nil, return an alist that can directly be used for
14376 completion."
14377 (let (vals)
14378 (cond
14379 ((equal property "TODO")
14380 (setq vals (org-with-point-at pom
14381 (append org-todo-keywords-1 '("")))))
14382 ((equal property "PRIORITY")
14383 (let ((n org-lowest-priority))
14384 (while (>= n org-highest-priority)
14385 (push (char-to-string n) vals)
14386 (setq n (1- n)))))
14387 ((member property org-special-properties))
14388 ((setq vals (run-hook-with-args-until-success
14389 'org-property-allowed-value-functions property)))
14391 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14392 (when (and vals (string-match "\\S-" vals))
14393 (setq vals (car (read-from-string (concat "(" vals ")"))))
14394 (setq vals (mapcar (lambda (x)
14395 (cond ((stringp x) x)
14396 ((numberp x) (number-to-string x))
14397 ((symbolp x) (symbol-name x))
14398 (t "???")))
14399 vals)))))
14400 (when (member ":ETC" vals)
14401 (setq vals (remove ":ETC" vals))
14402 (org-add-props (car vals) '(org-unrestricted t)))
14403 (if table (mapcar 'list vals) vals)))
14405 (defun org-property-previous-allowed-value (&optional previous)
14406 "Switch to the next allowed value for this property."
14407 (interactive)
14408 (org-property-next-allowed-value t))
14410 (defun org-property-next-allowed-value (&optional previous)
14411 "Switch to the next allowed value for this property."
14412 (interactive)
14413 (unless (org-at-property-p)
14414 (error "Not at a property"))
14415 (let* ((key (match-string 2))
14416 (value (match-string 3))
14417 (allowed (or (org-property-get-allowed-values (point) key)
14418 (and (member value '("[ ]" "[-]" "[X]"))
14419 '("[ ]" "[X]"))))
14420 nval)
14421 (unless allowed
14422 (error "Allowed values for this property have not been defined"))
14423 (if previous (setq allowed (reverse allowed)))
14424 (if (member value allowed)
14425 (setq nval (car (cdr (member value allowed)))))
14426 (setq nval (or nval (car allowed)))
14427 (if (equal nval value)
14428 (error "Only one allowed value for this property"))
14429 (org-at-property-p)
14430 (replace-match (concat " :" key ": " nval) t t)
14431 (org-indent-line-function)
14432 (beginning-of-line 1)
14433 (skip-chars-forward " \t")
14434 (run-hook-with-args 'org-property-changed-functions key nval)))
14436 (defun org-find-olp (path &optional this-buffer)
14437 "Return a marker pointing to the entry at outline path OLP.
14438 If anything goes wrong, throw an error.
14439 You can wrap this call to catch the error like this:
14441 (condition-case msg
14442 (org-mobile-locate-entry (match-string 4))
14443 (error (nth 1 msg)))
14445 The return value will then be either a string with the error message,
14446 or a marker if everything is OK.
14448 If THIS-BUFFER is set, the outline path does not contain a file,
14449 only headings."
14450 (let* ((file (if this-buffer buffer-file-name (pop path)))
14451 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14452 (level 1)
14453 (lmin 1)
14454 (lmax 1)
14455 limit re end found pos heading cnt flevel)
14456 (unless buffer (error "File not found :%s" file))
14457 (with-current-buffer buffer
14458 (save-excursion
14459 (save-restriction
14460 (widen)
14461 (setq limit (point-max))
14462 (goto-char (point-min))
14463 (while (setq heading (pop path))
14464 (setq re (format org-complex-heading-regexp-format
14465 (regexp-quote heading)))
14466 (setq cnt 0 pos (point))
14467 (while (re-search-forward re end t)
14468 (setq level (- (match-end 1) (match-beginning 1)))
14469 (if (and (>= level lmin) (<= level lmax))
14470 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14471 (when (= cnt 0) (error "Heading not found on level %d: %s"
14472 lmax heading))
14473 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14474 lmax heading))
14475 (goto-char found)
14476 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14477 (setq end (save-excursion (org-end-of-subtree t t))))
14478 (when (org-on-heading-p)
14479 (move-marker (make-marker) (point))))))))
14481 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14482 "Find node HEADING in BUFFER.
14483 Return a marker to the heading if it was found, or nil if not.
14484 If POS-ONLY is set, return just the position instead of a marker.
14486 The heading text must match exact, but it may have a TODO keyword,
14487 a priority cookie and tags in the standard locations."
14488 (with-current-buffer (or buffer (current-buffer))
14489 (save-excursion
14490 (save-restriction
14491 (widen)
14492 (goto-char (point-min))
14493 (let (case-fold-search)
14494 (if (re-search-forward
14495 (format org-complex-heading-regexp-format
14496 (regexp-quote heading)) nil t)
14497 (if pos-only
14498 (match-beginning 0)
14499 (move-marker (make-marker) (match-beginning 0)))))))))
14501 (defun org-find-exact-heading-in-directory (heading &optional dir)
14502 "Find Org node headline HEADING in all .org files in directory DIR.
14503 When the target headline is found, return a marker to this location."
14504 (let ((files (directory-files (or dir default-directory)
14505 nil "\\`[^.#].*\\.org\\'"))
14506 file visiting m buffer)
14507 (catch 'found
14508 (while (setq file (pop files))
14509 (message "trying %s" file)
14510 (setq visiting (org-find-base-buffer-visiting file))
14511 (setq buffer (or visiting (find-file-noselect file)))
14512 (setq m (org-find-exact-headline-in-buffer
14513 heading buffer))
14514 (when (and (not m) (not visiting)) (kill-buffer buffer))
14515 (and m (throw 'found m))))))
14517 (defun org-find-entry-with-id (ident)
14518 "Locate the entry that contains the ID property with exact value IDENT.
14519 IDENT can be a string, a symbol or a number, this function will search for
14520 the string representation of it.
14521 Return the position where this entry starts, or nil if there is no such entry."
14522 (interactive "sID: ")
14523 (let ((id (cond
14524 ((stringp ident) ident)
14525 ((symbol-name ident) (symbol-name ident))
14526 ((numberp ident) (number-to-string ident))
14527 (t (error "IDENT %s must be a string, symbol or number" ident))))
14528 (case-fold-search nil))
14529 (save-excursion
14530 (save-restriction
14531 (widen)
14532 (goto-char (point-min))
14533 (when (re-search-forward
14534 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14535 nil t)
14536 (org-back-to-heading t)
14537 (point))))))
14539 ;;;; Timestamps
14541 (defvar org-last-changed-timestamp nil)
14542 (defvar org-last-inserted-timestamp nil
14543 "The last time stamp inserted with `org-insert-time-stamp'.")
14544 (defvar org-time-was-given) ; dynamically scoped parameter
14545 (defvar org-end-time-was-given) ; dynamically scoped parameter
14546 (defvar org-ts-what) ; dynamically scoped parameter
14548 (defun org-time-stamp (arg &optional inactive)
14549 "Prompt for a date/time and insert a time stamp.
14550 If the user specifies a time like HH:MM, or if this command is called
14551 with a prefix argument, the time stamp will contain date and time.
14552 Otherwise, only the date will be included. All parts of a date not
14553 specified by the user will be filled in from the current date/time.
14554 So if you press just return without typing anything, the time stamp
14555 will represent the current date/time. If there is already a timestamp
14556 at the cursor, it will be modified."
14557 (interactive "P")
14558 (let* ((ts nil)
14559 (default-time
14560 ;; Default time is either today, or, when entering a range,
14561 ;; the range start.
14562 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14563 (save-excursion
14564 (re-search-backward
14565 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14566 (- (point) 20) t)))
14567 (apply 'encode-time (org-parse-time-string (match-string 1)))
14568 (current-time)))
14569 (default-input (and ts (org-get-compact-tod ts)))
14570 (repeater (save-excursion
14571 (save-match-data
14572 (beginning-of-line)
14573 (when (re-search-forward
14574 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14575 (save-excursion (progn (end-of-line) (point))) t)
14576 (match-string 0)))))
14577 org-time-was-given org-end-time-was-given time)
14578 (cond
14579 ((and (org-at-timestamp-p t)
14580 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14581 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14582 (insert "--")
14583 (setq time (let ((this-command this-command))
14584 (org-read-date arg 'totime nil nil
14585 default-time default-input)))
14586 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14587 ((org-at-timestamp-p t)
14588 (setq time (let ((this-command this-command))
14589 (org-read-date arg 'totime nil nil default-time default-input)))
14590 (when (org-at-timestamp-p t) ; just to get the match data
14591 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14592 (replace-match "")
14593 (setq org-last-changed-timestamp
14594 (org-insert-time-stamp
14595 time (or org-time-was-given arg)
14596 inactive nil nil (list org-end-time-was-given)))
14597 (when repeater (goto-char (1- (point))) (insert " " repeater)
14598 (setq org-last-changed-timestamp
14599 (concat (substring org-last-inserted-timestamp 0 -1)
14600 " " repeater ">"))))
14601 (message "Timestamp updated"))
14603 (setq time (let ((this-command this-command))
14604 (org-read-date arg 'totime nil nil default-time default-input)))
14605 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14606 nil nil (list org-end-time-was-given))))))
14608 ;; FIXME: can we use this for something else, like computing time differences?
14609 (defun org-get-compact-tod (s)
14610 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14611 (let* ((t1 (match-string 1 s))
14612 (h1 (string-to-number (match-string 2 s)))
14613 (m1 (string-to-number (match-string 3 s)))
14614 (t2 (and (match-end 4) (match-string 5 s)))
14615 (h2 (and t2 (string-to-number (match-string 6 s))))
14616 (m2 (and t2 (string-to-number (match-string 7 s))))
14617 dh dm)
14618 (if (not t2)
14620 (setq dh (- h2 h1) dm (- m2 m1))
14621 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14622 (concat t1 "+" (number-to-string dh)
14623 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14625 (defun org-time-stamp-inactive (&optional arg)
14626 "Insert an inactive time stamp.
14627 An inactive time stamp is enclosed in square brackets instead of angle
14628 brackets. It is inactive in the sense that it does not trigger agenda entries,
14629 does not link to the calendar and cannot be changed with the S-cursor keys.
14630 So these are more for recording a certain time/date."
14631 (interactive "P")
14632 (org-time-stamp arg 'inactive))
14634 (defvar org-date-ovl (make-overlay 1 1))
14635 (overlay-put org-date-ovl 'face 'org-warning)
14636 (org-detach-overlay org-date-ovl)
14638 (defvar org-ans1) ; dynamically scoped parameter
14639 (defvar org-ans2) ; dynamically scoped parameter
14641 (defvar org-plain-time-of-day-regexp) ; defined below
14643 (defvar org-overriding-default-time nil) ; dynamically scoped
14644 (defvar org-read-date-overlay nil)
14645 (defvar org-dcst nil) ; dynamically scoped
14646 (defvar org-read-date-history nil)
14647 (defvar org-read-date-final-answer nil)
14648 (defvar org-read-date-analyze-futurep nil)
14649 (defvar org-read-date-analyze-forced-year nil)
14651 (defun org-read-date (&optional with-time to-time from-string prompt
14652 default-time default-input)
14653 "Read a date, possibly a time, and make things smooth for the user.
14654 The prompt will suggest to enter an ISO date, but you can also enter anything
14655 which will at least partially be understood by `parse-time-string'.
14656 Unrecognized parts of the date will default to the current day, month, year,
14657 hour and minute. If this command is called to replace a timestamp at point,
14658 of to enter the second timestamp of a range, the default time is taken
14659 from the existing stamp. Furthermore, the command prefers the future,
14660 so if you are giving a date where the year is not given, and the day-month
14661 combination is already past in the current year, it will assume you
14662 mean next year. For details, see the manual. A few examples:
14664 3-2-5 --> 2003-02-05
14665 feb 15 --> currentyear-02-15
14666 2/15 --> currentyear-02-15
14667 sep 12 9 --> 2009-09-12
14668 12:45 --> today 12:45
14669 22 sept 0:34 --> currentyear-09-22 0:34
14670 12 --> currentyear-currentmonth-12
14671 Fri --> nearest Friday (today or later)
14672 etc.
14674 Furthermore you can specify a relative date by giving, as the *first* thing
14675 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14676 change in days weeks, months, years.
14677 With a single plus or minus, the date is relative to today. With a double
14678 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14679 +4d --> four days from today
14680 +4 --> same as above
14681 +2w --> two weeks from today
14682 ++5 --> five days from default date
14684 The function understands only English month and weekday abbreviations,
14685 but this can be configured with the variables `parse-time-months' and
14686 `parse-time-weekdays'.
14688 While prompting, a calendar is popped up - you can also select the
14689 date with the mouse (button 1). The calendar shows a period of three
14690 months. To scroll it to other months, use the keys `>' and `<'.
14691 If you don't like the calendar, turn it off with
14692 \(setq org-read-date-popup-calendar nil)
14694 With optional argument TO-TIME, the date will immediately be converted
14695 to an internal time.
14696 With an optional argument WITH-TIME, the prompt will suggest to also
14697 insert a time. Note that when WITH-TIME is not set, you can still
14698 enter a time, and this function will inform the calling routine about
14699 this change. The calling routine may then choose to change the format
14700 used to insert the time stamp into the buffer to include the time.
14701 With optional argument FROM-STRING, read from this string instead from
14702 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14703 the time/date that is used for everything that is not specified by the
14704 user."
14705 (require 'parse-time)
14706 (let* ((org-time-stamp-rounding-minutes
14707 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14708 (org-dcst org-display-custom-times)
14709 (ct (org-current-time))
14710 (def (or org-overriding-default-time default-time ct))
14711 (defdecode (decode-time def))
14712 (dummy (progn
14713 (when (< (nth 2 defdecode) org-extend-today-until)
14714 (setcar (nthcdr 2 defdecode) -1)
14715 (setcar (nthcdr 1 defdecode) 59)
14716 (setq def (apply 'encode-time defdecode)
14717 defdecode (decode-time def)))))
14718 (calendar-frame-setup nil)
14719 (calendar-setup nil)
14720 (calendar-move-hook nil)
14721 (calendar-view-diary-initially-flag nil)
14722 (calendar-view-holidays-initially-flag nil)
14723 (timestr (format-time-string
14724 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14725 (prompt (concat (if prompt (concat prompt " ") "")
14726 (format "Date+time [%s]: " timestr)))
14727 ans (org-ans0 "") org-ans1 org-ans2 final)
14729 (cond
14730 (from-string (setq ans from-string))
14731 (org-read-date-popup-calendar
14732 (save-excursion
14733 (save-window-excursion
14734 (calendar)
14735 (unwind-protect
14736 (progn
14737 (calendar-forward-day (- (time-to-days def)
14738 (calendar-absolute-from-gregorian
14739 (calendar-current-date))))
14740 (org-eval-in-calendar nil t)
14741 (let* ((old-map (current-local-map))
14742 (map (copy-keymap calendar-mode-map))
14743 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14744 (org-defkey map (kbd "RET") 'org-calendar-select)
14745 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14746 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14747 (org-defkey minibuffer-local-map [(meta shift left)]
14748 (lambda () (interactive)
14749 (org-eval-in-calendar '(calendar-backward-month 1))))
14750 (org-defkey minibuffer-local-map [(meta shift right)]
14751 (lambda () (interactive)
14752 (org-eval-in-calendar '(calendar-forward-month 1))))
14753 (org-defkey minibuffer-local-map [(meta shift up)]
14754 (lambda () (interactive)
14755 (org-eval-in-calendar '(calendar-backward-year 1))))
14756 (org-defkey minibuffer-local-map [(meta shift down)]
14757 (lambda () (interactive)
14758 (org-eval-in-calendar '(calendar-forward-year 1))))
14759 (org-defkey minibuffer-local-map [?\e (shift left)]
14760 (lambda () (interactive)
14761 (org-eval-in-calendar '(calendar-backward-month 1))))
14762 (org-defkey minibuffer-local-map [?\e (shift right)]
14763 (lambda () (interactive)
14764 (org-eval-in-calendar '(calendar-forward-month 1))))
14765 (org-defkey minibuffer-local-map [?\e (shift up)]
14766 (lambda () (interactive)
14767 (org-eval-in-calendar '(calendar-backward-year 1))))
14768 (org-defkey minibuffer-local-map [?\e (shift down)]
14769 (lambda () (interactive)
14770 (org-eval-in-calendar '(calendar-forward-year 1))))
14771 (org-defkey minibuffer-local-map [(shift up)]
14772 (lambda () (interactive)
14773 (org-eval-in-calendar '(calendar-backward-week 1))))
14774 (org-defkey minibuffer-local-map [(shift down)]
14775 (lambda () (interactive)
14776 (org-eval-in-calendar '(calendar-forward-week 1))))
14777 (org-defkey minibuffer-local-map [(shift left)]
14778 (lambda () (interactive)
14779 (org-eval-in-calendar '(calendar-backward-day 1))))
14780 (org-defkey minibuffer-local-map [(shift right)]
14781 (lambda () (interactive)
14782 (org-eval-in-calendar '(calendar-forward-day 1))))
14783 (org-defkey minibuffer-local-map ">"
14784 (lambda () (interactive)
14785 (org-eval-in-calendar '(scroll-calendar-left 1))))
14786 (org-defkey minibuffer-local-map "<"
14787 (lambda () (interactive)
14788 (org-eval-in-calendar '(scroll-calendar-right 1))))
14789 (org-defkey minibuffer-local-map "\C-v"
14790 (lambda () (interactive)
14791 (org-eval-in-calendar
14792 '(calendar-scroll-left-three-months 1))))
14793 (org-defkey minibuffer-local-map "\M-v"
14794 (lambda () (interactive)
14795 (org-eval-in-calendar
14796 '(calendar-scroll-right-three-months 1))))
14797 (run-hooks 'org-read-date-minibuffer-setup-hook)
14798 (unwind-protect
14799 (progn
14800 (use-local-map map)
14801 (add-hook 'post-command-hook 'org-read-date-display)
14802 (setq org-ans0 (read-string prompt default-input
14803 'org-read-date-history nil))
14804 ;; org-ans0: from prompt
14805 ;; org-ans1: from mouse click
14806 ;; org-ans2: from calendar motion
14807 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14808 (remove-hook 'post-command-hook 'org-read-date-display)
14809 (use-local-map old-map)
14810 (when org-read-date-overlay
14811 (delete-overlay org-read-date-overlay)
14812 (setq org-read-date-overlay nil)))))
14813 (bury-buffer "*Calendar*")))))
14815 (t ; Naked prompt only
14816 (unwind-protect
14817 (setq ans (read-string prompt default-input
14818 'org-read-date-history timestr))
14819 (when org-read-date-overlay
14820 (delete-overlay org-read-date-overlay)
14821 (setq org-read-date-overlay nil)))))
14823 (setq final (org-read-date-analyze ans def defdecode))
14825 (when org-read-date-analyze-forced-year
14826 (message "Year was forced into %s"
14827 (if org-read-date-force-compatible-dates
14828 "compatible range (1970-2037)"
14829 "range representable on this machine"))
14830 (ding))
14832 ;; One round trip to get rid of 34th of August and stuff like that....
14833 (setq final (decode-time (apply 'encode-time final)))
14835 (setq org-read-date-final-answer ans)
14837 (if to-time
14838 (apply 'encode-time final)
14839 (if (and (boundp 'org-time-was-given) org-time-was-given)
14840 (format "%04d-%02d-%02d %02d:%02d"
14841 (nth 5 final) (nth 4 final) (nth 3 final)
14842 (nth 2 final) (nth 1 final))
14843 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
14845 (defvar def)
14846 (defvar defdecode)
14847 (defvar with-time)
14848 (defun org-read-date-display ()
14849 "Display the current date prompt interpretation in the minibuffer."
14850 (when org-read-date-display-live
14851 (when org-read-date-overlay
14852 (delete-overlay org-read-date-overlay))
14853 (let ((p (point)))
14854 (end-of-line 1)
14855 (while (not (equal (buffer-substring
14856 (max (point-min) (- (point) 4)) (point))
14857 " "))
14858 (insert " "))
14859 (goto-char p))
14860 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
14861 " " (or org-ans1 org-ans2)))
14862 (org-end-time-was-given nil)
14863 (f (org-read-date-analyze ans def defdecode))
14864 (fmts (if org-dcst
14865 org-time-stamp-custom-formats
14866 org-time-stamp-formats))
14867 (fmt (if (or with-time
14868 (and (boundp 'org-time-was-given) org-time-was-given))
14869 (cdr fmts)
14870 (car fmts)))
14871 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
14872 (when (and org-end-time-was-given
14873 (string-match org-plain-time-of-day-regexp txt))
14874 (setq txt (concat (substring txt 0 (match-end 0)) "-"
14875 org-end-time-was-given
14876 (substring txt (match-end 0)))))
14877 (when org-read-date-analyze-futurep
14878 (setq txt (concat txt " (=>F)")))
14879 (setq org-read-date-overlay
14880 (make-overlay (1- (point-at-eol)) (point-at-eol)))
14881 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
14883 (defun org-read-date-analyze (ans def defdecode)
14884 "Analyze the combined answer of the date prompt."
14885 ;; FIXME: cleanup and comment
14886 (let ((nowdecode (decode-time (current-time)))
14887 delta deltan deltaw deltadef year month day
14888 hour minute second wday pm h2 m2 tl wday1
14889 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
14890 (setq org-read-date-analyze-futurep nil
14891 org-read-date-analyze-forced-year nil)
14892 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
14893 (setq ans "+0"))
14895 (when (setq delta (org-read-date-get-relative ans (current-time) def))
14896 (setq ans (replace-match "" t t ans)
14897 deltan (car delta)
14898 deltaw (nth 1 delta)
14899 deltadef (nth 2 delta)))
14901 ;; Check if there is an iso week date in there
14902 ;; If yes, store the info and postpone interpreting it until the rest
14903 ;; of the parsing is done
14904 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
14905 (setq iso-year (if (match-end 1)
14906 (org-small-year-to-year
14907 (string-to-number (match-string 1 ans))))
14908 iso-weekday (if (match-end 3)
14909 (string-to-number (match-string 3 ans)))
14910 iso-week (string-to-number (match-string 2 ans)))
14911 (setq ans (replace-match "" t t ans)))
14913 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
14914 (when (string-match
14915 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
14916 (setq year (if (match-end 2)
14917 (string-to-number (match-string 2 ans))
14918 (progn (setq kill-year t)
14919 (string-to-number (format-time-string "%Y"))))
14920 month (string-to-number (match-string 3 ans))
14921 day (string-to-number (match-string 4 ans)))
14922 (if (< year 100) (setq year (+ 2000 year)))
14923 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14924 t nil ans)))
14926 ;; Help matching dottet european dates
14927 (when (string-match
14928 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
14929 (setq year (if (match-end 3)
14930 (string-to-number (match-string 3 ans))
14931 (progn (setq kill-year t)
14932 (string-to-number (format-time-string "%Y"))))
14933 day (string-to-number (match-string 1 ans))
14934 month (string-to-number (match-string 2 ans))
14935 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14936 t nil ans)))
14938 ;; Help matching american dates, like 5/30 or 5/30/7
14939 (when (string-match
14940 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
14941 (setq year (if (match-end 4)
14942 (string-to-number (match-string 4 ans))
14943 (progn (setq kill-year t)
14944 (string-to-number (format-time-string "%Y"))))
14945 month (string-to-number (match-string 1 ans))
14946 day (string-to-number (match-string 2 ans)))
14947 (if (< year 100) (setq year (+ 2000 year)))
14948 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14949 t nil ans)))
14950 ;; Help matching am/pm times, because `parse-time-string' does not do that.
14951 ;; If there is a time with am/pm, and *no* time without it, we convert
14952 ;; so that matching will be successful.
14953 (loop for i from 1 to 2 do ; twice, for end time as well
14954 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
14955 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
14956 (setq hour (string-to-number (match-string 1 ans))
14957 minute (if (match-end 3)
14958 (string-to-number (match-string 3 ans))
14960 pm (equal ?p
14961 (string-to-char (downcase (match-string 4 ans)))))
14962 (if (and (= hour 12) (not pm))
14963 (setq hour 0)
14964 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
14965 (setq ans (replace-match (format "%02d:%02d" hour minute)
14966 t t ans))))
14968 ;; Check if a time range is given as a duration
14969 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
14970 (setq hour (string-to-number (match-string 1 ans))
14971 h2 (+ hour (string-to-number (match-string 3 ans)))
14972 minute (string-to-number (match-string 2 ans))
14973 m2 (+ minute (if (match-end 5) (string-to-number
14974 (match-string 5 ans))0)))
14975 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
14976 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
14977 t t ans)))
14979 ;; Check if there is a time range
14980 (when (boundp 'org-end-time-was-given)
14981 (setq org-time-was-given nil)
14982 (when (and (string-match org-plain-time-of-day-regexp ans)
14983 (match-end 8))
14984 (setq org-end-time-was-given (match-string 8 ans))
14985 (setq ans (concat (substring ans 0 (match-beginning 7))
14986 (substring ans (match-end 7))))))
14988 (setq tl (parse-time-string ans)
14989 day (or (nth 3 tl) (nth 3 defdecode))
14990 month (or (nth 4 tl)
14991 (if (and org-read-date-prefer-future
14992 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
14993 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
14994 (nth 4 defdecode)))
14995 year (or (and (not kill-year) (nth 5 tl))
14996 (if (and org-read-date-prefer-future
14997 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
14998 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
14999 (nth 5 defdecode)))
15000 hour (or (nth 2 tl) (nth 2 defdecode))
15001 minute (or (nth 1 tl) (nth 1 defdecode))
15002 second (or (nth 0 tl) 0)
15003 wday (nth 6 tl))
15005 (when (and (eq org-read-date-prefer-future 'time)
15006 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15007 (equal day (nth 3 nowdecode))
15008 (equal month (nth 4 nowdecode))
15009 (equal year (nth 5 nowdecode))
15010 (nth 2 tl)
15011 (or (< (nth 2 tl) (nth 2 nowdecode))
15012 (and (= (nth 2 tl) (nth 2 nowdecode))
15013 (nth 1 tl)
15014 (< (nth 1 tl) (nth 1 nowdecode)))))
15015 (setq day (1+ day)
15016 futurep t))
15018 ;; Special date definitions below
15019 (cond
15020 (iso-week
15021 ;; There was an iso week
15022 (require 'cal-iso)
15023 (setq futurep nil)
15024 (setq year (or iso-year year)
15025 day (or iso-weekday wday 1)
15026 wday nil ; to make sure that the trigger below does not match
15027 iso-date (calendar-gregorian-from-absolute
15028 (calendar-absolute-from-iso
15029 (list iso-week day year))))
15030 ; FIXME: Should we also push ISO weeks into the future?
15031 ; (when (and org-read-date-prefer-future
15032 ; (not iso-year)
15033 ; (< (calendar-absolute-from-gregorian iso-date)
15034 ; (time-to-days (current-time))))
15035 ; (setq year (1+ year)
15036 ; iso-date (calendar-gregorian-from-absolute
15037 ; (calendar-absolute-from-iso
15038 ; (list iso-week day year)))))
15039 (setq month (car iso-date)
15040 year (nth 2 iso-date)
15041 day (nth 1 iso-date)))
15042 (deltan
15043 (setq futurep nil)
15044 (unless deltadef
15045 (let ((now (decode-time (current-time))))
15046 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15047 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15048 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15049 ((equal deltaw "m") (setq month (+ month deltan)))
15050 ((equal deltaw "y") (setq year (+ year deltan)))))
15051 ((and wday (not (nth 3 tl)))
15052 (setq futurep nil)
15053 ;; Weekday was given, but no day, so pick that day in the week
15054 ;; on or after the derived date.
15055 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15056 (unless (equal wday wday1)
15057 (setq day (+ day (% (- wday wday1 -7) 7))))))
15058 (if (and (boundp 'org-time-was-given)
15059 (nth 2 tl))
15060 (setq org-time-was-given t))
15061 (if (< year 100) (setq year (+ 2000 year)))
15062 ;; Check of the date is representable
15063 (if org-read-date-force-compatible-dates
15064 (progn
15065 (if (< year 1970)
15066 (setq year 1970 org-read-date-analyze-forced-year t))
15067 (if (> year 2037)
15068 (setq year 2037 org-read-date-analyze-forced-year t)))
15069 (condition-case nil
15070 (ignore (encode-time second minute hour day month year))
15071 (error
15072 (setq year (nth 5 defdecode))
15073 (setq org-read-date-analyze-forced-year t))))
15074 (setq org-read-date-analyze-futurep futurep)
15075 (list second minute hour day month year)))
15077 (defvar parse-time-weekdays)
15079 (defun org-read-date-get-relative (s today default)
15080 "Check string S for special relative date string.
15081 TODAY and DEFAULT are internal times, for today and for a default.
15082 Return shift list (N what def-flag)
15083 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15084 N is the number of WHATs to shift.
15085 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15086 the DEFAULT date rather than TODAY."
15087 (when (and
15088 (string-match
15089 (concat
15090 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15091 "\\([0-9]+\\)?"
15092 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15093 "\\([ \t]\\|$\\)") s)
15094 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15095 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15096 (string-to-char (substring (match-string 1 s) -1))
15097 ?+))
15098 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15099 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15100 (what (if (match-end 3) (match-string 3 s) "d"))
15101 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15102 (date (if rel default today))
15103 (wday (nth 6 (decode-time date)))
15104 delta)
15105 (if wday1
15106 (progn
15107 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15108 (if (= dir ?-) (setq delta (- delta 7)))
15109 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15110 (list delta "d" rel))
15111 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15113 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15114 "Turn a user-specified date into the internal representation.
15115 The internal representation needed by the calendar is (month day year).
15116 This is a wrapper to handle the brain-dead convention in calendar that
15117 user function argument order change dependent on argument order."
15118 (if (boundp 'calendar-date-style)
15119 (cond
15120 ((eq calendar-date-style 'american)
15121 (list arg1 arg2 arg3))
15122 ((eq calendar-date-style 'european)
15123 (list arg2 arg1 arg3))
15124 ((eq calendar-date-style 'iso)
15125 (list arg2 arg3 arg1)))
15126 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15127 (if (org-bound-and-true-p european-calendar-style)
15128 (list arg2 arg1 arg3)
15129 (list arg1 arg2 arg3)))))
15131 (defun org-eval-in-calendar (form &optional keepdate)
15132 "Eval FORM in the calendar window and return to current window.
15133 Also, store the cursor date in variable org-ans2."
15134 (let ((sf (selected-frame))
15135 (sw (selected-window)))
15136 (select-window (get-buffer-window "*Calendar*" t))
15137 (eval form)
15138 (when (and (not keepdate) (calendar-cursor-to-date))
15139 (let* ((date (calendar-cursor-to-date))
15140 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15141 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15142 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15143 (select-window sw)
15144 (org-select-frame-set-input-focus sf)))
15146 (defun org-calendar-select ()
15147 "Return to `org-read-date' with the date currently selected.
15148 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15149 (interactive)
15150 (when (calendar-cursor-to-date)
15151 (let* ((date (calendar-cursor-to-date))
15152 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15153 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15154 (if (active-minibuffer-window) (exit-minibuffer))))
15156 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15157 "Insert a date stamp for the date given by the internal TIME.
15158 WITH-HM means use the stamp format that includes the time of the day.
15159 INACTIVE means use square brackets instead of angular ones, so that the
15160 stamp will not contribute to the agenda.
15161 PRE and POST are optional strings to be inserted before and after the
15162 stamp.
15163 The command returns the inserted time stamp."
15164 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15165 stamp)
15166 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15167 (insert-before-markers (or pre ""))
15168 (when (listp extra)
15169 (setq extra (car extra))
15170 (if (and (stringp extra)
15171 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15172 (setq extra (format "-%02d:%02d"
15173 (string-to-number (match-string 1 extra))
15174 (string-to-number (match-string 2 extra))))
15175 (setq extra nil)))
15176 (when extra
15177 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15178 (insert-before-markers (setq stamp (format-time-string fmt time)))
15179 (insert-before-markers (or post ""))
15180 (setq org-last-inserted-timestamp stamp)))
15182 (defun org-toggle-time-stamp-overlays ()
15183 "Toggle the use of custom time stamp formats."
15184 (interactive)
15185 (setq org-display-custom-times (not org-display-custom-times))
15186 (unless org-display-custom-times
15187 (let ((p (point-min)) (bmp (buffer-modified-p)))
15188 (while (setq p (next-single-property-change p 'display))
15189 (if (and (get-text-property p 'display)
15190 (eq (get-text-property p 'face) 'org-date))
15191 (remove-text-properties
15192 p (setq p (next-single-property-change p 'display))
15193 '(display t))))
15194 (set-buffer-modified-p bmp)))
15195 (if (featurep 'xemacs)
15196 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15197 (org-restart-font-lock)
15198 (setq org-table-may-need-update t)
15199 (if org-display-custom-times
15200 (message "Time stamps are overlayed with custom format")
15201 (message "Time stamp overlays removed")))
15203 (defun org-display-custom-time (beg end)
15204 "Overlay modified time stamp format over timestamp between BEG and END."
15205 (let* ((ts (buffer-substring beg end))
15206 t1 w1 with-hm tf time str w2 (off 0))
15207 (save-match-data
15208 (setq t1 (org-parse-time-string ts t))
15209 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15210 (setq off (- (match-end 0) (match-beginning 0)))))
15211 (setq end (- end off))
15212 (setq w1 (- end beg)
15213 with-hm (and (nth 1 t1) (nth 2 t1))
15214 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15215 time (org-fix-decoded-time t1)
15216 str (org-add-props
15217 (format-time-string
15218 (substring tf 1 -1) (apply 'encode-time time))
15219 nil 'mouse-face 'highlight)
15220 w2 (length str))
15221 (if (not (= w2 w1))
15222 (add-text-properties (1+ beg) (+ 2 beg)
15223 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15224 (if (featurep 'xemacs)
15225 (progn
15226 (put-text-property beg end 'invisible t)
15227 (put-text-property beg end 'end-glyph (make-glyph str)))
15228 (put-text-property beg end 'display str))))
15230 (defun org-translate-time (string)
15231 "Translate all timestamps in STRING to custom format.
15232 But do this only if the variable `org-display-custom-times' is set."
15233 (when org-display-custom-times
15234 (save-match-data
15235 (let* ((start 0)
15236 (re org-ts-regexp-both)
15237 t1 with-hm inactive tf time str beg end)
15238 (while (setq start (string-match re string start))
15239 (setq beg (match-beginning 0)
15240 end (match-end 0)
15241 t1 (save-match-data
15242 (org-parse-time-string (substring string beg end) t))
15243 with-hm (and (nth 1 t1) (nth 2 t1))
15244 inactive (equal (substring string beg (1+ beg)) "[")
15245 tf (funcall (if with-hm 'cdr 'car)
15246 org-time-stamp-custom-formats)
15247 time (org-fix-decoded-time t1)
15248 str (format-time-string
15249 (concat
15250 (if inactive "[" "<") (substring tf 1 -1)
15251 (if inactive "]" ">"))
15252 (apply 'encode-time time))
15253 string (replace-match str t t string)
15254 start (+ start (length str)))))))
15255 string)
15257 (defun org-fix-decoded-time (time)
15258 "Set 0 instead of nil for the first 6 elements of time.
15259 Don't touch the rest."
15260 (let ((n 0))
15261 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15263 (defun org-days-to-time (timestamp-string)
15264 "Difference between TIMESTAMP-STRING and now in days."
15265 (- (time-to-days (org-time-string-to-time timestamp-string))
15266 (time-to-days (current-time))))
15268 (defun org-deadline-close (timestamp-string &optional ndays)
15269 "Is the time in TIMESTAMP-STRING close to the current date?"
15270 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15271 (and (< (org-days-to-time timestamp-string) ndays)
15272 (not (org-entry-is-done-p))))
15274 (defun org-get-wdays (ts)
15275 "Get the deadline lead time appropriate for timestring TS."
15276 (cond
15277 ((<= org-deadline-warning-days 0)
15278 ;; 0 or negative, enforce this value no matter what
15279 (- org-deadline-warning-days))
15280 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15281 ;; lead time is specified.
15282 (floor (* (string-to-number (match-string 1 ts))
15283 (cdr (assoc (match-string 2 ts)
15284 '(("d" . 1) ("w" . 7)
15285 ("m" . 30.4) ("y" . 365.25)))))))
15286 ;; go for the default.
15287 (t org-deadline-warning-days)))
15289 (defun org-calendar-select-mouse (ev)
15290 "Return to `org-read-date' with the date currently selected.
15291 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15292 (interactive "e")
15293 (mouse-set-point ev)
15294 (when (calendar-cursor-to-date)
15295 (let* ((date (calendar-cursor-to-date))
15296 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15297 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15298 (if (active-minibuffer-window) (exit-minibuffer))))
15300 (defun org-check-deadlines (ndays)
15301 "Check if there are any deadlines due or past due.
15302 A deadline is considered due if it happens within `org-deadline-warning-days'
15303 days from today's date. If the deadline appears in an entry marked DONE,
15304 it is not shown. The prefix arg NDAYS can be used to test that many
15305 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15306 (interactive "P")
15307 (let* ((org-warn-days
15308 (cond
15309 ((equal ndays '(4)) 100000)
15310 (ndays (prefix-numeric-value ndays))
15311 (t (abs org-deadline-warning-days))))
15312 (case-fold-search nil)
15313 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15314 (callback
15315 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15317 (message "%d deadlines past-due or due within %d days"
15318 (org-occur regexp nil callback)
15319 org-warn-days)))
15321 (defun org-check-before-date (date)
15322 "Check if there are deadlines or scheduled entries before DATE."
15323 (interactive (list (org-read-date)))
15324 (let ((case-fold-search nil)
15325 (regexp (concat "\\<\\(" org-deadline-string
15326 "\\|" org-scheduled-string
15327 "\\) *<\\([^>]+\\)>"))
15328 (callback
15329 (lambda () (time-less-p
15330 (org-time-string-to-time (match-string 2))
15331 (org-time-string-to-time date)))))
15332 (message "%d entries before %s"
15333 (org-occur regexp nil callback) date)))
15335 (defun org-check-after-date (date)
15336 "Check if there are deadlines or scheduled entries after DATE."
15337 (interactive (list (org-read-date)))
15338 (let ((case-fold-search nil)
15339 (regexp (concat "\\<\\(" org-deadline-string
15340 "\\|" org-scheduled-string
15341 "\\) *<\\([^>]+\\)>"))
15342 (callback
15343 (lambda () (not
15344 (time-less-p
15345 (org-time-string-to-time (match-string 2))
15346 (org-time-string-to-time date))))))
15347 (message "%d entries after %s"
15348 (org-occur regexp nil callback) date)))
15350 (defun org-evaluate-time-range (&optional to-buffer)
15351 "Evaluate a time range by computing the difference between start and end.
15352 Normally the result is just printed in the echo area, but with prefix arg
15353 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15354 If the time range is actually in a table, the result is inserted into the
15355 next column.
15356 For time difference computation, a year is assumed to be exactly 365
15357 days in order to avoid rounding problems."
15358 (interactive "P")
15360 (org-clock-update-time-maybe)
15361 (save-excursion
15362 (unless (org-at-date-range-p t)
15363 (goto-char (point-at-bol))
15364 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15365 (if (not (org-at-date-range-p t))
15366 (error "Not at a time-stamp range, and none found in current line")))
15367 (let* ((ts1 (match-string 1))
15368 (ts2 (match-string 2))
15369 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15370 (match-end (match-end 0))
15371 (time1 (org-time-string-to-time ts1))
15372 (time2 (org-time-string-to-time ts2))
15373 (t1 (org-float-time time1))
15374 (t2 (org-float-time time2))
15375 (diff (abs (- t2 t1)))
15376 (negative (< (- t2 t1) 0))
15377 ;; (ys (floor (* 365 24 60 60)))
15378 (ds (* 24 60 60))
15379 (hs (* 60 60))
15380 (fy "%dy %dd %02d:%02d")
15381 (fy1 "%dy %dd")
15382 (fd "%dd %02d:%02d")
15383 (fd1 "%dd")
15384 (fh "%02d:%02d")
15385 y d h m align)
15386 (if havetime
15387 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15389 d (floor (/ diff ds)) diff (mod diff ds)
15390 h (floor (/ diff hs)) diff (mod diff hs)
15391 m (floor (/ diff 60)))
15392 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15394 d (floor (+ (/ diff ds) 0.5))
15395 h 0 m 0))
15396 (if (not to-buffer)
15397 (message "%s" (org-make-tdiff-string y d h m))
15398 (if (org-at-table-p)
15399 (progn
15400 (goto-char match-end)
15401 (setq align t)
15402 (and (looking-at " *|") (goto-char (match-end 0))))
15403 (goto-char match-end))
15404 (if (looking-at
15405 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15406 (replace-match ""))
15407 (if negative (insert " -"))
15408 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15409 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15410 (insert " " (format fh h m))))
15411 (if align (org-table-align))
15412 (message "Time difference inserted")))))
15414 (defun org-make-tdiff-string (y d h m)
15415 (let ((fmt "")
15416 (l nil))
15417 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15418 l (push y l)))
15419 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15420 l (push d l)))
15421 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15422 l (push h l)))
15423 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15424 l (push m l)))
15425 (apply 'format fmt (nreverse l))))
15427 (defun org-time-string-to-time (s &optional buffer pos)
15428 (condition-case errdata
15429 (apply 'encode-time (org-parse-time-string s))
15430 (error (error "Bad timestamp `%s'%s\nError was: %s"
15431 s (if (not (and buffer pos))
15433 (format " at %d in buffer `%s'" pos buffer))
15434 (cdr errdata)))))
15436 (defun org-time-string-to-seconds (s)
15437 (org-float-time (org-time-string-to-time s)))
15439 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
15440 "Convert a time stamp to an absolute day number.
15441 If there is a specifier for a cyclic time stamp, get the closest date to
15442 DAYNR.
15443 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15444 The variable date is bound by the calendar when this is called."
15445 (cond
15446 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15447 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15448 daynr
15449 (+ daynr 1000)))
15450 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15451 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15452 (time-to-days (current-time))) (match-string 0 s)
15453 prefer show-all))
15454 (t (time-to-days
15455 (condition-case errdata
15456 (apply 'encode-time (org-parse-time-string s))
15457 (error (error "Bad timestamp `%s'%s\nError was: %s"
15458 s (if (not (and buffer pos))
15460 (format " at %d in buffer `%s'" pos buffer))
15461 (cdr errdata))))))))
15463 (defun org-days-to-iso-week (days)
15464 "Return the iso week number."
15465 (require 'cal-iso)
15466 (car (calendar-iso-from-absolute days)))
15468 (defun org-small-year-to-year (year)
15469 "Convert 2-digit years into 4-digit years.
15470 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15471 The year 2000 cannot be abbreviated. Any year larger than 99
15472 is returned unchanged."
15473 (if (< year 38)
15474 (setq year (+ 2000 year))
15475 (if (< year 100)
15476 (setq year (+ 1900 year))))
15477 year)
15479 (defun org-time-from-absolute (d)
15480 "Return the time corresponding to date D.
15481 D may be an absolute day number, or a calendar-type list (month day year)."
15482 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15483 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15485 (defun org-calendar-holiday ()
15486 "List of holidays, for Diary display in Org-mode."
15487 (require 'holidays)
15488 (let ((hl (funcall
15489 (if (fboundp 'calendar-check-holidays)
15490 'calendar-check-holidays 'check-calendar-holidays) date)))
15491 (if hl (mapconcat 'identity hl "; "))))
15493 (defun org-diary-sexp-entry (sexp entry date)
15494 "Process a SEXP diary ENTRY for DATE."
15495 (require 'diary-lib)
15496 (let ((result (if calendar-debug-sexp
15497 (let ((stack-trace-on-error t))
15498 (eval (car (read-from-string sexp))))
15499 (condition-case nil
15500 (eval (car (read-from-string sexp)))
15501 (error
15502 (beep)
15503 (message "Bad sexp at line %d in %s: %s"
15504 (org-current-line)
15505 (buffer-file-name) sexp)
15506 (sleep-for 2))))))
15507 (cond ((stringp result) (split-string result "; "))
15508 ((and (consp result)
15509 (not (consp (cdr result)))
15510 (stringp (cdr result))) (cdr result))
15511 ((and (consp result)
15512 (stringp (car result))) result)
15513 (result entry)
15514 (t nil))))
15516 (defun org-diary-to-ical-string (frombuf)
15517 "Get iCalendar entries from diary entries in buffer FROMBUF.
15518 This uses the icalendar.el library."
15519 (let* ((tmpdir (if (featurep 'xemacs)
15520 (temp-directory)
15521 temporary-file-directory))
15522 (tmpfile (make-temp-name
15523 (expand-file-name "orgics" tmpdir)))
15524 buf rtn b e)
15525 (with-current-buffer frombuf
15526 (icalendar-export-region (point-min) (point-max) tmpfile)
15527 (setq buf (find-buffer-visiting tmpfile))
15528 (set-buffer buf)
15529 (goto-char (point-min))
15530 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15531 (setq b (match-beginning 0)))
15532 (goto-char (point-max))
15533 (if (re-search-backward "^END:VEVENT" nil t)
15534 (setq e (match-end 0)))
15535 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15536 (kill-buffer buf)
15537 (delete-file tmpfile)
15538 rtn))
15540 (defun org-closest-date (start current change prefer show-all)
15541 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15542 When PREFER is `past', return a date that is either CURRENT or past.
15543 When PREFER is `future', return a date that is either CURRENT or future.
15544 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15545 ;; Make the proper lists from the dates
15546 (catch 'exit
15547 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15548 dn dw sday cday n1 n2 n0
15549 d m y y1 y2 date1 date2 nmonths nm ny m2)
15551 (setq start (org-date-to-gregorian start)
15552 current (org-date-to-gregorian
15553 (if show-all
15554 current
15555 (time-to-days (current-time))))
15556 sday (calendar-absolute-from-gregorian start)
15557 cday (calendar-absolute-from-gregorian current))
15559 (if (<= cday sday) (throw 'exit sday))
15561 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15562 (setq dn (string-to-number (match-string 1 change))
15563 dw (cdr (assoc (match-string 2 change) a1)))
15564 (error "Invalid change specifier: %s" change))
15565 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15566 (cond
15567 ((eq dw 'day)
15568 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15569 n2 (+ n1 dn)))
15570 ((eq dw 'year)
15571 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15572 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15573 (setq date1 (list m d y1)
15574 n1 (calendar-absolute-from-gregorian date1)
15575 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15576 n2 (calendar-absolute-from-gregorian date2)))
15577 ((eq dw 'month)
15578 ;; approx number of month between the two dates
15579 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15580 ;; How often does dn fit in there?
15581 (setq d (nth 1 start) m (car start) y (nth 2 start)
15582 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15583 m (+ m nm)
15584 ny (floor (/ m 12))
15585 y (+ y ny)
15586 m (- m (* ny 12)))
15587 (while (> m 12) (setq m (- m 12) y (1+ y)))
15588 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15589 (setq m2 (+ m dn) y2 y)
15590 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15591 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15592 (while (<= n2 cday)
15593 (setq n1 n2 m m2 y y2)
15594 (setq m2 (+ m dn) y2 y)
15595 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15596 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15597 ;; Make sure n1 is the earlier date
15598 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15599 (if show-all
15600 (cond
15601 ((eq prefer 'past) (if (= cday n2) n2 n1))
15602 ((eq prefer 'future) (if (= cday n1) n1 n2))
15603 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15604 (cond
15605 ((eq prefer 'past) (if (= cday n2) n2 n1))
15606 ((eq prefer 'future) (if (= cday n1) n1 n2))
15607 (t (if (= cday n1) n1 n2)))))))
15609 (defun org-date-to-gregorian (date)
15610 "Turn any specification of DATE into a Gregorian date for the calendar."
15611 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15612 ((and (listp date) (= (length date) 3)) date)
15613 ((stringp date)
15614 (setq date (org-parse-time-string date))
15615 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15616 ((listp date)
15617 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15619 (defun org-parse-time-string (s &optional nodefault)
15620 "Parse the standard Org-mode time string.
15621 This should be a lot faster than the normal `parse-time-string'.
15622 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15623 hour and minute fields will be nil if not given."
15624 (if (string-match org-ts-regexp0 s)
15625 (list 0
15626 (if (or (match-beginning 8) (not nodefault))
15627 (string-to-number (or (match-string 8 s) "0")))
15628 (if (or (match-beginning 7) (not nodefault))
15629 (string-to-number (or (match-string 7 s) "0")))
15630 (string-to-number (match-string 4 s))
15631 (string-to-number (match-string 3 s))
15632 (string-to-number (match-string 2 s))
15633 nil nil nil)
15634 (error "Not a standard Org-mode time string: %s" s)))
15636 (defun org-timestamp-up (&optional arg)
15637 "Increase the date item at the cursor by one.
15638 If the cursor is on the year, change the year. If it is on the month,
15639 the day or the time, change that.
15640 With prefix ARG, change by that many units."
15641 (interactive "p")
15642 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15644 (defun org-timestamp-down (&optional arg)
15645 "Decrease the date item at the cursor by one.
15646 If the cursor is on the year, change the year. If it is on the month,
15647 the day or the time, change that.
15648 With prefix ARG, change by that many units."
15649 (interactive "p")
15650 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15652 (defun org-timestamp-up-day (&optional arg)
15653 "Increase the date in the time stamp by one day.
15654 With prefix ARG, change that many days."
15655 (interactive "p")
15656 (if (and (not (org-at-timestamp-p t))
15657 (org-on-heading-p))
15658 (org-todo 'up)
15659 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15661 (defun org-timestamp-down-day (&optional arg)
15662 "Decrease the date in the time stamp by one day.
15663 With prefix ARG, change that many days."
15664 (interactive "p")
15665 (if (and (not (org-at-timestamp-p t))
15666 (org-on-heading-p))
15667 (org-todo 'down)
15668 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15670 (defun org-at-timestamp-p (&optional inactive-ok)
15671 "Determine if the cursor is in or at a timestamp."
15672 (interactive)
15673 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15674 (pos (point))
15675 (ans (or (looking-at tsr)
15676 (save-excursion
15677 (skip-chars-backward "^[<\n\r\t")
15678 (if (> (point) (point-min)) (backward-char 1))
15679 (and (looking-at tsr)
15680 (> (- (match-end 0) pos) -1))))))
15681 (and ans
15682 (boundp 'org-ts-what)
15683 (setq org-ts-what
15684 (cond
15685 ((= pos (match-beginning 0)) 'bracket)
15686 ;; Point is considered to be "on the bracket" whether
15687 ;; it's really on it or right after it.
15688 ((or (= pos (1- (match-end 0)))
15689 (= pos (match-end 0))) 'bracket)
15690 ((org-pos-in-match-range pos 2) 'year)
15691 ((org-pos-in-match-range pos 3) 'month)
15692 ((org-pos-in-match-range pos 7) 'hour)
15693 ((org-pos-in-match-range pos 8) 'minute)
15694 ((or (org-pos-in-match-range pos 4)
15695 (org-pos-in-match-range pos 5)) 'day)
15696 ((and (> pos (or (match-end 8) (match-end 5)))
15697 (< pos (match-end 0)))
15698 (- pos (or (match-end 8) (match-end 5))))
15699 (t 'day))))
15700 ans))
15702 (defun org-toggle-timestamp-type ()
15703 "Toggle the type (<active> or [inactive]) of a time stamp."
15704 (interactive)
15705 (when (org-at-timestamp-p t)
15706 (let ((beg (match-beginning 0)) (end (match-end 0))
15707 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
15708 (save-excursion
15709 (goto-char beg)
15710 (while (re-search-forward "[][<>]" end t)
15711 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
15712 t t)))
15713 (message "Timestamp is now %sactive"
15714 (if (equal (char-after beg) ?<) "" "in")))))
15716 (defun org-timestamp-change (n &optional what updown)
15717 "Change the date in the time stamp at point.
15718 The date will be changed by N times WHAT. WHAT can be `day', `month',
15719 `year', `minute', `second'. If WHAT is not given, the cursor position
15720 in the timestamp determines what will be changed."
15721 (let ((origin (point)) origin-cat
15722 with-hm inactive
15723 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
15724 org-ts-what
15725 extra rem
15726 ts time time0)
15727 (if (not (org-at-timestamp-p t))
15728 (error "Not at a timestamp"))
15729 (if (and (not what) (eq org-ts-what 'bracket))
15730 (org-toggle-timestamp-type)
15731 ;; Point isn't on brackets. Remember the part of the time-stamp
15732 ;; the point was in. Indeed, size of time-stamps may change,
15733 ;; but point must be kept in the same category nonetheless.
15734 (setq origin-cat org-ts-what)
15735 (if (and (not what) (not (eq org-ts-what 'day))
15736 org-display-custom-times
15737 (get-text-property (point) 'display)
15738 (not (get-text-property (1- (point)) 'display)))
15739 (setq org-ts-what 'day))
15740 (setq org-ts-what (or what org-ts-what)
15741 inactive (= (char-after (match-beginning 0)) ?\[)
15742 ts (match-string 0))
15743 (replace-match "")
15744 (if (string-match
15745 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
15747 (setq extra (match-string 1 ts)))
15748 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15749 (setq with-hm t))
15750 (setq time0 (org-parse-time-string ts))
15751 (when (and updown
15752 (eq org-ts-what 'minute)
15753 (not current-prefix-arg))
15754 ;; This looks like s-up and s-down. Change by one rounding step.
15755 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
15756 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
15757 (setcar (cdr time0) (+ (nth 1 time0)
15758 (if (> n 0) (- rem) (- dm rem))))))
15759 (setq time
15760 (encode-time (or (car time0) 0)
15761 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
15762 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
15763 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
15764 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
15765 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
15766 (nthcdr 6 time0)))
15767 (when (and (member org-ts-what '(hour minute))
15768 extra
15769 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
15770 (setq extra (org-modify-ts-extra
15771 extra
15772 (if (eq org-ts-what 'hour) 2 5)
15773 n dm)))
15774 (when (integerp org-ts-what)
15775 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
15776 (if (eq what 'calendar)
15777 (let ((cal-date (org-get-date-from-calendar)))
15778 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15779 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15780 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15781 (setcar time0 (or (car time0) 0))
15782 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15783 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15784 (setq time (apply 'encode-time time0))))
15785 ;; Insert the new time-stamp, and ensure point stays in the same
15786 ;; category as before (i.e. not after the last position in that
15787 ;; category).
15788 (let ((pos (point)))
15789 ;; Stay before inserted string. `save-excursion' is of no use.
15790 (setq org-last-changed-timestamp
15791 (org-insert-time-stamp time with-hm inactive nil nil extra))
15792 (goto-char pos))
15793 (save-match-data
15794 (looking-at org-ts-regexp3)
15795 (goto-char (cond
15796 ;; `day' category ends before `hour' if any, or at
15797 ;; the end of the day name.
15798 ((eq origin-cat 'day)
15799 (min (or (match-beginning 7) (1- (match-end 5))) origin))
15800 ((eq origin-cat 'hour) (min (match-end 7) origin))
15801 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
15802 ((integerp origin-cat) (min (1- (match-end 0)) origin))
15803 ;; `year' and `month' have both fixed size: point
15804 ;; couldn't have moved into another part.
15805 (t origin))))
15806 ;; Update clock if on a CLOCK line.
15807 (org-clock-update-time-maybe)
15808 ;; Try to recenter the calendar window, if any.
15809 (if (and org-calendar-follow-timestamp-change
15810 (get-buffer-window "*Calendar*" t)
15811 (memq org-ts-what '(day month year)))
15812 (org-recenter-calendar (time-to-days time))))))
15814 (defun org-modify-ts-extra (s pos n dm)
15815 "Change the different parts of the lead-time and repeat fields in timestamp."
15816 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15817 ng h m new rem)
15818 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15819 (cond
15820 ((or (org-pos-in-match-range pos 2)
15821 (org-pos-in-match-range pos 3))
15822 (setq m (string-to-number (match-string 3 s))
15823 h (string-to-number (match-string 2 s)))
15824 (if (org-pos-in-match-range pos 2)
15825 (setq h (+ h n))
15826 (setq n (* dm (org-no-warnings (signum n))))
15827 (when (not (= 0 (setq rem (% m dm))))
15828 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
15829 (setq m (+ m n)))
15830 (if (< m 0) (setq m (+ m 60) h (1- h)))
15831 (if (> m 59) (setq m (- m 60) h (1+ h)))
15832 (setq h (min 24 (max 0 h)))
15833 (setq ng 1 new (format "-%02d:%02d" h m)))
15834 ((org-pos-in-match-range pos 6)
15835 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15836 ((org-pos-in-match-range pos 5)
15837 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
15839 ((org-pos-in-match-range pos 9)
15840 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
15841 ((org-pos-in-match-range pos 8)
15842 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
15844 (when ng
15845 (setq s (concat
15846 (substring s 0 (match-beginning ng))
15848 (substring s (match-end ng))))))
15851 (defun org-recenter-calendar (date)
15852 "If the calendar is visible, recenter it to DATE."
15853 (let* ((win (selected-window))
15854 (cwin (get-buffer-window "*Calendar*" t))
15855 (calendar-move-hook nil))
15856 (when cwin
15857 (select-window cwin)
15858 (calendar-goto-date (if (listp date) date
15859 (calendar-gregorian-from-absolute date)))
15860 (select-window win))))
15862 (defun org-goto-calendar (&optional arg)
15863 "Go to the Emacs calendar at the current date.
15864 If there is a time stamp in the current line, go to that date.
15865 A prefix ARG can be used to force the current date."
15866 (interactive "P")
15867 (let ((tsr org-ts-regexp) diff
15868 (calendar-move-hook nil)
15869 (calendar-view-holidays-initially-flag nil)
15870 (calendar-view-diary-initially-flag nil))
15871 (if (or (org-at-timestamp-p)
15872 (save-excursion
15873 (beginning-of-line 1)
15874 (looking-at (concat ".*" tsr))))
15875 (let ((d1 (time-to-days (current-time)))
15876 (d2 (time-to-days
15877 (org-time-string-to-time (match-string 1)))))
15878 (setq diff (- d2 d1))))
15879 (calendar)
15880 (calendar-goto-today)
15881 (if (and diff (not arg)) (calendar-forward-day diff))))
15883 (defun org-get-date-from-calendar ()
15884 "Return a list (month day year) of date at point in calendar."
15885 (with-current-buffer "*Calendar*"
15886 (save-match-data
15887 (calendar-cursor-to-date))))
15889 (defun org-date-from-calendar ()
15890 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
15891 If there is already a time stamp at the cursor position, update it."
15892 (interactive)
15893 (if (org-at-timestamp-p t)
15894 (org-timestamp-change 0 'calendar)
15895 (let ((cal-date (org-get-date-from-calendar)))
15896 (org-insert-time-stamp
15897 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
15899 (defun org-minutes-to-hh:mm-string (m)
15900 "Compute H:MM from a number of minutes."
15901 (let ((h (/ m 60)))
15902 (setq m (- m (* 60 h)))
15903 (format org-time-clocksum-format h m)))
15905 (defun org-hh:mm-string-to-minutes (s)
15906 "Convert a string H:MM to a number of minutes.
15907 If the string is just a number, interpret it as minutes.
15908 In fact, the first hh:mm or number in the string will be taken,
15909 there can be extra stuff in the string.
15910 If no number is found, the return value is 0."
15911 (cond
15912 ((integerp s) s)
15913 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
15914 (+ (* (string-to-number (match-string 1 s)) 60)
15915 (string-to-number (match-string 2 s))))
15916 ((string-match "\\([0-9]+\\)" s)
15917 (string-to-number (match-string 1 s)))
15918 (t 0)))
15920 (defcustom org-effort-durations
15921 `(("h" . 60)
15922 ("d" . ,(* 60 8))
15923 ("w" . ,(* 60 8 5))
15924 ("m" . ,(* 60 8 5 4))
15925 ("y" . ,(* 60 8 5 40)))
15926 "Conversion factor to minutes for an effort modifier.
15928 Each entry has the form (MODIFIER . MINUTES).
15930 In an effort string, a number followed by MODIFIER is multiplied
15931 by the specified number of MINUTES to obtain an effort in
15932 minutes.
15934 For example, if the value of this variable is ((\"hours\" . 60)), then an
15935 effort string \"2hours\" is equivalent to 120 minutes."
15936 :group 'org-agenda
15937 :type '(alist :key-type (string :tag "Modifier")
15938 :value-type (number :tag "Minutes")))
15940 (defun org-duration-string-to-minutes (s)
15941 "Convert a duration string S to minutes.
15943 A bare number is interpreted as minutes, modifiers can be set by
15944 customizing `org-effort-durations' (which see).
15946 Entries containing a colon are interpreted as H:MM by
15947 `org-hh:mm-string-to-minutes'."
15948 (let ((result 0)
15949 (re (concat "\\([0-9]+\\) *\\("
15950 (regexp-opt (mapcar 'car org-effort-durations))
15951 "\\)")))
15952 (while (string-match re s)
15953 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
15954 (string-to-number (match-string 1 s))))
15955 (setq s (replace-match "" nil t s)))
15956 (incf result (org-hh:mm-string-to-minutes s))
15957 result))
15959 ;;;; Files
15961 (defun org-save-all-org-buffers ()
15962 "Save all Org-mode buffers without user confirmation."
15963 (interactive)
15964 (message "Saving all Org-mode buffers...")
15965 (save-some-buffers t 'org-mode-p)
15966 (when (featurep 'org-id) (org-id-locations-save))
15967 (message "Saving all Org-mode buffers... done"))
15969 (defun org-revert-all-org-buffers ()
15970 "Revert all Org-mode buffers.
15971 Prompt for confirmation when there are unsaved changes.
15972 Be sure you know what you are doing before letting this function
15973 overwrite your changes.
15975 This function is useful in a setup where one tracks org files
15976 with a version control system, to revert on one machine after pulling
15977 changes from another. I believe the procedure must be like this:
15979 1. M-x org-save-all-org-buffers
15980 2. Pull changes from the other machine, resolve conflicts
15981 3. M-x org-revert-all-org-buffers"
15982 (interactive)
15983 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
15984 (error "Abort"))
15985 (save-excursion
15986 (save-window-excursion
15987 (mapc
15988 (lambda (b)
15989 (when (and (with-current-buffer b (org-mode-p))
15990 (with-current-buffer b buffer-file-name))
15991 (org-pop-to-buffer-same-window b)
15992 (revert-buffer t 'no-confirm)))
15993 (buffer-list))
15994 (when (and (featurep 'org-id) org-id-track-globally)
15995 (org-id-locations-load)))))
15997 ;;;; Agenda files
15999 ;;;###autoload
16000 (defun org-switchb (&optional arg)
16001 "Switch between Org buffers.
16002 With a prefix argument, restrict available to files.
16003 With two prefix arguments, restrict available buffers to agenda files.
16005 Defaults to `iswitchb' for buffer name completion.
16006 Set `org-completion-use-ido' to make it use ido instead."
16007 (interactive "P")
16008 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16009 ((equal arg '(16)) (org-buffer-list 'agenda))
16010 (t (org-buffer-list))))
16011 (org-completion-use-iswitchb org-completion-use-iswitchb)
16012 (org-completion-use-ido org-completion-use-ido))
16013 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16014 (setq org-completion-use-iswitchb t))
16015 (org-pop-to-buffer-same-window
16016 (org-icompleting-read "Org buffer: "
16017 (mapcar 'list (mapcar 'buffer-name blist))
16018 nil t))))
16020 ;;; Define some older names previously used for this functionality
16021 ;;;###autoload
16022 (defalias 'org-ido-switchb 'org-switchb)
16023 ;;;###autoload
16024 (defalias 'org-iswitchb 'org-switchb)
16026 (defun org-buffer-list (&optional predicate exclude-tmp)
16027 "Return a list of Org buffers.
16028 PREDICATE can be `export', `files' or `agenda'.
16030 export restrict the list to Export buffers.
16031 files restrict the list to buffers visiting Org files.
16032 agenda restrict the list to buffers visiting agenda files.
16034 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16035 (let* ((bfn nil)
16036 (agenda-files (and (eq predicate 'agenda)
16037 (mapcar 'file-truename (org-agenda-files t))))
16038 (filter
16039 (cond
16040 ((eq predicate 'files)
16041 (lambda (b) (with-current-buffer b (org-mode-p))))
16042 ((eq predicate 'export)
16043 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16044 ((eq predicate 'agenda)
16045 (lambda (b)
16046 (with-current-buffer b
16047 (and (org-mode-p)
16048 (setq bfn (buffer-file-name b))
16049 (member (file-truename bfn) agenda-files)))))
16050 (t (lambda (b) (with-current-buffer b
16051 (or (org-mode-p)
16052 (string-match "\*Org .*Export"
16053 (buffer-name b)))))))))
16054 (delq nil
16055 (mapcar
16056 (lambda(b)
16057 (if (and (funcall filter b)
16058 (or (not exclude-tmp)
16059 (not (string-match "tmp" (buffer-name b)))))
16061 nil))
16062 (buffer-list)))))
16064 (defun org-agenda-files (&optional unrestricted archives)
16065 "Get the list of agenda files.
16066 Optional UNRESTRICTED means return the full list even if a restriction
16067 is currently in place.
16068 When ARCHIVES is t, include all archive files that are really being
16069 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16070 `org-agenda-archives-mode' is t."
16071 (let ((files
16072 (cond
16073 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16074 ((stringp org-agenda-files) (org-read-agenda-file-list))
16075 ((listp org-agenda-files) org-agenda-files)
16076 (t (error "Invalid value of `org-agenda-files'")))))
16077 (setq files (apply 'append
16078 (mapcar (lambda (f)
16079 (if (file-directory-p f)
16080 (directory-files
16081 f t org-agenda-file-regexp)
16082 (list f)))
16083 files)))
16084 (when org-agenda-skip-unavailable-files
16085 (setq files (delq nil
16086 (mapcar (function
16087 (lambda (file)
16088 (and (file-readable-p file) file)))
16089 files))))
16090 (when (or (eq archives t)
16091 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16092 (setq files (org-add-archive-files files)))
16093 files))
16095 (defun org-agenda-file-p (&optional file)
16096 "Return non-nil, if FILE is an agenda file.
16097 If FILE is omitted, use the file associated with the current
16098 buffer."
16099 (member (or file (buffer-file-name))
16100 (org-agenda-files t)))
16102 (defun org-edit-agenda-file-list ()
16103 "Edit the list of agenda files.
16104 Depending on setup, this either uses customize to edit the variable
16105 `org-agenda-files', or it visits the file that is holding the list. In the
16106 latter case, the buffer is set up in a way that saving it automatically kills
16107 the buffer and restores the previous window configuration."
16108 (interactive)
16109 (if (stringp org-agenda-files)
16110 (let ((cw (current-window-configuration)))
16111 (find-file org-agenda-files)
16112 (org-set-local 'org-window-configuration cw)
16113 (org-add-hook 'after-save-hook
16114 (lambda ()
16115 (set-window-configuration
16116 (prog1 org-window-configuration
16117 (kill-buffer (current-buffer))))
16118 (org-install-agenda-files-menu)
16119 (message "New agenda file list installed"))
16120 nil 'local)
16121 (message "%s" (substitute-command-keys
16122 "Edit list and finish with \\[save-buffer]")))
16123 (customize-variable 'org-agenda-files)))
16125 (defun org-store-new-agenda-file-list (list)
16126 "Set new value for the agenda file list and save it correctly."
16127 (if (stringp org-agenda-files)
16128 (let ((fe (org-read-agenda-file-list t)) b u)
16129 (while (setq b (find-buffer-visiting org-agenda-files))
16130 (kill-buffer b))
16131 (with-temp-file org-agenda-files
16132 (insert
16133 (mapconcat
16134 (lambda (f) ;; Keep un-expanded entries.
16135 (if (setq u (assoc f fe))
16136 (cdr u)
16138 list "\n")
16139 "\n")))
16140 (let ((org-mode-hook nil) (org-inhibit-startup t)
16141 (org-insert-mode-line-in-empty-file nil))
16142 (setq org-agenda-files list)
16143 (customize-save-variable 'org-agenda-files org-agenda-files))))
16145 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16146 "Read the list of agenda files from a file.
16147 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16148 filenames, used by `org-store-new-agenda-file-list' to write back
16149 un-expanded file names."
16150 (when (file-directory-p org-agenda-files)
16151 (error "`org-agenda-files' cannot be a single directory"))
16152 (when (stringp org-agenda-files)
16153 (with-temp-buffer
16154 (insert-file-contents org-agenda-files)
16155 (mapcar
16156 (lambda (f)
16157 (let ((e (expand-file-name (substitute-in-file-name f)
16158 org-directory)))
16159 (if pair-with-expansion
16160 (cons e f)
16161 e)))
16162 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16164 ;;;###autoload
16165 (defun org-cycle-agenda-files ()
16166 "Cycle through the files in `org-agenda-files'.
16167 If the current buffer visits an agenda file, find the next one in the list.
16168 If the current buffer does not, find the first agenda file."
16169 (interactive)
16170 (let* ((fs (org-agenda-files t))
16171 (files (append fs (list (car fs))))
16172 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16173 file)
16174 (unless files (error "No agenda files"))
16175 (catch 'exit
16176 (while (setq file (pop files))
16177 (if (equal (file-truename file) tcf)
16178 (when (car files)
16179 (find-file (car files))
16180 (throw 'exit t))))
16181 (find-file (car fs)))
16182 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16184 (defun org-agenda-file-to-front (&optional to-end)
16185 "Move/add the current file to the top of the agenda file list.
16186 If the file is not present in the list, it is added to the front. If it is
16187 present, it is moved there. With optional argument TO-END, add/move to the
16188 end of the list."
16189 (interactive "P")
16190 (let ((org-agenda-skip-unavailable-files nil)
16191 (file-alist (mapcar (lambda (x)
16192 (cons (file-truename x) x))
16193 (org-agenda-files t)))
16194 (ctf (file-truename buffer-file-name))
16195 x had)
16196 (setq x (assoc ctf file-alist) had x)
16198 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16199 (if to-end
16200 (setq file-alist (append (delq x file-alist) (list x)))
16201 (setq file-alist (cons x (delq x file-alist))))
16202 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16203 (org-install-agenda-files-menu)
16204 (message "File %s to %s of agenda file list"
16205 (if had "moved" "added") (if to-end "end" "front"))))
16207 (defun org-remove-file (&optional file)
16208 "Remove current file from the list of files in variable `org-agenda-files'.
16209 These are the files which are being checked for agenda entries.
16210 Optional argument FILE means use this file instead of the current."
16211 (interactive)
16212 (let* ((org-agenda-skip-unavailable-files nil)
16213 (file (or file buffer-file-name))
16214 (true-file (file-truename file))
16215 (afile (abbreviate-file-name file))
16216 (files (delq nil (mapcar
16217 (lambda (x)
16218 (if (equal true-file
16219 (file-truename x))
16220 nil x))
16221 (org-agenda-files t)))))
16222 (if (not (= (length files) (length (org-agenda-files t))))
16223 (progn
16224 (org-store-new-agenda-file-list files)
16225 (org-install-agenda-files-menu)
16226 (message "Removed file: %s" afile))
16227 (message "File was not in list: %s (not removed)" afile))))
16229 (defun org-file-menu-entry (file)
16230 (vector file (list 'find-file file) t))
16232 (defun org-check-agenda-file (file)
16233 "Make sure FILE exists. If not, ask user what to do."
16234 (when (not (file-exists-p file))
16235 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16236 (abbreviate-file-name file))
16237 (let ((r (downcase (read-char-exclusive))))
16238 (cond
16239 ((equal r ?r)
16240 (org-remove-file file)
16241 (throw 'nextfile t))
16242 (t (error "Abort"))))))
16244 (defun org-get-agenda-file-buffer (file)
16245 "Get a buffer visiting FILE. If the buffer needs to be created, add
16246 it to the list of buffers which might be released later."
16247 (let ((buf (org-find-base-buffer-visiting file)))
16248 (if buf
16249 buf ; just return it
16250 ;; Make a new buffer and remember it
16251 (setq buf (find-file-noselect file))
16252 (if buf (push buf org-agenda-new-buffers))
16253 buf)))
16255 (defun org-release-buffers (blist)
16256 "Release all buffers in list, asking the user for confirmation when needed.
16257 When a buffer is unmodified, it is just killed. When modified, it is saved
16258 \(if the user agrees) and then killed."
16259 (let (buf file)
16260 (while (setq buf (pop blist))
16261 (setq file (buffer-file-name buf))
16262 (when (and (buffer-modified-p buf)
16263 file
16264 (y-or-n-p (format "Save file %s? " file)))
16265 (with-current-buffer buf (save-buffer)))
16266 (kill-buffer buf))))
16268 (defun org-prepare-agenda-buffers (files)
16269 "Create buffers for all agenda files, protect archived trees and comments."
16270 (interactive)
16271 (let ((pa '(:org-archived t))
16272 (pc '(:org-comment t))
16273 (pall '(:org-archived t :org-comment t))
16274 (inhibit-read-only t)
16275 (rea (concat ":" org-archive-tag ":"))
16276 bmp file re)
16277 (save-excursion
16278 (save-restriction
16279 (while (setq file (pop files))
16280 (catch 'nextfile
16281 (if (bufferp file)
16282 (set-buffer file)
16283 (org-check-agenda-file file)
16284 (set-buffer (org-get-agenda-file-buffer file)))
16285 (widen)
16286 (setq bmp (buffer-modified-p))
16287 (org-refresh-category-properties)
16288 (setq org-todo-keywords-for-agenda
16289 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16290 (setq org-done-keywords-for-agenda
16291 (append org-done-keywords-for-agenda org-done-keywords))
16292 (setq org-todo-keyword-alist-for-agenda
16293 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16294 (setq org-drawers-for-agenda
16295 (append org-drawers-for-agenda org-drawers))
16296 (setq org-tag-alist-for-agenda
16297 (append org-tag-alist-for-agenda org-tag-alist))
16299 (save-excursion
16300 (remove-text-properties (point-min) (point-max) pall)
16301 (when org-agenda-skip-archived-trees
16302 (goto-char (point-min))
16303 (while (re-search-forward rea nil t)
16304 (if (org-on-heading-p t)
16305 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16306 (goto-char (point-min))
16307 (setq re (concat org-outline-regexp-bol "+" org-comment-string "\\>"))
16308 (while (re-search-forward re nil t)
16309 (add-text-properties
16310 (match-beginning 0) (org-end-of-subtree t) pc)))
16311 (set-buffer-modified-p bmp)))))
16312 (setq org-todo-keywords-for-agenda
16313 (org-uniquify org-todo-keywords-for-agenda))
16314 (setq org-todo-keyword-alist-for-agenda
16315 (org-uniquify org-todo-keyword-alist-for-agenda)
16316 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16318 ;;;; Embedded LaTeX
16320 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16321 "Keymap for the minor `org-cdlatex-mode'.")
16323 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16324 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16325 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16326 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16327 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16329 (defvar org-cdlatex-texmathp-advice-is-done nil
16330 "Flag remembering if we have applied the advice to texmathp already.")
16332 (define-minor-mode org-cdlatex-mode
16333 "Toggle the minor `org-cdlatex-mode'.
16334 This mode supports entering LaTeX environment and math in LaTeX fragments
16335 in Org-mode.
16336 \\{org-cdlatex-mode-map}"
16337 nil " OCDL" nil
16338 (when org-cdlatex-mode (require 'cdlatex))
16339 (unless org-cdlatex-texmathp-advice-is-done
16340 (setq org-cdlatex-texmathp-advice-is-done t)
16341 (defadvice texmathp (around org-math-always-on activate)
16342 "Always return t in org-mode buffers.
16343 This is because we want to insert math symbols without dollars even outside
16344 the LaTeX math segments. If Orgmode thinks that point is actually inside
16345 an embedded LaTeX fragment, let texmathp do its job.
16346 \\[org-cdlatex-mode-map]"
16347 (interactive)
16348 (let (p)
16349 (cond
16350 ((not (org-mode-p)) ad-do-it)
16351 ((eq this-command 'cdlatex-math-symbol)
16352 (setq ad-return-value t
16353 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16355 (let ((p (org-inside-LaTeX-fragment-p)))
16356 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16357 (setq ad-return-value t
16358 texmathp-why '("Org-mode embedded math" . 0))
16359 (if p ad-do-it)))))))))
16361 (defun turn-on-org-cdlatex ()
16362 "Unconditionally turn on `org-cdlatex-mode'."
16363 (org-cdlatex-mode 1))
16365 (defun org-inside-LaTeX-fragment-p ()
16366 "Test if point is inside a LaTeX fragment.
16367 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16368 sequence appearing also before point.
16369 Even though the matchers for math are configurable, this function assumes
16370 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16371 delimiters are skipped when they have been removed by customization.
16372 The return value is nil, or a cons cell with the delimiter and the
16373 position of this delimiter.
16375 This function does a reasonably good job, but can locally be fooled by
16376 for example currency specifications. For example it will assume being in
16377 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16378 fragments that are properly closed, but during editing, we have to live
16379 with the uncertainty caused by missing closing delimiters. This function
16380 looks only before point, not after."
16381 (catch 'exit
16382 (let ((pos (point))
16383 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16384 (lim (progn
16385 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16386 (point)))
16387 dd-on str (start 0) m re)
16388 (goto-char pos)
16389 (when dodollar
16390 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16391 re (nth 1 (assoc "$" org-latex-regexps)))
16392 (while (string-match re str start)
16393 (cond
16394 ((= (match-end 0) (length str))
16395 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16396 ((= (match-end 0) (- (length str) 5))
16397 (throw 'exit nil))
16398 (t (setq start (match-end 0))))))
16399 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16400 (goto-char pos)
16401 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16402 (and (match-beginning 2) (throw 'exit nil))
16403 ;; count $$
16404 (while (re-search-backward "\\$\\$" lim t)
16405 (setq dd-on (not dd-on)))
16406 (goto-char pos)
16407 (if dd-on (cons "$$" m))))))
16409 (defun org-inside-latex-macro-p ()
16410 "Is point inside a LaTeX macro or its arguments?"
16411 (save-match-data
16412 (org-in-regexp
16413 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16415 (defun org-try-cdlatex-tab ()
16416 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16417 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16418 - inside a LaTeX fragment, or
16419 - after the first word in a line, where an abbreviation expansion could
16420 insert a LaTeX environment."
16421 (when org-cdlatex-mode
16422 (cond
16423 ((save-excursion
16424 (skip-chars-backward "a-zA-Z0-9*")
16425 (skip-chars-backward " \t")
16426 (bolp))
16427 (cdlatex-tab) t)
16428 ((org-inside-LaTeX-fragment-p)
16429 (cdlatex-tab) t)
16430 (t nil))))
16432 (defun org-cdlatex-underscore-caret (&optional arg)
16433 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16434 Revert to the normal definition outside of these fragments."
16435 (interactive "P")
16436 (if (org-inside-LaTeX-fragment-p)
16437 (call-interactively 'cdlatex-sub-superscript)
16438 (let (org-cdlatex-mode)
16439 (call-interactively (key-binding (vector last-input-event))))))
16441 (defun org-cdlatex-math-modify (&optional arg)
16442 "Execute `cdlatex-math-modify' in LaTeX fragments.
16443 Revert to the normal definition outside of these fragments."
16444 (interactive "P")
16445 (if (org-inside-LaTeX-fragment-p)
16446 (call-interactively 'cdlatex-math-modify)
16447 (let (org-cdlatex-mode)
16448 (call-interactively (key-binding (vector last-input-event))))))
16450 (defvar org-latex-fragment-image-overlays nil
16451 "List of overlays carrying the images of latex fragments.")
16452 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16454 (defun org-remove-latex-fragment-image-overlays ()
16455 "Remove all overlays with LaTeX fragment images in current buffer."
16456 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16457 (setq org-latex-fragment-image-overlays nil))
16459 (defun org-preview-latex-fragment (&optional subtree)
16460 "Preview the LaTeX fragment at point, or all locally or globally.
16461 If the cursor is in a LaTeX fragment, create the image and overlay
16462 it over the source code. If there is no fragment at point, display
16463 all fragments in the current text, from one headline to the next. With
16464 prefix SUBTREE, display all fragments in the current subtree. With a
16465 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16466 the cursor is before the first headline,
16467 display all fragments in the buffer.
16468 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16469 (interactive "P")
16470 (org-remove-latex-fragment-image-overlays)
16471 (save-excursion
16472 (save-restriction
16473 (let (beg end at msg)
16474 (cond
16475 ((or (equal subtree '(16))
16476 (not (save-excursion
16477 (re-search-backward org-outline-regexp-bol nil t))))
16478 (setq beg (point-min) end (point-max)
16479 msg "Creating images for buffer...%s"))
16480 ((equal subtree '(4))
16481 (org-back-to-heading)
16482 (setq beg (point) end (org-end-of-subtree t)
16483 msg "Creating images for subtree...%s"))
16485 (if (setq at (org-inside-LaTeX-fragment-p))
16486 (goto-char (max (point-min) (- (cdr at) 2)))
16487 (org-back-to-heading))
16488 (setq beg (point) end (progn (outline-next-heading) (point))
16489 msg (if at "Creating image...%s"
16490 "Creating images for entry...%s"))))
16491 (message msg "")
16492 (narrow-to-region beg end)
16493 (goto-char beg)
16494 (org-format-latex
16495 (concat "ltxpng/" (file-name-sans-extension
16496 (file-name-nondirectory
16497 buffer-file-name)))
16498 default-directory 'overlays msg at 'forbuffer 'dvipng)
16499 (message msg "done. Use `C-c C-c' to remove images.")))))
16501 (defvar org-latex-regexps
16502 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16503 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16504 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16505 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16506 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16507 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16508 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16509 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16510 "Regular expressions for matching embedded LaTeX.")
16512 (defvar org-export-have-math nil) ;; dynamic scoping
16513 (defun org-format-latex (prefix &optional dir overlays msg at
16514 forbuffer processing-type)
16515 "Replace LaTeX fragments with links to an image, and produce images.
16516 Some of the options can be changed using the variable
16517 `org-format-latex-options'."
16518 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16519 (let* ((prefixnodir (file-name-nondirectory prefix))
16520 (absprefix (expand-file-name prefix dir))
16521 (todir (file-name-directory absprefix))
16522 (opt org-format-latex-options)
16523 (matchers (plist-get opt :matchers))
16524 (re-list org-latex-regexps)
16525 (org-format-latex-header-extra
16526 (plist-get (org-infile-export-plist) :latex-header-extra))
16527 (cnt 0) txt hash link beg end re e checkdir
16528 executables-checked string
16529 m n block linkfile movefile ov)
16530 ;; Check the different regular expressions
16531 (while (setq e (pop re-list))
16532 (setq m (car e) re (nth 1 e) n (nth 2 e)
16533 block (if (nth 3 e) "\n\n" ""))
16534 (when (member m matchers)
16535 (goto-char (point-min))
16536 (while (re-search-forward re nil t)
16537 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16538 (not (get-text-property (match-beginning n)
16539 'org-protected))
16540 (or (not overlays)
16541 (not (eq (get-char-property (match-beginning n)
16542 'org-overlay-type)
16543 'org-latex-overlay))))
16544 (setq org-export-have-math t)
16545 (cond
16546 ((eq processing-type 'verbatim)
16547 ;; Leave the text verbatim, just protect it
16548 (add-text-properties (match-beginning n) (match-end n)
16549 '(org-protected t)))
16550 ((eq processing-type 'mathjax)
16551 ;; Prepare for MathJax processing
16552 (setq string (match-string n))
16553 (if (member m '("$" "$1"))
16554 (save-excursion
16555 (delete-region (match-beginning n) (match-end n))
16556 (goto-char (match-beginning n))
16557 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16558 "\\)")
16559 '(org-protected t))))
16560 (add-text-properties (match-beginning n) (match-end n)
16561 '(org-protected t))))
16562 ((or (eq processing-type 'dvipng) t)
16563 ;; Process to an image
16564 (setq txt (match-string n)
16565 beg (match-beginning n) end (match-end n)
16566 cnt (1+ cnt))
16567 (let (print-length print-level) ; make sure full list is printed
16568 (setq hash (sha1 (prin1-to-string
16569 (list org-format-latex-header
16570 org-format-latex-header-extra
16571 org-export-latex-default-packages-alist
16572 org-export-latex-packages-alist
16573 org-format-latex-options
16574 forbuffer txt)))
16575 linkfile (format "%s_%s.png" prefix hash)
16576 movefile (format "%s_%s.png" absprefix hash)))
16577 (setq link (concat block "[[file:" linkfile "]]" block))
16578 (if msg (message msg cnt))
16579 (goto-char beg)
16580 (unless checkdir ; make sure the directory exists
16581 (setq checkdir t)
16582 (or (file-directory-p todir) (make-directory todir t)))
16584 (unless executables-checked
16585 (org-check-external-command
16586 "latex" "needed to convert LaTeX fragments to images")
16587 (org-check-external-command
16588 "dvipng" "needed to convert LaTeX fragments to images")
16589 (setq executables-checked t))
16591 (unless (file-exists-p movefile)
16592 (org-create-formula-image
16593 txt movefile opt forbuffer))
16594 (if overlays
16595 (progn
16596 (mapc (lambda (o)
16597 (if (eq (overlay-get o 'org-overlay-type)
16598 'org-latex-overlay)
16599 (delete-overlay o)))
16600 (overlays-in beg end))
16601 (setq ov (make-overlay beg end))
16602 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16603 (if (featurep 'xemacs)
16604 (progn
16605 (overlay-put ov 'invisible t)
16606 (overlay-put
16607 ov 'end-glyph
16608 (make-glyph (vector 'png :file movefile))))
16609 (overlay-put
16610 ov 'display
16611 (list 'image :type 'png :file movefile :ascent 'center)))
16612 (push ov org-latex-fragment-image-overlays)
16613 (goto-char end))
16614 (delete-region beg end)
16615 (insert (org-add-props link
16616 (list 'org-latex-src
16617 (replace-regexp-in-string
16618 "\"" "" txt)))))))))))))
16620 ;; This function borrows from Ganesh Swami's latex2png.el
16621 (defun org-create-formula-image (string tofile options buffer)
16622 "This calls dvipng."
16623 (require 'org-latex)
16624 (let* ((tmpdir (if (featurep 'xemacs)
16625 (temp-directory)
16626 temporary-file-directory))
16627 (texfilebase (make-temp-name
16628 (expand-file-name "orgtex" tmpdir)))
16629 (texfile (concat texfilebase ".tex"))
16630 (dvifile (concat texfilebase ".dvi"))
16631 (pngfile (concat texfilebase ".png"))
16632 (fnh (if (featurep 'xemacs)
16633 (font-height (get-face-font 'default))
16634 (face-attribute 'default :height nil)))
16635 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
16636 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
16637 (fg (or (plist-get options (if buffer :foreground :html-foreground))
16638 "Black"))
16639 (bg (or (plist-get options (if buffer :background :html-background))
16640 "Transparent")))
16641 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
16642 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
16643 (with-temp-file texfile
16644 (insert (org-splice-latex-header
16645 org-format-latex-header
16646 org-export-latex-default-packages-alist
16647 org-export-latex-packages-alist t
16648 org-format-latex-header-extra))
16649 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
16650 (require 'org-latex)
16651 (org-export-latex-fix-inputenc))
16652 (let ((dir default-directory))
16653 (condition-case nil
16654 (progn
16655 (cd tmpdir)
16656 (call-process "latex" nil nil nil texfile))
16657 (error nil))
16658 (cd dir))
16659 (if (not (file-exists-p dvifile))
16660 (progn (message "Failed to create dvi file from %s" texfile) nil)
16661 (condition-case nil
16662 (call-process "dvipng" nil nil nil
16663 "-fg" fg "-bg" bg
16664 "-D" dpi
16665 ;;"-x" scale "-y" scale
16666 "-T" "tight"
16667 "-o" pngfile
16668 dvifile)
16669 (error nil))
16670 (if (not (file-exists-p pngfile))
16671 (if org-format-latex-signal-error
16672 (error "Failed to create png file from %s" texfile)
16673 (message "Failed to create png file from %s" texfile)
16674 nil)
16675 ;; Use the requested file name and clean up
16676 (copy-file pngfile tofile 'replace)
16677 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16678 (delete-file (concat texfilebase e)))
16679 pngfile))))
16681 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
16682 "Fill a LaTeX header template TPL.
16683 In the template, the following place holders will be recognized:
16685 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
16686 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
16687 [PACKAGES] \\usepackage statements for PKG
16688 [NO-PACKAGES] do not include PKG
16689 [EXTRA] the string EXTRA
16690 [NO-EXTRA] do not include EXTRA
16692 For backward compatibility, if both the positive and the negative place
16693 holder is missing, the positive one (without the \"NO-\") will be
16694 assumed to be present at the end of the template.
16695 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
16696 EXTRA is a string.
16697 SNIPPETS-P indicates if this is run to create snippet images for HTML."
16698 (let (rpl (end ""))
16699 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
16700 (setq rpl (if (or (match-end 1) (not def-pkg))
16701 "" (org-latex-packages-to-string def-pkg snippets-p t))
16702 tpl (replace-match rpl t t tpl))
16703 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
16705 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
16706 (setq rpl (if (or (match-end 1) (not pkg))
16707 "" (org-latex-packages-to-string pkg snippets-p t))
16708 tpl (replace-match rpl t t tpl))
16709 (if pkg (setq end
16710 (concat end "\n"
16711 (org-latex-packages-to-string pkg snippets-p)))))
16713 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
16714 (setq rpl (if (or (match-end 1) (not extra))
16715 "" (concat extra "\n"))
16716 tpl (replace-match rpl t t tpl))
16717 (if (and extra (string-match "\\S-" extra))
16718 (setq end (concat end "\n" extra))))
16720 (if (string-match "\\S-" end)
16721 (concat tpl "\n" end)
16722 tpl)))
16724 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
16725 "Turn an alist of packages into a string with the \\usepackage macros."
16726 (setq pkg (mapconcat (lambda(p)
16727 (cond
16728 ((stringp p) p)
16729 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
16730 (format "%% Package %s omitted" (cadr p)))
16731 ((equal "" (car p))
16732 (format "\\usepackage{%s}" (cadr p)))
16734 (format "\\usepackage[%s]{%s}"
16735 (car p) (cadr p)))))
16737 "\n"))
16738 (if newline (concat pkg "\n") pkg))
16740 (defun org-dvipng-color (attr)
16741 "Return an rgb color specification for dvipng."
16742 (apply 'format "rgb %s %s %s"
16743 (mapcar 'org-normalize-color
16744 (color-values (face-attribute 'default attr nil)))))
16746 (defun org-normalize-color (value)
16747 "Return string to be used as color value for an RGB component."
16748 (format "%g" (/ value 65535.0)))
16750 ;; Image display
16753 (defvar org-inline-image-overlays nil)
16754 (make-variable-buffer-local 'org-inline-image-overlays)
16756 (defun org-toggle-inline-images (&optional include-linked)
16757 "Toggle the display of inline images.
16758 INCLUDE-LINKED is passed to `org-display-inline-images'."
16759 (interactive "P")
16760 (if org-inline-image-overlays
16761 (progn
16762 (org-remove-inline-images)
16763 (message "Inline image display turned off"))
16764 (org-display-inline-images include-linked)
16765 (if org-inline-image-overlays
16766 (message "%d images displayed inline"
16767 (length org-inline-image-overlays))
16768 (message "No images to display inline"))))
16770 (defun org-display-inline-images (&optional include-linked refresh beg end)
16771 "Display inline images.
16772 Normally only links without a description part are inlined, because this
16773 is how it will work for export. When INCLUDE-LINKED is set, also links
16774 with a description part will be inlined. This can be nice for a quick
16775 look at those images, but it does not reflect what exported files will look
16776 like.
16777 When REFRESH is set, refresh existing images between BEG and END.
16778 This will create new image displays only if necessary.
16779 BEG and END default to the buffer boundaries."
16780 (interactive "P")
16781 (unless refresh
16782 (org-remove-inline-images)
16783 (if (fboundp 'clear-image-cache) (clear-image-cache)))
16784 (save-excursion
16785 (save-restriction
16786 (widen)
16787 (setq beg (or beg (point-min)) end (or end (point-max)))
16788 (goto-char (point-min))
16789 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
16790 (substring (org-image-file-name-regexp) 0 -2)
16791 "\\)\\]" (if include-linked "" "\\]")))
16792 old file ov img)
16793 (while (re-search-forward re end t)
16794 (setq old (get-char-property-and-overlay (match-beginning 1)
16795 'org-image-overlay))
16796 (setq file (expand-file-name
16797 (concat (or (match-string 3) "") (match-string 4))))
16798 (when (file-exists-p file)
16799 (if (and (car-safe old) refresh)
16800 (image-refresh (overlay-get (cdr old) 'display))
16801 (setq img (save-match-data (create-image file)))
16802 (when img
16803 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
16804 (overlay-put ov 'display img)
16805 (overlay-put ov 'face 'default)
16806 (overlay-put ov 'org-image-overlay t)
16807 (overlay-put ov 'modification-hooks
16808 (list 'org-display-inline-modification-hook))
16809 (push ov org-inline-image-overlays)))))))))
16811 (defun org-display-inline-modification-hook (ov after beg end &optional len)
16812 "Remove inline-display overlay if a corresponding region is modified."
16813 (let ((inhibit-modification-hooks t))
16814 (when (and ov after)
16815 (delete ov org-inline-image-overlays)
16816 (delete-overlay ov))))
16818 (defun org-remove-inline-images ()
16819 "Remove inline display of images."
16820 (interactive)
16821 (mapc 'delete-overlay org-inline-image-overlays)
16822 (setq org-inline-image-overlays nil))
16824 ;;;; Key bindings
16826 ;; Make `C-c C-x' a prefix key
16827 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
16829 ;; TAB key with modifiers
16830 (org-defkey org-mode-map "\C-i" 'org-cycle)
16831 (org-defkey org-mode-map [(tab)] 'org-cycle)
16832 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
16833 (org-defkey org-mode-map [(meta tab)] 'pcomplete)
16834 (org-defkey org-mode-map "\M-\t" 'pcomplete)
16835 (org-defkey org-mode-map "\M-\C-i" 'pcomplete)
16836 ;; The following line is necessary under Suse GNU/Linux
16837 (unless (featurep 'xemacs)
16838 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
16839 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
16840 (define-key org-mode-map [backtab] 'org-shifttab)
16842 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
16843 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
16844 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
16846 ;; Cursor keys with modifiers
16847 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
16848 (org-defkey org-mode-map [(meta right)] 'org-metaright)
16849 (org-defkey org-mode-map [(meta up)] 'org-metaup)
16850 (org-defkey org-mode-map [(meta down)] 'org-metadown)
16852 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
16853 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
16854 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
16855 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
16857 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
16858 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
16859 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
16860 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
16862 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
16863 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
16864 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
16865 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
16867 ;; Babel keys
16868 (define-key org-mode-map org-babel-key-prefix org-babel-map)
16869 (mapc (lambda (pair)
16870 (define-key org-babel-map (car pair) (cdr pair)))
16871 org-babel-key-bindings)
16873 ;;; Extra keys for tty access.
16874 ;; We only set them when really needed because otherwise the
16875 ;; menus don't show the simple keys
16877 (when (or org-use-extra-keys
16878 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
16879 (not window-system))
16880 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
16881 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
16882 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
16883 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
16884 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
16885 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
16886 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
16887 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
16888 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
16889 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
16890 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
16891 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
16892 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
16893 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
16894 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
16895 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
16896 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
16897 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
16898 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
16899 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
16900 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
16901 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
16902 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
16903 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
16904 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
16905 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
16906 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
16907 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
16909 ;; All the other keys
16911 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
16912 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
16913 (if (boundp 'narrow-map)
16914 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
16915 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
16916 (if (boundp 'narrow-map)
16917 (org-defkey narrow-map "b" 'org-narrow-to-block)
16918 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
16919 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
16920 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
16921 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
16922 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
16923 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
16924 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
16925 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
16926 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
16927 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
16928 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
16929 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
16930 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
16931 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
16932 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
16933 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
16934 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
16935 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
16936 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
16937 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
16938 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
16939 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
16940 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
16941 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
16942 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
16943 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
16944 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
16945 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
16946 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
16947 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
16948 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
16949 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
16950 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
16951 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
16952 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
16953 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
16954 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
16955 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
16956 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
16957 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
16958 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
16959 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
16960 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16961 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
16962 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
16963 (org-defkey org-mode-map "\C-c^" 'org-sort)
16964 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
16965 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
16966 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
16967 (org-defkey org-mode-map "\C-m" 'org-return)
16968 (org-defkey org-mode-map "\C-j" 'org-return-indent)
16969 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
16970 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
16971 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
16972 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
16973 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
16974 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
16975 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
16976 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
16977 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
16978 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
16979 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
16980 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
16981 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
16982 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
16983 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
16984 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
16985 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
16986 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
16987 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
16988 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
16989 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
16991 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
16992 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
16993 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
16994 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
16996 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
16997 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
16998 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
16999 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17000 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17001 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17002 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17003 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17004 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17005 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
17006 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
17007 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17008 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
17009 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
17010 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
17011 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
17012 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
17013 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
17015 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
17016 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
17017 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
17018 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
17019 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
17021 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
17023 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
17025 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
17026 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
17028 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
17031 (when (featurep 'xemacs)
17032 (org-defkey org-mode-map 'button3 'popup-mode-menu))
17035 (defconst org-speed-commands-default
17037 ("Outline Navigation")
17038 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
17039 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
17040 ("f" . (org-speed-move-safe 'org-forward-same-level))
17041 ("b" . (org-speed-move-safe 'org-backward-same-level))
17042 ("u" . (org-speed-move-safe 'outline-up-heading))
17043 ("j" . org-goto)
17044 ("g" . (org-refile t))
17045 ("Outline Visibility")
17046 ("c" . org-cycle)
17047 ("C" . org-shifttab)
17048 (" " . org-display-outline-path)
17049 ("Outline Structure Editing")
17050 ("U" . org-shiftmetaup)
17051 ("D" . org-shiftmetadown)
17052 ("r" . org-metaright)
17053 ("l" . org-metaleft)
17054 ("R" . org-shiftmetaright)
17055 ("L" . org-shiftmetaleft)
17056 ("i" . (progn (forward-char 1) (call-interactively
17057 'org-insert-heading-respect-content)))
17058 ("^" . org-sort)
17059 ("w" . org-refile)
17060 ("a" . org-archive-subtree-default-with-confirmation)
17061 ("." . org-mark-subtree)
17062 ("Clock Commands")
17063 ("I" . org-clock-in)
17064 ("O" . org-clock-out)
17065 ("Meta Data Editing")
17066 ("t" . org-todo)
17067 ("0" . (org-priority ?\ ))
17068 ("1" . (org-priority ?A))
17069 ("2" . (org-priority ?B))
17070 ("3" . (org-priority ?C))
17071 (";" . org-set-tags-command)
17072 ("e" . org-set-effort)
17073 ("Agenda Views etc")
17074 ("v" . org-agenda)
17075 ("/" . org-sparse-tree)
17076 ("Misc")
17077 ("o" . org-open-at-point)
17078 ("?" . org-speed-command-help)
17079 ("<" . (org-agenda-set-restriction-lock 'subtree))
17080 (">" . (org-agenda-remove-restriction-lock))
17082 "The default speed commands.")
17084 (defun org-print-speed-command (e)
17085 (if (> (length (car e)) 1)
17086 (progn
17087 (princ "\n")
17088 (princ (car e))
17089 (princ "\n")
17090 (princ (make-string (length (car e)) ?-))
17091 (princ "\n"))
17092 (princ (car e))
17093 (princ " ")
17094 (if (symbolp (cdr e))
17095 (princ (symbol-name (cdr e)))
17096 (prin1 (cdr e)))
17097 (princ "\n")))
17099 (defun org-speed-command-help ()
17100 "Show the available speed commands."
17101 (interactive)
17102 (if (not org-use-speed-commands)
17103 (error "Speed commands are not activated, customize `org-use-speed-commands'")
17104 (with-output-to-temp-buffer "*Help*"
17105 (princ "User-defined Speed commands\n===========================\n")
17106 (mapc 'org-print-speed-command org-speed-commands-user)
17107 (princ "\n")
17108 (princ "Built-in Speed commands\n=======================\n")
17109 (mapc 'org-print-speed-command org-speed-commands-default))
17110 (with-current-buffer "*Help*"
17111 (setq truncate-lines t))))
17113 (defun org-speed-move-safe (cmd)
17114 "Execute CMD, but make sure that the cursor always ends up in a headline.
17115 If not, return to the original position and throw an error."
17116 (interactive)
17117 (let ((pos (point)))
17118 (call-interactively cmd)
17119 (unless (and (bolp) (org-on-heading-p))
17120 (goto-char pos)
17121 (error "Boundary reached while executing %s" cmd))))
17123 (defvar org-self-insert-command-undo-counter 0)
17125 (defvar org-table-auto-blank-field) ; defined in org-table.el
17126 (defvar org-speed-command nil)
17128 (defun org-speed-command-default-hook (keys)
17129 "Hook for activating single-letter speed commands.
17130 `org-speed-commands-default' specifies a minimal command set.
17131 Use `org-speed-commands-user' for further customization."
17132 (when (or (and (bolp) (looking-at org-outline-regexp))
17133 (and (functionp org-use-speed-commands)
17134 (funcall org-use-speed-commands)))
17135 (cdr (assoc keys (append org-speed-commands-user
17136 org-speed-commands-default)))))
17138 (defun org-babel-speed-command-hook (keys)
17139 "Hook for activating single-letter code block commands."
17140 (when (and (bolp) (looking-at org-babel-src-block-regexp))
17141 (cdr (assoc keys org-babel-key-bindings))))
17143 (defcustom org-speed-command-hook
17144 '(org-speed-command-default-hook org-babel-speed-command-hook)
17145 "Hook for activating speed commands at strategic locations.
17146 Hook functions are called in sequence until a valid handler is
17147 found.
17149 Each hook takes a single argument, a user-pressed command key
17150 which is also a `self-insert-command' from the global map.
17152 Within the hook, examine the cursor position and the command key
17153 and return nil or a valid handler as appropriate. Handler could
17154 be one of an interactive command, a function, or a form.
17156 Set `org-use-speed-commands' to non-nil value to enable this
17157 hook. The default setting is `org-speed-command-default-hook'."
17158 :group 'org-structure
17159 :type 'hook)
17161 (defun org-self-insert-command (N)
17162 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17163 If the cursor is in a table looking at whitespace, the whitespace is
17164 overwritten, and the table is not marked as requiring realignment."
17165 (interactive "p")
17166 (cond
17167 ((and org-use-speed-commands
17168 (setq org-speed-command
17169 (run-hook-with-args-until-success
17170 'org-speed-command-hook (this-command-keys))))
17171 (cond
17172 ((commandp org-speed-command)
17173 (setq this-command org-speed-command)
17174 (call-interactively org-speed-command))
17175 ((functionp org-speed-command)
17176 (funcall org-speed-command))
17177 ((and org-speed-command (listp org-speed-command))
17178 (eval org-speed-command))
17179 (t (let (org-use-speed-commands)
17180 (call-interactively 'org-self-insert-command)))))
17181 ((and
17182 (org-table-p)
17183 (progn
17184 ;; check if we blank the field, and if that triggers align
17185 (and (featurep 'org-table) org-table-auto-blank-field
17186 (member last-command
17187 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
17188 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17189 ;; got extra space, this field does not determine column width
17190 (let (org-table-may-need-update) (org-table-blank-field))
17191 ;; no extra space, this field may determine column width
17192 (org-table-blank-field)))
17194 (eq N 1)
17195 (looking-at "[^|\n]* |"))
17196 (let (org-table-may-need-update)
17197 (goto-char (1- (match-end 0)))
17198 (delete-char -1)
17199 (goto-char (match-beginning 0))
17200 (self-insert-command N)))
17202 (setq org-table-may-need-update t)
17203 (self-insert-command N)
17204 (org-fix-tags-on-the-fly)
17205 (if org-self-insert-cluster-for-undo
17206 (if (not (eq last-command 'org-self-insert-command))
17207 (setq org-self-insert-command-undo-counter 1)
17208 (if (>= org-self-insert-command-undo-counter 20)
17209 (setq org-self-insert-command-undo-counter 1)
17210 (and (> org-self-insert-command-undo-counter 0)
17211 buffer-undo-list (listp buffer-undo-list)
17212 (not (cadr buffer-undo-list)) ; remove nil entry
17213 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17214 (setq org-self-insert-command-undo-counter
17215 (1+ org-self-insert-command-undo-counter))))))))
17217 (defun org-fix-tags-on-the-fly ()
17218 (when (and (equal (char-after (point-at-bol)) ?*)
17219 (org-on-heading-p))
17220 (org-align-tags-here org-tags-column)))
17222 (defun org-delete-backward-char (N)
17223 "Like `delete-backward-char', insert whitespace at field end in tables.
17224 When deleting backwards, in tables this function will insert whitespace in
17225 front of the next \"|\" separator, to keep the table aligned. The table will
17226 still be marked for re-alignment if the field did fill the entire column,
17227 because, in this case the deletion might narrow the column."
17228 (interactive "p")
17229 (if (and (org-table-p)
17230 (eq N 1)
17231 (string-match "|" (buffer-substring (point-at-bol) (point)))
17232 (looking-at ".*?|"))
17233 (let ((pos (point))
17234 (noalign (looking-at "[^|\n\r]* |"))
17235 (c org-table-may-need-update))
17236 (backward-delete-char N)
17237 (if (not overwrite-mode)
17238 (progn
17239 (skip-chars-forward "^|")
17240 (insert " ")
17241 (goto-char (1- pos))))
17242 ;; noalign: if there were two spaces at the end, this field
17243 ;; does not determine the width of the column.
17244 (if noalign (setq org-table-may-need-update c)))
17245 (backward-delete-char N)
17246 (org-fix-tags-on-the-fly)))
17248 (defun org-delete-char (N)
17249 "Like `delete-char', but insert whitespace at field end in tables.
17250 When deleting characters, in tables this function will insert whitespace in
17251 front of the next \"|\" separator, to keep the table aligned. The table will
17252 still be marked for re-alignment if the field did fill the entire column,
17253 because, in this case the deletion might narrow the column."
17254 (interactive "p")
17255 (if (and (org-table-p)
17256 (not (bolp))
17257 (not (= (char-after) ?|))
17258 (eq N 1))
17259 (if (looking-at ".*?|")
17260 (let ((pos (point))
17261 (noalign (looking-at "[^|\n\r]* |"))
17262 (c org-table-may-need-update))
17263 (replace-match (concat
17264 (substring (match-string 0) 1 -1)
17265 " |"))
17266 (goto-char pos)
17267 ;; noalign: if there were two spaces at the end, this field
17268 ;; does not determine the width of the column.
17269 (if noalign (setq org-table-may-need-update c)))
17270 (delete-char N))
17271 (delete-char N)
17272 (org-fix-tags-on-the-fly)))
17274 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17275 (put 'org-self-insert-command 'delete-selection t)
17276 (put 'orgtbl-self-insert-command 'delete-selection t)
17277 (put 'org-delete-char 'delete-selection 'supersede)
17278 (put 'org-delete-backward-char 'delete-selection 'supersede)
17279 (put 'org-yank 'delete-selection 'yank)
17281 ;; Make `flyspell-mode' delay after some commands
17282 (put 'org-self-insert-command 'flyspell-delayed t)
17283 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17284 (put 'org-delete-char 'flyspell-delayed t)
17285 (put 'org-delete-backward-char 'flyspell-delayed t)
17287 ;; Make pabbrev-mode expand after org-mode commands
17288 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17289 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17291 ;; How to do this: Measure non-white length of current string
17292 ;; If equal to column width, we should realign.
17294 (defun org-remap (map &rest commands)
17295 "In MAP, remap the functions given in COMMANDS.
17296 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17297 (let (new old)
17298 (while commands
17299 (setq old (pop commands) new (pop commands))
17300 (if (fboundp 'command-remapping)
17301 (org-defkey map (vector 'remap old) new)
17302 (substitute-key-definition old new map global-map)))))
17304 (when (eq org-enable-table-editor 'optimized)
17305 ;; If the user wants maximum table support, we need to hijack
17306 ;; some standard editing functions
17307 (org-remap org-mode-map
17308 'self-insert-command 'org-self-insert-command
17309 'delete-char 'org-delete-char
17310 'delete-backward-char 'org-delete-backward-char)
17311 (org-defkey org-mode-map "|" 'org-force-self-insert))
17313 (defvar org-ctrl-c-ctrl-c-hook nil
17314 "Hook for functions attaching themselves to `C-c C-c'.
17316 This can be used to add additional functionality to the C-c C-c
17317 key which executes context-dependent commands. This hook is run
17318 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
17319 run after the last test.
17321 Each function will be called with no arguments. The function
17322 must check if the context is appropriate for it to act. If yes,
17323 it should do its thing and then return a non-nil value. If the
17324 context is wrong, just do nothing and return nil.")
17326 (defvar org-ctrl-c-ctrl-c-final-hook nil
17327 "Hook for functions attaching themselves to `C-c C-c'.
17329 This can be used to add additional functionality to the C-c C-c
17330 key which executes context-dependent commands. This hook is run
17331 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
17332 before the first test.
17334 Each function will be called with no arguments. The function
17335 must check if the context is appropriate for it to act. If yes,
17336 it should do its thing and then return a non-nil value. If the
17337 context is wrong, just do nothing and return nil.")
17339 (defvar org-tab-first-hook nil
17340 "Hook for functions to attach themselves to TAB.
17341 See `org-ctrl-c-ctrl-c-hook' for more information.
17342 This hook runs as the first action when TAB is pressed, even before
17343 `org-cycle' messes around with the `outline-regexp' to cater for
17344 inline tasks and plain list item folding.
17345 If any function in this hook returns t, any other actions that
17346 would have been caused by TAB (such as table field motion or visibility
17347 cycling) will not occur.")
17349 (defvar org-tab-after-check-for-table-hook nil
17350 "Hook for functions to attach themselves to TAB.
17351 See `org-ctrl-c-ctrl-c-hook' for more information.
17352 This hook runs after it has been established that the cursor is not in a
17353 table, but before checking if the cursor is in a headline or if global cycling
17354 should be done.
17355 If any function in this hook returns t, not other actions like visibility
17356 cycling will be done.")
17358 (defvar org-tab-after-check-for-cycling-hook nil
17359 "Hook for functions to attach themselves to TAB.
17360 See `org-ctrl-c-ctrl-c-hook' for more information.
17361 This hook runs after it has been established that not table field motion and
17362 not visibility should be done because of current context. This is probably
17363 the place where a package like yasnippets can hook in.")
17365 (defvar org-tab-before-tab-emulation-hook nil
17366 "Hook for functions to attach themselves to TAB.
17367 See `org-ctrl-c-ctrl-c-hook' for more information.
17368 This hook runs after every other options for TAB have been exhausted, but
17369 before indentation and \t insertion takes place.")
17371 (defvar org-metaleft-hook nil
17372 "Hook for functions attaching themselves to `M-left'.
17373 See `org-ctrl-c-ctrl-c-hook' for more information.")
17374 (defvar org-metaright-hook nil
17375 "Hook for functions attaching themselves to `M-right'.
17376 See `org-ctrl-c-ctrl-c-hook' for more information.")
17377 (defvar org-metaup-hook nil
17378 "Hook for functions attaching themselves to `M-up'.
17379 See `org-ctrl-c-ctrl-c-hook' for more information.")
17380 (defvar org-metadown-hook nil
17381 "Hook for functions attaching themselves to `M-down'.
17382 See `org-ctrl-c-ctrl-c-hook' for more information.")
17383 (defvar org-shiftmetaleft-hook nil
17384 "Hook for functions attaching themselves to `M-S-left'.
17385 See `org-ctrl-c-ctrl-c-hook' for more information.")
17386 (defvar org-shiftmetaright-hook nil
17387 "Hook for functions attaching themselves to `M-S-right'.
17388 See `org-ctrl-c-ctrl-c-hook' for more information.")
17389 (defvar org-shiftmetaup-hook nil
17390 "Hook for functions attaching themselves to `M-S-up'.
17391 See `org-ctrl-c-ctrl-c-hook' for more information.")
17392 (defvar org-shiftmetadown-hook nil
17393 "Hook for functions attaching themselves to `M-S-down'.
17394 See `org-ctrl-c-ctrl-c-hook' for more information.")
17395 (defvar org-metareturn-hook nil
17396 "Hook for functions attaching themselves to `M-RET'.
17397 See `org-ctrl-c-ctrl-c-hook' for more information.")
17398 (defvar org-shiftup-hook nil
17399 "Hook for functions attaching themselves to `S-up'.
17400 See `org-ctrl-c-ctrl-c-hook' for more information.")
17401 (defvar org-shiftup-final-hook nil
17402 "Hook for functions attaching themselves to `S-up'.
17403 This one runs after all other options except shift-select have been excluded.
17404 See `org-ctrl-c-ctrl-c-hook' for more information.")
17405 (defvar org-shiftdown-hook nil
17406 "Hook for functions attaching themselves to `S-down'.
17407 See `org-ctrl-c-ctrl-c-hook' for more information.")
17408 (defvar org-shiftdown-final-hook nil
17409 "Hook for functions attaching themselves to `S-down'.
17410 This one runs after all other options except shift-select have been excluded.
17411 See `org-ctrl-c-ctrl-c-hook' for more information.")
17412 (defvar org-shiftleft-hook nil
17413 "Hook for functions attaching themselves to `S-left'.
17414 See `org-ctrl-c-ctrl-c-hook' for more information.")
17415 (defvar org-shiftleft-final-hook nil
17416 "Hook for functions attaching themselves to `S-left'.
17417 This one runs after all other options except shift-select have been excluded.
17418 See `org-ctrl-c-ctrl-c-hook' for more information.")
17419 (defvar org-shiftright-hook nil
17420 "Hook for functions attaching themselves to `S-right'.
17421 See `org-ctrl-c-ctrl-c-hook' for more information.")
17422 (defvar org-shiftright-final-hook nil
17423 "Hook for functions attaching themselves to `S-right'.
17424 This one runs after all other options except shift-select have been excluded.
17425 See `org-ctrl-c-ctrl-c-hook' for more information.")
17427 (defun org-modifier-cursor-error ()
17428 "Throw an error, a modified cursor command was applied in wrong context."
17429 (error "This command is active in special context like tables, headlines or items"))
17431 (defun org-shiftselect-error ()
17432 "Throw an error because Shift-Cursor command was applied in wrong context."
17433 (if (and (boundp 'shift-select-mode) shift-select-mode)
17434 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
17435 (error "This command works only in special context like headlines or timestamps")))
17437 (defun org-call-for-shift-select (cmd)
17438 (let ((this-command-keys-shift-translated t))
17439 (call-interactively cmd)))
17441 (defun org-shifttab (&optional arg)
17442 "Global visibility cycling or move to previous table field.
17443 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17444 on context.
17445 See the individual commands for more information."
17446 (interactive "P")
17447 (cond
17448 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17449 ((integerp arg)
17450 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
17451 (message "Content view to level: %d" arg)
17452 (org-content (prefix-numeric-value arg2))
17453 (setq org-cycle-global-status 'overview)))
17454 (t (call-interactively 'org-global-cycle))))
17456 (defun org-shiftmetaleft ()
17457 "Promote subtree or delete table column.
17458 Calls `org-promote-subtree', `org-outdent-item',
17459 or `org-table-delete-column', depending on context.
17460 See the individual commands for more information."
17461 (interactive)
17462 (cond
17463 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
17464 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17465 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
17466 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
17467 (t (org-modifier-cursor-error))))
17469 (defun org-shiftmetaright ()
17470 "Demote subtree or insert table column.
17471 Calls `org-demote-subtree', `org-indent-item',
17472 or `org-table-insert-column', depending on context.
17473 See the individual commands for more information."
17474 (interactive)
17475 (cond
17476 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
17477 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17478 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
17479 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
17480 (t (org-modifier-cursor-error))))
17482 (defun org-shiftmetaup (&optional arg)
17483 "Move subtree up or kill table row.
17484 Calls `org-move-subtree-up' or `org-table-kill-row' or
17485 `org-move-item-up' depending on context. See the individual commands
17486 for more information."
17487 (interactive "P")
17488 (cond
17489 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
17490 ((org-at-table-p) (call-interactively 'org-table-kill-row))
17491 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17492 ((org-at-item-p) (call-interactively 'org-move-item-up))
17493 (t (org-modifier-cursor-error))))
17495 (defun org-shiftmetadown (&optional arg)
17496 "Move subtree down or insert table row.
17497 Calls `org-move-subtree-down' or `org-table-insert-row' or
17498 `org-move-item-down', depending on context. See the individual
17499 commands for more information."
17500 (interactive "P")
17501 (cond
17502 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
17503 ((org-at-table-p) (call-interactively 'org-table-insert-row))
17504 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17505 ((org-at-item-p) (call-interactively 'org-move-item-down))
17506 (t (org-modifier-cursor-error))))
17508 (defsubst org-hidden-tree-error ()
17509 (error
17510 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
17512 (defun org-metaleft (&optional arg)
17513 "Promote heading or move table column to left.
17514 Calls `org-do-promote' or `org-table-move-column', depending on context.
17515 With no specific context, calls the Emacs default `backward-word'.
17516 See the individual commands for more information."
17517 (interactive "P")
17518 (cond
17519 ((run-hook-with-args-until-success 'org-metaleft-hook))
17520 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
17521 ((org-with-limited-levels
17522 (or (org-on-heading-p)
17523 (and (org-region-active-p)
17524 (save-excursion
17525 (goto-char (region-beginning))
17526 (org-on-heading-p)))))
17527 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17528 (call-interactively 'org-do-promote))
17529 ;; At an inline task.
17530 ((org-on-heading-p)
17531 (call-interactively 'org-inlinetask-promote))
17532 ((or (org-at-item-p)
17533 (and (org-region-active-p)
17534 (save-excursion
17535 (goto-char (region-beginning))
17536 (org-at-item-p))))
17537 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17538 (call-interactively 'org-outdent-item))
17539 (t (call-interactively 'backward-word))))
17541 (defun org-metaright (&optional arg)
17542 "Demote subtree or move table column to right.
17543 Calls `org-do-demote' or `org-table-move-column', depending on context.
17544 With no specific context, calls the Emacs default `forward-word'.
17545 See the individual commands for more information."
17546 (interactive "P")
17547 (cond
17548 ((run-hook-with-args-until-success 'org-metaright-hook))
17549 ((org-at-table-p) (call-interactively 'org-table-move-column))
17550 ((org-with-limited-levels
17551 (or (org-on-heading-p)
17552 (and (org-region-active-p)
17553 (save-excursion
17554 (goto-char (region-beginning))
17555 (org-on-heading-p)))))
17556 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17557 (call-interactively 'org-do-demote))
17558 ;; At an inline task.
17559 ((org-on-heading-p)
17560 (call-interactively 'org-inlinetask-demote))
17561 ((or (org-at-item-p)
17562 (and (org-region-active-p)
17563 (save-excursion
17564 (goto-char (region-beginning))
17565 (org-at-item-p))))
17566 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17567 (call-interactively 'org-indent-item))
17568 (t (call-interactively 'forward-word))))
17570 (defun org-check-for-hidden (what)
17571 "Check if there are hidden headlines/items in the current visual line.
17572 WHAT can be either `headlines' or `items'. If the current line is
17573 an outline or item heading and it has a folded subtree below it,
17574 this function returns t, nil otherwise."
17575 (let ((re (cond
17576 ((eq what 'headlines) org-outline-regexp-bol)
17577 ((eq what 'items) (org-item-beginning-re))
17578 (t (error "This should not happen"))))
17579 beg end)
17580 (save-excursion
17581 (catch 'exit
17582 (unless (org-region-active-p)
17583 (setq beg (point-at-bol))
17584 (beginning-of-line 2)
17585 (while (and (not (eobp)) ;; this is like `next-line'
17586 (get-char-property (1- (point)) 'invisible))
17587 (beginning-of-line 2))
17588 (setq end (point))
17589 (goto-char beg)
17590 (goto-char (point-at-eol))
17591 (setq end (max end (point)))
17592 (while (re-search-forward re end t)
17593 (if (get-char-property (match-beginning 0) 'invisible)
17594 (throw 'exit t))))
17595 nil))))
17597 (defun org-metaup (&optional arg)
17598 "Move subtree up or move table row up.
17599 Calls `org-move-subtree-up' or `org-table-move-row' or
17600 `org-move-item-up', depending on context. See the individual commands
17601 for more information."
17602 (interactive "P")
17603 (cond
17604 ((run-hook-with-args-until-success 'org-metaup-hook))
17605 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
17606 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17607 ((org-at-item-p) (call-interactively 'org-move-item-up))
17608 (t (transpose-lines 1) (beginning-of-line -1))))
17610 (defun org-metadown (&optional arg)
17611 "Move subtree down or move table row down.
17612 Calls `org-move-subtree-down' or `org-table-move-row' or
17613 `org-move-item-down', depending on context. See the individual
17614 commands for more information."
17615 (interactive "P")
17616 (cond
17617 ((run-hook-with-args-until-success 'org-metadown-hook))
17618 ((org-at-table-p) (call-interactively 'org-table-move-row))
17619 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17620 ((org-at-item-p) (call-interactively 'org-move-item-down))
17621 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
17623 (defun org-shiftup (&optional arg)
17624 "Increase item in timestamp or increase priority of current headline.
17625 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
17626 depending on context. See the individual commands for more information."
17627 (interactive "P")
17628 (cond
17629 ((run-hook-with-args-until-success 'org-shiftup-hook))
17630 ((and org-support-shift-select (org-region-active-p))
17631 (org-call-for-shift-select 'previous-line))
17632 ((org-at-timestamp-p t)
17633 (call-interactively (if org-edit-timestamp-down-means-later
17634 'org-timestamp-down 'org-timestamp-up)))
17635 ((and (not (eq org-support-shift-select 'always))
17636 org-enable-priority-commands
17637 (org-on-heading-p))
17638 (call-interactively 'org-priority-up))
17639 ((and (not org-support-shift-select) (org-at-item-p))
17640 (call-interactively 'org-previous-item))
17641 ((org-clocktable-try-shift 'up arg))
17642 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
17643 (org-support-shift-select
17644 (org-call-for-shift-select 'previous-line))
17645 (t (org-shiftselect-error))))
17647 (defun org-shiftdown (&optional arg)
17648 "Decrease item in timestamp or decrease priority of current headline.
17649 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
17650 depending on context. See the individual commands for more information."
17651 (interactive "P")
17652 (cond
17653 ((run-hook-with-args-until-success 'org-shiftdown-hook))
17654 ((and org-support-shift-select (org-region-active-p))
17655 (org-call-for-shift-select 'next-line))
17656 ((org-at-timestamp-p t)
17657 (call-interactively (if org-edit-timestamp-down-means-later
17658 'org-timestamp-up 'org-timestamp-down)))
17659 ((and (not (eq org-support-shift-select 'always))
17660 org-enable-priority-commands
17661 (org-on-heading-p))
17662 (call-interactively 'org-priority-down))
17663 ((and (not org-support-shift-select) (org-at-item-p))
17664 (call-interactively 'org-next-item))
17665 ((org-clocktable-try-shift 'down arg))
17666 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
17667 (org-support-shift-select
17668 (org-call-for-shift-select 'next-line))
17669 (t (org-shiftselect-error))))
17671 (defun org-shiftright (&optional arg)
17672 "Cycle the thing at point or in the current line, depending on context.
17673 Depending on context, this does one of the following:
17675 - switch a timestamp at point one day into the future
17676 - on a headline, switch to the next TODO keyword.
17677 - on an item, switch entire list to the next bullet type
17678 - on a property line, switch to the next allowed value
17679 - on a clocktable definition line, move time block into the future"
17680 (interactive "P")
17681 (cond
17682 ((run-hook-with-args-until-success 'org-shiftright-hook))
17683 ((and org-support-shift-select (org-region-active-p))
17684 (org-call-for-shift-select 'forward-char))
17685 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
17686 ((and (not (eq org-support-shift-select 'always))
17687 (org-on-heading-p))
17688 (let ((org-inhibit-logging
17689 (not org-treat-S-cursor-todo-selection-as-state-change))
17690 (org-inhibit-blocking
17691 (not org-treat-S-cursor-todo-selection-as-state-change)))
17692 (org-call-with-arg 'org-todo 'right)))
17693 ((or (and org-support-shift-select
17694 (not (eq org-support-shift-select 'always))
17695 (org-at-item-bullet-p))
17696 (and (not org-support-shift-select) (org-at-item-p)))
17697 (org-call-with-arg 'org-cycle-list-bullet nil))
17698 ((and (not (eq org-support-shift-select 'always))
17699 (org-at-property-p))
17700 (call-interactively 'org-property-next-allowed-value))
17701 ((org-clocktable-try-shift 'right arg))
17702 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
17703 (org-support-shift-select
17704 (org-call-for-shift-select 'forward-char))
17705 (t (org-shiftselect-error))))
17707 (defun org-shiftleft (&optional arg)
17708 "Cycle the thing at point or in the current line, depending on context.
17709 Depending on context, this does one of the following:
17711 - switch a timestamp at point one day into the past
17712 - on a headline, switch to the previous TODO keyword.
17713 - on an item, switch entire list to the previous bullet type
17714 - on a property line, switch to the previous allowed value
17715 - on a clocktable definition line, move time block into the past"
17716 (interactive "P")
17717 (cond
17718 ((run-hook-with-args-until-success 'org-shiftleft-hook))
17719 ((and org-support-shift-select (org-region-active-p))
17720 (org-call-for-shift-select 'backward-char))
17721 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
17722 ((and (not (eq org-support-shift-select 'always))
17723 (org-on-heading-p))
17724 (let ((org-inhibit-logging
17725 (not org-treat-S-cursor-todo-selection-as-state-change))
17726 (org-inhibit-blocking
17727 (not org-treat-S-cursor-todo-selection-as-state-change)))
17728 (org-call-with-arg 'org-todo 'left)))
17729 ((or (and org-support-shift-select
17730 (not (eq org-support-shift-select 'always))
17731 (org-at-item-bullet-p))
17732 (and (not org-support-shift-select) (org-at-item-p)))
17733 (org-call-with-arg 'org-cycle-list-bullet 'previous))
17734 ((and (not (eq org-support-shift-select 'always))
17735 (org-at-property-p))
17736 (call-interactively 'org-property-previous-allowed-value))
17737 ((org-clocktable-try-shift 'left arg))
17738 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
17739 (org-support-shift-select
17740 (org-call-for-shift-select 'backward-char))
17741 (t (org-shiftselect-error))))
17743 (defun org-shiftcontrolright ()
17744 "Switch to next TODO set."
17745 (interactive)
17746 (cond
17747 ((and org-support-shift-select (org-region-active-p))
17748 (org-call-for-shift-select 'forward-word))
17749 ((and (not (eq org-support-shift-select 'always))
17750 (org-on-heading-p))
17751 (org-call-with-arg 'org-todo 'nextset))
17752 (org-support-shift-select
17753 (org-call-for-shift-select 'forward-word))
17754 (t (org-shiftselect-error))))
17756 (defun org-shiftcontrolleft ()
17757 "Switch to previous TODO set."
17758 (interactive)
17759 (cond
17760 ((and org-support-shift-select (org-region-active-p))
17761 (org-call-for-shift-select 'backward-word))
17762 ((and (not (eq org-support-shift-select 'always))
17763 (org-on-heading-p))
17764 (org-call-with-arg 'org-todo 'previousset))
17765 (org-support-shift-select
17766 (org-call-for-shift-select 'backward-word))
17767 (t (org-shiftselect-error))))
17769 (defun org-shiftcontrolup ()
17770 "Change timestamps synchronously up in CLOCK log lines."
17771 (interactive)
17772 (cond ((and (not org-support-shift-select)
17773 (org-at-clock-log-p)
17774 (org-at-timestamp-p t))
17775 (org-clock-timestamps-up))
17776 (t (org-shiftselect-error))))
17778 (defun org-shiftcontroldown ()
17779 "Change timestamps synchronously down in CLOCK log lines."
17780 (interactive)
17781 (cond ((and (not org-support-shift-select)
17782 (org-at-clock-log-p)
17783 (org-at-timestamp-p t))
17784 (org-clock-timestamps-down))
17785 (t (org-shiftselect-error))))
17787 (defun org-ctrl-c-ret ()
17788 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
17789 (interactive)
17790 (cond
17791 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
17792 (t (call-interactively 'org-insert-heading))))
17794 (defun org-find-visible ()
17795 (let ((s (point)))
17796 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
17797 (get-char-property s 'invisible)))
17799 (defun org-find-invisible ()
17800 (let ((s (point)))
17801 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
17802 (not (get-char-property s 'invisible))))
17805 (defun org-copy-visible (beg end)
17806 "Copy the visible parts of the region."
17807 (interactive "r")
17808 (let (snippets s)
17809 (save-excursion
17810 (save-restriction
17811 (narrow-to-region beg end)
17812 (setq s (goto-char (point-min)))
17813 (while (not (= (point) (point-max)))
17814 (goto-char (org-find-invisible))
17815 (push (buffer-substring s (point)) snippets)
17816 (setq s (goto-char (org-find-visible))))))
17817 (kill-new (apply 'concat (nreverse snippets)))))
17819 (defun org-copy-special ()
17820 "Copy region in table or copy current subtree.
17821 Calls `org-table-copy' or `org-copy-subtree', depending on context.
17822 See the individual commands for more information."
17823 (interactive)
17824 (call-interactively
17825 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
17827 (defun org-cut-special ()
17828 "Cut region in table or cut current subtree.
17829 Calls `org-table-copy' or `org-cut-subtree', depending on context.
17830 See the individual commands for more information."
17831 (interactive)
17832 (call-interactively
17833 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
17835 (defun org-paste-special (arg)
17836 "Paste rectangular region into table, or past subtree relative to level.
17837 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
17838 See the individual commands for more information."
17839 (interactive "P")
17840 (if (org-at-table-p)
17841 (org-table-paste-rectangle)
17842 (org-paste-subtree arg)))
17844 (defun org-edit-special (&optional arg)
17845 "Call a special editor for the stuff at point.
17846 When at a table, call the formula editor with `org-table-edit-formulas'.
17847 When at the first line of an src example, call `org-edit-src-code'.
17848 When in an #+include line, visit the include file. Otherwise call
17849 `ffap' to visit the file at point."
17850 (interactive)
17851 ;; possibly prep session before editing source
17852 (when arg
17853 (let* ((info (org-babel-get-src-block-info))
17854 (lang (nth 0 info))
17855 (params (nth 2 info))
17856 (session (cdr (assoc :session params))))
17857 (when (and info session) ;; we are in a source-code block with a session
17858 (funcall
17859 (intern (concat "org-babel-prep-session:" lang)) session params))))
17860 (cond ;; proceed with `org-edit-special'
17861 ((save-excursion
17862 (beginning-of-line 1)
17863 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
17864 (find-file (org-trim (match-string 1))))
17865 ((org-edit-src-code))
17866 ((org-edit-fixed-width-region))
17867 ((org-at-table.el-p)
17868 (org-edit-src-code))
17869 ((or (org-at-table-p)
17870 (save-excursion
17871 (beginning-of-line 1)
17872 (looking-at "[ \t]*#\\+TBLFM:")))
17873 (call-interactively 'org-table-edit-formulas))
17874 (t (call-interactively 'ffap))))
17876 (defun org-ctrl-c-ctrl-c (&optional arg)
17877 "Set tags in headline, or update according to changed information at point.
17879 This command does many different things, depending on context:
17881 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
17882 this is what we do.
17884 - If the cursor is on a statistics cookie, update it.
17886 - If the cursor is in a headline, prompt for tags and insert them
17887 into the current line, aligned to `org-tags-column'. When called
17888 with prefix arg, realign all tags in the current buffer.
17890 - If the cursor is in one of the special #+KEYWORD lines, this
17891 triggers scanning the buffer for these lines and updating the
17892 information.
17894 - If the cursor is inside a table, realign the table. This command
17895 works even if the automatic table editor has been turned off.
17897 - If the cursor is on a #+TBLFM line, re-apply the formulas to
17898 the entire table.
17900 - If the cursor is at a footnote reference or definition, jump to
17901 the corresponding definition or references, respectively.
17903 - If the cursor is a the beginning of a dynamic block, update it.
17905 - If the current buffer is a capture buffer, close note and file it.
17907 - If the cursor is on a <<<target>>>, update radio targets and
17908 corresponding links in this buffer.
17910 - If the cursor is on a numbered item in a plain list, renumber the
17911 ordered list.
17913 - If the cursor is on a checkbox, toggle it.
17915 - If the cursor is on a code block, evaluate it. The variable
17916 `org-confirm-babel-evaluate' can be used to control prompting
17917 before code block evaluation, by default every code block
17918 evaluation requires confirmation. Code block evaluation can be
17919 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
17920 (interactive "P")
17921 (let ((org-enable-table-editor t))
17922 (cond
17923 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
17924 org-occur-highlights
17925 org-latex-fragment-image-overlays)
17926 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
17927 (org-remove-occur-highlights)
17928 (org-remove-latex-fragment-image-overlays)
17929 (message "Temporary highlights/overlays removed from current buffer"))
17930 ((and (local-variable-p 'org-finish-function (current-buffer))
17931 (fboundp org-finish-function))
17932 (funcall org-finish-function))
17933 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
17934 ((or (looking-at org-property-start-re)
17935 (org-at-property-p))
17936 (call-interactively 'org-property-action))
17937 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
17938 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
17939 (or (org-on-heading-p) (org-at-item-p)))
17940 (call-interactively 'org-update-statistics-cookies))
17941 ((org-on-heading-p) (call-interactively 'org-set-tags))
17942 ((org-at-table.el-p)
17943 (message "Use C-c ' to edit table.el tables"))
17944 ((org-at-table-p)
17945 (org-table-maybe-eval-formula)
17946 (if arg
17947 (call-interactively 'org-table-recalculate)
17948 (org-table-maybe-recalculate-line))
17949 (call-interactively 'org-table-align)
17950 (orgtbl-send-table 'maybe))
17951 ((or (org-footnote-at-reference-p)
17952 (org-footnote-at-definition-p))
17953 (call-interactively 'org-footnote-action))
17954 ((org-at-item-checkbox-p)
17955 ;; Cursor at a checkbox: repair list and update checkboxes. Send
17956 ;; list only if at top item.
17957 (let* ((cbox (match-string 1))
17958 (struct (org-list-struct))
17959 (old-struct (copy-tree struct))
17960 (parents (org-list-parents-alist struct))
17961 (orderedp (org-entry-get nil "ORDERED"))
17962 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
17963 block-item)
17964 ;; Use a light version of `org-toggle-checkbox' to avoid
17965 ;; computing list structure twice.
17966 (org-list-set-checkbox (point-at-bol) struct
17967 (cond
17968 ((equal arg '(16)) "[-]")
17969 ((equal arg '(4)) nil)
17970 ((equal "[X]" cbox) "[ ]")
17971 (t "[X]")))
17972 ;; Replicate `org-list-write-struct', while grabbing a return
17973 ;; value from `org-list-struct-fix-box'.
17974 (org-list-struct-fix-ind struct parents 2)
17975 (org-list-struct-fix-item-end struct)
17976 (let ((prevs (org-list-prevs-alist struct)))
17977 (org-list-struct-fix-bul struct prevs)
17978 (org-list-struct-fix-ind struct parents)
17979 (setq block-item
17980 (org-list-struct-fix-box struct parents prevs orderedp)))
17981 (org-list-struct-apply-struct struct old-struct)
17982 (org-update-checkbox-count-maybe)
17983 (when block-item
17984 (message
17985 "Checkboxes were removed due to unchecked box at line %d"
17986 (org-current-line block-item)))
17987 (when firstp (org-list-send-list 'maybe))))
17988 ((org-at-item-p)
17989 ;; Cursor at an item: repair list. Do checkbox related actions
17990 ;; only if function was called with an argument. Send list only
17991 ;; if at top item.
17992 (let* ((struct (org-list-struct))
17993 (firstp (= (org-list-get-top-point struct) (point-at-bol))))
17994 (when arg (org-list-set-checkbox (point-at-bol) struct "[ ]"))
17995 (org-list-write-struct struct (org-list-parents-alist struct))
17996 (when arg (org-update-checkbox-count-maybe))
17997 (when firstp (org-list-send-list 'maybe))))
17998 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
17999 ;; Dynamic block
18000 (beginning-of-line 1)
18001 (save-excursion (org-update-dblock)))
18002 ((save-excursion
18003 (beginning-of-line 1)
18004 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
18005 (cond
18006 ((equal (match-string 1) "TBLFM")
18007 ;; Recalculate the table before this line
18008 (save-excursion
18009 (beginning-of-line 1)
18010 (skip-chars-backward " \r\n\t")
18011 (if (org-at-table-p)
18012 (org-call-with-arg 'org-table-recalculate (or arg t)))))
18014 (let ((org-inhibit-startup-visibility-stuff t)
18015 (org-startup-align-all-tables nil))
18016 (org-save-outline-visibility 'use-markers (org-mode-restart)))
18017 (message "Local setup has been refreshed"))))
18018 ((org-clock-update-time-maybe))
18020 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
18021 (error "C-c C-c can do nothing useful at this location"))))))
18023 (defun org-mode-restart ()
18024 "Restart Org-mode, to scan again for special lines.
18025 Also updates the keyword regular expressions."
18026 (interactive)
18027 (org-mode)
18028 (message "Org-mode restarted"))
18030 (defun org-kill-note-or-show-branches ()
18031 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
18032 (interactive)
18033 (if (not org-finish-function)
18034 (progn
18035 (hide-subtree)
18036 (call-interactively 'show-branches))
18037 (let ((org-note-abort t))
18038 (funcall org-finish-function))))
18040 (defun org-return (&optional indent)
18041 "Goto next table row or insert a newline.
18042 Calls `org-table-next-row' or `newline', depending on context.
18043 See the individual commands for more information."
18044 (interactive)
18045 (cond
18046 ((bobp) (if indent (newline-and-indent) (newline)))
18047 ((org-at-table-p)
18048 (org-table-justify-field-maybe)
18049 (call-interactively 'org-table-next-row))
18050 ;; when `newline-and-indent' is called within a list, make sure
18051 ;; text moved stays inside the item.
18052 ((and (org-in-item-p) indent)
18053 (if (and (org-at-item-p) (>= (point) (match-end 0)))
18054 (progn
18055 (save-match-data (newline))
18056 (org-indent-line-to (length (match-string 0))))
18057 (let ((ind (org-get-indentation)))
18058 (newline)
18059 (if (org-looking-back org-list-end-re)
18060 (org-indent-line-function)
18061 (org-indent-line-to ind)))))
18062 ((and org-return-follows-link
18063 (eq (get-text-property (point) 'face) 'org-link))
18064 (call-interactively 'org-open-at-point))
18065 ((and (org-at-heading-p)
18066 (looking-at
18067 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
18068 (org-show-entry)
18069 (end-of-line 1)
18070 (newline))
18071 (t (if indent (newline-and-indent) (newline)))))
18073 (defun org-return-indent ()
18074 "Goto next table row or insert a newline and indent.
18075 Calls `org-table-next-row' or `newline-and-indent', depending on
18076 context. See the individual commands for more information."
18077 (interactive)
18078 (org-return t))
18080 (defun org-ctrl-c-star ()
18081 "Compute table, or change heading status of lines.
18082 Calls `org-table-recalculate' or `org-toggle-heading',
18083 depending on context."
18084 (interactive)
18085 (cond
18086 ((org-at-table-p)
18087 (call-interactively 'org-table-recalculate))
18089 ;; Convert all lines in region to list items
18090 (call-interactively 'org-toggle-heading))))
18092 (defun org-ctrl-c-minus ()
18093 "Insert separator line in table or modify bullet status of line.
18094 Also turns a plain line or a region of lines into list items.
18095 Calls `org-table-insert-hline', `org-toggle-item', or
18096 `org-cycle-list-bullet', depending on context."
18097 (interactive)
18098 (cond
18099 ((org-at-table-p)
18100 (call-interactively 'org-table-insert-hline))
18101 ((org-region-active-p)
18102 (call-interactively 'org-toggle-item))
18103 ((org-in-item-p)
18104 (call-interactively 'org-cycle-list-bullet))
18106 (call-interactively 'org-toggle-item))))
18108 (defun org-toggle-item (arg)
18109 "Convert headings or normal lines to items, items to normal lines.
18110 If there is no active region, only the current line is considered.
18112 If the first non blank line in the region is an headline, convert
18113 all headlines to items, shifting text accordingly.
18115 If it is an item, convert all items to normal lines.
18117 If it is normal text, change region into an item. With a prefix
18118 argument ARG, change each line in region into an item."
18119 (interactive "P")
18120 (let ((shift-text
18121 (function
18122 ;; Shift text in current section to IND, from point to END.
18123 ;; The function leaves point to END line.
18124 (lambda (ind end)
18125 (let ((min-i 1000) (end (copy-marker end)))
18126 ;; First determine the minimum indentation (MIN-I) of
18127 ;; the text.
18128 (save-excursion
18129 (catch 'exit
18130 (while (< (point) end)
18131 (let ((i (org-get-indentation)))
18132 (cond
18133 ;; Skip blank lines and inline tasks.
18134 ((looking-at "^[ \t]*$"))
18135 ((looking-at org-outline-regexp-bol))
18136 ;; We can't find less than 0 indentation.
18137 ((zerop i) (throw 'exit (setq min-i 0)))
18138 ((< i min-i) (setq min-i i))))
18139 (forward-line))))
18140 ;; Then indent each line so that a line indented to
18141 ;; MIN-I becomes indented to IND. Ignore blank lines
18142 ;; and inline tasks in the process.
18143 (let ((delta (- ind min-i)))
18144 (while (< (point) end)
18145 (unless (or (looking-at "^[ \t]*$")
18146 (looking-at org-outline-regexp-bol))
18147 (org-indent-line-to (+ (org-get-indentation) delta)))
18148 (forward-line)))))))
18149 (skip-blanks
18150 (function
18151 ;; Return beginning of first non-blank line, starting from
18152 ;; line at POS.
18153 (lambda (pos)
18154 (save-excursion
18155 (goto-char pos)
18156 (skip-chars-forward " \r\t\n")
18157 (point-at-bol)))))
18158 beg end)
18159 ;; Determine boundaries of changes.
18160 (if (org-region-active-p)
18161 (setq beg (funcall skip-blanks (region-beginning))
18162 end (copy-marker (region-end)))
18163 (setq beg (funcall skip-blanks (point-at-bol))
18164 end (copy-marker (point-at-eol))))
18165 ;; Depending on the starting line, choose an action on the text
18166 ;; between BEG and END.
18167 (org-with-limited-levels
18168 (save-excursion
18169 (goto-char beg)
18170 (cond
18171 ;; Case 1. Start at an item: de-itemize. Note that it only
18172 ;; happens when a region is active: `org-ctrl-c-minus'
18173 ;; would call `org-cycle-list-bullet' otherwise.
18174 ((org-at-item-p)
18175 (while (< (point) end)
18176 (when (org-at-item-p)
18177 (skip-chars-forward " \t")
18178 (delete-region (point) (match-end 0)))
18179 (forward-line)))
18180 ;; Case 2. Start at an heading: convert to items.
18181 ((org-on-heading-p)
18182 (let* ((bul (org-list-bullet-string "-"))
18183 (bul-len (length bul))
18184 ;; Indentation of the first heading. It should be
18185 ;; relative to the indentation of its parent, if any.
18186 (start-ind (save-excursion
18187 (cond
18188 ((not org-adapt-indentation) 0)
18189 ((not (outline-previous-heading)) 0)
18190 (t (length (match-string 0))))))
18191 ;; Level of first heading. Further headings will be
18192 ;; compared to it to determine hierarchy in the list.
18193 (ref-level (org-reduced-level (org-outline-level))))
18194 (while (< (point) end)
18195 (let* ((level (org-reduced-level (org-outline-level)))
18196 (delta (max 0 (- level ref-level))))
18197 ;; If current headline is less indented than the first
18198 ;; one, set it as reference, in order to preserve
18199 ;; subtrees.
18200 (when (< level ref-level) (setq ref-level level))
18201 (replace-match bul t t)
18202 (org-indent-line-to (+ start-ind (* delta bul-len)))
18203 ;; Ensure all text down to END (or SECTION-END) belongs
18204 ;; to the newly created item.
18205 (let ((section-end (save-excursion
18206 (or (outline-next-heading) (point)))))
18207 (forward-line)
18208 (funcall shift-text
18209 (+ start-ind (* (1+ delta) bul-len))
18210 (min end section-end)))))))
18211 ;; Case 3. Normal line with ARG: turn each non-item line into
18212 ;; an item.
18213 (arg
18214 (while (< (point) end)
18215 (unless (or (org-on-heading-p) (org-at-item-p))
18216 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
18217 (replace-match
18218 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
18219 (forward-line)))
18220 ;; Case 4. Normal line without ARG: make the first line of
18221 ;; region an item, and shift indentation of others
18222 ;; lines to set them as item's body.
18223 (t (let* ((bul (org-list-bullet-string "-"))
18224 (bul-len (length bul))
18225 (ref-ind (org-get-indentation)))
18226 (skip-chars-forward " \t")
18227 (insert bul)
18228 (forward-line)
18229 (while (< (point) end)
18230 ;; Ensure that lines less indented than first one
18231 ;; still get included in item body.
18232 (funcall shift-text
18233 (+ ref-ind bul-len)
18234 (min end (save-excursion (or (outline-next-heading)
18235 (point)))))
18236 (forward-line)))))))))
18238 (defun org-toggle-heading (&optional nstars)
18239 "Convert headings to normal text, or items or text to headings.
18240 If there is no active region, only the current line is considered.
18242 If the first non blank line is an headline, remove the stars from
18243 all headlines in the region.
18245 If it is a plain list item, turn all plain list items into headings.
18247 If it is a normal line, turn each and every normal line (i.e. not
18248 an heading or an item) in the region into a heading.
18250 When converting a line into a heading, the number of stars is chosen
18251 such that the lines become children of the current entry. However,
18252 when a prefix argument is given, its value determines the number of
18253 stars to add."
18254 (interactive "P")
18255 (let ((skip-blanks
18256 (function
18257 ;; Return beginning of first non-blank line, starting from
18258 ;; line at POS.
18259 (lambda (pos)
18260 (save-excursion
18261 (goto-char pos)
18262 (skip-chars-forward " \r\t\n")
18263 (point-at-bol)))))
18264 beg end)
18265 ;; Determine boundaries of changes. If region ends at a bol, do
18266 ;; not consider the last line to be in the region.
18267 (if (org-region-active-p)
18268 (setq beg (funcall skip-blanks (region-beginning))
18269 end (copy-marker (save-excursion
18270 (goto-char (region-end))
18271 (if (bolp) (point) (point-at-eol)))))
18272 (setq beg (funcall skip-blanks (point-at-bol))
18273 end (copy-marker (point-at-eol))))
18274 ;; Ensure inline tasks don't count as headings.
18275 (org-with-limited-levels
18276 (save-excursion
18277 (goto-char beg)
18278 (cond
18279 ;; Case 1. Started at an heading: de-star headings.
18280 ((org-on-heading-p)
18281 (while (< (point) end)
18282 (when (org-on-heading-p t)
18283 (looking-at org-outline-regexp) (replace-match ""))
18284 (forward-line)))
18285 ;; Case 2. Started at an item: change items into headlines.
18286 ;; One star will be added by `org-list-to-subtree'.
18287 ((org-at-item-p)
18288 (let* ((stars (make-string
18289 (if nstars
18290 ;; subtract the star that will be added again by
18291 ;; `org-list-to-subtree'
18292 (1- (prefix-numeric-value current-prefix-arg))
18293 (or (org-current-level) 0))
18294 ?*))
18295 (add-stars
18296 (cond (nstars "") ; stars from prefix only
18297 ((equal stars "") "") ; before first heading
18298 (org-odd-levels-only "*") ; inside heading, odd
18299 (t "")))) ; inside heading, oddeven
18300 (while (< (point) end)
18301 (when (org-at-item-p)
18302 ;; Pay attention to cases when region ends before list.
18303 (let* ((struct (org-list-struct))
18304 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18305 (save-restriction
18306 (narrow-to-region (point) list-end)
18307 (insert
18308 (org-list-to-subtree
18309 (org-list-parse-list t)
18310 '(:istart (concat stars add-stars (funcall get-stars depth))
18311 :icount (concat stars add-stars (funcall get-stars depth))))))))
18312 (forward-line))))
18313 ;; Case 3. Started at normal text: make every line an heading,
18314 ;; skipping headlines and items.
18315 (t (let* ((stars (make-string
18316 (if nstars
18317 (prefix-numeric-value current-prefix-arg)
18318 (or (org-current-level) 0))
18319 ?*))
18320 (add-stars
18321 (cond (nstars "") ; stars from prefix only
18322 ((equal stars "") "*") ; before first heading
18323 (org-odd-levels-only "**") ; inside heading, odd
18324 (t "*"))) ; inside heading, oddeven
18325 (rpl (concat stars add-stars " ")))
18326 (while (< (point) end)
18327 (when (and (not (org-on-heading-p)) (not (org-at-item-p))
18328 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18329 (replace-match (concat rpl (match-string 2))))
18330 (forward-line)))))))))
18332 (defun org-meta-return (&optional arg)
18333 "Insert a new heading or wrap a region in a table.
18334 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18335 See the individual commands for more information."
18336 (interactive "P")
18337 (cond
18338 ((run-hook-with-args-until-success 'org-metareturn-hook))
18339 ((org-at-table-p)
18340 (call-interactively 'org-table-wrap-region))
18341 (t (call-interactively 'org-insert-heading))))
18343 ;;; Menu entries
18345 ;; Define the Org-mode menus
18346 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18347 '("Tbl"
18348 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18349 ["Next Field" org-cycle (org-at-table-p)]
18350 ["Previous Field" org-shifttab (org-at-table-p)]
18351 ["Next Row" org-return (org-at-table-p)]
18352 "--"
18353 ["Blank Field" org-table-blank-field (org-at-table-p)]
18354 ["Edit Field" org-table-edit-field (org-at-table-p)]
18355 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18356 "--"
18357 ("Column"
18358 ["Move Column Left" org-metaleft (org-at-table-p)]
18359 ["Move Column Right" org-metaright (org-at-table-p)]
18360 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18361 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18362 ("Row"
18363 ["Move Row Up" org-metaup (org-at-table-p)]
18364 ["Move Row Down" org-metadown (org-at-table-p)]
18365 ["Delete Row" org-shiftmetaup (org-at-table-p)]
18366 ["Insert Row" org-shiftmetadown (org-at-table-p)]
18367 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
18368 "--"
18369 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
18370 ("Rectangle"
18371 ["Copy Rectangle" org-copy-special (org-at-table-p)]
18372 ["Cut Rectangle" org-cut-special (org-at-table-p)]
18373 ["Paste Rectangle" org-paste-special (org-at-table-p)]
18374 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
18375 "--"
18376 ("Calculate"
18377 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
18378 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
18379 ["Edit Formulas" org-edit-special (org-at-table-p)]
18380 "--"
18381 ["Recalculate line" org-table-recalculate (org-at-table-p)]
18382 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
18383 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
18384 "--"
18385 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
18386 "--"
18387 ["Sum Column/Rectangle" org-table-sum
18388 (or (org-at-table-p) (org-region-active-p))]
18389 ["Which Column?" org-table-current-column (org-at-table-p)])
18390 ["Debug Formulas"
18391 org-table-toggle-formula-debugger
18392 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
18393 ["Show Col/Row Numbers"
18394 org-table-toggle-coordinate-overlays
18395 :style toggle
18396 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
18397 "--"
18398 ["Create" org-table-create (and (not (org-at-table-p))
18399 org-enable-table-editor)]
18400 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
18401 ["Import from File" org-table-import (not (org-at-table-p))]
18402 ["Export to File" org-table-export (org-at-table-p)]
18403 "--"
18404 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
18406 (easy-menu-define org-org-menu org-mode-map "Org menu"
18407 '("Org"
18408 ("Show/Hide"
18409 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
18410 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
18411 ["Sparse Tree..." org-sparse-tree t]
18412 ["Reveal Context" org-reveal t]
18413 ["Show All" show-all t]
18414 "--"
18415 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
18416 "--"
18417 ["New Heading" org-insert-heading t]
18418 ("Navigate Headings"
18419 ["Up" outline-up-heading t]
18420 ["Next" outline-next-visible-heading t]
18421 ["Previous" outline-previous-visible-heading t]
18422 ["Next Same Level" outline-forward-same-level t]
18423 ["Previous Same Level" outline-backward-same-level t]
18424 "--"
18425 ["Jump" org-goto t])
18426 ("Edit Structure"
18427 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
18428 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
18429 "--"
18430 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
18431 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
18432 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
18433 "--"
18434 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
18435 "--"
18436 ["Copy visible text" org-copy-visible t]
18437 "--"
18438 ["Promote Heading" org-metaleft (not (org-at-table-p))]
18439 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
18440 ["Demote Heading" org-metaright (not (org-at-table-p))]
18441 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
18442 "--"
18443 ["Sort Region/Children" org-sort (not (org-at-table-p))]
18444 "--"
18445 ["Convert to odd levels" org-convert-to-odd-levels t]
18446 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
18447 ("Editing"
18448 ["Emphasis..." org-emphasize t]
18449 ["Edit Source Example" org-edit-special t]
18450 "--"
18451 ["Footnote new/jump" org-footnote-action t]
18452 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
18453 ("Archive"
18454 ["Archive (default method)" org-archive-subtree-default t]
18455 "--"
18456 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
18457 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
18458 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
18460 "--"
18461 ("Hyperlinks"
18462 ["Store Link (Global)" org-store-link t]
18463 ["Find existing link to here" org-occur-link-in-agenda-files t]
18464 ["Insert Link" org-insert-link t]
18465 ["Follow Link" org-open-at-point t]
18466 "--"
18467 ["Next link" org-next-link t]
18468 ["Previous link" org-previous-link t]
18469 "--"
18470 ["Descriptive Links"
18471 org-toggle-link-display
18472 :style radio
18473 :selected org-descriptive-links
18475 ["Literal Links"
18476 org-toggle-link-display
18477 :style radio
18478 :selected (not org-descriptive-links)])
18479 "--"
18480 ("TODO Lists"
18481 ["TODO/DONE/-" org-todo t]
18482 ("Select keyword"
18483 ["Next keyword" org-shiftright (org-on-heading-p)]
18484 ["Previous keyword" org-shiftleft (org-on-heading-p)]
18485 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
18486 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
18487 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
18488 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
18489 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
18490 "--"
18491 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
18492 :selected org-enforce-todo-dependencies :style toggle :active t]
18493 "Settings for tree at point"
18494 ["Do Children sequentially" org-toggle-ordered-property :style radio
18495 :selected (org-entry-get nil "ORDERED")
18496 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18497 ["Do Children parallel" org-toggle-ordered-property :style radio
18498 :selected (not (org-entry-get nil "ORDERED"))
18499 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18500 "--"
18501 ["Set Priority" org-priority t]
18502 ["Priority Up" org-shiftup t]
18503 ["Priority Down" org-shiftdown t]
18504 "--"
18505 ["Get news from all feeds" org-feed-update-all t]
18506 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
18507 ["Customize feeds" (customize-variable 'org-feed-alist) t])
18508 ("TAGS and Properties"
18509 ["Set Tags" org-set-tags-command t]
18510 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
18511 "--"
18512 ["Set property" org-set-property t]
18513 ["Column view of properties" org-columns t]
18514 ["Insert Column View DBlock" org-insert-columns-dblock t])
18515 ("Dates and Scheduling"
18516 ["Timestamp" org-time-stamp t]
18517 ["Timestamp (inactive)" org-time-stamp-inactive t]
18518 ("Change Date"
18519 ["1 Day Later" org-shiftright t]
18520 ["1 Day Earlier" org-shiftleft t]
18521 ["1 ... Later" org-shiftup t]
18522 ["1 ... Earlier" org-shiftdown t])
18523 ["Compute Time Range" org-evaluate-time-range t]
18524 ["Schedule Item" org-schedule t]
18525 ["Deadline" org-deadline t]
18526 "--"
18527 ["Custom time format" org-toggle-time-stamp-overlays
18528 :style radio :selected org-display-custom-times]
18529 "--"
18530 ["Goto Calendar" org-goto-calendar t]
18531 ["Date from Calendar" org-date-from-calendar t]
18532 "--"
18533 ["Start/Restart Timer" org-timer-start t]
18534 ["Pause/Continue Timer" org-timer-pause-or-continue t]
18535 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
18536 ["Insert Timer String" org-timer t]
18537 ["Insert Timer Item" org-timer-item t])
18538 ("Logging work"
18539 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
18540 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
18541 ["Clock out" org-clock-out t]
18542 ["Clock cancel" org-clock-cancel t]
18543 "--"
18544 ["Mark as default task" org-clock-mark-default-task t]
18545 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
18546 ["Goto running clock" org-clock-goto t]
18547 "--"
18548 ["Display times" org-clock-display t]
18549 ["Create clock table" org-clock-report t]
18550 "--"
18551 ["Record DONE time"
18552 (progn (setq org-log-done (not org-log-done))
18553 (message "Switching to %s will %s record a timestamp"
18554 (car org-done-keywords)
18555 (if org-log-done "automatically" "not")))
18556 :style toggle :selected org-log-done])
18557 "--"
18558 ["Agenda Command..." org-agenda t]
18559 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
18560 ("File List for Agenda")
18561 ("Special views current file"
18562 ["TODO Tree" org-show-todo-tree t]
18563 ["Check Deadlines" org-check-deadlines t]
18564 ["Timeline" org-timeline t]
18565 ["Tags/Property tree" org-match-sparse-tree t])
18566 "--"
18567 ["Export/Publish..." org-export t]
18568 ("LaTeX"
18569 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
18570 :selected org-cdlatex-mode]
18571 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
18572 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
18573 ["Modify math symbol" org-cdlatex-math-modify
18574 (org-inside-LaTeX-fragment-p)]
18575 ["Insert citation" org-reftex-citation t]
18576 "--"
18577 ["Template for BEAMER" org-insert-beamer-options-template t])
18578 "--"
18579 ("MobileOrg"
18580 ["Push Files and Views" org-mobile-push t]
18581 ["Get Captured and Flagged" org-mobile-pull t]
18582 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
18583 "--"
18584 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
18585 "--"
18586 ("Documentation"
18587 ["Show Version" org-version t]
18588 ["Info Documentation" org-info t])
18589 ("Customize"
18590 ["Browse Org Group" org-customize t]
18591 "--"
18592 ["Expand This Menu" org-create-customize-menu
18593 (fboundp 'customize-menu-create)])
18594 ["Send bug report" org-submit-bug-report t]
18595 "--"
18596 ("Refresh/Reload"
18597 ["Refresh setup current buffer" org-mode-restart t]
18598 ["Reload Org (after update)" org-reload t]
18599 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
18602 (defun org-info (&optional node)
18603 "Read documentation for Org-mode in the info system.
18604 With optional NODE, go directly to that node."
18605 (interactive)
18606 (info (format "(org)%s" (or node ""))))
18608 ;;;###autoload
18609 (defun org-submit-bug-report ()
18610 "Submit a bug report on Org-mode via mail.
18612 Don't hesitate to report any problems or inaccurate documentation.
18614 If you don't have setup sending mail from (X)Emacs, please copy the
18615 output buffer into your mail program, as it gives us important
18616 information about your Org-mode version and configuration."
18617 (interactive)
18618 (require 'reporter)
18619 (org-load-modules-maybe)
18620 (org-require-autoloaded-modules)
18621 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
18622 (reporter-submit-bug-report
18623 "emacs-orgmode@gnu.org"
18624 (org-version)
18625 (let (list)
18626 (save-window-excursion
18627 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
18628 (delete-other-windows)
18629 (erase-buffer)
18630 (insert "You are about to submit a bug report to the Org-mode mailing list.
18632 We would like to add your full Org-mode and Outline configuration to the
18633 bug report. This greatly simplifies the work of the maintainer and
18634 other experts on the mailing list.
18636 HOWEVER, some variables you have customized may contain private
18637 information. The names of customers, colleagues, or friends, might
18638 appear in the form of file names, tags, todo states, or search strings.
18639 If you answer yes to the prompt, you might want to check and remove
18640 such private information before sending the email.")
18641 (add-text-properties (point-min) (point-max) '(face org-warning))
18642 (when (yes-or-no-p "Include your Org-mode configuration ")
18643 (mapatoms
18644 (lambda (v)
18645 (and (boundp v)
18646 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
18647 (or (and (symbol-value v)
18648 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
18649 (and
18650 (get v 'custom-type) (get v 'standard-value)
18651 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
18652 (push v list)))))
18653 (kill-buffer (get-buffer "*Warn about privacy*"))
18654 list))
18655 nil nil
18656 "Remember to cover the basics, that is, what you expected to happen and
18657 what in fact did happen. You don't know how to make a good report? See
18659 http://orgmode.org/manual/Feedback.html#Feedback
18661 Your bug report will be posted to the Org-mode mailing list.
18662 ------------------------------------------------------------------------")
18663 (save-excursion
18664 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
18665 (replace-match "\\1Bug: \\3 [\\2]")))))
18668 (defun org-install-agenda-files-menu ()
18669 (let ((bl (buffer-list)))
18670 (save-excursion
18671 (while bl
18672 (set-buffer (pop bl))
18673 (if (org-mode-p) (setq bl nil)))
18674 (when (org-mode-p)
18675 (easy-menu-change
18676 '("Org") "File List for Agenda"
18677 (append
18678 (list
18679 ["Edit File List" (org-edit-agenda-file-list) t]
18680 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
18681 ["Remove Current File from List" org-remove-file t]
18682 ["Cycle through agenda files" org-cycle-agenda-files t]
18683 ["Occur in all agenda files" org-occur-in-agenda-files t]
18684 "--")
18685 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
18687 ;;;; Documentation
18689 ;;;###autoload
18690 (defun org-require-autoloaded-modules ()
18691 (interactive)
18692 (mapc 'require
18693 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
18694 org-docbook org-exp org-html org-icalendar
18695 org-id org-latex
18696 org-publish org-remember org-table
18697 org-timer org-xoxo)))
18699 ;;;###autoload
18700 (defun org-reload (&optional uncompiled)
18701 "Reload all org lisp files.
18702 With prefix arg UNCOMPILED, load the uncompiled versions."
18703 (interactive "P")
18704 (require 'find-func)
18705 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
18706 (dir-org (file-name-directory (org-find-library-name "org")))
18707 (dir-org-contrib (ignore-errors
18708 (file-name-directory
18709 (org-find-library-name "org-contribdir"))))
18710 (babel-files
18711 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
18712 (append (list nil "comint" "eval" "exp" "keys"
18713 "lob" "ref" "table" "tangle")
18714 (delq nil
18715 (mapcar
18716 (lambda (lang)
18717 (when (cdr lang) (symbol-name (car lang))))
18718 org-babel-load-languages)))))
18719 (files
18720 (append (directory-files dir-org t file-re)
18721 babel-files
18722 (and dir-org-contrib
18723 (directory-files dir-org-contrib t file-re))))
18724 (remove-re (concat (if (featurep 'xemacs)
18725 "org-colview" "org-colview-xemacs")
18726 "\\'")))
18727 (setq files (mapcar 'file-name-sans-extension files))
18728 (setq files (mapcar
18729 (lambda (x) (if (string-match remove-re x) nil x))
18730 files))
18731 (setq files (delq nil files))
18732 (mapc
18733 (lambda (f)
18734 (when (featurep (intern (file-name-nondirectory f)))
18735 (if (and (not uncompiled)
18736 (file-exists-p (concat f ".elc")))
18737 (load (concat f ".elc") nil nil t)
18738 (load (concat f ".el") nil nil t))))
18739 files))
18740 (org-version))
18742 ;;;###autoload
18743 (defun org-customize ()
18744 "Call the customize function with org as argument."
18745 (interactive)
18746 (org-load-modules-maybe)
18747 (org-require-autoloaded-modules)
18748 (customize-browse 'org))
18750 (defun org-create-customize-menu ()
18751 "Create a full customization menu for Org-mode, insert it into the menu."
18752 (interactive)
18753 (org-load-modules-maybe)
18754 (org-require-autoloaded-modules)
18755 (if (fboundp 'customize-menu-create)
18756 (progn
18757 (easy-menu-change
18758 '("Org") "Customize"
18759 `(["Browse Org group" org-customize t]
18760 "--"
18761 ,(customize-menu-create 'org)
18762 ["Set" Custom-set t]
18763 ["Save" Custom-save t]
18764 ["Reset to Current" Custom-reset-current t]
18765 ["Reset to Saved" Custom-reset-saved t]
18766 ["Reset to Standard Settings" Custom-reset-standard t]))
18767 (message "\"Org\"-menu now contains full customization menu"))
18768 (error "Cannot expand menu (outdated version of cus-edit.el)")))
18770 ;;;; Miscellaneous stuff
18772 ;;; Generally useful functions
18774 (defun org-get-at-bol (property)
18775 "Get text property PROPERTY at beginning of line."
18776 (get-text-property (point-at-bol) property))
18778 (defun org-find-text-property-in-string (prop s)
18779 "Return the first non-nil value of property PROP in string S."
18780 (or (get-text-property 0 prop s)
18781 (get-text-property (or (next-single-property-change 0 prop s) 0)
18782 prop s)))
18784 (defun org-display-warning (message) ;; Copied from Emacs-Muse
18785 "Display the given MESSAGE as a warning."
18786 (if (fboundp 'display-warning)
18787 (display-warning 'org message
18788 (if (featurep 'xemacs) 'warning :warning))
18789 (let ((buf (get-buffer-create "*Org warnings*")))
18790 (with-current-buffer buf
18791 (goto-char (point-max))
18792 (insert "Warning (Org): " message)
18793 (unless (bolp)
18794 (newline)))
18795 (display-buffer buf)
18796 (sit-for 0))))
18798 (defun org-eval (form)
18799 "Eval FORM and return result."
18800 (condition-case error
18801 (eval form)
18802 (error (format "%%![Error: %s]" error))))
18804 (defun org-in-commented-line ()
18805 "Is point in a line starting with `#'?"
18806 (equal (char-after (point-at-bol)) ?#))
18808 (defun org-in-indented-comment-line ()
18809 "Is point in a line starting with `#' after some white space?"
18810 (save-excursion
18811 (save-match-data
18812 (goto-char (point-at-bol))
18813 (looking-at "[ \t]*#"))))
18815 (defun org-in-verbatim-emphasis ()
18816 (save-match-data
18817 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
18819 (defun org-goto-marker-or-bmk (marker &optional bookmark)
18820 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
18821 (if (and marker (marker-buffer marker)
18822 (buffer-live-p (marker-buffer marker)))
18823 (progn
18824 (org-pop-to-buffer-same-window (marker-buffer marker))
18825 (if (or (> marker (point-max)) (< marker (point-min)))
18826 (widen))
18827 (goto-char marker)
18828 (org-show-context 'org-goto))
18829 (if bookmark
18830 (bookmark-jump bookmark)
18831 (error "Cannot find location"))))
18833 (defun org-quote-csv-field (s)
18834 "Quote field for inclusion in CSV material."
18835 (if (string-match "[\",]" s)
18836 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
18839 (defun org-force-self-insert (N)
18840 "Needed to enforce self-insert under remapping."
18841 (interactive "p")
18842 (self-insert-command N))
18844 (defun org-string-width (s)
18845 "Compute width of string, ignoring invisible characters.
18846 This ignores character with invisibility property `org-link', and also
18847 characters with property `org-cwidth', because these will become invisible
18848 upon the next fontification round."
18849 (let (b l)
18850 (when (or (eq t buffer-invisibility-spec)
18851 (assq 'org-link buffer-invisibility-spec))
18852 (while (setq b (text-property-any 0 (length s)
18853 'invisible 'org-link s))
18854 (setq s (concat (substring s 0 b)
18855 (substring s (or (next-single-property-change
18856 b 'invisible s) (length s)))))))
18857 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
18858 (setq s (concat (substring s 0 b)
18859 (substring s (or (next-single-property-change
18860 b 'org-cwidth s) (length s))))))
18861 (setq l (string-width s) b -1)
18862 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
18863 (setq l (- l (get-text-property b 'org-dwidth-n s))))
18866 (defun org-shorten-string (s maxlength)
18867 "Shorten string S so tht it is no longer than MAXLENGTH characters.
18868 If the string is shorter or has length MAXLENGTH, just return the
18869 original string. If it is longer, the functions finds a space in the
18870 string, breaks this string off at that locations and adds three dots
18871 as ellipsis. Including the ellipsis, the string will not be longer
18872 than MAXLENGTH. If finding a good breaking point in the string does
18873 not work, the string is just chopped off in the middle of a word
18874 if necessary."
18875 (if (<= (length s) maxlength)
18877 (let* ((n (max (- maxlength 4) 1))
18878 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
18879 (if (string-match re s)
18880 (concat (match-string 1 s) "...")
18881 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
18883 (defun org-get-indentation (&optional line)
18884 "Get the indentation of the current line, interpreting tabs.
18885 When LINE is given, assume it represents a line and compute its indentation."
18886 (if line
18887 (if (string-match "^ *" (org-remove-tabs line))
18888 (match-end 0))
18889 (save-excursion
18890 (beginning-of-line 1)
18891 (skip-chars-forward " \t")
18892 (current-column))))
18894 (defun org-get-string-indentation (s)
18895 "What indentation has S due to SPACE and TAB at the beginning of the string?"
18896 (let ((n -1) (i 0) (w tab-width) c)
18897 (catch 'exit
18898 (while (< (setq n (1+ n)) (length s))
18899 (setq c (aref s n))
18900 (cond ((= c ?\ ) (setq i (1+ i)))
18901 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
18902 (t (throw 'exit t)))))
18905 (defun org-remove-tabs (s &optional width)
18906 "Replace tabulators in S with spaces.
18907 Assumes that s is a single line, starting in column 0."
18908 (setq width (or width tab-width))
18909 (while (string-match "\t" s)
18910 (setq s (replace-match
18911 (make-string
18912 (- (* width (/ (+ (match-beginning 0) width) width))
18913 (match-beginning 0)) ?\ )
18914 t t s)))
18917 (defun org-fix-indentation (line ind)
18918 "Fix indentation in LINE.
18919 IND is a cons cell with target and minimum indentation.
18920 If the current indentation in LINE is smaller than the minimum,
18921 leave it alone. If it is larger than ind, set it to the target."
18922 (let* ((l (org-remove-tabs line))
18923 (i (org-get-indentation l))
18924 (i1 (car ind)) (i2 (cdr ind)))
18925 (if (>= i i2) (setq l (substring line i2)))
18926 (if (> i1 0)
18927 (concat (make-string i1 ?\ ) l)
18928 l)))
18930 (defun org-remove-indentation (code &optional n)
18931 "Remove the maximum common indentation from the lines in CODE.
18932 N may optionally be the number of spaces to remove."
18933 (with-temp-buffer
18934 (insert code)
18935 (org-do-remove-indentation n)
18936 (buffer-string)))
18938 (defun org-do-remove-indentation (&optional n)
18939 "Remove the maximum common indentation from the buffer."
18940 (untabify (point-min) (point-max))
18941 (let ((min 10000) re)
18942 (if n
18943 (setq min n)
18944 (goto-char (point-min))
18945 (while (re-search-forward "^ *[^ \n]" nil t)
18946 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
18947 (unless (or (= min 0) (= min 10000))
18948 (setq re (format "^ \\{%d\\}" min))
18949 (goto-char (point-min))
18950 (while (re-search-forward re nil t)
18951 (replace-match "")
18952 (end-of-line 1))
18953 min)))
18955 (defun org-fill-template (template alist)
18956 "Find each %key of ALIST in TEMPLATE and replace it."
18957 (let ((case-fold-search nil)
18958 entry key value)
18959 (setq alist (sort (copy-sequence alist)
18960 (lambda (a b) (< (length (car a)) (length (car b))))))
18961 (while (setq entry (pop alist))
18962 (setq template
18963 (replace-regexp-in-string
18964 (concat "%" (regexp-quote (car entry)))
18965 (cdr entry) template t t)))
18966 template))
18968 (defun org-base-buffer (buffer)
18969 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
18970 (if (not buffer)
18971 buffer
18972 (or (buffer-base-buffer buffer)
18973 buffer)))
18975 (defun org-trim (s)
18976 "Remove whitespace at beginning and end of string."
18977 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
18978 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
18981 (defun org-wrap (string &optional width lines)
18982 "Wrap string to either a number of lines, or a width in characters.
18983 If WIDTH is non-nil, the string is wrapped to that width, however many lines
18984 that costs. If there is a word longer than WIDTH, the text is actually
18985 wrapped to the length of that word.
18986 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
18987 many lines, whatever width that takes.
18988 The return value is a list of lines, without newlines at the end."
18989 (let* ((words (org-split-string string "[ \t\n]+"))
18990 (maxword (apply 'max (mapcar 'org-string-width words)))
18991 w ll)
18992 (cond (width
18993 (org-do-wrap words (max maxword width)))
18994 (lines
18995 (setq w maxword)
18996 (setq ll (org-do-wrap words maxword))
18997 (if (<= (length ll) lines)
18999 (setq ll words)
19000 (while (> (length ll) lines)
19001 (setq w (1+ w))
19002 (setq ll (org-do-wrap words w)))
19003 ll))
19004 (t (error "Cannot wrap this")))))
19006 (defun org-do-wrap (words width)
19007 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
19008 (let (lines line)
19009 (while words
19010 (setq line (pop words))
19011 (while (and words (< (+ (length line) (length (car words))) width))
19012 (setq line (concat line " " (pop words))))
19013 (setq lines (push line lines)))
19014 (nreverse lines)))
19016 (defun org-split-string (string &optional separators)
19017 "Splits STRING into substrings at SEPARATORS.
19018 No empty strings are returned if there are matches at the beginning
19019 and end of string."
19020 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
19021 (start 0)
19022 notfirst
19023 (list nil))
19024 (while (and (string-match rexp string
19025 (if (and notfirst
19026 (= start (match-beginning 0))
19027 (< start (length string)))
19028 (1+ start) start))
19029 (< (match-beginning 0) (length string)))
19030 (setq notfirst t)
19031 (or (eq (match-beginning 0) 0)
19032 (and (eq (match-beginning 0) (match-end 0))
19033 (eq (match-beginning 0) start))
19034 (setq list
19035 (cons (substring string start (match-beginning 0))
19036 list)))
19037 (setq start (match-end 0)))
19038 (or (eq start (length string))
19039 (setq list
19040 (cons (substring string start)
19041 list)))
19042 (nreverse list)))
19044 (defun org-quote-vert (s)
19045 "Replace \"|\" with \"\\vert\"."
19046 (while (string-match "|" s)
19047 (setq s (replace-match "\\vert" t t s)))
19050 (defun org-uuidgen-p (s)
19051 "Is S an ID created by UUIDGEN?"
19052 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
19054 (defun org-context ()
19055 "Return a list of contexts of the current cursor position.
19056 If several contexts apply, all are returned.
19057 Each context entry is a list with a symbol naming the context, and
19058 two positions indicating start and end of the context. Possible
19059 contexts are:
19061 :headline anywhere in a headline
19062 :headline-stars on the leading stars in a headline
19063 :todo-keyword on a TODO keyword (including DONE) in a headline
19064 :tags on the TAGS in a headline
19065 :priority on the priority cookie in a headline
19066 :item on the first line of a plain list item
19067 :item-bullet on the bullet/number of a plain list item
19068 :checkbox on the checkbox in a plain list item
19069 :table in an org-mode table
19070 :table-special on a special filed in a table
19071 :table-table in a table.el table
19072 :link on a hyperlink
19073 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
19074 :target on a <<target>>
19075 :radio-target on a <<<radio-target>>>
19076 :latex-fragment on a LaTeX fragment
19077 :latex-preview on a LaTeX fragment with overlayed preview image
19079 This function expects the position to be visible because it uses font-lock
19080 faces as a help to recognize the following contexts: :table-special, :link,
19081 and :keyword."
19082 (let* ((f (get-text-property (point) 'face))
19083 (faces (if (listp f) f (list f)))
19084 (p (point)) clist o)
19085 ;; First the large context
19086 (cond
19087 ((org-on-heading-p t)
19088 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19089 (when (progn
19090 (beginning-of-line 1)
19091 (looking-at org-todo-line-tags-regexp))
19092 (push (org-point-in-group p 1 :headline-stars) clist)
19093 (push (org-point-in-group p 2 :todo-keyword) clist)
19094 (push (org-point-in-group p 4 :tags) clist))
19095 (goto-char p)
19096 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
19097 (if (looking-at "\\[#[A-Z0-9]\\]")
19098 (push (org-point-in-group p 0 :priority) clist)))
19100 ((org-at-item-p)
19101 (push (org-point-in-group p 2 :item-bullet) clist)
19102 (push (list :item (point-at-bol)
19103 (save-excursion (org-end-of-item) (point)))
19104 clist)
19105 (and (org-at-item-checkbox-p)
19106 (push (org-point-in-group p 0 :checkbox) clist)))
19108 ((org-at-table-p)
19109 (push (list :table (org-table-begin) (org-table-end)) clist)
19110 (if (memq 'org-formula faces)
19111 (push (list :table-special
19112 (previous-single-property-change p 'face)
19113 (next-single-property-change p 'face)) clist)))
19114 ((org-at-table-p 'any)
19115 (push (list :table-table) clist)))
19116 (goto-char p)
19118 ;; Now the small context
19119 (cond
19120 ((org-at-timestamp-p)
19121 (push (org-point-in-group p 0 :timestamp) clist))
19122 ((memq 'org-link faces)
19123 (push (list :link
19124 (previous-single-property-change p 'face)
19125 (next-single-property-change p 'face)) clist))
19126 ((memq 'org-special-keyword faces)
19127 (push (list :keyword
19128 (previous-single-property-change p 'face)
19129 (next-single-property-change p 'face)) clist))
19130 ((org-on-target-p)
19131 (push (org-point-in-group p 0 :target) clist)
19132 (goto-char (1- (match-beginning 0)))
19133 (if (looking-at org-radio-target-regexp)
19134 (push (org-point-in-group p 0 :radio-target) clist))
19135 (goto-char p))
19136 ((setq o (car (delq nil
19137 (mapcar
19138 (lambda (x)
19139 (if (memq x org-latex-fragment-image-overlays) x))
19140 (overlays-at (point))))))
19141 (push (list :latex-fragment
19142 (overlay-start o) (overlay-end o)) clist)
19143 (push (list :latex-preview
19144 (overlay-start o) (overlay-end o)) clist))
19145 ((org-inside-LaTeX-fragment-p)
19146 ;; FIXME: positions wrong.
19147 (push (list :latex-fragment (point) (point)) clist)))
19149 (setq clist (nreverse (delq nil clist)))
19150 clist))
19152 ;; FIXME: Compare with at-regexp-p Do we need both?
19153 (defun org-in-regexp (re &optional nlines visually)
19154 "Check if point is inside a match of regexp.
19155 Normally only the current line is checked, but you can include NLINES extra
19156 lines both before and after point into the search.
19157 If VISUALLY is set, require that the cursor is not after the match but
19158 really on, so that the block visually is on the match."
19159 (catch 'exit
19160 (let ((pos (point))
19161 (eol (point-at-eol (+ 1 (or nlines 0))))
19162 (inc (if visually 1 0)))
19163 (save-excursion
19164 (beginning-of-line (- 1 (or nlines 0)))
19165 (while (re-search-forward re eol t)
19166 (if (and (<= (match-beginning 0) pos)
19167 (>= (+ inc (match-end 0)) pos))
19168 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
19170 (defun org-at-regexp-p (regexp)
19171 "Is point inside a match of REGEXP in the current line?"
19172 (catch 'exit
19173 (save-excursion
19174 (let ((pos (point)) (end (point-at-eol)))
19175 (beginning-of-line 1)
19176 (while (re-search-forward regexp end t)
19177 (if (and (<= (match-beginning 0) pos)
19178 (>= (match-end 0) pos))
19179 (throw 'exit t)))
19180 nil))))
19182 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
19183 "Non-nil when point is between matches of START-RE and END-RE.
19185 Also return a non-nil value when point is on one of the matches.
19187 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
19188 buffer positions. Default values are the positions of headlines
19189 surrounding the point.
19191 The functions returns a cons cell whose car (resp. cdr) is the
19192 position before START-RE (resp. after END-RE)."
19193 (save-match-data
19194 (let ((pos (point))
19195 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
19196 (limit-down (or lim-down (save-excursion (outline-next-heading))))
19197 beg end)
19198 (save-excursion
19199 ;; Point is on a block when on START-RE or if START-RE can be
19200 ;; found before it...
19201 (and (or (org-at-regexp-p start-re)
19202 (re-search-backward start-re limit-up t))
19203 (setq beg (match-beginning 0))
19204 ;; ... and END-RE after it...
19205 (goto-char (match-end 0))
19206 (re-search-forward end-re limit-down t)
19207 (> (setq end (match-end 0)) pos)
19208 ;; ... without another START-RE in-between.
19209 (goto-char (match-beginning 0))
19210 (not (re-search-backward start-re (1+ beg) t))
19211 ;; Return value.
19212 (cons beg end))))))
19214 (defun org-in-block-p (names)
19215 "Is point inside any block whose name belongs to NAMES?
19217 NAMES is a list of strings containing names of blocks."
19218 (save-match-data
19219 (catch 'exit
19220 (let ((case-fold-search t)
19221 (lim-up (save-excursion (outline-previous-heading)))
19222 (lim-down (save-excursion (outline-next-heading))))
19223 (mapc (lambda (name)
19224 (let ((n (regexp-quote name)))
19225 (when (org-between-regexps-p
19226 (concat "^[ \t]*#\\+begin_" n)
19227 (concat "^[ \t]*#\\+end_" n)
19228 lim-up lim-down)
19229 (throw 'exit t))))
19230 names))
19231 nil)))
19233 (defun org-occur-in-agenda-files (regexp &optional nlines)
19234 "Call `multi-occur' with buffers for all agenda files."
19235 (interactive "sOrg-files matching: \np")
19236 (let* ((files (org-agenda-files))
19237 (tnames (mapcar 'file-truename files))
19238 (extra org-agenda-text-search-extra-files)
19240 (when (eq (car extra) 'agenda-archives)
19241 (setq extra (cdr extra))
19242 (setq files (org-add-archive-files files)))
19243 (while (setq f (pop extra))
19244 (unless (member (file-truename f) tnames)
19245 (add-to-list 'files f 'append)
19246 (add-to-list 'tnames (file-truename f) 'append)))
19247 (multi-occur
19248 (mapcar (lambda (x)
19249 (with-current-buffer
19250 (or (get-file-buffer x) (find-file-noselect x))
19251 (widen)
19252 (current-buffer)))
19253 files)
19254 regexp)))
19256 (if (boundp 'occur-mode-find-occurrence-hook)
19257 ;; Emacs 23
19258 (add-hook 'occur-mode-find-occurrence-hook
19259 (lambda ()
19260 (when (org-mode-p)
19261 (org-reveal))))
19262 ;; Emacs 22
19263 (defadvice occur-mode-goto-occurrence
19264 (after org-occur-reveal activate)
19265 (and (org-mode-p) (org-reveal)))
19266 (defadvice occur-mode-goto-occurrence-other-window
19267 (after org-occur-reveal activate)
19268 (and (org-mode-p) (org-reveal)))
19269 (defadvice occur-mode-display-occurrence
19270 (after org-occur-reveal activate)
19271 (when (org-mode-p)
19272 (let ((pos (occur-mode-find-occurrence)))
19273 (with-current-buffer (marker-buffer pos)
19274 (save-excursion
19275 (goto-char pos)
19276 (org-reveal)))))))
19278 (defun org-occur-link-in-agenda-files ()
19279 "Create a link and search for it in the agendas.
19280 The link is not stored in `org-stored-links', it is just created
19281 for the search purpose."
19282 (interactive)
19283 (let ((link (condition-case nil
19284 (org-store-link nil)
19285 (error "Unable to create a link to here"))))
19286 (org-occur-in-agenda-files (regexp-quote link))))
19288 (defun org-uniquify (list)
19289 "Remove duplicate elements from LIST."
19290 (let (res)
19291 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
19292 res))
19294 (defun org-delete-all (elts list)
19295 "Remove all elements in ELTS from LIST."
19296 (while elts
19297 (setq list (delete (pop elts) list)))
19298 list)
19300 (defun org-count (cl-item cl-seq)
19301 "Count the number of occurrences of ITEM in SEQ.
19302 Taken from `count' in cl-seq.el with all keyword arguments removed."
19303 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
19304 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
19305 (while (< cl-start cl-end)
19306 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
19307 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
19308 (setq cl-start (1+ cl-start)))
19309 cl-count))
19311 (defun org-remove-if (predicate seq)
19312 "Remove everything from SEQ that fulfills PREDICATE."
19313 (let (res e)
19314 (while seq
19315 (setq e (pop seq))
19316 (if (not (funcall predicate e)) (push e res)))
19317 (nreverse res)))
19319 (defun org-remove-if-not (predicate seq)
19320 "Remove everything from SEQ that does not fulfill PREDICATE."
19321 (let (res e)
19322 (while seq
19323 (setq e (pop seq))
19324 (if (funcall predicate e) (push e res)))
19325 (nreverse res)))
19327 (defun org-back-over-empty-lines ()
19328 "Move backwards over whitespace, to the beginning of the first empty line.
19329 Returns the number of empty lines passed."
19330 (let ((pos (point)))
19331 (if (cdr (assoc 'heading org-blank-before-new-entry))
19332 (skip-chars-backward " \t\n\r")
19333 (unless (eobp)
19334 (forward-line -1)))
19335 (beginning-of-line 2)
19336 (goto-char (min (point) pos))
19337 (count-lines (point) pos)))
19339 (defun org-skip-whitespace ()
19340 (skip-chars-forward " \t\n\r"))
19342 (defun org-point-in-group (point group &optional context)
19343 "Check if POINT is in match-group GROUP.
19344 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
19345 match. If the match group does not exist or point is not inside it,
19346 return nil."
19347 (and (match-beginning group)
19348 (>= point (match-beginning group))
19349 (<= point (match-end group))
19350 (if context
19351 (list context (match-beginning group) (match-end group))
19352 t)))
19354 (defun org-switch-to-buffer-other-window (&rest args)
19355 "Switch to buffer in a second window on the current frame.
19356 In particular, do not allow pop-up frames.
19357 Returns the newly created buffer."
19358 (let (pop-up-frames special-display-buffer-names special-display-regexps
19359 special-display-function)
19360 (apply 'switch-to-buffer-other-window args)))
19362 (defun org-combine-plists (&rest plists)
19363 "Create a single property list from all plists in PLISTS.
19364 The process starts by copying the first list, and then setting properties
19365 from the other lists. Settings in the last list are the most significant
19366 ones and overrule settings in the other lists."
19367 (let ((rtn (copy-sequence (pop plists)))
19368 p v ls)
19369 (while plists
19370 (setq ls (pop plists))
19371 (while ls
19372 (setq p (pop ls) v (pop ls))
19373 (setq rtn (plist-put rtn p v))))
19374 rtn))
19376 (defun org-move-line-down (arg)
19377 "Move the current line down. With prefix argument, move it past ARG lines."
19378 (interactive "p")
19379 (let ((col (current-column))
19380 beg end pos)
19381 (beginning-of-line 1) (setq beg (point))
19382 (beginning-of-line 2) (setq end (point))
19383 (beginning-of-line (+ 1 arg))
19384 (setq pos (move-marker (make-marker) (point)))
19385 (insert (delete-and-extract-region beg end))
19386 (goto-char pos)
19387 (org-move-to-column col)))
19389 (defun org-move-line-up (arg)
19390 "Move the current line up. With prefix argument, move it past ARG lines."
19391 (interactive "p")
19392 (let ((col (current-column))
19393 beg end pos)
19394 (beginning-of-line 1) (setq beg (point))
19395 (beginning-of-line 2) (setq end (point))
19396 (beginning-of-line (- arg))
19397 (setq pos (move-marker (make-marker) (point)))
19398 (insert (delete-and-extract-region beg end))
19399 (goto-char pos)
19400 (org-move-to-column col)))
19402 (defun org-replace-escapes (string table)
19403 "Replace %-escapes in STRING with values in TABLE.
19404 TABLE is an association list with keys like \"%a\" and string values.
19405 The sequences in STRING may contain normal field width and padding information,
19406 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
19407 so values can contain further %-escapes if they are define later in TABLE."
19408 (let ((tbl (copy-alist table))
19409 (case-fold-search nil)
19410 (pchg 0)
19411 e re rpl)
19412 (while (setq e (pop tbl))
19413 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
19414 (when (and (cdr e) (string-match re (cdr e)))
19415 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
19416 (safe "SREF"))
19417 (add-text-properties 0 3 (list 'sref sref) safe)
19418 (setcdr e (replace-match safe t t (cdr e)))))
19419 (while (string-match re string)
19420 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
19421 (cdr e)))
19422 (setq string (replace-match rpl t t string))))
19423 (while (setq pchg (next-property-change pchg string))
19424 (let ((sref (get-text-property pchg 'sref string)))
19425 (when (and sref (string-match "SREF" string pchg))
19426 (setq string (replace-match sref t t string)))))
19427 string))
19429 (defun org-sublist (list start end)
19430 "Return a section of LIST, from START to END.
19431 Counting starts at 1."
19432 (let (rtn (c start))
19433 (setq list (nthcdr (1- start) list))
19434 (while (and list (<= c end))
19435 (push (pop list) rtn)
19436 (setq c (1+ c)))
19437 (nreverse rtn)))
19439 (defun org-find-base-buffer-visiting (file)
19440 "Like `find-buffer-visiting' but always return the base buffer and
19441 not an indirect buffer."
19442 (let ((buf (or (get-file-buffer file)
19443 (find-buffer-visiting file))))
19444 (if buf
19445 (or (buffer-base-buffer buf) buf)
19446 nil)))
19448 (defun org-image-file-name-regexp (&optional extensions)
19449 "Return regexp matching the file names of images.
19450 If EXTENSIONS is given, only match these."
19451 (if (and (not extensions) (fboundp 'image-file-name-regexp))
19452 (image-file-name-regexp)
19453 (let ((image-file-name-extensions
19454 (or extensions
19455 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
19456 "xbm" "xpm" "pbm" "pgm" "ppm"))))
19457 (concat "\\."
19458 (regexp-opt (nconc (mapcar 'upcase
19459 image-file-name-extensions)
19460 image-file-name-extensions)
19462 "\\'"))))
19464 (defun org-file-image-p (file &optional extensions)
19465 "Return non-nil if FILE is an image."
19466 (save-match-data
19467 (string-match (org-image-file-name-regexp extensions) file)))
19469 (defun org-get-cursor-date ()
19470 "Return the date at cursor in as a time.
19471 This works in the calendar and in the agenda, anywhere else it just
19472 returns the current time."
19473 (let (date day defd)
19474 (cond
19475 ((eq major-mode 'calendar-mode)
19476 (setq date (calendar-cursor-to-date)
19477 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
19478 ((eq major-mode 'org-agenda-mode)
19479 (setq day (get-text-property (point) 'day))
19480 (if day
19481 (setq date (calendar-gregorian-from-absolute day)
19482 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
19483 (nth 2 date))))))
19484 (or defd (current-time))))
19486 (defvar org-agenda-action-marker (make-marker)
19487 "Marker pointing to the entry for the next agenda action.")
19489 (defun org-mark-entry-for-agenda-action ()
19490 "Mark the current entry as target of an agenda action.
19491 Agenda actions are actions executed from the agenda with the key `k',
19492 which make use of the date at the cursor."
19493 (interactive)
19494 (move-marker org-agenda-action-marker
19495 (save-excursion (org-back-to-heading t) (point))
19496 (current-buffer))
19497 (message
19498 "Entry marked for action; press `k' at desired date in agenda or calendar"))
19500 (defun org-mark-subtree ()
19501 "Mark the current subtree.
19502 This puts point at the start of the current subtree, and mark at the end.
19504 If point is in an inline task, mark that task instead."
19505 (interactive)
19506 (let ((inline-task-p
19507 (and (featurep 'org-inlinetask)
19508 (org-inlinetask-in-task-p)))
19509 (beg))
19510 ;; Get beginning of subtree
19511 (cond
19512 (inline-task-p (org-inlinetask-goto-beginning))
19513 ((org-at-heading-p) (beginning-of-line))
19514 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
19515 (setq beg (point))
19516 ;; Get end of it
19517 (if inline-task-p
19518 (org-inlinetask-goto-end)
19519 (org-end-of-subtree))
19520 ;; Mark zone
19521 (push-mark (point) nil t)
19522 (goto-char beg)))
19524 ;;; Paragraph filling stuff.
19525 ;; We want this to be just right, so use the full arsenal.
19527 (defun org-indent-line-function ()
19528 "Indent line depending on context."
19529 (interactive)
19530 (let* ((pos (point))
19531 (itemp (org-at-item-p))
19532 (case-fold-search t)
19533 (org-drawer-regexp (or org-drawer-regexp "\000"))
19534 (inline-task-p (and (featurep 'org-inlinetask)
19535 (org-inlinetask-in-task-p)))
19536 (inline-re (and inline-task-p
19537 (org-inlinetask-outline-regexp)))
19538 column)
19539 (beginning-of-line 1)
19540 (cond
19541 ;; Comments
19542 ((looking-at "# ") (setq column 0))
19543 ;; Headings
19544 ((looking-at org-outline-regexp) (setq column 0))
19545 ;; Included files
19546 ((looking-at "#\\+include:") (setq column 0))
19547 ;; Footnote definition
19548 ((looking-at org-footnote-definition-re) (setq column 0))
19549 ;; Literal examples
19550 ((looking-at "[ \t]*:\\( \\|$\\)")
19551 (setq column (org-get-indentation))) ; do nothing
19552 ;; Lists
19553 ((ignore-errors (goto-char (org-in-item-p)))
19554 (setq column (if itemp
19555 (org-get-indentation)
19556 (org-list-item-body-column (point))))
19557 (goto-char pos))
19558 ;; Drawers
19559 ((and (looking-at "[ \t]*:END:")
19560 (save-excursion (re-search-backward org-drawer-regexp nil t)))
19561 (save-excursion
19562 (goto-char (1- (match-beginning 1)))
19563 (setq column (current-column))))
19564 ;; Special blocks
19565 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
19566 (save-excursion
19567 (re-search-backward
19568 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
19569 (setq column (org-get-indentation (match-string 0))))
19570 ((and (not (looking-at "[ \t]*#\\+begin_"))
19571 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
19572 (save-excursion
19573 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
19574 (setq column
19575 (cond ((equal (downcase (match-string 1)) "src")
19576 ;; src blocks: let `org-edit-src-exit' handle them
19577 (org-get-indentation))
19578 ((equal (downcase (match-string 1)) "example")
19579 (max (org-get-indentation)
19580 (org-get-indentation (match-string 0))))
19582 (org-get-indentation (match-string 0))))))
19583 ;; This line has nothing special, look at the previous relevant
19584 ;; line to compute indentation
19586 (beginning-of-line 0)
19587 (while (and (not (bobp))
19588 (not (looking-at org-drawer-regexp))
19589 ;; When point started in an inline task, do not move
19590 ;; above task starting line.
19591 (not (and inline-task-p (looking-at inline-re)))
19592 ;; Skip drawers, blocks, empty lines, verbatim,
19593 ;; comments, tables, footnotes definitions, lists,
19594 ;; inline tasks.
19595 (or (and (looking-at "[ \t]*:END:")
19596 (re-search-backward org-drawer-regexp nil t))
19597 (and (looking-at "[ \t]*#\\+end_")
19598 (re-search-backward "[ \t]*#\\+begin_"nil t))
19599 (looking-at "[ \t]*[\n:#|]")
19600 (looking-at org-footnote-definition-re)
19601 (and (ignore-errors (goto-char (org-in-item-p)))
19602 (goto-char
19603 (org-list-get-top-point (org-list-struct))))
19604 (and (not inline-task-p)
19605 (featurep 'org-inlinetask)
19606 (org-inlinetask-in-task-p)
19607 (or (org-inlinetask-goto-beginning) t))))
19608 (beginning-of-line 0))
19609 (cond
19610 ;; There was an heading above.
19611 ((looking-at "\\*+[ \t]+")
19612 (if (not org-adapt-indentation)
19613 (setq column 0)
19614 (goto-char (match-end 0))
19615 (setq column (current-column))))
19616 ;; A drawer had started and is unfinished
19617 ((looking-at org-drawer-regexp)
19618 (goto-char (1- (match-beginning 1)))
19619 (setq column (current-column)))
19620 ;; Else, nothing noticeable found: get indentation and go on.
19621 (t (setq column (org-get-indentation))))))
19622 ;; Now apply indentation and move cursor accordingly
19623 (goto-char pos)
19624 (if (<= (current-column) (current-indentation))
19625 (org-indent-line-to column)
19626 (save-excursion (org-indent-line-to column)))
19627 ;; Special polishing for properties, see `org-property-format'
19628 (setq column (current-column))
19629 (beginning-of-line 1)
19630 (if (looking-at
19631 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
19632 (replace-match (concat (match-string 1)
19633 (format org-property-format
19634 (match-string 2) (match-string 3)))
19635 t t))
19636 (org-move-to-column column)))
19638 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
19639 "Variable to store copy of `adaptive-fill-regexp'.
19640 Since `adaptive-fill-regexp' is set to never match, we need to
19641 store a backup of its value before entering `org-mode' so that
19642 the functionality can be provided as a fall-back.")
19644 (defun org-set-autofill-regexps ()
19645 (interactive)
19646 ;; In the paragraph separator we include headlines, because filling
19647 ;; text in a line directly attached to a headline would otherwise
19648 ;; fill the headline as well.
19649 (org-set-local 'comment-start-skip "^#+[ \t]*")
19650 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
19651 ;; The paragraph starter includes hand-formatted lists.
19652 (org-set-local
19653 'paragraph-start
19654 (concat
19655 "\f" "\\|"
19656 "[ ]*$" "\\|"
19657 org-outline-regexp "\\|"
19658 "[ \t]*#" "\\|"
19659 (org-item-re) "\\|"
19660 "[ \t]*[:|]" "\\|"
19661 "\\$\\$" "\\|"
19662 "\\\\\\(begin\\|end\\|[][]\\)"))
19663 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
19664 ;; But only if the user has not turned off tables or fixed-width regions
19665 (org-set-local
19666 'auto-fill-inhibit-regexp
19667 (concat org-outline-regexp
19668 "\\|#\\+"
19669 "\\|[ \t]*" org-keyword-time-regexp
19670 (if (or org-enable-table-editor org-enable-fixed-width-editor)
19671 (concat
19672 "\\|[ \t]*["
19673 (if org-enable-table-editor "|" "")
19674 (if org-enable-fixed-width-editor ":" "")
19675 "]"))))
19676 ;; We use our own fill-paragraph function, to make sure that tables
19677 ;; and fixed-width regions are not wrapped. That function will pass
19678 ;; through to `fill-paragraph' when appropriate.
19679 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
19680 ;; Prevent auto-fill from inserting unwanted new items.
19681 (org-set-local 'fill-nobreak-predicate
19682 (if (memq 'org-fill-item-nobreak-p fill-nobreak-predicate)
19683 fill-nobreak-predicate
19684 (cons 'org-fill-item-nobreak-p fill-nobreak-predicate)))
19685 ;; Adaptive filling: To get full control, first make sure that
19686 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
19687 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
19688 (org-set-local 'org-adaptive-fill-regexp-backup
19689 adaptive-fill-regexp))
19690 (org-set-local 'adaptive-fill-regexp "\000")
19691 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
19692 (org-set-local 'adaptive-fill-function
19693 'org-adaptive-fill-function)
19694 (org-set-local
19695 'align-mode-rules-list
19696 '((org-in-buffer-settings
19697 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
19698 (modes . '(org-mode))))))
19700 (defun org-fill-item-nobreak-p ()
19701 "Non-nil when a line break at point would insert a new item."
19702 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
19704 (defun org-fill-paragraph (&optional justify)
19705 "Re-align a table, pass through to fill-paragraph if no table."
19706 (let ((table-p (org-at-table-p))
19707 (table.el-p (org-at-table.el-p))
19708 (itemp (org-in-item-p)))
19709 (cond ((and (equal (char-after (point-at-bol)) ?*)
19710 (save-excursion (goto-char (point-at-bol))
19711 (looking-at org-outline-regexp)))
19712 t) ; skip headlines
19713 (table.el-p t) ; skip table.el tables
19714 (table-p (org-table-align) t) ; align Org tables
19715 (itemp ; align text in items
19716 (let* ((struct (save-excursion (goto-char itemp)
19717 (org-list-struct)))
19718 (parents (org-list-parents-alist struct))
19719 (children (org-list-get-children itemp struct parents))
19720 beg end prev next prefix)
19721 ;; Determine in which part of item point is: before
19722 ;; first child, after last child, between two
19723 ;; sub-lists, or simply in item if there's no child.
19724 (cond
19725 ((not children)
19726 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19727 beg itemp
19728 end (org-list-get-item-end itemp struct)))
19729 ((< (point) (setq next (car children)))
19730 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19731 beg itemp
19732 end next))
19733 ((> (point) (setq prev (car (last children))))
19734 (setq beg (org-list-get-item-end prev struct)
19735 end (org-list-get-item-end itemp struct)
19736 prefix (save-excursion
19737 (goto-char beg)
19738 (skip-chars-forward " \t")
19739 (make-string (current-column) ?\ ))))
19740 (t (catch 'exit
19741 (while (setq next (pop children))
19742 (if (> (point) next)
19743 (setq prev next)
19744 (setq beg (org-list-get-item-end prev struct)
19745 end next
19746 prefix (save-excursion
19747 (goto-char beg)
19748 (skip-chars-forward " \t")
19749 (make-string (current-column) ?\ )))
19750 (throw 'exit nil))))))
19751 ;; Use `fill-paragraph' with buffer narrowed to item
19752 ;; without any child, and with our computed PREFIX.
19753 (flet ((fill-context-prefix (from to &optional flr) prefix))
19754 (save-restriction
19755 (narrow-to-region beg end)
19756 (save-excursion (fill-paragraph justify)))) t))
19757 ;; Special case where point is not in a list but is on
19758 ;; a paragraph adjacent to a list: make sure this paragraph
19759 ;; doesn't get merged with the end of the list by narrowing
19760 ;; buffer first.
19761 ((save-excursion (forward-paragraph -1)
19762 (setq itemp (org-in-item-p)))
19763 (let ((struct (save-excursion (goto-char itemp)
19764 (org-list-struct))))
19765 (save-restriction
19766 (narrow-to-region (org-list-get-bottom-point struct)
19767 (save-excursion (forward-paragraph 1)
19768 (point)))
19769 (fill-paragraph justify) t)))
19770 ;; Else simply call `fill-paragraph'.
19771 (t nil))))
19773 ;; For reference, this is the default value of adaptive-fill-regexp
19774 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
19776 (defun org-adaptive-fill-function ()
19777 "Return a fill prefix for org-mode files."
19778 (let (itemp)
19779 (save-excursion
19780 (cond
19781 ;; Comment line
19782 ((looking-at "#[ \t]+")
19783 (match-string-no-properties 0))
19784 ;; Plain list item
19785 ((org-at-item-p)
19786 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
19787 ;; Point is in a list after `backward-paragraph': original
19788 ;; point wasn't in the list, or filling would have been taken
19789 ;; care of by `org-auto-fill-function', but the list and the
19790 ;; real paragraph are not separated by a blank line. Thus, move
19791 ;; point after the list to go back to real paragraph and
19792 ;; determine fill-prefix.
19793 ((setq itemp (org-in-item-p))
19794 (goto-char itemp)
19795 (let* ((struct (org-list-struct))
19796 (bottom (org-list-get-bottom-point struct)))
19797 (goto-char bottom)
19798 (make-string (org-get-indentation) ?\ )))
19799 ;; Other text
19800 ((looking-at org-adaptive-fill-regexp-backup)
19801 (match-string-no-properties 0))))))
19803 (defun org-auto-fill-function ()
19804 "Auto-fill function."
19805 (let (itemp prefix)
19806 ;; When in a list, compute an appropriate fill-prefix and make
19807 ;; sure it will be used by `do-auto-fill'.
19808 (if (setq itemp (org-in-item-p))
19809 (progn
19810 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
19811 (flet ((fill-context-prefix (from to &optional flr) prefix))
19812 (do-auto-fill)))
19813 ;; Else just use `do-auto-fill'.
19814 (do-auto-fill))))
19816 ;;; Other stuff.
19818 (defun org-toggle-fixed-width-section (arg)
19819 "Toggle the fixed-width export.
19820 If there is no active region, the QUOTE keyword at the current headline is
19821 inserted or removed. When present, it causes the text between this headline
19822 and the next to be exported as fixed-width text, and unmodified.
19823 If there is an active region, this command adds or removes a colon as the
19824 first character of this line. If the first character of a line is a colon,
19825 this line is also exported in fixed-width font."
19826 (interactive "P")
19827 (let* ((cc 0)
19828 (regionp (org-region-active-p))
19829 (beg (if regionp (region-beginning) (point)))
19830 (end (if regionp (region-end)))
19831 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
19832 (case-fold-search nil)
19833 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
19834 off)
19835 (if regionp
19836 (save-excursion
19837 (goto-char beg)
19838 (setq cc (current-column))
19839 (beginning-of-line 1)
19840 (setq off (looking-at re))
19841 (while (> nlines 0)
19842 (setq nlines (1- nlines))
19843 (beginning-of-line 1)
19844 (cond
19845 (arg
19846 (org-move-to-column cc t)
19847 (insert ": \n")
19848 (forward-line -1))
19849 ((and off (looking-at re))
19850 (replace-match "" t t nil 1))
19851 ((not off) (org-move-to-column cc t) (insert ": ")))
19852 (forward-line 1)))
19853 (save-excursion
19854 (org-back-to-heading)
19855 (if (looking-at (concat org-outline-regexp
19856 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
19857 (replace-match "" t t nil 1)
19858 (if (looking-at org-outline-regexp)
19859 (progn
19860 (goto-char (match-end 0))
19861 (insert org-quote-string " "))))))))
19863 (defun org-reftex-citation ()
19864 "Use reftex-citation to insert a citation into the buffer.
19865 This looks for a line like
19867 #+BIBLIOGRAPHY: foo plain option:-d
19869 and derives from it that foo.bib is the bibliography file relevant
19870 for this document. It then installs the necessary environment for RefTeX
19871 to work in this buffer and calls `reftex-citation' to insert a citation
19872 into the buffer.
19874 Export of such citations to both LaTeX and HTML is handled by the contributed
19875 package org-exp-bibtex by Taru Karttunen."
19876 (interactive)
19877 (let ((reftex-docstruct-symbol 'rds)
19878 (reftex-cite-format "\\cite{%l}")
19879 rds bib)
19880 (save-excursion
19881 (save-restriction
19882 (widen)
19883 (let ((case-fold-search t)
19884 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
19885 (if (not (save-excursion
19886 (or (re-search-forward re nil t)
19887 (re-search-backward re nil t))))
19888 (error "No bibliography defined in file")
19889 (setq bib (concat (match-string 1) ".bib")
19890 rds (list (list 'bib bib)))))))
19891 (call-interactively 'reftex-citation)))
19893 ;;;; Functions extending outline functionality
19895 (defun org-beginning-of-line (&optional arg)
19896 "Go to the beginning of the current line. If that is invisible, continue
19897 to a visible line beginning. This makes the function of C-a more intuitive.
19898 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
19899 first attempt, and only move to after the tags when the cursor is already
19900 beyond the end of the headline."
19901 (interactive "P")
19902 (let ((pos (point))
19903 (special (if (consp org-special-ctrl-a/e)
19904 (car org-special-ctrl-a/e)
19905 org-special-ctrl-a/e))
19906 refpos)
19907 (if (org-bound-and-true-p line-move-visual)
19908 (beginning-of-visual-line 1)
19909 (beginning-of-line 1))
19910 (if (and arg (fboundp 'move-beginning-of-line))
19911 (call-interactively 'move-beginning-of-line)
19912 (if (bobp)
19914 (backward-char 1)
19915 (if (org-truely-invisible-p)
19916 (while (and (not (bobp)) (org-truely-invisible-p))
19917 (backward-char 1)
19918 (beginning-of-line 1))
19919 (forward-char 1))))
19920 (when special
19921 (cond
19922 ((and (looking-at org-complex-heading-regexp)
19923 (= (char-after (match-end 1)) ?\ ))
19924 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
19925 (point-at-eol)))
19926 (goto-char
19927 (if (eq special t)
19928 (cond ((> pos refpos) refpos)
19929 ((= pos (point)) refpos)
19930 (t (point)))
19931 (cond ((> pos (point)) (point))
19932 ((not (eq last-command this-command)) (point))
19933 (t refpos)))))
19934 ((org-at-item-p)
19935 (goto-char
19936 (if (eq special t)
19937 (cond ((> pos (match-end 0)) (match-end 0))
19938 ((= pos (point)) (match-end 0))
19939 (t (point)))
19940 (cond ((> pos (point)) (point))
19941 ((not (eq last-command this-command)) (point))
19942 (t (match-end 0))))))))
19943 (org-no-warnings
19944 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
19946 (defun org-end-of-line (&optional arg)
19947 "Go to the end of the line.
19948 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
19949 first attempt, and only move to after the tags when the cursor is already
19950 beyond the end of the headline."
19951 (interactive "P")
19952 (let ((special (if (consp org-special-ctrl-a/e)
19953 (cdr org-special-ctrl-a/e)
19954 org-special-ctrl-a/e)))
19955 (cond
19956 ((or (not special) arg
19957 (not (or (org-on-heading-p) (org-at-item-p))))
19958 (call-interactively
19959 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
19960 ((fboundp 'move-end-of-line) 'move-end-of-line)
19961 (t 'end-of-line))))
19962 ((org-on-heading-p)
19963 (let ((pos (point)))
19964 (beginning-of-line 1)
19965 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
19966 (if (eq special t)
19967 (if (or (< pos (match-beginning 1))
19968 (= pos (match-end 0)))
19969 (goto-char (match-beginning 1))
19970 (goto-char (match-end 0)))
19971 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
19972 (goto-char (match-end 0))
19973 (goto-char (match-beginning 1))))
19974 (call-interactively (if (fboundp 'move-end-of-line)
19975 'move-end-of-line
19976 'end-of-line)))))
19977 ;; At an item: Move before any hidden text.
19978 (t (call-interactively 'end-of-line)))
19979 (org-no-warnings
19980 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
19982 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
19983 (define-key org-mode-map "\C-e" 'org-end-of-line)
19985 (defun org-backward-sentence (&optional arg)
19986 "Go to beginning of sentence, or beginning of table field.
19987 This will call `backward-sentence' or `org-table-beginning-of-field',
19988 depending on context."
19989 (interactive "P")
19990 (cond
19991 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
19992 (t (call-interactively 'backward-sentence))))
19994 (defun org-forward-sentence (&optional arg)
19995 "Go to end of sentence, or end of table field.
19996 This will call `forward-sentence' or `org-table-end-of-field',
19997 depending on context."
19998 (interactive "P")
19999 (cond
20000 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
20001 (t (call-interactively 'forward-sentence))))
20003 (define-key org-mode-map "\M-a" 'org-backward-sentence)
20004 (define-key org-mode-map "\M-e" 'org-forward-sentence)
20006 (defun org-kill-line (&optional arg)
20007 "Kill line, to tags or end of line."
20008 (interactive "P")
20009 (cond
20010 ((or (not org-special-ctrl-k)
20011 (bolp)
20012 (not (org-on-heading-p)))
20013 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
20014 org-ctrl-k-protect-subtree)
20015 (if (or (eq org-ctrl-k-protect-subtree 'error)
20016 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
20017 (error "C-k aborted - would kill hidden subtree")))
20018 (call-interactively 'kill-line))
20019 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
20020 (kill-region (point) (match-beginning 1))
20021 (org-set-tags nil t))
20022 (t (kill-region (point) (point-at-eol)))))
20024 (define-key org-mode-map "\C-k" 'org-kill-line)
20026 (defun org-yank (&optional arg)
20027 "Yank. If the kill is a subtree, treat it specially.
20028 This command will look at the current kill and check if is a single
20029 subtree, or a series of subtrees[1]. If it passes the test, and if the
20030 cursor is at the beginning of a line or after the stars of a currently
20031 empty headline, then the yank is handled specially. How exactly depends
20032 on the value of the following variables, both set by default.
20034 org-yank-folded-subtrees
20035 When set, the subtree(s) will be folded after insertion, but only
20036 if doing so would now swallow text after the yanked text.
20038 org-yank-adjusted-subtrees
20039 When set, the subtree will be promoted or demoted in order to
20040 fit into the local outline tree structure, which means that the level
20041 will be adjusted so that it becomes the smaller one of the two
20042 *visible* surrounding headings.
20044 Any prefix to this command will cause `yank' to be called directly with
20045 no special treatment. In particular, a simple \\[universal-argument] prefix \
20046 will just
20047 plainly yank the text as it is.
20049 \[1] The test checks if the first non-white line is a heading
20050 and if there are no other headings with fewer stars."
20051 (interactive "P")
20052 (org-yank-generic 'yank arg))
20054 (defun org-yank-generic (command arg)
20055 "Perform some yank-like command.
20057 This function implements the behavior described in the `org-yank'
20058 documentation. However, it has been generalized to work for any
20059 interactive command with similar behavior."
20061 ;; pretend to be command COMMAND
20062 (setq this-command command)
20064 (if arg
20065 (call-interactively command)
20067 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
20068 (and (org-kill-is-subtree-p)
20069 (or (bolp)
20070 (and (looking-at "[ \t]*$")
20071 (string-match
20072 "\\`\\*+\\'"
20073 (buffer-substring (point-at-bol) (point)))))))
20074 swallowp)
20075 (cond
20076 ((and subtreep org-yank-folded-subtrees)
20077 (let ((beg (point))
20078 end)
20079 (if (and subtreep org-yank-adjusted-subtrees)
20080 (org-paste-subtree nil nil 'for-yank)
20081 (call-interactively command))
20083 (setq end (point))
20084 (goto-char beg)
20085 (when (and (bolp) subtreep
20086 (not (setq swallowp
20087 (org-yank-folding-would-swallow-text beg end))))
20088 (org-with-limited-levels
20089 (or (looking-at org-outline-regexp)
20090 (re-search-forward org-outline-regexp-bol end t))
20091 (while (and (< (point) end) (looking-at org-outline-regexp))
20092 (hide-subtree)
20093 (org-cycle-show-empty-lines 'folded)
20094 (condition-case nil
20095 (outline-forward-same-level 1)
20096 (error (goto-char end))))))
20097 (when swallowp
20098 (message
20099 "Inserted text not folded because that would swallow text"))
20101 (goto-char end)
20102 (skip-chars-forward " \t\n\r")
20103 (beginning-of-line 1)
20104 (push-mark beg 'nomsg)))
20105 ((and subtreep org-yank-adjusted-subtrees)
20106 (let ((beg (point-at-bol)))
20107 (org-paste-subtree nil nil 'for-yank)
20108 (push-mark beg 'nomsg)))
20110 (call-interactively command))))))
20112 (defun org-yank-folding-would-swallow-text (beg end)
20113 "Would hide-subtree at BEG swallow any text after END?"
20114 (let (level)
20115 (org-with-limited-levels
20116 (save-excursion
20117 (goto-char beg)
20118 (when (or (looking-at org-outline-regexp)
20119 (re-search-forward org-outline-regexp-bol end t))
20120 (setq level (org-outline-level)))
20121 (goto-char end)
20122 (skip-chars-forward " \t\r\n\v\f")
20123 (if (or (eobp)
20124 (and (bolp) (looking-at org-outline-regexp)
20125 (<= (org-outline-level) level)))
20126 nil ; Nothing would be swallowed
20127 t))))) ; something would swallow
20129 (define-key org-mode-map "\C-y" 'org-yank)
20131 (defun org-truely-invisible-p ()
20132 "Check if point is at a character currently not visible.
20133 This version does not only check the character property, but also
20134 `visible-mode'."
20135 ;; Early versions of noutline don't have `outline-invisible-p'.
20136 (if (org-bound-and-true-p visible-mode)
20138 (outline-invisible-p)))
20140 (defun org-invisible-p2 ()
20141 "Check if point is at a character currently not visible."
20142 (save-excursion
20143 (if (and (eolp) (not (bobp))) (backward-char 1))
20144 ;; Early versions of noutline don't have `outline-invisible-p'.
20145 (outline-invisible-p)))
20147 (defun org-back-to-heading (&optional invisible-ok)
20148 "Call `outline-back-to-heading', but provide a better error message."
20149 (condition-case nil
20150 (outline-back-to-heading invisible-ok)
20151 (error (error "Before first headline at position %d in buffer %s"
20152 (point) (current-buffer)))))
20154 (defun org-beginning-of-defun ()
20155 "Go to the beginning of the subtree, i.e. back to the heading."
20156 (org-back-to-heading))
20157 (defun org-end-of-defun ()
20158 "Go to the end of the subtree."
20159 (org-end-of-subtree nil t))
20161 (defun org-before-first-heading-p ()
20162 "Before first heading?"
20163 (save-excursion
20164 (end-of-line)
20165 (null (re-search-backward org-outline-regexp-bol nil t))))
20167 (defun org-on-heading-p (&optional ignored)
20168 (outline-on-heading-p t))
20169 (defun org-at-heading-p (&optional ignored)
20170 (outline-on-heading-p t))
20172 (defun org-point-at-end-of-empty-headline ()
20173 "If point is at the end of an empty headline, return t, else nil.
20174 If the heading only contains a TODO keyword, it is still still considered
20175 empty."
20176 (and (looking-at "[ \t]*$")
20177 (save-excursion
20178 (beginning-of-line 1)
20179 (let ((case-fold-search nil))
20180 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
20181 "\\)?[ \t]*$"))))))
20182 (defun org-at-heading-or-item-p ()
20183 (or (org-on-heading-p) (org-at-item-p)))
20185 (defun org-on-target-p ()
20186 (or (org-in-regexp org-radio-target-regexp)
20187 (org-in-regexp org-target-regexp)))
20189 (defun org-up-heading-all (arg)
20190 "Move to the heading line of which the present line is a subheading.
20191 This function considers both visible and invisible heading lines.
20192 With argument, move up ARG levels."
20193 (if (fboundp 'outline-up-heading-all)
20194 (outline-up-heading-all arg) ; emacs 21 version of outline.el
20195 (outline-up-heading arg t))) ; emacs 22 version of outline.el
20197 (defun org-up-heading-safe ()
20198 "Move to the heading line of which the present line is a subheading.
20199 This version will not throw an error. It will return the level of the
20200 headline found, or nil if no higher level is found.
20202 Also, this function will be a lot faster than `outline-up-heading',
20203 because it relies on stars being the outline starters. This can really
20204 make a significant difference in outlines with very many siblings."
20205 (let (start-level re)
20206 (org-back-to-heading t)
20207 (setq start-level (funcall outline-level))
20208 (if (equal start-level 1)
20210 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
20211 (if (re-search-backward re nil t)
20212 (funcall outline-level)))))
20214 (defun org-first-sibling-p ()
20215 "Is this heading the first child of its parents?"
20216 (interactive)
20217 (let ((re org-outline-regexp-bol)
20218 level l)
20219 (unless (org-at-heading-p t)
20220 (error "Not at a heading"))
20221 (setq level (funcall outline-level))
20222 (save-excursion
20223 (if (not (re-search-backward re nil t))
20225 (setq l (funcall outline-level))
20226 (< l level)))))
20228 (defun org-goto-sibling (&optional previous)
20229 "Goto the next sibling, even if it is invisible.
20230 When PREVIOUS is set, go to the previous sibling instead. Returns t
20231 when a sibling was found. When none is found, return nil and don't
20232 move point."
20233 (let ((fun (if previous 're-search-backward 're-search-forward))
20234 (pos (point))
20235 (re org-outline-regexp-bol)
20236 level l)
20237 (when (condition-case nil (org-back-to-heading t) (error nil))
20238 (setq level (funcall outline-level))
20239 (catch 'exit
20240 (or previous (forward-char 1))
20241 (while (funcall fun re nil t)
20242 (setq l (funcall outline-level))
20243 (when (< l level) (goto-char pos) (throw 'exit nil))
20244 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
20245 (goto-char pos)
20246 nil))))
20248 (defun org-show-siblings ()
20249 "Show all siblings of the current headline."
20250 (save-excursion
20251 (while (org-goto-sibling) (org-flag-heading nil)))
20252 (save-excursion
20253 (while (org-goto-sibling 'previous)
20254 (org-flag-heading nil))))
20256 (defun org-goto-first-child ()
20257 "Goto the first child, even if it is invisible.
20258 Return t when a child was found. Otherwise don't move point and
20259 return nil."
20260 (let (level (pos (point)) (re org-outline-regexp-bol))
20261 (when (condition-case nil (org-back-to-heading t) (error nil))
20262 (setq level (outline-level))
20263 (forward-char 1)
20264 (if (and (re-search-forward re nil t) (> (outline-level) level))
20265 (progn (goto-char (match-beginning 0)) t)
20266 (goto-char pos) nil))))
20268 (defun org-show-hidden-entry ()
20269 "Show an entry where even the heading is hidden."
20270 (save-excursion
20271 (org-show-entry)))
20273 (defun org-flag-heading (flag &optional entry)
20274 "Flag the current heading. FLAG non-nil means make invisible.
20275 When ENTRY is non-nil, show the entire entry."
20276 (save-excursion
20277 (org-back-to-heading t)
20278 ;; Check if we should show the entire entry
20279 (if entry
20280 (progn
20281 (org-show-entry)
20282 (save-excursion
20283 (and (outline-next-heading)
20284 (org-flag-heading nil))))
20285 (outline-flag-region (max (point-min) (1- (point)))
20286 (save-excursion (outline-end-of-heading) (point))
20287 flag))))
20289 (defun org-get-next-sibling ()
20290 "Move to next heading of the same level, and return point.
20291 If there is no such heading, return nil.
20292 This is like outline-next-sibling, but invisible headings are ok."
20293 (let ((level (funcall outline-level)))
20294 (outline-next-heading)
20295 (while (and (not (eobp)) (> (funcall outline-level) level))
20296 (outline-next-heading))
20297 (if (or (eobp) (< (funcall outline-level) level))
20299 (point))))
20301 (defun org-get-last-sibling ()
20302 "Move to previous heading of the same level, and return point.
20303 If there is no such heading, return nil."
20304 (let ((opoint (point))
20305 (level (funcall outline-level)))
20306 (outline-previous-heading)
20307 (when (and (/= (point) opoint) (outline-on-heading-p t))
20308 (while (and (> (funcall outline-level) level)
20309 (not (bobp)))
20310 (outline-previous-heading))
20311 (if (< (funcall outline-level) level)
20313 (point)))))
20315 (defun org-end-of-subtree (&optional invisible-OK to-heading)
20316 ;; This contains an exact copy of the original function, but it uses
20317 ;; `org-back-to-heading', to make it work also in invisible
20318 ;; trees. And is uses an invisible-OK argument.
20319 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
20320 ;; Furthermore, when used inside Org, finding the end of a large subtree
20321 ;; with many children and grandchildren etc, this can be much faster
20322 ;; than the outline version.
20323 (org-back-to-heading invisible-OK)
20324 (let ((first t)
20325 (level (funcall outline-level)))
20326 (if (and (org-mode-p) (< level 1000))
20327 ;; A true heading (not a plain list item), in Org-mode
20328 ;; This means we can easily find the end by looking
20329 ;; only for the right number of stars. Using a regexp to do
20330 ;; this is so much faster than using a Lisp loop.
20331 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
20332 (forward-char 1)
20333 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
20334 ;; something else, do it the slow way
20335 (while (and (not (eobp))
20336 (or first (> (funcall outline-level) level)))
20337 (setq first nil)
20338 (outline-next-heading)))
20339 (unless to-heading
20340 (if (memq (preceding-char) '(?\n ?\^M))
20341 (progn
20342 ;; Go to end of line before heading
20343 (forward-char -1)
20344 (if (memq (preceding-char) '(?\n ?\^M))
20345 ;; leave blank line before heading
20346 (forward-char -1))))))
20347 (point))
20349 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
20350 "Use Org version in org-mode, for dramatic speed-up."
20351 (if (org-mode-p)
20352 (progn
20353 (org-end-of-subtree nil t)
20354 (unless (eobp) (backward-char 1)))
20355 ad-do-it))
20357 (defun org-end-of-meta-data-and-drawers ()
20358 "Jump to the first text after meta data and drawers in the current entry.
20359 This will move over empty lines, lines with planning time stamps,
20360 clocking lines, and drawers."
20361 (org-back-to-heading t)
20362 (let ((end (save-excursion (outline-next-heading) (point)))
20363 (re (concat "\\(" org-drawer-regexp "\\)"
20364 "\\|" "[ \t]*" org-keyword-time-regexp)))
20365 (forward-line 1)
20366 (while (re-search-forward re end t)
20367 (if (not (match-end 1))
20368 ;; empty or planning line
20369 (forward-line 1)
20370 ;; a drawer, find the end
20371 (re-search-forward "^[ \t]*:END:" end 'move)
20372 (forward-line 1)))
20373 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
20374 (point)))
20376 (defun org-forward-same-level (arg &optional invisible-ok)
20377 "Move forward to the arg'th subheading at same level as this one.
20378 Stop at the first and last subheadings of a superior heading.
20379 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
20380 it wil also look at invisible ones."
20381 (interactive "p")
20382 (org-back-to-heading invisible-ok)
20383 (org-on-heading-p)
20384 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20385 (re (format "^\\*\\{1,%d\\} " level))
20387 (forward-char 1)
20388 (while (> arg 0)
20389 (while (and (re-search-forward re nil 'move)
20390 (setq l (- (match-end 0) (match-beginning 0) 1))
20391 (= l level)
20392 (not invisible-ok)
20393 (progn (backward-char 1) (outline-invisible-p)))
20394 (if (< l level) (setq arg 1)))
20395 (setq arg (1- arg)))
20396 (beginning-of-line 1)))
20398 (defun org-backward-same-level (arg &optional invisible-ok)
20399 "Move backward to the arg'th subheading at same level as this one.
20400 Stop at the first and last subheadings of a superior heading."
20401 (interactive "p")
20402 (org-back-to-heading)
20403 (org-on-heading-p)
20404 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20405 (re (format "^\\*\\{1,%d\\} " level))
20407 (while (> arg 0)
20408 (while (and (re-search-backward re nil 'move)
20409 (setq l (- (match-end 0) (match-beginning 0) 1))
20410 (= l level)
20411 (not invisible-ok)
20412 (outline-invisible-p))
20413 (if (< l level) (setq arg 1)))
20414 (setq arg (1- arg)))))
20416 (defun org-show-subtree ()
20417 "Show everything after this heading at deeper levels."
20418 (outline-flag-region
20419 (point)
20420 (save-excursion
20421 (org-end-of-subtree t t))
20422 nil))
20424 (defun org-show-entry ()
20425 "Show the body directly following this heading.
20426 Show the heading too, if it is currently invisible."
20427 (interactive)
20428 (save-excursion
20429 (condition-case nil
20430 (progn
20431 (org-back-to-heading t)
20432 (outline-flag-region
20433 (max (point-min) (1- (point)))
20434 (save-excursion
20435 (if (re-search-forward
20436 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
20437 (match-beginning 1)
20438 (point-max)))
20439 nil)
20440 (org-cycle-hide-drawers 'children))
20441 (error nil))))
20443 (defun org-make-options-regexp (kwds &optional extra)
20444 "Make a regular expression for keyword lines."
20445 (concat
20447 "#?[ \t]*\\+\\("
20448 (mapconcat 'regexp-quote kwds "\\|")
20449 (if extra (concat "\\|" extra))
20450 "\\):[ \t]*"
20451 "\\(.*\\)"))
20453 ;; Make isearch reveal the necessary context
20454 (defun org-isearch-end ()
20455 "Reveal context after isearch exits."
20456 (when isearch-success ; only if search was successful
20457 (if (featurep 'xemacs)
20458 ;; Under XEmacs, the hook is run in the correct place,
20459 ;; we directly show the context.
20460 (org-show-context 'isearch)
20461 ;; In Emacs the hook runs *before* restoring the overlays.
20462 ;; So we have to use a one-time post-command-hook to do this.
20463 ;; (Emacs 22 has a special variable, see function `org-mode')
20464 (unless (and (boundp 'isearch-mode-end-hook-quit)
20465 isearch-mode-end-hook-quit)
20466 ;; Only when the isearch was not quitted.
20467 (org-add-hook 'post-command-hook 'org-isearch-post-command
20468 'append 'local)))))
20470 (defun org-isearch-post-command ()
20471 "Remove self from hook, and show context."
20472 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
20473 (org-show-context 'isearch))
20476 ;;;; Integration with and fixes for other packages
20478 ;;; Imenu support
20480 (defvar org-imenu-markers nil
20481 "All markers currently used by Imenu.")
20482 (make-variable-buffer-local 'org-imenu-markers)
20484 (defun org-imenu-new-marker (&optional pos)
20485 "Return a new marker for use by Imenu, and remember the marker."
20486 (let ((m (make-marker)))
20487 (move-marker m (or pos (point)))
20488 (push m org-imenu-markers)
20491 (defun org-imenu-get-tree ()
20492 "Produce the index for Imenu."
20493 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
20494 (setq org-imenu-markers nil)
20495 (let* ((n org-imenu-depth)
20496 (re (concat "^" (org-get-limited-outline-regexp)))
20497 (subs (make-vector (1+ n) nil))
20498 (last-level 0)
20499 m level head)
20500 (save-excursion
20501 (save-restriction
20502 (widen)
20503 (goto-char (point-max))
20504 (while (re-search-backward re nil t)
20505 (setq level (org-reduced-level (funcall outline-level)))
20506 (when (<= level n)
20507 (looking-at org-complex-heading-regexp)
20508 (setq head (org-link-display-format
20509 (org-match-string-no-properties 4))
20510 m (org-imenu-new-marker))
20511 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
20512 (if (>= level last-level)
20513 (push (cons head m) (aref subs level))
20514 (push (cons head (aref subs (1+ level))) (aref subs level))
20515 (loop for i from (1+ level) to n do (aset subs i nil)))
20516 (setq last-level level)))))
20517 (aref subs 1)))
20519 (eval-after-load "imenu"
20520 '(progn
20521 (add-hook 'imenu-after-jump-hook
20522 (lambda ()
20523 (if (org-mode-p)
20524 (org-show-context 'org-goto))))))
20526 (defun org-link-display-format (link)
20527 "Replace a link with either the description, or the link target
20528 if no description is present"
20529 (save-match-data
20530 (if (string-match org-bracket-link-analytic-regexp link)
20531 (replace-match (if (match-end 5)
20532 (match-string 5 link)
20533 (concat (match-string 1 link)
20534 (match-string 3 link)))
20535 nil t link)
20536 link)))
20538 (defun org-toggle-link-display ()
20539 "Toggle the literal or descriptive display of links."
20540 (interactive)
20541 (if org-descriptive-links
20542 (progn (org-remove-from-invisibility-spec '(org-link))
20543 (org-restart-font-lock)
20544 (setq org-descriptive-links nil))
20545 (progn (add-to-invisibility-spec '(org-link))
20546 (org-restart-font-lock)
20547 (setq org-descriptive-links t))))
20549 ;; Speedbar support
20551 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
20552 "Overlay marking the agenda restriction line in speedbar.")
20553 (overlay-put org-speedbar-restriction-lock-overlay
20554 'face 'org-agenda-restriction-lock)
20555 (overlay-put org-speedbar-restriction-lock-overlay
20556 'help-echo "Agendas are currently limited to this item.")
20557 (org-detach-overlay org-speedbar-restriction-lock-overlay)
20559 (defun org-speedbar-set-agenda-restriction ()
20560 "Restrict future agenda commands to the location at point in speedbar.
20561 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
20562 (interactive)
20563 (require 'org-agenda)
20564 (let (p m tp np dir txt)
20565 (cond
20566 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20567 'org-imenu t))
20568 (setq m (get-text-property p 'org-imenu-marker))
20569 (with-current-buffer (marker-buffer m)
20570 (goto-char m)
20571 (org-agenda-set-restriction-lock 'subtree)))
20572 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20573 'speedbar-function 'speedbar-find-file))
20574 (setq tp (previous-single-property-change
20575 (1+ p) 'speedbar-function)
20576 np (next-single-property-change
20577 tp 'speedbar-function)
20578 dir (speedbar-line-directory)
20579 txt (buffer-substring-no-properties (or tp (point-min))
20580 (or np (point-max))))
20581 (with-current-buffer (find-file-noselect
20582 (let ((default-directory dir))
20583 (expand-file-name txt)))
20584 (unless (org-mode-p)
20585 (error "Cannot restrict to non-Org-mode file"))
20586 (org-agenda-set-restriction-lock 'file)))
20587 (t (error "Don't know how to restrict Org-mode's agenda")))
20588 (move-overlay org-speedbar-restriction-lock-overlay
20589 (point-at-bol) (point-at-eol))
20590 (setq current-prefix-arg nil)
20591 (org-agenda-maybe-redo)))
20593 (eval-after-load "speedbar"
20594 '(progn
20595 (speedbar-add-supported-extension ".org")
20596 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
20597 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
20598 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
20599 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
20600 (add-hook 'speedbar-visiting-tag-hook
20601 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
20603 ;;; Fixes and Hacks for problems with other packages
20605 ;; Make flyspell not check words in links, to not mess up our keymap
20606 (defun org-mode-flyspell-verify ()
20607 "Don't let flyspell put overlays at active buttons, or on
20608 {todo,all-time,additional-option-like}-keywords."
20609 (let ((pos (max (1- (point)) (point-min)))
20610 (word (thing-at-point 'word)))
20611 (and (not (get-text-property pos 'keymap))
20612 (not (get-text-property pos 'org-no-flyspell))
20613 (not (member word org-todo-keywords-1))
20614 (not (member word org-all-time-keywords))
20615 (not (member word org-additional-option-like-keywords)))))
20617 (defun org-remove-flyspell-overlays-in (beg end)
20618 "Remove flyspell overlays in region."
20619 (and (org-bound-and-true-p flyspell-mode)
20620 (fboundp 'flyspell-delete-region-overlays)
20621 (flyspell-delete-region-overlays beg end))
20622 (add-text-properties beg end '(org-no-flyspell t)))
20624 ;; Make `bookmark-jump' shows the jump location if it was hidden.
20625 (eval-after-load "bookmark"
20626 '(if (boundp 'bookmark-after-jump-hook)
20627 ;; We can use the hook
20628 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
20629 ;; Hook not available, use advice
20630 (defadvice bookmark-jump (after org-make-visible activate)
20631 "Make the position visible."
20632 (org-bookmark-jump-unhide))))
20634 ;; Make sure saveplace shows the location if it was hidden
20635 (eval-after-load "saveplace"
20636 '(defadvice save-place-find-file-hook (after org-make-visible activate)
20637 "Make the position visible."
20638 (org-bookmark-jump-unhide)))
20640 ;; Make sure ecb shows the location if it was hidden
20641 (eval-after-load "ecb"
20642 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
20643 "Make hierarchy visible when jumping into location from ECB tree buffer."
20644 (if (org-mode-p)
20645 (org-show-context))))
20647 (defun org-bookmark-jump-unhide ()
20648 "Unhide the current position, to show the bookmark location."
20649 (and (org-mode-p)
20650 (or (outline-invisible-p)
20651 (save-excursion (goto-char (max (point-min) (1- (point))))
20652 (outline-invisible-p)))
20653 (org-show-context 'bookmark-jump)))
20655 ;; Make session.el ignore our circular variable
20656 (eval-after-load "session"
20657 '(add-to-list 'session-globals-exclude 'org-mark-ring))
20659 ;;;; Experimental code
20661 (defun org-closed-in-range ()
20662 "Sparse tree of items closed in a certain time range.
20663 Still experimental, may disappear in the future."
20664 (interactive)
20665 ;; Get the time interval from the user.
20666 (let* ((time1 (org-float-time
20667 (org-read-date nil 'to-time nil "Starting date: ")))
20668 (time2 (org-float-time
20669 (org-read-date nil 'to-time nil "End date:")))
20670 ;; callback function
20671 (callback (lambda ()
20672 (let ((time
20673 (org-float-time
20674 (apply 'encode-time
20675 (org-parse-time-string
20676 (match-string 1))))))
20677 ;; check if time in interval
20678 (and (>= time time1) (<= time time2))))))
20679 ;; make tree, check each match with the callback
20680 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
20682 ;;;; Finish up
20684 (provide 'org)
20686 (run-hooks 'org-load-hook)
20688 ;;; org.el ends here