Wondering if error messages ought to be standardized?
[org-mode.git] / lisp / org.el
blob6118e13960c8030d400fe71792d3706369fa3cd8
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010
4 ;; Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 6.36trans
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)
78 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
79 (when (fboundp 'defvaralias)
80 (unless (boundp 'calendar-view-holidays-initially-flag)
81 (defvaralias 'calendar-view-holidays-initially-flag
82 'view-calendar-holidays-initially))
83 (unless (boundp 'calendar-view-diary-initially-flag)
84 (defvaralias 'calendar-view-diary-initially-flag
85 'view-diary-entries-initially))
86 (unless (boundp 'diary-fancy-buffer)
87 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
89 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
90 ;; the file noutline.el being loaded.
91 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
92 ;; We require noutline, which might be provided in outline.el
93 (require 'outline) (require 'noutline)
94 ;; Other stuff we need.
95 (require 'time-date)
96 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
97 (require 'easymenu)
98 (require 'overlay)
100 (require 'org-macs)
101 (require 'org-entities)
102 (require 'org-compat)
103 (require 'org-faces)
104 (require 'org-list)
105 (require 'org-src)
106 (require 'org-footnote)
108 ;; babel
109 (require 'ob)
110 (require 'ob-table)
111 (require 'ob-lob)
112 (require 'ob-ref)
113 (require 'ob-tangle)
114 (require 'ob-comint)
115 (require 'ob-keys)
117 ;; load languages based on value of `org-babel-load-languages'
118 (defvar org-babel-load-languages)
119 ;;;###autoload
120 (defun org-babel-do-load-languages (sym value)
121 "Load the languages defined in `org-babel-load-languages'."
122 (set-default sym value)
123 (mapc (lambda (pair)
124 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
125 (if active
126 (progn
127 (require (intern (concat "ob-" lang))))
128 (progn
129 (funcall 'fmakunbound
130 (intern (concat "org-babel-execute:" lang)))
131 (funcall 'fmakunbound
132 (intern (concat "org-babel-expand-body:" lang)))))))
133 org-babel-load-languages))
135 (defcustom org-babel-load-languages '((emacs-lisp . t))
136 "Languages which can be evaluated in Org-mode buffers. This
137 list can be used to load support for any of the languages below,
138 note that each language will depend on a different set of system
139 executables and/or Emacs modes. When a language is \"loaded\",
140 then code blocks in that language can be evaluated with
141 `org-babel-execute-src-block' bound by default to C-c C-c (note
142 the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be set to
143 remove code block evaluation from the C-c C-c keybinding. By
144 default only Emacs Lisp (which has no requirements) is loaded."
145 :group 'org-babel
146 :set 'org-babel-do-load-languages
147 :type '(alist :tag "Babel Languages"
148 :key-type
149 (choice
150 (const :tag "C" C)
151 (const :tag "R" R)
152 (const :tag "Asymptote" asymptote)
153 (const :tag "Clojure" clojure)
154 (const :tag "CSS" css)
155 (const :tag "Ditaa" ditaa)
156 (const :tag "Dot" dot)
157 (const :tag "Emacs Lisp" emacs-lisp)
158 (const :tag "Gnuplot" gnuplot)
159 (const :tag "Haskell" haskell)
160 (const :tag "Latex" latex)
161 (const :tag "Matlab" matlab)
162 (const :tag "Mscgen" mscgen)
163 (const :tag "Ocaml" ocaml)
164 (const :tag "Octave" octave)
165 (const :tag "Perl" perl)
166 (const :tag "Python" python)
167 (const :tag "Ruby" ruby)
168 (const :tag "Sass" sass)
169 (const :tag "Screen" screen)
170 (const :tag "Shell Script" sh)
171 (const :tag "Sql" sql)
172 (const :tag "Sqlite" sqlite))
173 :value-type (boolean :tag "Activate" :value t)))
175 ;;;; Customization variables
176 (defcustom org-clone-delete-id nil
177 "Remove ID property of clones of a subtree.
178 When non-nil, clones of a subtree don't inherit the ID property.
179 Otherwise they inherit the ID property with a new unique
180 identifier."
181 :type 'boolean
182 :group 'org-id)
184 ;;; Version
186 (defconst org-version "6.36trans"
187 "The version number of the file org.el.")
189 (defun org-version (&optional here)
190 "Show the org-mode version in the echo area.
191 With prefix arg HERE, insert it at point."
192 (interactive "P")
193 (let* ((origin default-directory)
194 (version org-version)
195 (git-version)
196 (dir (concat (file-name-directory (locate-library "org")) "../" )))
197 (when (and (file-exists-p (expand-file-name ".git" dir))
198 (executable-find "git"))
199 (unwind-protect
200 (progn
201 (cd dir)
202 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
203 (with-current-buffer "*Shell Command Output*"
204 (goto-char (point-min))
205 (setq git-version (buffer-substring (point) (point-at-eol))))
206 (subst-char-in-string ?- ?. git-version t)
207 (when (string-match "\\S-"
208 (shell-command-to-string
209 "git diff-index --name-only HEAD --"))
210 (setq git-version (concat git-version ".dirty")))
211 (setq version (concat version " (" git-version ")"))))
212 (cd origin)))
213 (setq version (format "Org-mode version %s" version))
214 (if here (insert version))
215 (message version)))
217 ;;; Compatibility constants
219 ;;; The custom variables
221 (defgroup org nil
222 "Outline-based notes management and organizer."
223 :tag "Org"
224 :group 'outlines
225 :group 'calendar)
227 (defcustom org-mode-hook nil
228 "Mode hook for Org-mode, run after the mode was turned on."
229 :group 'org
230 :type 'hook)
232 (defcustom org-load-hook nil
233 "Hook that is run after org.el has been loaded."
234 :group 'org
235 :type 'hook)
237 (defvar org-modules) ; defined below
238 (defvar org-modules-loaded nil
239 "Have the modules been loaded already?")
241 (defun org-load-modules-maybe (&optional force)
242 "Load all extensions listed in `org-modules'."
243 (when (or force (not org-modules-loaded))
244 (mapc (lambda (ext)
245 (condition-case nil (require ext)
246 (error (message "Problems while trying to load feature `%s'" ext))))
247 org-modules)
248 (setq org-modules-loaded t)))
250 (defun org-set-modules (var value)
251 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
252 (set var value)
253 (when (featurep 'org)
254 (org-load-modules-maybe 'force)))
256 (when (org-bound-and-true-p org-modules)
257 (let ((a (member 'org-infojs org-modules)))
258 (and a (setcar a 'org-jsinfo))))
260 (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)
261 "Modules that should always be loaded together with org.el.
262 If a description starts with <C>, the file is not part of Emacs
263 and loading it will require that you have downloaded and properly installed
264 the org-mode distribution.
266 You can also use this system to load external packages (i.e. neither Org
267 core modules, nor modules from the CONTRIB directory). Just add symbols
268 to the end of the list. If the package is called org-xyz.el, then you need
269 to add the symbol `xyz', and the package must have a call to
271 (provide 'org-xyz)"
272 :group 'org
273 :set 'org-set-modules
274 :type
275 '(set :greedy t
276 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
277 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
278 (const :tag " crypt: Encryption of subtrees" org-crypt)
279 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
280 (const :tag " docview: Links to doc-view buffers" org-docview)
281 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
282 (const :tag " id: Global IDs for identifying entries" org-id)
283 (const :tag " info: Links to Info nodes" org-info)
284 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
285 (const :tag " habit: Track your consistency with habits" org-habit)
286 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
287 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
288 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
289 (const :tag " mew Links to Mew folders/messages" org-mew)
290 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
291 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
292 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
293 (const :tag " vm: Links to VM folders/messages" org-vm)
294 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
295 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
296 (const :tag " mouse: Additional mouse support" org-mouse)
298 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
299 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
300 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
301 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
302 (const :tag "C collector: Collect properties into tables" org-collector)
303 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
304 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
305 (const :tag "C eval: Include command output as text" org-eval)
306 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
307 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
308 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
309 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
310 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
312 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
314 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
315 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
316 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
317 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
318 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
319 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
320 (const :tag "C mtags: Support for muse-like tags" org-mtags)
321 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
322 (const :tag "C registry: A registry for Org-mode links" org-registry)
323 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
324 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
325 (const :tag "C secretary: Team management with org-mode" org-secretary)
326 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
327 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
328 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
329 (const :tag "C track: Keep up with Org-mode development" org-track)
330 (const :tag "C TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
331 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
333 (defcustom org-support-shift-select nil
334 "Non-nil means make shift-cursor commands select text when possible.
336 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
337 selecting a region, or enlarge thusly regions started in this way.
338 In Org-mode, in special contexts, these same keys are used for other
339 purposes, important enough to compete with shift selection. Org tries
340 to balance these needs by supporting `shift-select-mode' outside these
341 special contexts, under control of this variable.
343 The default of this variable is nil, to avoid confusing behavior. Shifted
344 cursor keys will then execute Org commands in the following contexts:
345 - on a headline, changing TODO state (left/right) and priority (up/down)
346 - on a time stamp, changing the time
347 - in a plain list item, changing the bullet type
348 - in a property definition line, switching between allowed values
349 - in the BEGIN line of a clock table (changing the time block).
350 Outside these contexts, the commands will throw an error.
352 When this variable is t and the cursor is not in a special context,
353 Org-mode will support shift-selection for making and enlarging regions.
354 To make this more effective, the bullet cycling will no longer happen
355 anywhere in an item line, but only if the cursor is exactly on the bullet.
357 If you set this variable to the symbol `always', then the keys
358 will not be special in headlines, property lines, and item lines, to make
359 shift selection work there as well. If this is what you want, you can
360 use the following alternative commands: `C-c C-t' and `C-c ,' to
361 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
362 TODO sets, `C-c -' to cycle item bullet types, and properties can be
363 edited by hand or in column view.
365 However, when the cursor is on a timestamp, shift-cursor commands
366 will still edit the time stamp - this is just too good to give up.
368 XEmacs user should have this variable set to nil, because shift-select-mode
369 is Emacs 23 only."
370 :group 'org
371 :type '(choice
372 (const :tag "Never" nil)
373 (const :tag "When outside special context" t)
374 (const :tag "Everywhere except timestamps" always)))
376 (defgroup org-startup nil
377 "Options concerning startup of Org-mode."
378 :tag "Org Startup"
379 :group 'org)
381 (defcustom org-startup-folded t
382 "Non-nil means entering Org-mode will switch to OVERVIEW.
383 This can also be configured on a per-file basis by adding one of
384 the following lines anywhere in the buffer:
386 #+STARTUP: fold (or `overview', this is equivalent)
387 #+STARTUP: nofold (or `showall', this is equivalent)
388 #+STARTUP: content
389 #+STARTUP: showeverything"
390 :group 'org-startup
391 :type '(choice
392 (const :tag "nofold: show all" nil)
393 (const :tag "fold: overview" t)
394 (const :tag "content: all headlines" content)
395 (const :tag "show everything, even drawers" showeverything)))
397 (defcustom org-startup-truncated t
398 "Non-nil means entering Org-mode will set `truncate-lines'.
399 This is useful since some lines containing links can be very long and
400 uninteresting. Also tables look terrible when wrapped."
401 :group 'org-startup
402 :type 'boolean)
404 (defcustom org-startup-indented nil
405 "Non-nil means turn on `org-indent-mode' on startup.
406 This can also be configured on a per-file basis by adding one of
407 the following lines anywhere in the buffer:
409 #+STARTUP: indent
410 #+STARTUP: noindent"
411 :group 'org-structure
412 :type '(choice
413 (const :tag "Not" nil)
414 (const :tag "Globally (slow on startup in large files)" t)))
416 (defcustom org-use-sub-superscripts t
417 "Non-nil means interpret \"_\" and \"^\" for export.
418 When this option is turned on, you can use TeX-like syntax for sub- and
419 superscripts. Several characters after \"_\" or \"^\" will be
420 considered as a single item - so grouping with {} is normally not
421 needed. For example, the following things will be parsed as single
422 sub- or superscripts.
424 10^24 or 10^tau several digits will be considered 1 item.
425 10^-12 or 10^-tau a leading sign with digits or a word
426 x^2-y^3 will be read as x^2 - y^3, because items are
427 terminated by almost any nonword/nondigit char.
428 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
430 Still, ambiguity is possible - so when in doubt use {} to enclose the
431 sub/superscript. If you set this variable to the symbol `{}',
432 the braces are *required* in order to trigger interpretations as
433 sub/superscript. This can be helpful in documents that need \"_\"
434 frequently in plain text.
436 Not all export backends support this, but HTML does.
438 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
439 :group 'org-startup
440 :group 'org-export-translation
441 :type '(choice
442 (const :tag "Always interpret" t)
443 (const :tag "Only with braces" {})
444 (const :tag "Never interpret" nil)))
446 (if (fboundp 'defvaralias)
447 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
450 (defcustom org-startup-with-beamer-mode nil
451 "Non-nil means turn on `org-beamer-mode' on startup.
452 This can also be configured on a per-file basis by adding one of
453 the following lines anywhere in the buffer:
455 #+STARTUP: beamer"
456 :group 'org-startup
457 :type 'boolean)
459 (defcustom org-startup-align-all-tables nil
460 "Non-nil means align all tables when visiting a file.
461 This is useful when the column width in tables is forced with <N> cookies
462 in table fields. Such tables will look correct only after the first re-align.
463 This can also be configured on a per-file basis by adding one of
464 the following lines anywhere in the buffer:
465 #+STARTUP: align
466 #+STARTUP: noalign"
467 :group 'org-startup
468 :type 'boolean)
470 (defcustom org-insert-mode-line-in-empty-file nil
471 "Non-nil means insert the first line setting Org-mode in empty files.
472 When the function `org-mode' is called interactively in an empty file, this
473 normally means that the file name does not automatically trigger Org-mode.
474 To ensure that the file will always be in Org-mode in the future, a
475 line enforcing Org-mode will be inserted into the buffer, if this option
476 has been set."
477 :group 'org-startup
478 :type 'boolean)
480 (defcustom org-replace-disputed-keys nil
481 "Non-nil means use alternative key bindings for some keys.
482 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
483 These keys are also used by other packages like shift-selection-mode'
484 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
485 If you want to use Org-mode together with one of these other modes,
486 or more generally if you would like to move some Org-mode commands to
487 other keys, set this variable and configure the keys with the variable
488 `org-disputed-keys'.
490 This option is only relevant at load-time of Org-mode, and must be set
491 *before* org.el is loaded. Changing it requires a restart of Emacs to
492 become effective."
493 :group 'org-startup
494 :type 'boolean)
496 (defcustom org-use-extra-keys nil
497 "Non-nil means use extra key sequence definitions for certain
498 commands. This happens automatically if you run XEmacs or if
499 window-system is nil. This variable lets you do the same
500 manually. You must set it before loading org.
502 Example: on Carbon Emacs 22 running graphically, with an external
503 keyboard on a Powerbook, the default way of setting M-left might
504 not work for either Alt or ESC. Setting this variable will make
505 it work for ESC."
506 :group 'org-startup
507 :type 'boolean)
509 (if (fboundp 'defvaralias)
510 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
512 (defcustom org-disputed-keys
513 '(([(shift up)] . [(meta p)])
514 ([(shift down)] . [(meta n)])
515 ([(shift left)] . [(meta -)])
516 ([(shift right)] . [(meta +)])
517 ([(control shift right)] . [(meta shift +)])
518 ([(control shift left)] . [(meta shift -)]))
519 "Keys for which Org-mode and other modes compete.
520 This is an alist, cars are the default keys, second element specifies
521 the alternative to use when `org-replace-disputed-keys' is t.
523 Keys can be specified in any syntax supported by `define-key'.
524 The value of this option takes effect only at Org-mode's startup,
525 therefore you'll have to restart Emacs to apply it after changing."
526 :group 'org-startup
527 :type 'alist)
529 (defun org-key (key)
530 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
531 Or return the original if not disputed.
532 Also apply the trnaslations defined in `org-xemacs-key-equivalents'."
533 (when org-replace-disputed-keys
534 (let* ((nkey (key-description key))
535 (x (org-find-if (lambda (x)
536 (equal (key-description (car x)) nkey))
537 org-disputed-keys)))
538 (setq key (if x (cdr x) key))))
539 (when (featurep 'xemacs)
540 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
541 key)
543 (defun org-find-if (predicate seq)
544 (catch 'exit
545 (while seq
546 (if (funcall predicate (car seq))
547 (throw 'exit (car seq))
548 (pop seq)))))
550 (defun org-defkey (keymap key def)
551 "Define a key, possibly translated, as returned by `org-key'."
552 (define-key keymap (org-key key) def))
554 (defcustom org-ellipsis nil
555 "The ellipsis to use in the Org-mode outline.
556 When nil, just use the standard three dots. When a string, use that instead,
557 When a face, use the standard 3 dots, but with the specified face.
558 The change affects only Org-mode (which will then use its own display table).
559 Changing this requires executing `M-x org-mode' in a buffer to become
560 effective."
561 :group 'org-startup
562 :type '(choice (const :tag "Default" nil)
563 (face :tag "Face" :value org-warning)
564 (string :tag "String" :value "...#")))
566 (defvar org-display-table nil
567 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
569 (defgroup org-keywords nil
570 "Keywords in Org-mode."
571 :tag "Org Keywords"
572 :group 'org)
574 (defcustom org-deadline-string "DEADLINE:"
575 "String to mark deadline entries.
576 A deadline is this string, followed by a time stamp. Should be a word,
577 terminated by a colon. You can insert a schedule keyword and
578 a timestamp with \\[org-deadline].
579 Changes become only effective after restarting Emacs."
580 :group 'org-keywords
581 :type 'string)
583 (defcustom org-scheduled-string "SCHEDULED:"
584 "String to mark scheduled TODO entries.
585 A schedule is this string, followed by a time stamp. Should be a word,
586 terminated by a colon. You can insert a schedule keyword and
587 a timestamp with \\[org-schedule].
588 Changes become only effective after restarting Emacs."
589 :group 'org-keywords
590 :type 'string)
592 (defcustom org-closed-string "CLOSED:"
593 "String used as the prefix for timestamps logging closing a TODO entry."
594 :group 'org-keywords
595 :type 'string)
597 (defcustom org-clock-string "CLOCK:"
598 "String used as prefix for timestamps clocking work hours on an item."
599 :group 'org-keywords
600 :type 'string)
602 (defcustom org-comment-string "COMMENT"
603 "Entries starting with this keyword will never be exported.
604 An entry can be toggled between COMMENT and normal with
605 \\[org-toggle-comment].
606 Changes become only effective after restarting Emacs."
607 :group 'org-keywords
608 :type 'string)
610 (defcustom org-quote-string "QUOTE"
611 "Entries starting with this keyword will be exported in fixed-width font.
612 Quoting applies only to the text in the entry following the headline, and does
613 not extend beyond the next headline, even if that is lower level.
614 An entry can be toggled between QUOTE and normal with
615 \\[org-toggle-fixed-width-section]."
616 :group 'org-keywords
617 :type 'string)
619 (defconst org-repeat-re
620 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
621 "Regular expression for specifying repeated events.
622 After a match, group 1 contains the repeat expression.")
624 (defgroup org-structure nil
625 "Options concerning the general structure of Org-mode files."
626 :tag "Org Structure"
627 :group 'org)
629 (defgroup org-reveal-location nil
630 "Options about how to make context of a location visible."
631 :tag "Org Reveal Location"
632 :group 'org-structure)
634 (defconst org-context-choice
635 '(choice
636 (const :tag "Always" t)
637 (const :tag "Never" nil)
638 (repeat :greedy t :tag "Individual contexts"
639 (cons
640 (choice :tag "Context"
641 (const agenda)
642 (const org-goto)
643 (const occur-tree)
644 (const tags-tree)
645 (const link-search)
646 (const mark-goto)
647 (const bookmark-jump)
648 (const isearch)
649 (const default))
650 (boolean))))
651 "Contexts for the reveal options.")
653 (defcustom org-show-hierarchy-above '((default . t))
654 "Non-nil means show full hierarchy when revealing a location.
655 Org-mode often shows locations in an org-mode file which might have
656 been invisible before. When this is set, the hierarchy of headings
657 above the exposed location is shown.
658 Turning this off for example for sparse trees makes them very compact.
659 Instead of t, this can also be an alist specifying this option for different
660 contexts. Valid contexts are
661 agenda when exposing an entry from the agenda
662 org-goto when using the command `org-goto' on key C-c C-j
663 occur-tree when using the command `org-occur' on key C-c /
664 tags-tree when constructing a sparse tree based on tags matches
665 link-search when exposing search matches associated with a link
666 mark-goto when exposing the jump goal of a mark
667 bookmark-jump when exposing a bookmark location
668 isearch when exiting from an incremental search
669 default default for all contexts not set explicitly"
670 :group 'org-reveal-location
671 :type org-context-choice)
673 (defcustom org-show-following-heading '((default . nil))
674 "Non-nil means show following heading when revealing a location.
675 Org-mode often shows locations in an org-mode file which might have
676 been invisible before. When this is set, the heading following the
677 match is shown.
678 Turning this off for example for sparse trees makes them very compact,
679 but makes it harder to edit the location of the match. In such a case,
680 use the command \\[org-reveal] to show more context.
681 Instead of t, this can also be an alist specifying this option for different
682 contexts. See `org-show-hierarchy-above' for valid contexts."
683 :group 'org-reveal-location
684 :type org-context-choice)
686 (defcustom org-show-siblings '((default . nil) (isearch t))
687 "Non-nil means show all sibling heading when revealing a location.
688 Org-mode often shows locations in an org-mode file which might have
689 been invisible before. When this is set, the sibling of the current entry
690 heading are all made visible. If `org-show-hierarchy-above' is t,
691 the same happens on each level of the hierarchy above the current entry.
693 By default this is on for the isearch context, off for all other contexts.
694 Turning this off for example for sparse trees makes them very compact,
695 but makes it harder to edit the location of the match. In such a case,
696 use the command \\[org-reveal] to show more context.
697 Instead of t, this can also be an alist specifying this option for different
698 contexts. See `org-show-hierarchy-above' for valid contexts."
699 :group 'org-reveal-location
700 :type org-context-choice)
702 (defcustom org-show-entry-below '((default . nil))
703 "Non-nil means show the entry below a headline when revealing a location.
704 Org-mode often shows locations in an org-mode file which might have
705 been invisible before. When this is set, the text below the headline that is
706 exposed is also shown.
708 By default this is off for all contexts.
709 Instead of t, this can also be an alist specifying this option for different
710 contexts. See `org-show-hierarchy-above' for valid contexts."
711 :group 'org-reveal-location
712 :type org-context-choice)
714 (defcustom org-indirect-buffer-display 'other-window
715 "How should indirect tree buffers be displayed?
716 This applies to indirect buffers created with the commands
717 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
718 Valid values are:
719 current-window Display in the current window
720 other-window Just display in another window.
721 dedicated-frame Create one new frame, and re-use it each time.
722 new-frame Make a new frame each time. Note that in this case
723 previously-made indirect buffers are kept, and you need to
724 kill these buffers yourself."
725 :group 'org-structure
726 :group 'org-agenda-windows
727 :type '(choice
728 (const :tag "In current window" current-window)
729 (const :tag "In current frame, other window" other-window)
730 (const :tag "Each time a new frame" new-frame)
731 (const :tag "One dedicated frame" dedicated-frame)))
733 (defcustom org-use-speed-commands nil
734 "Non-nil means activate single letter commands at beginning of a headline.
735 This may also be a function to test for appropriate locations where speed
736 commands should be active."
737 :group 'org-structure
738 :type '(choice
739 (const :tag "Never" nil)
740 (const :tag "At beginning of headline stars" t)
741 (function)))
743 (defcustom org-speed-commands-user nil
744 "Alist of additional speed commands.
745 This list will be checked before `org-speed-commands-default'
746 when the variable `org-use-speed-commands' is non-nil
747 and when the cursor is at the beginning of a headline.
748 The car if each entry is a string with a single letter, which must
749 be assigned to `self-insert-command' in the global map.
750 The cdr is either a command to be called interactively, a function
751 to be called, or a form to be evaluated.
752 An entry that is just a list with a single string will be interpreted
753 as a descriptive headline that will be added when listing the speed
754 copmmands in the Help buffer using the `?' speed command."
755 :group 'org-structure
756 :type '(repeat :value ("k" . ignore)
757 (choice :value ("k" . ignore)
758 (list :tag "Descriptive Headline" (string :tag "Headline"))
759 (cons :tag "Letter and Command"
760 (string :tag "Command letter")
761 (choice
762 (function)
763 (sexp))))))
765 (defgroup org-cycle nil
766 "Options concerning visibility cycling in Org-mode."
767 :tag "Org Cycle"
768 :group 'org-structure)
770 (defcustom org-cycle-skip-children-state-if-no-children t
771 "Non-nil means skip CHILDREN state in entries that don't have any."
772 :group 'org-cycle
773 :type 'boolean)
775 (defcustom org-cycle-max-level nil
776 "Maximum level which should still be subject to visibility cycling.
777 Levels higher than this will, for cycling, be treated as text, not a headline.
778 When `org-odd-levels-only' is set, a value of N in this variable actually
779 means 2N-1 stars as the limiting headline.
780 When nil, cycle all levels.
781 Note that the limiting level of cycling is also influenced by
782 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
783 `org-inlinetask-min-level' is, cycling will be limited to levels one less
784 than its value."
785 :group 'org-cycle
786 :type '(choice
787 (const :tag "No limit" nil)
788 (integer :tag "Maximum level")))
790 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
791 "Names of drawers. Drawers are not opened by cycling on the headline above.
792 Drawers only open with a TAB on the drawer line itself. A drawer looks like
793 this:
794 :DRAWERNAME:
795 .....
796 :END:
797 The drawer \"PROPERTIES\" is special for capturing properties through
798 the property API.
800 Drawers can be defined on the per-file basis with a line like:
802 #+DRAWERS: HIDDEN STATE PROPERTIES"
803 :group 'org-structure
804 :group 'org-cycle
805 :type '(repeat (string :tag "Drawer Name")))
807 (defcustom org-hide-block-startup nil
808 "Non-nil means entering Org-mode will fold all blocks.
809 This can also be set in on a per-file basis with
811 #+STARTUP: hideblocks
812 #+STARTUP: showblocks"
813 :group 'org-startup
814 :group 'org-cycle
815 :type 'boolean)
817 (defcustom org-cycle-global-at-bob nil
818 "Cycle globally if cursor is at beginning of buffer and not at a headline.
819 This makes it possible to do global cycling without having to use S-TAB or
820 C-u TAB. For this special case to work, the first line of the buffer
821 must not be a headline - it may be empty or some other text. When used in
822 this way, `org-cycle-hook' is disables temporarily, to make sure the
823 cursor stays at the beginning of the buffer.
824 When this option is nil, don't do anything special at the beginning
825 of the buffer."
826 :group 'org-cycle
827 :type 'boolean)
829 (defcustom org-cycle-level-after-item/entry-creation t
830 "Non-nil means cycle entry level or item indentation in new empty entries.
832 When the cursor is at the end of an empty headline, i.e with only stars
833 and maybe a TODO keyword, TAB will then switch the entry to become a child,
834 and then all possible anchestor states, before returning to the original state.
835 This makes data entry extremely fast: M-RET to create a new headline,
836 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
838 When the cursor is at the end of an empty plain list item, one TAB will
839 make it a subitem, two or more tabs will back up to make this an item
840 higher up in the item hierarchy."
841 :group 'org-cycle
842 :type 'boolean)
844 (defcustom org-cycle-emulate-tab t
845 "Where should `org-cycle' emulate TAB.
846 nil Never
847 white Only in completely white lines
848 whitestart Only at the beginning of lines, before the first non-white char
849 t Everywhere except in headlines
850 exc-hl-bol Everywhere except at the start of a headline
851 If TAB is used in a place where it does not emulate TAB, the current subtree
852 visibility is cycled."
853 :group 'org-cycle
854 :type '(choice (const :tag "Never" nil)
855 (const :tag "Only in completely white lines" white)
856 (const :tag "Before first char in a line" whitestart)
857 (const :tag "Everywhere except in headlines" t)
858 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
861 (defcustom org-cycle-separator-lines 2
862 "Number of empty lines needed to keep an empty line between collapsed trees.
863 If you leave an empty line between the end of a subtree and the following
864 headline, this empty line is hidden when the subtree is folded.
865 Org-mode will leave (exactly) one empty line visible if the number of
866 empty lines is equal or larger to the number given in this variable.
867 So the default 2 means at least 2 empty lines after the end of a subtree
868 are needed to produce free space between a collapsed subtree and the
869 following headline.
871 If the number is negative, and the number of empty lines is at least -N,
872 all empty lines are shown.
874 Special case: when 0, never leave empty lines in collapsed view."
875 :group 'org-cycle
876 :type 'integer)
877 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
879 (defcustom org-pre-cycle-hook nil
880 "Hook that is run before visibility cycling is happening.
881 The function(s) in this hook must accept a single argument which indicates
882 the new state that will be set right after running this hook. The
883 argument is a symbol. Before a global state change, it can have the values
884 `overview', `content', or `all'. Before a local state change, it can have
885 the values `folded', `children', or `subtree'."
886 :group 'org-cycle
887 :type 'hook)
889 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
890 org-cycle-hide-drawers
891 org-cycle-show-empty-lines
892 org-optimize-window-after-visibility-change)
893 "Hook that is run after `org-cycle' has changed the buffer visibility.
894 The function(s) in this hook must accept a single argument which indicates
895 the new state that was set by the most recent `org-cycle' command. The
896 argument is a symbol. After a global state change, it can have the values
897 `overview', `content', or `all'. After a local state change, it can have
898 the values `folded', `children', or `subtree'."
899 :group 'org-cycle
900 :type 'hook)
902 (defgroup org-edit-structure nil
903 "Options concerning structure editing in Org-mode."
904 :tag "Org Edit Structure"
905 :group 'org-structure)
907 (defcustom org-odd-levels-only nil
908 "Non-nil means skip even levels and only use odd levels for the outline.
909 This has the effect that two stars are being added/taken away in
910 promotion/demotion commands. It also influences how levels are
911 handled by the exporters.
912 Changing it requires restart of `font-lock-mode' to become effective
913 for fontification also in regions already fontified.
914 You may also set this on a per-file basis by adding one of the following
915 lines to the buffer:
917 #+STARTUP: odd
918 #+STARTUP: oddeven"
919 :group 'org-edit-structure
920 :group 'org-appearance
921 :type 'boolean)
923 (defcustom org-adapt-indentation t
924 "Non-nil means adapt indentation to outline node level.
926 When this variable is set, Org assumes that you write outlines by
927 indenting text in each node to align with the headline (after the stars).
928 The following issues are influenced by this variable:
930 - When this is set and the *entire* text in an entry is indented, the
931 indentation is increased by one space in a demotion command, and
932 decreased by one in a promotion command. If any line in the entry
933 body starts with text at column 0, indentation is not changed at all.
935 - Property drawers and planning information is inserted indented when
936 this variable s set. When nil, they will not be indented.
938 - TAB indents a line relative to context. The lines below a headline
939 will be indented when this variable is set.
941 Note that this is all about true indentation, by adding and removing
942 space characters. See also `org-indent.el' which does level-dependent
943 indentation in a virtual way, i.e. at display time in Emacs."
944 :group 'org-edit-structure
945 :type 'boolean)
947 (defcustom org-special-ctrl-a/e nil
948 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
950 When t, `C-a' will bring back the cursor to the beginning of the
951 headline text, i.e. after the stars and after a possible TODO keyword.
952 In an item, this will be the position after the bullet.
953 When the cursor is already at that position, another `C-a' will bring
954 it to the beginning of the line.
956 `C-e' will jump to the end of the headline, ignoring the presence of tags
957 in the headline. A second `C-e' will then jump to the true end of the
958 line, after any tags. This also means that, when this variable is
959 non-nil, `C-e' also will never jump beyond the end of the heading of a
960 folded section, i.e. not after the ellipses.
962 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
963 going to the true line boundary first. Only a directly following, identical
964 keypress will bring the cursor to the special positions.
966 This may also be a cons cell where the behavior for `C-a' and `C-e' is
967 set separately."
968 :group 'org-edit-structure
969 :type '(choice
970 (const :tag "off" nil)
971 (const :tag "on: after stars/bullet and before tags first" t)
972 (const :tag "reversed: true line boundary first" reversed)
973 (cons :tag "Set C-a and C-e separately"
974 (choice :tag "Special C-a"
975 (const :tag "off" nil)
976 (const :tag "on: after stars/bullet first" t)
977 (const :tag "reversed: before stars/bullet first" reversed))
978 (choice :tag "Special C-e"
979 (const :tag "off" nil)
980 (const :tag "on: before tags first" t)
981 (const :tag "reversed: after tags first" reversed)))))
982 (if (fboundp 'defvaralias)
983 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
985 (defcustom org-special-ctrl-k nil
986 "Non-nil means `C-k' will behave specially in headlines.
987 When nil, `C-k' will call the default `kill-line' command.
988 When t, the following will happen while the cursor is in the headline:
990 - When the cursor is at the beginning of a headline, kill the entire
991 line and possible the folded subtree below the line.
992 - When in the middle of the headline text, kill the headline up to the tags.
993 - When after the headline text, kill the tags."
994 :group 'org-edit-structure
995 :type 'boolean)
997 (defcustom org-ctrl-k-protect-subtree nil
998 "Non-nil means, do not delete a hidden subtree with C-k.
999 When set to the symbol `error', simply throw an error when C-k is
1000 used to kill (part-of) a headline that has hidden text behind it.
1001 Any other non-nil value will result in a query to the user, if it is
1002 OK to kill that hidden subtree. When nil, kill without remorse."
1003 :group 'org-edit-structure
1004 :type '(choice
1005 (const :tag "Do not protect hidden subtrees" nil)
1006 (const :tag "Protect hidden subtrees with a security query" t)
1007 (const :tag "Never kill a hidden subtree with C-k" error)))
1009 (defcustom org-yank-folded-subtrees t
1010 "Non-nil means when yanking subtrees, fold them.
1011 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1012 it starts with a heading and all other headings in it are either children
1013 or siblings, then fold all the subtrees. However, do this only if no
1014 text after the yank would be swallowed into a folded tree by this action."
1015 :group 'org-edit-structure
1016 :type 'boolean)
1018 (defcustom org-yank-adjusted-subtrees nil
1019 "Non-nil means when yanking subtrees, adjust the level.
1020 With this setting, `org-paste-subtree' is used to insert the subtree, see
1021 this function for details."
1022 :group 'org-edit-structure
1023 :type 'boolean)
1025 (defcustom org-M-RET-may-split-line '((default . t))
1026 "Non-nil means M-RET will split the line at the cursor position.
1027 When nil, it will go to the end of the line before making a
1028 new line.
1029 You may also set this option in a different way for different
1030 contexts. Valid contexts are:
1032 headline when creating a new headline
1033 item when creating a new item
1034 table in a table field
1035 default the value to be used for all contexts not explicitly
1036 customized"
1037 :group 'org-structure
1038 :group 'org-table
1039 :type '(choice
1040 (const :tag "Always" t)
1041 (const :tag "Never" nil)
1042 (repeat :greedy t :tag "Individual contexts"
1043 (cons
1044 (choice :tag "Context"
1045 (const headline)
1046 (const item)
1047 (const table)
1048 (const default))
1049 (boolean)))))
1052 (defcustom org-insert-heading-respect-content nil
1053 "Non-nil means insert new headings after the current subtree.
1054 When nil, the new heading is created directly after the current line.
1055 The commands \\[org-insert-heading-respect-content] and
1056 \\[org-insert-todo-heading-respect-content] turn this variable on
1057 for the duration of the command."
1058 :group 'org-structure
1059 :type 'boolean)
1061 (defcustom org-blank-before-new-entry '((heading . auto)
1062 (plain-list-item . auto))
1063 "Should `org-insert-heading' leave a blank line before new heading/item?
1064 The value is an alist, with `heading' and `plain-list-item' as car,
1065 and a boolean flag as cdr. For plain lists, if the variable
1066 `org-empty-line-terminates-plain-lists' is set, the setting here
1067 is ignored and no empty line is inserted, to keep the list in tact."
1068 :group 'org-edit-structure
1069 :type '(list
1070 (cons (const heading)
1071 (choice (const :tag "Never" nil)
1072 (const :tag "Always" t)
1073 (const :tag "Auto" auto)))
1074 (cons (const plain-list-item)
1075 (choice (const :tag "Never" nil)
1076 (const :tag "Always" t)
1077 (const :tag "Auto" auto)))))
1079 (defcustom org-insert-heading-hook nil
1080 "Hook being run after inserting a new heading."
1081 :group 'org-edit-structure
1082 :type 'hook)
1084 (defcustom org-enable-fixed-width-editor t
1085 "Non-nil means lines starting with \":\" are treated as fixed-width.
1086 This currently only means they are never auto-wrapped.
1087 When nil, such lines will be treated like ordinary lines.
1088 See also the QUOTE keyword."
1089 :group 'org-edit-structure
1090 :type 'boolean)
1093 (defcustom org-goto-auto-isearch t
1094 "Non-nil means typing characters in org-goto starts incremental search."
1095 :group 'org-edit-structure
1096 :type 'boolean)
1098 (defgroup org-sparse-trees nil
1099 "Options concerning sparse trees in Org-mode."
1100 :tag "Org Sparse Trees"
1101 :group 'org-structure)
1103 (defcustom org-highlight-sparse-tree-matches t
1104 "Non-nil means highlight all matches that define a sparse tree.
1105 The highlights will automatically disappear the next time the buffer is
1106 changed by an edit command."
1107 :group 'org-sparse-trees
1108 :type 'boolean)
1110 (defcustom org-remove-highlights-with-change t
1111 "Non-nil means any change to the buffer will remove temporary highlights.
1112 Such highlights are created by `org-occur' and `org-clock-display'.
1113 When nil, `C-c C-c needs to be used to get rid of the highlights.
1114 The highlights created by `org-preview-latex-fragment' always need
1115 `C-c C-c' to be removed."
1116 :group 'org-sparse-trees
1117 :group 'org-time
1118 :type 'boolean)
1121 (defcustom org-occur-hook '(org-first-headline-recenter)
1122 "Hook that is run after `org-occur' has constructed a sparse tree.
1123 This can be used to recenter the window to show as much of the structure
1124 as possible."
1125 :group 'org-sparse-trees
1126 :type 'hook)
1128 (defgroup org-imenu-and-speedbar nil
1129 "Options concerning imenu and speedbar in Org-mode."
1130 :tag "Org Imenu and Speedbar"
1131 :group 'org-structure)
1133 (defcustom org-imenu-depth 2
1134 "The maximum level for Imenu access to Org-mode headlines.
1135 This also applied for speedbar access."
1136 :group 'org-imenu-and-speedbar
1137 :type 'integer)
1139 (defgroup org-table nil
1140 "Options concerning tables in Org-mode."
1141 :tag "Org Table"
1142 :group 'org)
1144 (defcustom org-enable-table-editor 'optimized
1145 "Non-nil means lines starting with \"|\" are handled by the table editor.
1146 When nil, such lines will be treated like ordinary lines.
1148 When equal to the symbol `optimized', the table editor will be optimized to
1149 do the following:
1150 - Automatic overwrite mode in front of whitespace in table fields.
1151 This makes the structure of the table stay in tact as long as the edited
1152 field does not exceed the column width.
1153 - Minimize the number of realigns. Normally, the table is aligned each time
1154 TAB or RET are pressed to move to another field. With optimization this
1155 happens only if changes to a field might have changed the column width.
1156 Optimization requires replacing the functions `self-insert-command',
1157 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1158 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1159 very good at guessing when a re-align will be necessary, but you can always
1160 force one with \\[org-ctrl-c-ctrl-c].
1162 If you would like to use the optimized version in Org-mode, but the
1163 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1165 This variable can be used to turn on and off the table editor during a session,
1166 but in order to toggle optimization, a restart is required.
1168 See also the variable `org-table-auto-blank-field'."
1169 :group 'org-table
1170 :type '(choice
1171 (const :tag "off" nil)
1172 (const :tag "on" t)
1173 (const :tag "on, optimized" optimized)))
1175 (defcustom org-self-insert-cluster-for-undo t
1176 "Non-nil means cluster self-insert commands for undo when possible.
1177 If this is set, then, like in the Emacs command loop, 20 consecutive
1178 characters will be undone together.
1179 This is configurable, because there is some impact on typing performance."
1180 :group 'org-table
1181 :type 'boolean)
1183 (defcustom org-table-tab-recognizes-table.el t
1184 "Non-nil means TAB will automatically notice a table.el table.
1185 When it sees such a table, it moves point into it and - if necessary -
1186 calls `table-recognize-table'."
1187 :group 'org-table-editing
1188 :type 'boolean)
1190 (defgroup org-link nil
1191 "Options concerning links in Org-mode."
1192 :tag "Org Link"
1193 :group 'org)
1195 (defvar org-link-abbrev-alist-local nil
1196 "Buffer-local version of `org-link-abbrev-alist', which see.
1197 The value of this is taken from the #+LINK lines.")
1198 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1200 (defcustom org-link-abbrev-alist nil
1201 "Alist of link abbreviations.
1202 The car of each element is a string, to be replaced at the start of a link.
1203 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1204 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1206 [[linkkey:tag][description]]
1208 The 'linkkey' must be a word word, starting with a letter, followed
1209 by letters, numbers, '-' or '_'.
1211 If REPLACE is a string, the tag will simply be appended to create the link.
1212 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1213 the placeholder \"%h\" will cause a url-encoded version of the tag to
1214 be inserted at that point (see the function `url-hexify-string').
1216 REPLACE may also be a function that will be called with the tag as the
1217 only argument to create the link, which should be returned as a string.
1219 See the manual for examples."
1220 :group 'org-link
1221 :type '(repeat
1222 (cons
1223 (string :tag "Protocol")
1224 (choice
1225 (string :tag "Format")
1226 (function)))))
1228 (defcustom org-descriptive-links t
1229 "Non-nil means hide link part and only show description of bracket links.
1230 Bracket links are like [[link][description]]. This variable sets the initial
1231 state in new org-mode buffers. The setting can then be toggled on a
1232 per-buffer basis from the Org->Hyperlinks menu."
1233 :group 'org-link
1234 :type 'boolean)
1236 (defcustom org-link-file-path-type 'adaptive
1237 "How the path name in file links should be stored.
1238 Valid values are:
1240 relative Relative to the current directory, i.e. the directory of the file
1241 into which the link is being inserted.
1242 absolute Absolute path, if possible with ~ for home directory.
1243 noabbrev Absolute path, no abbreviation of home directory.
1244 adaptive Use relative path for files in the current directory and sub-
1245 directories of it. For other files, use an absolute path."
1246 :group 'org-link
1247 :type '(choice
1248 (const relative)
1249 (const absolute)
1250 (const noabbrev)
1251 (const adaptive)))
1253 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1254 "Types of links that should be activated in Org-mode files.
1255 This is a list of symbols, each leading to the activation of a certain link
1256 type. In principle, it does not hurt to turn on most link types - there may
1257 be a small gain when turning off unused link types. The types are:
1259 bracket The recommended [[link][description]] or [[link]] links with hiding.
1260 angular Links in angular brackets that may contain whitespace like
1261 <bbdb:Carsten Dominik>.
1262 plain Plain links in normal text, no whitespace, like http://google.com.
1263 radio Text that is matched by a radio target, see manual for details.
1264 tag Tag settings in a headline (link to tag search).
1265 date Time stamps (link to calendar).
1266 footnote Footnote labels.
1268 Changing this variable requires a restart of Emacs to become effective."
1269 :group 'org-link
1270 :type '(set :greedy t
1271 (const :tag "Double bracket links (new style)" bracket)
1272 (const :tag "Angular bracket links (old style)" angular)
1273 (const :tag "Plain text links" plain)
1274 (const :tag "Radio target matches" radio)
1275 (const :tag "Tags" tag)
1276 (const :tag "Timestamps" date)
1277 (const :tag "Footnotes" footnote)))
1279 (defcustom org-make-link-description-function nil
1280 "Function to use to generate link descriptions from links. If
1281 nil the link location will be used. This function must take two
1282 parameters; the first is the link and the second the description
1283 org-insert-link has generated, and should return the description
1284 to use."
1285 :group 'org-link
1286 :type 'function)
1288 (defgroup org-link-store nil
1289 "Options concerning storing links in Org-mode."
1290 :tag "Org Store Link"
1291 :group 'org-link)
1293 (defcustom org-email-link-description-format "Email %c: %.30s"
1294 "Format of the description part of a link to an email or usenet message.
1295 The following %-escapes will be replaced by corresponding information:
1297 %F full \"From\" field
1298 %f name, taken from \"From\" field, address if no name
1299 %T full \"To\" field
1300 %t first name in \"To\" field, address if no name
1301 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1302 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1303 %s subject
1304 %m message-id.
1306 You may use normal field width specification between the % and the letter.
1307 This is for example useful to limit the length of the subject.
1309 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1310 :group 'org-link-store
1311 :type 'string)
1313 (defcustom org-from-is-user-regexp
1314 (let (r1 r2)
1315 (when (and user-mail-address (not (string= user-mail-address "")))
1316 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1317 (when (and user-full-name (not (string= user-full-name "")))
1318 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1319 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1320 "Regexp matched against the \"From:\" header of an email or usenet message.
1321 It should match if the message is from the user him/herself."
1322 :group 'org-link-store
1323 :type 'regexp)
1325 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1326 "Non-nil means storing a link to an Org file will use entry IDs.
1328 Note that before this variable is even considered, org-id must be loaded,
1329 so please customize `org-modules' and turn it on.
1331 The variable can have the following values:
1333 t Create an ID if needed to make a link to the current entry.
1335 create-if-interactive
1336 If `org-store-link' is called directly (interactively, as a user
1337 command), do create an ID to support the link. But when doing the
1338 job for remember, only use the ID if it already exists. The
1339 purpose of this setting is to avoid proliferation of unwanted
1340 IDs, just because you happen to be in an Org file when you
1341 call `org-remember' that automatically and preemptively
1342 creates a link. If you do want to get an ID link in a remember
1343 template to an entry not having an ID, create it first by
1344 explicitly creating a link to it, using `C-c C-l' first.
1346 create-if-interactive-and-no-custom-id
1347 Like create-if-interactive, but do not create an ID if there is
1348 a CUSTOM_ID property defined in the entry. This is the default.
1350 use-existing
1351 Use existing ID, do not create one.
1353 nil Never use an ID to make a link, instead link using a text search for
1354 the headline text."
1355 :group 'org-link-store
1356 :type '(choice
1357 (const :tag "Create ID to make link" t)
1358 (const :tag "Create if storing link interactively"
1359 create-if-interactive)
1360 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1361 create-if-interactive-and-no-custom-id)
1362 (const :tag "Only use existing" use-existing)
1363 (const :tag "Do not use ID to create link" nil)))
1365 (defcustom org-context-in-file-links t
1366 "Non-nil means file links from `org-store-link' contain context.
1367 A search string will be added to the file name with :: as separator and
1368 used to find the context when the link is activated by the command
1369 `org-open-at-point'.
1370 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1371 negates this setting for the duration of the command."
1372 :group 'org-link-store
1373 :type 'boolean)
1375 (defcustom org-keep-stored-link-after-insertion nil
1376 "Non-nil means keep link in list for entire session.
1378 The command `org-store-link' adds a link pointing to the current
1379 location to an internal list. These links accumulate during a session.
1380 The command `org-insert-link' can be used to insert links into any
1381 Org-mode file (offering completion for all stored links). When this
1382 option is nil, every link which has been inserted once using \\[org-insert-link]
1383 will be removed from the list, to make completing the unused links
1384 more efficient."
1385 :group 'org-link-store
1386 :type 'boolean)
1388 (defgroup org-link-follow nil
1389 "Options concerning following links in Org-mode."
1390 :tag "Org Follow Link"
1391 :group 'org-link)
1393 (defcustom org-link-translation-function nil
1394 "Function to translate links with different syntax to Org syntax.
1395 This can be used to translate links created for example by the Planner
1396 or emacs-wiki packages to Org syntax.
1397 The function must accept two parameters, a TYPE containing the link
1398 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1399 which is everything after the link protocol. It should return a cons
1400 with possibly modified values of type and path.
1401 Org contains a function for this, so if you set this variable to
1402 `org-translate-link-from-planner', you should be able follow many
1403 links created by planner."
1404 :group 'org-link-follow
1405 :type 'function)
1407 (defcustom org-follow-link-hook nil
1408 "Hook that is run after a link has been followed."
1409 :group 'org-link-follow
1410 :type 'hook)
1412 (defcustom org-tab-follows-link nil
1413 "Non-nil means on links TAB will follow the link.
1414 Needs to be set before org.el is loaded.
1415 This really should not be used, it does not make sense, and the
1416 implementation is bad."
1417 :group 'org-link-follow
1418 :type 'boolean)
1420 (defcustom org-return-follows-link nil
1421 "Non-nil means on links RET will follow the link."
1422 :group 'org-link-follow
1423 :type 'boolean)
1425 (defcustom org-mouse-1-follows-link
1426 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1427 "Non-nil means mouse-1 on a link will follow the link.
1428 A longer mouse click will still set point. Does not work on XEmacs.
1429 Needs to be set before org.el is loaded."
1430 :group 'org-link-follow
1431 :type 'boolean)
1433 (defcustom org-mark-ring-length 4
1434 "Number of different positions to be recorded in the ring
1435 Changing this requires a restart of Emacs to work correctly."
1436 :group 'org-link-follow
1437 :type 'integer)
1439 (defcustom org-link-frame-setup
1440 '((vm . vm-visit-folder-other-frame)
1441 (gnus . org-gnus-no-new-news)
1442 (file . find-file-other-window)
1443 (wl . wl-other-frame))
1444 "Setup the frame configuration for following links.
1445 When following a link with Emacs, it may often be useful to display
1446 this link in another window or frame. This variable can be used to
1447 set this up for the different types of links.
1448 For VM, use any of
1449 `vm-visit-folder'
1450 `vm-visit-folder-other-frame'
1451 For Gnus, use any of
1452 `gnus'
1453 `gnus-other-frame'
1454 `org-gnus-no-new-news'
1455 For FILE, use any of
1456 `find-file'
1457 `find-file-other-window'
1458 `find-file-other-frame'
1459 For Wanderlust use any of
1460 `wl'
1461 `wl-other-frame'
1462 For the calendar, use the variable `calendar-setup'.
1463 For BBDB, it is currently only possible to display the matches in
1464 another window."
1465 :group 'org-link-follow
1466 :type '(list
1467 (cons (const vm)
1468 (choice
1469 (const vm-visit-folder)
1470 (const vm-visit-folder-other-window)
1471 (const vm-visit-folder-other-frame)))
1472 (cons (const gnus)
1473 (choice
1474 (const gnus)
1475 (const gnus-other-frame)
1476 (const org-gnus-no-new-news)))
1477 (cons (const file)
1478 (choice
1479 (const find-file)
1480 (const find-file-other-window)
1481 (const find-file-other-frame)))
1482 (cons (const wl)
1483 (choice
1484 (const wl)
1485 (const wl-other-frame)))))
1487 (defcustom org-display-internal-link-with-indirect-buffer nil
1488 "Non-nil means use indirect buffer to display infile links.
1489 Activating internal links (from one location in a file to another location
1490 in the same file) normally just jumps to the location. When the link is
1491 activated with a C-u prefix (or with mouse-3), the link is displayed in
1492 another window. When this option is set, the other window actually displays
1493 an indirect buffer clone of the current buffer, to avoid any visibility
1494 changes to the current buffer."
1495 :group 'org-link-follow
1496 :type 'boolean)
1498 (defcustom org-open-non-existing-files nil
1499 "Non-nil means `org-open-file' will open non-existing files.
1500 When nil, an error will be generated.
1501 This variable applies only to external applications because they
1502 might choke on non-existing files. If the link is to a file that
1503 will be opened in Emacs, the variable is ignored."
1504 :group 'org-link-follow
1505 :type 'boolean)
1507 (defcustom org-open-directory-means-index-dot-org nil
1508 "Non-nil means a link to a directory really means to index.org.
1509 When nil, following a directory link will run dired or open a finder/explorer
1510 window on that directory."
1511 :group 'org-link-follow
1512 :type 'boolean)
1514 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1515 "Function and arguments to call for following mailto links.
1516 This is a list with the first element being a lisp function, and the
1517 remaining elements being arguments to the function. In string arguments,
1518 %a will be replaced by the address, and %s will be replaced by the subject
1519 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1520 :group 'org-link-follow
1521 :type '(choice
1522 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1523 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1524 (const :tag "message-mail" (message-mail "%a" "%s"))
1525 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1527 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1528 "Non-nil means ask for confirmation before executing shell links.
1529 Shell links can be dangerous: just think about a link
1531 [[shell:rm -rf ~/*][Google Search]]
1533 This link would show up in your Org-mode document as \"Google Search\",
1534 but really it would remove your entire home directory.
1535 Therefore we advise against setting this variable to nil.
1536 Just change it to `y-or-n-p' if you want to confirm with a
1537 single keystroke rather than having to type \"yes\"."
1538 :group 'org-link-follow
1539 :type '(choice
1540 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1541 (const :tag "with y-or-n (faster)" y-or-n-p)
1542 (const :tag "no confirmation (dangerous)" nil)))
1543 (put 'org-confirm-shell-link-function
1544 'safe-local-variable
1545 '(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1547 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1548 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1549 Elisp links can be dangerous: just think about a link
1551 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1553 This link would show up in your Org-mode document as \"Google Search\",
1554 but really it would remove your entire home directory.
1555 Therefore we advise against setting this variable to nil.
1556 Just change it to `y-or-n-p' if you want to confirm with a
1557 single keystroke rather than having to type \"yes\"."
1558 :group 'org-link-follow
1559 :type '(choice
1560 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1561 (const :tag "with y-or-n (faster)" y-or-n-p)
1562 (const :tag "no confirmation (dangerous)" nil)))
1563 (put 'org-confirm-shell-link-function
1564 'safe-local-variable
1565 '(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1567 (defconst org-file-apps-defaults-gnu
1568 '((remote . emacs)
1569 (system . mailcap)
1570 (t . mailcap))
1571 "Default file applications on a UNIX or GNU/Linux system.
1572 See `org-file-apps'.")
1574 (defconst org-file-apps-defaults-macosx
1575 '((remote . emacs)
1576 (t . "open %s")
1577 (system . "open %s")
1578 ("ps.gz" . "gv %s")
1579 ("eps.gz" . "gv %s")
1580 ("dvi" . "xdvi %s")
1581 ("fig" . "xfig %s"))
1582 "Default file applications on a MacOS X system.
1583 The system \"open\" is known as a default, but we use X11 applications
1584 for some files for which the OS does not have a good default.
1585 See `org-file-apps'.")
1587 (defconst org-file-apps-defaults-windowsnt
1588 (list
1589 '(remote . emacs)
1590 (cons t
1591 (list (if (featurep 'xemacs)
1592 'mswindows-shell-execute
1593 'w32-shell-execute)
1594 "open" 'file))
1595 (cons 'system
1596 (list (if (featurep 'xemacs)
1597 'mswindows-shell-execute
1598 'w32-shell-execute)
1599 "open" 'file)))
1600 "Default file applications on a Windows NT system.
1601 The system \"open\" is used for most files.
1602 See `org-file-apps'.")
1604 (defcustom org-file-apps
1606 (auto-mode . emacs)
1607 ("\\.mm\\'" . default)
1608 ("\\.x?html?\\'" . default)
1609 ("\\.pdf\\'" . default)
1611 "External applications for opening `file:path' items in a document.
1612 Org-mode uses system defaults for different file types, but
1613 you can use this variable to set the application for a given file
1614 extension. The entries in this list are cons cells where the car identifies
1615 files and the cdr the corresponding command. Possible values for the
1616 file identifier are
1617 \"string\" A string as a file identifier can be interpreted in different
1618 ways, depending on its contents:
1620 - Alphanumeric characters only:
1621 Match links with this file extension.
1622 Example: (\"pdf\" . \"evince %s\")
1623 to open PDFs with evince.
1625 - Regular expression: Match links where the
1626 filename matches the regexp. If you want to
1627 use groups here, use shy groups.
1629 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1630 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1631 to open *.html and *.xhtml with firefox.
1633 - Regular expression which contains (non-shy) groups:
1634 Match links where the whole link, including \"::\", and
1635 anything after that, matches the regexp.
1636 In a custom command string, %1, %2, etc. are replaced with
1637 the parts of the link that were matched by the groups.
1638 For backwards compatibility, if a command string is given
1639 that does not use any of the group matches, this case is
1640 handled identically to the second one (i.e. match against
1641 file name only).
1643 In a custom lisp form, you can access the group matches with
1644 (match-string n link).
1646 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1647 to open [[file:document.pdf::5]] with evince at page 5.
1649 `directory' Matches a directory
1650 `remote' Matches a remote file, accessible through tramp or efs.
1651 Remote files most likely should be visited through Emacs
1652 because external applications cannot handle such paths.
1653 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1654 so all files Emacs knows how to handle. Using this with
1655 command `emacs' will open most files in Emacs. Beware that this
1656 will also open html files inside Emacs, unless you add
1657 (\"html\" . default) to the list as well.
1658 t Default for files not matched by any of the other options.
1659 `system' The system command to open files, like `open' on Windows
1660 and Mac OS X, and mailcap under GNU/Linux. This is the command
1661 that will be selected if you call `C-c C-o' with a double
1662 `C-u C-u' prefix.
1664 Possible values for the command are:
1665 `emacs' The file will be visited by the current Emacs process.
1666 `default' Use the default application for this file type, which is the
1667 association for t in the list, most likely in the system-specific
1668 part.
1669 This can be used to overrule an unwanted setting in the
1670 system-specific variable.
1671 `system' Use the system command for opening files, like \"open\".
1672 This command is specified by the entry whose car is `system'.
1673 Most likely, the system-specific version of this variable
1674 does define this command, but you can overrule/replace it
1675 here.
1676 string A command to be executed by a shell; %s will be replaced
1677 by the path to the file.
1678 sexp A Lisp form which will be evaluated. The file path will
1679 be available in the Lisp variable `file'.
1680 For more examples, see the system specific constants
1681 `org-file-apps-defaults-macosx'
1682 `org-file-apps-defaults-windowsnt'
1683 `org-file-apps-defaults-gnu'."
1684 :group 'org-link-follow
1685 :type '(repeat
1686 (cons (choice :value ""
1687 (string :tag "Extension")
1688 (const :tag "System command to open files" system)
1689 (const :tag "Default for unrecognized files" t)
1690 (const :tag "Remote file" remote)
1691 (const :tag "Links to a directory" directory)
1692 (const :tag "Any files that have Emacs modes"
1693 auto-mode))
1694 (choice :value ""
1695 (const :tag "Visit with Emacs" emacs)
1696 (const :tag "Use default" default)
1697 (const :tag "Use the system command" system)
1698 (string :tag "Command")
1699 (sexp :tag "Lisp form")))))
1703 (defgroup org-refile nil
1704 "Options concerning refiling entries in Org-mode."
1705 :tag "Org Refile"
1706 :group 'org)
1708 (defcustom org-directory "~/org"
1709 "Directory with org files.
1710 This is just a default location to look for Org files. There is no need
1711 at all to put your files into this directory. It is only used in the
1712 following situations:
1714 1. When a remember template specifies a target file that is not an
1715 absolute path. The path will then be interpreted relative to
1716 `org-directory'
1717 2. When a remember note is filed away in an interactive way (when exiting the
1718 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1719 with `org-directory' as the default path."
1720 :group 'org-refile
1721 :group 'org-remember
1722 :type 'directory)
1724 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1725 "Default target for storing notes.
1726 Used as a fall back file for org-remember.el and org-capture.el, for
1727 templates that do not specify a target file."
1728 :group 'org-refile
1729 :group 'org-remember
1730 :type '(choice
1731 (const :tag "Default from remember-data-file" nil)
1732 file))
1734 (defcustom org-goto-interface 'outline
1735 "The default interface to be used for `org-goto'.
1736 Allowed values are:
1737 outline The interface shows an outline of the relevant file
1738 and the correct heading is found by moving through
1739 the outline or by searching with incremental search.
1740 outline-path-completion Headlines in the current buffer are offered via
1741 completion. This is the interface also used by
1742 the refile command."
1743 :group 'org-refile
1744 :type '(choice
1745 (const :tag "Outline" outline)
1746 (const :tag "Outline-path-completion" outline-path-completion)))
1748 (defcustom org-goto-max-level 5
1749 "Maximum level to be considered when running org-goto with refile interface."
1750 :group 'org-refile
1751 :type 'integer)
1753 (defcustom org-reverse-note-order nil
1754 "Non-nil means store new notes at the beginning of a file or entry.
1755 When nil, new notes will be filed to the end of a file or entry.
1756 This can also be a list with cons cells of regular expressions that
1757 are matched against file names, and values."
1758 :group 'org-remember
1759 :group 'org-refile
1760 :type '(choice
1761 (const :tag "Reverse always" t)
1762 (const :tag "Reverse never" nil)
1763 (repeat :tag "By file name regexp"
1764 (cons regexp boolean))))
1766 (defcustom org-log-refile nil
1767 "Information to record when a task is refiled.
1769 Possible values are:
1771 nil Don't add anything
1772 time Add a time stamp to the task
1773 note Prompt for a note and add it with template `org-log-note-headings'
1775 This option can also be set with on a per-file-basis with
1777 #+STARTUP: nologrefile
1778 #+STARTUP: logrefile
1779 #+STARTUP: lognoterefile
1781 You can have local logging settings for a subtree by setting the LOGGING
1782 property to one or more of these keywords.
1784 When bulk-refiling from the agenda, the value `note' is forbidden and
1785 will temporarily be changed to `time'."
1786 :group 'org-refile
1787 :group 'org-progress
1788 :type '(choice
1789 (const :tag "No logging" nil)
1790 (const :tag "Record timestamp" time)
1791 (const :tag "Record timestamp with note." note)))
1793 (defcustom org-refile-targets nil
1794 "Targets for refiling entries with \\[org-refile].
1795 This is list of cons cells. Each cell contains:
1796 - a specification of the files to be considered, either a list of files,
1797 or a symbol whose function or variable value will be used to retrieve
1798 a file name or a list of file names. If you use `org-agenda-files' for
1799 that, all agenda files will be scanned for targets. Nil means consider
1800 headings in the current buffer.
1801 - A specification of how to find candidate refile targets. This may be
1802 any of:
1803 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1804 This tag has to be present in all target headlines, inheritance will
1805 not be considered.
1806 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1807 todo keyword.
1808 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1809 headlines that are refiling targets.
1810 - a cons cell (:level . N). Any headline of level N is considered a target.
1811 Note that, when `org-odd-levels-only' is set, level corresponds to
1812 order in hierarchy, not to the number of stars.
1813 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1814 Note that, when `org-odd-levels-only' is set, level corresponds to
1815 order in hierarchy, not to the number of stars.
1817 You can set the variable `org-refile-target-verify-function' to a function
1818 to verify each headline found by the simple critery above.
1820 When this variable is nil, all top-level headlines in the current buffer
1821 are used, equivalent to the value `((nil . (:level . 1))'."
1822 :group 'org-refile
1823 :type '(repeat
1824 (cons
1825 (choice :value org-agenda-files
1826 (const :tag "All agenda files" org-agenda-files)
1827 (const :tag "Current buffer" nil)
1828 (function) (variable) (file))
1829 (choice :tag "Identify target headline by"
1830 (cons :tag "Specific tag" (const :value :tag) (string))
1831 (cons :tag "TODO keyword" (const :value :todo) (string))
1832 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1833 (cons :tag "Level number" (const :value :level) (integer))
1834 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1836 (defcustom org-refile-target-verify-function nil
1837 "Function to verify if the headline at point should be a refile target.
1838 The function will be called without arguments, with point at the
1839 beginning of the headline. It should return t and leave point
1840 where it is if the headline is a valid target for refiling.
1842 If the target should not be selected, the function must return nil.
1843 In addition to this, it may move point to a place from where the search
1844 should be continued. For example, the function may decide that the entire
1845 subtree of the current entry should be excluded and move point to the end
1846 of the subtree."
1847 :group 'org-refile
1848 :type 'function)
1850 (defcustom org-refile-use-cache nil
1851 "Non-nil means cache refile targets to speed up the process.
1852 The cache for a particular file will be updated automatically when
1853 the buffer has been killed, or when any of the marker used for flagging
1854 refile targets no longer points at a live buffer.
1855 If you have added new entries to a buffer that might themselves be targets,
1856 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1857 find that easier, `C-u C-u C-u C-c C-w'."
1858 :group 'org-refile
1859 :type 'boolean)
1861 (defcustom org-refile-use-outline-path nil
1862 "Non-nil means provide refile targets as paths.
1863 So a level 3 headline will be available as level1/level2/level3.
1865 When the value is `file', also include the file name (without directory)
1866 into the path. In this case, you can also stop the completion after
1867 the file name, to get entries inserted as top level in the file.
1869 When `full-file-path', include the full file path."
1870 :group 'org-refile
1871 :type '(choice
1872 (const :tag "Not" nil)
1873 (const :tag "Yes" t)
1874 (const :tag "Start with file name" file)
1875 (const :tag "Start with full file path" full-file-path)))
1877 (defcustom org-outline-path-complete-in-steps t
1878 "Non-nil means complete the outline path in hierarchical steps.
1879 When Org-mode uses the refile interface to select an outline path
1880 \(see variable `org-refile-use-outline-path'), the completion of
1881 the path can be done is a single go, or if can be done in steps down
1882 the headline hierarchy. Going in steps is probably the best if you
1883 do not use a special completion package like `ido' or `icicles'.
1884 However, when using these packages, going in one step can be very
1885 fast, while still showing the whole path to the entry."
1886 :group 'org-refile
1887 :type 'boolean)
1889 (defcustom org-refile-allow-creating-parent-nodes nil
1890 "Non-nil means allow to create new nodes as refile targets.
1891 New nodes are then created by adding \"/new node name\" to the completion
1892 of an existing node. When the value of this variable is `confirm',
1893 new node creation must be confirmed by the user (recommended)
1894 When nil, the completion must match an existing entry.
1896 Note that, if the new heading is not seen by the criteria
1897 listed in `org-refile-targets', multiple instances of the same
1898 heading would be created by trying again to file under the new
1899 heading."
1900 :group 'org-refile
1901 :type '(choice
1902 (const :tag "Never" nil)
1903 (const :tag "Always" t)
1904 (const :tag "Prompt for confirmation" confirm)))
1906 (defgroup org-todo nil
1907 "Options concerning TODO items in Org-mode."
1908 :tag "Org TODO"
1909 :group 'org)
1911 (defgroup org-progress nil
1912 "Options concerning Progress logging in Org-mode."
1913 :tag "Org Progress"
1914 :group 'org-time)
1916 (defvar org-todo-interpretation-widgets
1918 (:tag "Sequence (cycling hits every state)" sequence)
1919 (:tag "Type (cycling directly to DONE)" type))
1920 "The available interpretation symbols for customizing
1921 `org-todo-keywords'.
1922 Interested libraries should add to this list.")
1924 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1925 "List of TODO entry keyword sequences and their interpretation.
1926 \\<org-mode-map>This is a list of sequences.
1928 Each sequence starts with a symbol, either `sequence' or `type',
1929 indicating if the keywords should be interpreted as a sequence of
1930 action steps, or as different types of TODO items. The first
1931 keywords are states requiring action - these states will select a headline
1932 for inclusion into the global TODO list Org-mode produces. If one of
1933 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1934 signify that no further action is necessary. If \"|\" is not found,
1935 the last keyword is treated as the only DONE state of the sequence.
1937 The command \\[org-todo] cycles an entry through these states, and one
1938 additional state where no keyword is present. For details about this
1939 cycling, see the manual.
1941 TODO keywords and interpretation can also be set on a per-file basis with
1942 the special #+SEQ_TODO and #+TYP_TODO lines.
1944 Each keyword can optionally specify a character for fast state selection
1945 \(in combination with the variable `org-use-fast-todo-selection')
1946 and specifiers for state change logging, using the same syntax
1947 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1948 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1949 indicates to record a time stamp each time this state is selected.
1951 Each keyword may also specify if a timestamp or a note should be
1952 recorded when entering or leaving the state, by adding additional
1953 characters in the parenthesis after the keyword. This looks like this:
1954 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1955 record only the time of the state change. With X and Y being either
1956 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1957 Y when leaving the state if and only if the *target* state does not
1958 define X. You may omit any of the fast-selection key or X or /Y,
1959 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1961 For backward compatibility, this variable may also be just a list
1962 of keywords - in this case the interpretation (sequence or type) will be
1963 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1964 :group 'org-todo
1965 :group 'org-keywords
1966 :type '(choice
1967 (repeat :tag "Old syntax, just keywords"
1968 (string :tag "Keyword"))
1969 (repeat :tag "New syntax"
1970 (cons
1971 (choice
1972 :tag "Interpretation"
1973 ;;Quick and dirty way to see
1974 ;;`org-todo-interpretations'. This takes the
1975 ;;place of item arguments
1976 :convert-widget
1977 (lambda (widget)
1978 (widget-put widget
1979 :args (mapcar
1980 #'(lambda (x)
1981 (widget-convert
1982 (cons 'const x)))
1983 org-todo-interpretation-widgets))
1984 widget))
1985 (repeat
1986 (string :tag "Keyword"))))))
1988 (defvar org-todo-keywords-1 nil
1989 "All TODO and DONE keywords active in a buffer.")
1990 (make-variable-buffer-local 'org-todo-keywords-1)
1991 (defvar org-todo-keywords-for-agenda nil)
1992 (defvar org-done-keywords-for-agenda nil)
1993 (defvar org-drawers-for-agenda nil)
1994 (defvar org-todo-keyword-alist-for-agenda nil)
1995 (defvar org-tag-alist-for-agenda nil)
1996 (defvar org-agenda-contributing-files nil)
1997 (defvar org-not-done-keywords nil)
1998 (make-variable-buffer-local 'org-not-done-keywords)
1999 (defvar org-done-keywords nil)
2000 (make-variable-buffer-local 'org-done-keywords)
2001 (defvar org-todo-heads nil)
2002 (make-variable-buffer-local 'org-todo-heads)
2003 (defvar org-todo-sets nil)
2004 (make-variable-buffer-local 'org-todo-sets)
2005 (defvar org-todo-log-states nil)
2006 (make-variable-buffer-local 'org-todo-log-states)
2007 (defvar org-todo-kwd-alist nil)
2008 (make-variable-buffer-local 'org-todo-kwd-alist)
2009 (defvar org-todo-key-alist nil)
2010 (make-variable-buffer-local 'org-todo-key-alist)
2011 (defvar org-todo-key-trigger nil)
2012 (make-variable-buffer-local 'org-todo-key-trigger)
2014 (defcustom org-todo-interpretation 'sequence
2015 "Controls how TODO keywords are interpreted.
2016 This variable is in principle obsolete and is only used for
2017 backward compatibility, if the interpretation of todo keywords is
2018 not given already in `org-todo-keywords'. See that variable for
2019 more information."
2020 :group 'org-todo
2021 :group 'org-keywords
2022 :type '(choice (const sequence)
2023 (const type)))
2025 (defcustom org-use-fast-todo-selection t
2026 "Non-nil means use the fast todo selection scheme with C-c C-t.
2027 This variable describes if and under what circumstances the cycling
2028 mechanism for TODO keywords will be replaced by a single-key, direct
2029 selection scheme.
2031 When nil, fast selection is never used.
2033 When the symbol `prefix', it will be used when `org-todo' is called with
2034 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2035 in an agenda buffer.
2037 When t, fast selection is used by default. In this case, the prefix
2038 argument forces cycling instead.
2040 In all cases, the special interface is only used if access keys have actually
2041 been assigned by the user, i.e. if keywords in the configuration are followed
2042 by a letter in parenthesis, like TODO(t)."
2043 :group 'org-todo
2044 :type '(choice
2045 (const :tag "Never" nil)
2046 (const :tag "By default" t)
2047 (const :tag "Only with C-u C-c C-t" prefix)))
2049 (defcustom org-provide-todo-statistics t
2050 "Non-nil means update todo statistics after insert and toggle.
2051 ALL-HEADLINES means update todo statistics by including headlines
2052 with no TODO keyword as well, counting them as not done.
2053 A list of TODO keywords means the same, but skip keywords that are
2054 not in this list.
2056 When this is set, todo statistics is updated in the parent of the
2057 current entry each time a todo state is changed."
2058 :group 'org-todo
2059 :type '(choice
2060 (const :tag "Yes, only for TODO entries" t)
2061 (const :tag "Yes, including all entries" 'all-headlines)
2062 (repeat :tag "Yes, for TODOs in this list"
2063 (string :tag "TODO keyword"))
2064 (other :tag "No TODO statistics" nil)))
2066 (defcustom org-hierarchical-todo-statistics t
2067 "Non-nil means TODO statistics covers just direct children.
2068 When nil, all entries in the subtree are considered.
2069 This has only an effect if `org-provide-todo-statistics' is set.
2070 To set this to nil for only a single subtree, use a COOKIE_DATA
2071 property and include the word \"recursive\" into the value."
2072 :group 'org-todo
2073 :type 'boolean)
2075 (defcustom org-after-todo-state-change-hook nil
2076 "Hook which is run after the state of a TODO item was changed.
2077 The new state (a string with a TODO keyword, or nil) is available in the
2078 Lisp variable `state'."
2079 :group 'org-todo
2080 :type 'hook)
2082 (defvar org-blocker-hook nil
2083 "Hook for functions that are allowed to block a state change.
2085 Each function gets as its single argument a property list, see
2086 `org-trigger-hook' for more information about this list.
2088 If any of the functions in this hook returns nil, the state change
2089 is blocked.")
2091 (defvar org-trigger-hook nil
2092 "Hook for functions that are triggered by a state change.
2094 Each function gets as its single argument a property list with at least
2095 the following elements:
2097 (:type type-of-change :position pos-at-entry-start
2098 :from old-state :to new-state)
2100 Depending on the type, more properties may be present.
2102 This mechanism is currently implemented for:
2104 TODO state changes
2105 ------------------
2106 :type todo-state-change
2107 :from previous state (keyword as a string), or nil, or a symbol
2108 'todo' or 'done', to indicate the general type of state.
2109 :to new state, like in :from")
2111 (defcustom org-enforce-todo-dependencies nil
2112 "Non-nil means undone TODO entries will block switching the parent to DONE.
2113 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2114 be blocked if any prior sibling is not yet done.
2115 Finally, if the parent is blocked because of ordered siblings of its own,
2116 the child will also be blocked.
2117 This variable needs to be set before org.el is loaded, and you need to
2118 restart Emacs after a change to make the change effective. The only way
2119 to change is while Emacs is running is through the customize interface."
2120 :set (lambda (var val)
2121 (set var val)
2122 (if val
2123 (add-hook 'org-blocker-hook
2124 'org-block-todo-from-children-or-siblings-or-parent)
2125 (remove-hook 'org-blocker-hook
2126 'org-block-todo-from-children-or-siblings-or-parent)))
2127 :group 'org-todo
2128 :type 'boolean)
2130 (defcustom org-enforce-todo-checkbox-dependencies nil
2131 "Non-nil means unchecked boxes will block switching the parent to DONE.
2132 When this is nil, checkboxes have no influence on switching TODO states.
2133 When non-nil, you first need to check off all check boxes before the TODO
2134 entry can be switched to DONE.
2135 This variable needs to be set before org.el is loaded, and you need to
2136 restart Emacs after a change to make the change effective. The only way
2137 to change is while Emacs is running is through the customize interface."
2138 :set (lambda (var val)
2139 (set var val)
2140 (if val
2141 (add-hook 'org-blocker-hook
2142 'org-block-todo-from-checkboxes)
2143 (remove-hook 'org-blocker-hook
2144 'org-block-todo-from-checkboxes)))
2145 :group 'org-todo
2146 :type 'boolean)
2148 (defcustom org-treat-insert-todo-heading-as-state-change nil
2149 "Non-nil means inserting a TODO heading is treated as state change.
2150 So when the command \\[org-insert-todo-heading] is used, state change
2151 logging will apply if appropriate. When nil, the new TODO item will
2152 be inserted directly, and no logging will take place."
2153 :group 'org-todo
2154 :type 'boolean)
2156 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2157 "Non-nil means switching TODO states with S-cursor counts as state change.
2158 This is the default behavior. However, setting this to nil allows a
2159 convenient way to select a TODO state and bypass any logging associated
2160 with that."
2161 :group 'org-todo
2162 :type 'boolean)
2164 (defcustom org-todo-state-tags-triggers nil
2165 "Tag changes that should be triggered by TODO state changes.
2166 This is a list. Each entry is
2168 (state-change (tag . flag) .......)
2170 State-change can be a string with a state, and empty string to indicate the
2171 state that has no TODO keyword, or it can be one of the symbols `todo'
2172 or `done', meaning any not-done or done state, respectively."
2173 :group 'org-todo
2174 :group 'org-tags
2175 :type '(repeat
2176 (cons (choice :tag "When changing to"
2177 (const :tag "Not-done state" todo)
2178 (const :tag "Done state" done)
2179 (string :tag "State"))
2180 (repeat
2181 (cons :tag "Tag action"
2182 (string :tag "Tag")
2183 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2185 (defcustom org-log-done nil
2186 "Information to record when a task moves to the DONE state.
2188 Possible values are:
2190 nil Don't add anything, just change the keyword
2191 time Add a time stamp to the task
2192 note Prompt for a note and add it with template `org-log-note-headings'
2194 This option can also be set with on a per-file-basis with
2196 #+STARTUP: nologdone
2197 #+STARTUP: logdone
2198 #+STARTUP: lognotedone
2200 You can have local logging settings for a subtree by setting the LOGGING
2201 property to one or more of these keywords."
2202 :group 'org-todo
2203 :group 'org-progress
2204 :type '(choice
2205 (const :tag "No logging" nil)
2206 (const :tag "Record CLOSED timestamp" time)
2207 (const :tag "Record CLOSED timestamp with note." note)))
2209 ;; Normalize old uses of org-log-done.
2210 (cond
2211 ((eq org-log-done t) (setq org-log-done 'time))
2212 ((and (listp org-log-done) (memq 'done org-log-done))
2213 (setq org-log-done 'note)))
2215 (defcustom org-log-reschedule nil
2216 "Information to record when the scheduling date of a tasks is modified.
2218 Possible values are:
2220 nil Don't add anything, just change the date
2221 time Add a time stamp to the task
2222 note Prompt for a note and add it with template `org-log-note-headings'
2224 This option can also be set with on a per-file-basis with
2226 #+STARTUP: nologreschedule
2227 #+STARTUP: logreschedule
2228 #+STARTUP: lognotereschedule"
2229 :group 'org-todo
2230 :group 'org-progress
2231 :type '(choice
2232 (const :tag "No logging" nil)
2233 (const :tag "Record timestamp" time)
2234 (const :tag "Record timestamp with note." note)))
2236 (defcustom org-log-redeadline nil
2237 "Information to record when the deadline date of a tasks is modified.
2239 Possible values are:
2241 nil Don't add anything, just change the date
2242 time Add a time stamp to the task
2243 note Prompt for a note and add it with template `org-log-note-headings'
2245 This option can also be set with on a per-file-basis with
2247 #+STARTUP: nologredeadline
2248 #+STARTUP: logredeadline
2249 #+STARTUP: lognoteredeadline
2251 You can have local logging settings for a subtree by setting the LOGGING
2252 property to one or more of these keywords."
2253 :group 'org-todo
2254 :group 'org-progress
2255 :type '(choice
2256 (const :tag "No logging" nil)
2257 (const :tag "Record timestamp" time)
2258 (const :tag "Record timestamp with note." note)))
2260 (defcustom org-log-note-clock-out nil
2261 "Non-nil means record a note when clocking out of an item.
2262 This can also be configured on a per-file basis by adding one of
2263 the following lines anywhere in the buffer:
2265 #+STARTUP: lognoteclock-out
2266 #+STARTUP: nolognoteclock-out"
2267 :group 'org-todo
2268 :group 'org-progress
2269 :type 'boolean)
2271 (defcustom org-log-done-with-time t
2272 "Non-nil means the CLOSED time stamp will contain date and time.
2273 When nil, only the date will be recorded."
2274 :group 'org-progress
2275 :type 'boolean)
2277 (defcustom org-log-note-headings
2278 '((done . "CLOSING NOTE %t")
2279 (state . "State %-12s from %-12S %t")
2280 (note . "Note taken on %t")
2281 (reschedule . "Rescheduled from %S on %t")
2282 (delschedule . "Not scheduled, was %S on %t")
2283 (redeadline . "New deadline from %S on %t")
2284 (deldeadline . "Removed deadline, was %S on %t")
2285 (refile . "Refiled on %t")
2286 (clock-out . ""))
2287 "Headings for notes added to entries.
2288 The value is an alist, with the car being a symbol indicating the note
2289 context, and the cdr is the heading to be used. The heading may also be the
2290 empty string.
2291 %t in the heading will be replaced by a time stamp.
2292 %T will be an acive time stamp instead the default inacive one
2293 %s will be replaced by the new TODO state, in double quotes.
2294 %S will be replaced by the old TODO state, in double quotes.
2295 %u will be replaced by the user name.
2296 %U will be replaced by the full user name.
2298 In fact, it is not a good idea to change the `state' entry, because
2299 agenda log mode depends on the format of these entries."
2300 :group 'org-todo
2301 :group 'org-progress
2302 :type '(list :greedy t
2303 (cons (const :tag "Heading when closing an item" done) string)
2304 (cons (const :tag
2305 "Heading when changing todo state (todo sequence only)"
2306 state) string)
2307 (cons (const :tag "Heading when just taking a note" note) string)
2308 (cons (const :tag "Heading when clocking out" clock-out) string)
2309 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2310 (cons (const :tag "Heading when rescheduling" reschedule) string)
2311 (cons (const :tag "Heading when changing deadline" redeadline) string)
2312 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2313 (cons (const :tag "Heading when refiling" refile) string)))
2315 (unless (assq 'note org-log-note-headings)
2316 (push '(note . "%t") org-log-note-headings))
2318 (defcustom org-log-into-drawer nil
2319 "Non-nil means insert state change notes and time stamps into a drawer.
2320 When nil, state changes notes will be inserted after the headline and
2321 any scheduling and clock lines, but not inside a drawer.
2323 The value of this variable should be the name of the drawer to use.
2324 LOGBOOK is proposed at the default drawer for this purpose, you can
2325 also set this to a string to define the drawer of your choice.
2327 A value of t is also allowed, representing \"LOGBOOK\".
2329 If this variable is set, `org-log-state-notes-insert-after-drawers'
2330 will be ignored.
2332 You can set the property LOG_INTO_DRAWER to overrule this setting for
2333 a subtree."
2334 :group 'org-todo
2335 :group 'org-progress
2336 :type '(choice
2337 (const :tag "Not into a drawer" nil)
2338 (const :tag "LOGBOOK" t)
2339 (string :tag "Other")))
2341 (if (fboundp 'defvaralias)
2342 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2344 (defun org-log-into-drawer ()
2345 "Return the value of `org-log-into-drawer', but let properties overrule.
2346 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2347 used instead of the default value."
2348 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2349 (cond
2350 ((or (not p) (equal p "nil")) org-log-into-drawer)
2351 ((equal p "t") "LOGBOOK")
2352 (t p))))
2354 (defcustom org-log-state-notes-insert-after-drawers nil
2355 "Non-nil means insert state change notes after any drawers in entry.
2356 Only the drawers that *immediately* follow the headline and the
2357 deadline/scheduled line are skipped.
2358 When nil, insert notes right after the heading and perhaps the line
2359 with deadline/scheduling if present.
2361 This variable will have no effect if `org-log-into-drawer' is
2362 set."
2363 :group 'org-todo
2364 :group 'org-progress
2365 :type 'boolean)
2367 (defcustom org-log-states-order-reversed t
2368 "Non-nil means the latest state note will be directly after heading.
2369 When nil, the state change notes will be ordered according to time."
2370 :group 'org-todo
2371 :group 'org-progress
2372 :type 'boolean)
2374 (defcustom org-todo-repeat-to-state nil
2375 "The TODO state to which a repeater should return the repeating task.
2376 By default this is the first task in a TODO sequence, or the previous state
2377 in a TODO_TYP set. But you can specify another task here.
2378 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2379 :group 'org-todo
2380 :type '(choice (const :tag "Head of sequence" nil)
2381 (string :tag "Specific state")))
2383 (defcustom org-log-repeat 'time
2384 "Non-nil means record moving through the DONE state when triggering repeat.
2385 An auto-repeating task is immediately switched back to TODO when
2386 marked DONE. If you are not logging state changes (by adding \"@\"
2387 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2388 record a closing note, there will be no record of the task moving
2389 through DONE. This variable forces taking a note anyway.
2391 nil Don't force a record
2392 time Record a time stamp
2393 note Record a note
2395 This option can also be set with on a per-file-basis with
2397 #+STARTUP: logrepeat
2398 #+STARTUP: lognoterepeat
2399 #+STARTUP: nologrepeat
2401 You can have local logging settings for a subtree by setting the LOGGING
2402 property to one or more of these keywords."
2403 :group 'org-todo
2404 :group 'org-progress
2405 :type '(choice
2406 (const :tag "Don't force a record" nil)
2407 (const :tag "Force recording the DONE state" time)
2408 (const :tag "Force recording a note with the DONE state" note)))
2411 (defgroup org-priorities nil
2412 "Priorities in Org-mode."
2413 :tag "Org Priorities"
2414 :group 'org-todo)
2416 (defcustom org-enable-priority-commands t
2417 "Non-nil means priority commands are active.
2418 When nil, these commands will be disabled, so that you never accidentally
2419 set a priority."
2420 :group 'org-priorities
2421 :type 'boolean)
2423 (defcustom org-highest-priority ?A
2424 "The highest priority of TODO items. A character like ?A, ?B etc.
2425 Must have a smaller ASCII number than `org-lowest-priority'."
2426 :group 'org-priorities
2427 :type 'character)
2429 (defcustom org-lowest-priority ?C
2430 "The lowest priority of TODO items. A character like ?A, ?B etc.
2431 Must have a larger ASCII number than `org-highest-priority'."
2432 :group 'org-priorities
2433 :type 'character)
2435 (defcustom org-default-priority ?B
2436 "The default priority of TODO items.
2437 This is the priority an item get if no explicit priority is given."
2438 :group 'org-priorities
2439 :type 'character)
2441 (defcustom org-priority-start-cycle-with-default t
2442 "Non-nil means start with default priority when starting to cycle.
2443 When this is nil, the first step in the cycle will be (depending on the
2444 command used) one higher or lower that the default priority."
2445 :group 'org-priorities
2446 :type 'boolean)
2448 (defgroup org-time nil
2449 "Options concerning time stamps and deadlines in Org-mode."
2450 :tag "Org Time"
2451 :group 'org)
2453 (defcustom org-insert-labeled-timestamps-at-point nil
2454 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2455 When nil, these labeled time stamps are forces into the second line of an
2456 entry, just after the headline. When scheduling from the global TODO list,
2457 the time stamp will always be forced into the second line."
2458 :group 'org-time
2459 :type 'boolean)
2461 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2462 "Formats for `format-time-string' which are used for time stamps.
2463 It is not recommended to change this constant.")
2465 (defcustom org-time-stamp-rounding-minutes '(0 5)
2466 "Number of minutes to round time stamps to.
2467 These are two values, the first applies when first creating a time stamp.
2468 The second applies when changing it with the commands `S-up' and `S-down'.
2469 When changing the time stamp, this means that it will change in steps
2470 of N minutes, as given by the second value.
2472 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2473 numbers should be factors of 60, so for example 5, 10, 15.
2475 When this is larger than 1, you can still force an exact time-stamp by using
2476 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2477 and by using a prefix arg to `S-up/down' to specify the exact number
2478 of minutes to shift."
2479 :group 'org-time
2480 :get '(lambda (var) ; Make sure both elements are there
2481 (if (integerp (default-value var))
2482 (list (default-value var) 5)
2483 (default-value var)))
2484 :type '(list
2485 (integer :tag "when inserting times")
2486 (integer :tag "when modifying times")))
2488 ;; Normalize old customizations of this variable.
2489 (when (integerp org-time-stamp-rounding-minutes)
2490 (setq org-time-stamp-rounding-minutes
2491 (list org-time-stamp-rounding-minutes
2492 org-time-stamp-rounding-minutes)))
2494 (defcustom org-display-custom-times nil
2495 "Non-nil means overlay custom formats over all time stamps.
2496 The formats are defined through the variable `org-time-stamp-custom-formats'.
2497 To turn this on on a per-file basis, insert anywhere in the file:
2498 #+STARTUP: customtime"
2499 :group 'org-time
2500 :set 'set-default
2501 :type 'sexp)
2502 (make-variable-buffer-local 'org-display-custom-times)
2504 (defcustom org-time-stamp-custom-formats
2505 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2506 "Custom formats for time stamps. See `format-time-string' for the syntax.
2507 These are overlayed over the default ISO format if the variable
2508 `org-display-custom-times' is set. Time like %H:%M should be at the
2509 end of the second format. The custom formats are also honored by export
2510 commands, if custom time display is turned on at the time of export."
2511 :group 'org-time
2512 :type 'sexp)
2514 (defun org-time-stamp-format (&optional long inactive)
2515 "Get the right format for a time string."
2516 (let ((f (if long (cdr org-time-stamp-formats)
2517 (car org-time-stamp-formats))))
2518 (if inactive
2519 (concat "[" (substring f 1 -1) "]")
2520 f)))
2522 (defcustom org-time-clocksum-format "%d:%02d"
2523 "The format string used when creating CLOCKSUM lines, or when
2524 org-mode generates a time duration."
2525 :group 'org-time
2526 :type 'string)
2528 (defcustom org-time-clocksum-use-fractional nil
2529 "If non-nil, \\[org-clock-display] uses fractional times.
2530 org-mode generates a time duration."
2531 :group 'org-time
2532 :type 'boolean)
2534 (defcustom org-time-clocksum-fractional-format "%.2f"
2535 "The format string used when creating CLOCKSUM lines, or when
2536 org-mode generates a time duration."
2537 :group 'org-time
2538 :type 'string)
2540 (defcustom org-deadline-warning-days 14
2541 "No. of days before expiration during which a deadline becomes active.
2542 This variable governs the display in sparse trees and in the agenda.
2543 When 0 or negative, it means use this number (the absolute value of it)
2544 even if a deadline has a different individual lead time specified.
2546 Custom commands can set this variable in the options section."
2547 :group 'org-time
2548 :group 'org-agenda-daily/weekly
2549 :type 'integer)
2551 (defcustom org-read-date-prefer-future t
2552 "Non-nil means assume future for incomplete date input from user.
2553 This affects the following situations:
2554 1. The user gives a month but not a year.
2555 For example, if it is april and you enter \"feb 2\", this will be read
2556 as feb 2, *next* year. \"May 5\", however, will be this year.
2557 2. The user gives a day, but no month.
2558 For example, if today is the 15th, and you enter \"3\", Org-mode will
2559 read this as the third of *next* month. However, if you enter \"17\",
2560 it will be considered as *this* month.
2562 If you set this variable to the symbol `time', then also the following
2563 will work:
2565 3. If the user gives a time, but no day. If the time is before now,
2566 to will be interpreted as tomorrow.
2568 Currently none of this works for ISO week specifications.
2570 When this option is nil, the current day, month and year will always be
2571 used as defaults."
2572 :group 'org-time
2573 :type '(choice
2574 (const :tag "Never" nil)
2575 (const :tag "Check month and day" t)
2576 (const :tag "Check month, day, and time" time)))
2578 (defcustom org-read-date-display-live t
2579 "Non-nil means display current interpretation of date prompt live.
2580 This display will be in an overlay, in the minibuffer."
2581 :group 'org-time
2582 :type 'boolean)
2584 (defcustom org-read-date-popup-calendar t
2585 "Non-nil means pop up a calendar when prompting for a date.
2586 In the calendar, the date can be selected with mouse-1. However, the
2587 minibuffer will also be active, and you can simply enter the date as well.
2588 When nil, only the minibuffer will be available."
2589 :group 'org-time
2590 :type 'boolean)
2591 (if (fboundp 'defvaralias)
2592 (defvaralias 'org-popup-calendar-for-date-prompt
2593 'org-read-date-popup-calendar))
2595 (defcustom org-read-date-minibuffer-setup-hook nil
2596 "Hook to be used to set up keys for the date/time interface.
2597 Add key definitions to `minibuffer-local-map', which will be a temporary
2598 copy."
2599 :group 'org-time
2600 :type 'hook)
2602 (defcustom org-extend-today-until 0
2603 "The hour when your day really ends. Must be an integer.
2604 This has influence for the following applications:
2605 - When switching the agenda to \"today\". It it is still earlier than
2606 the time given here, the day recognized as TODAY is actually yesterday.
2607 - When a date is read from the user and it is still before the time given
2608 here, the current date and time will be assumed to be yesterday, 23:59.
2609 Also, timestamps inserted in remember templates follow this rule.
2611 IMPORTANT: This is a feature whose implementation is and likely will
2612 remain incomplete. Really, it is only here because past midnight seems to
2613 be the favorite working time of John Wiegley :-)"
2614 :group 'org-time
2615 :type 'integer)
2617 (defcustom org-edit-timestamp-down-means-later nil
2618 "Non-nil means S-down will increase the time in a time stamp.
2619 When nil, S-up will increase."
2620 :group 'org-time
2621 :type 'boolean)
2623 (defcustom org-calendar-follow-timestamp-change t
2624 "Non-nil means make the calendar window follow timestamp changes.
2625 When a timestamp is modified and the calendar window is visible, it will be
2626 moved to the new date."
2627 :group 'org-time
2628 :type 'boolean)
2630 (defgroup org-tags nil
2631 "Options concerning tags in Org-mode."
2632 :tag "Org Tags"
2633 :group 'org)
2635 (defcustom org-tag-alist nil
2636 "List of tags allowed in Org-mode files.
2637 When this list is nil, Org-mode will base TAG input on what is already in the
2638 buffer.
2639 The value of this variable is an alist, the car of each entry must be a
2640 keyword as a string, the cdr may be a character that is used to select
2641 that tag through the fast-tag-selection interface.
2642 See the manual for details."
2643 :group 'org-tags
2644 :type '(repeat
2645 (choice
2646 (cons (string :tag "Tag name")
2647 (character :tag "Access char"))
2648 (list :tag "Start radio group"
2649 (const :startgroup)
2650 (option (string :tag "Group description")))
2651 (list :tag "End radio group"
2652 (const :endgroup)
2653 (option (string :tag "Group description")))
2654 (const :tag "New line" (:newline)))))
2656 (defcustom org-tag-persistent-alist nil
2657 "List of tags that will always appear in all Org-mode files.
2658 This is in addition to any in buffer settings or customizations
2659 of `org-tag-alist'.
2660 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2661 The value of this variable is an alist, the car of each entry must be a
2662 keyword as a string, the cdr may be a character that is used to select
2663 that tag through the fast-tag-selection interface.
2664 See the manual for details.
2665 To disable these tags on a per-file basis, insert anywhere in the file:
2666 #+STARTUP: noptag"
2667 :group 'org-tags
2668 :type '(repeat
2669 (choice
2670 (cons (string :tag "Tag name")
2671 (character :tag "Access char"))
2672 (const :tag "Start radio group" (:startgroup))
2673 (const :tag "End radio group" (:endgroup))
2674 (const :tag "New line" (:newline)))))
2676 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2677 "If non-nil, always offer completion for all tags of all agenda files.
2678 Instead of customizing this variable directly, you might want to
2679 set it locally for remember buffers, because there no list of
2680 tags in that file can be created dynamically (there are none).
2682 (add-hook 'org-remember-mode-hook
2683 (lambda ()
2684 (set (make-local-variable
2685 'org-complete-tags-always-offer-all-agenda-tags)
2686 t)))"
2687 :group 'org-tags
2688 :type 'boolean)
2690 (defvar org-file-tags nil
2691 "List of tags that can be inherited by all entries in the file.
2692 The tags will be inherited if the variable `org-use-tag-inheritance'
2693 says they should be.
2694 This variable is populated from #+FILETAGS lines.")
2696 (defcustom org-use-fast-tag-selection 'auto
2697 "Non-nil means use fast tag selection scheme.
2698 This is a special interface to select and deselect tags with single keys.
2699 When nil, fast selection is never used.
2700 When the symbol `auto', fast selection is used if and only if selection
2701 characters for tags have been configured, either through the variable
2702 `org-tag-alist' or through a #+TAGS line in the buffer.
2703 When t, fast selection is always used and selection keys are assigned
2704 automatically if necessary."
2705 :group 'org-tags
2706 :type '(choice
2707 (const :tag "Always" t)
2708 (const :tag "Never" nil)
2709 (const :tag "When selection characters are configured" 'auto)))
2711 (defcustom org-fast-tag-selection-single-key nil
2712 "Non-nil means fast tag selection exits after first change.
2713 When nil, you have to press RET to exit it.
2714 During fast tag selection, you can toggle this flag with `C-c'.
2715 This variable can also have the value `expert'. In this case, the window
2716 displaying the tags menu is not even shown, until you press C-c again."
2717 :group 'org-tags
2718 :type '(choice
2719 (const :tag "No" nil)
2720 (const :tag "Yes" t)
2721 (const :tag "Expert" expert)))
2723 (defvar org-fast-tag-selection-include-todo nil
2724 "Non-nil means fast tags selection interface will also offer TODO states.
2725 This is an undocumented feature, you should not rely on it.")
2727 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2728 "The column to which tags should be indented in a headline.
2729 If this number is positive, it specifies the column. If it is negative,
2730 it means that the tags should be flushright to that column. For example,
2731 -80 works well for a normal 80 character screen."
2732 :group 'org-tags
2733 :type 'integer)
2735 (defcustom org-auto-align-tags t
2736 "Non-nil means realign tags after pro/demotion of TODO state change.
2737 These operations change the length of a headline and therefore shift
2738 the tags around. With this options turned on, after each such operation
2739 the tags are again aligned to `org-tags-column'."
2740 :group 'org-tags
2741 :type 'boolean)
2743 (defcustom org-use-tag-inheritance t
2744 "Non-nil means tags in levels apply also for sublevels.
2745 When nil, only the tags directly given in a specific line apply there.
2746 This may also be a list of tags that should be inherited, or a regexp that
2747 matches tags that should be inherited. Additional control is possible
2748 with the variable `org-tags-exclude-from-inheritance' which gives an
2749 explicit list of tags to be excluded from inheritance., even if the value of
2750 `org-use-tag-inheritance' would select it for inheritance.
2752 If this option is t, a match early-on in a tree can lead to a large
2753 number of matches in the subtree when constructing the agenda or creating
2754 a sparse tree. If you only want to see the first match in a tree during
2755 a search, check out the variable `org-tags-match-list-sublevels'."
2756 :group 'org-tags
2757 :type '(choice
2758 (const :tag "Not" nil)
2759 (const :tag "Always" t)
2760 (repeat :tag "Specific tags" (string :tag "Tag"))
2761 (regexp :tag "Tags matched by regexp")))
2763 (defcustom org-tags-exclude-from-inheritance nil
2764 "List of tags that should never be inherited.
2765 This is a way to exclude a few tags from inheritance. For way to do
2766 the opposite, to actively allow inheritance for selected tags,
2767 see the variable `org-use-tag-inheritance'."
2768 :group 'org-tags
2769 :type '(repeat (string :tag "Tag")))
2771 (defun org-tag-inherit-p (tag)
2772 "Check if TAG is one that should be inherited."
2773 (cond
2774 ((member tag org-tags-exclude-from-inheritance) nil)
2775 ((eq org-use-tag-inheritance t) t)
2776 ((not org-use-tag-inheritance) nil)
2777 ((stringp org-use-tag-inheritance)
2778 (string-match org-use-tag-inheritance tag))
2779 ((listp org-use-tag-inheritance)
2780 (member tag org-use-tag-inheritance))
2781 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2783 (defcustom org-tags-match-list-sublevels t
2784 "Non-nil means list also sublevels of headlines matching a search.
2785 This variable applies to tags/property searches, and also to stuck
2786 projects because this search is based on a tags match as well.
2788 When set to the symbol `indented', sublevels are indented with
2789 leading dots.
2791 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2792 the sublevels of a headline matching a tag search often also match
2793 the same search. Listing all of them can create very long lists.
2794 Setting this variable to nil causes subtrees of a match to be skipped.
2796 This variable is semi-obsolete and probably should always be true. It
2797 is better to limit inheritance to certain tags using the variables
2798 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2799 :group 'org-tags
2800 :type '(choice
2801 (const :tag "No, don't list them" nil)
2802 (const :tag "Yes, do list them" t)
2803 (const :tag "List them, indented with leading dots" indented)))
2805 (defcustom org-tags-sort-function nil
2806 "When set, tags are sorted using this function as a comparator"
2807 :group 'org-tags
2808 :type '(choice
2809 (const :tag "No sorting" nil)
2810 (const :tag "Alphabetical" string<)
2811 (const :tag "Reverse alphabetical" string>)
2812 (function :tag "Custom function" nil)))
2814 (defvar org-tags-history nil
2815 "History of minibuffer reads for tags.")
2816 (defvar org-last-tags-completion-table nil
2817 "The last used completion table for tags.")
2818 (defvar org-after-tags-change-hook nil
2819 "Hook that is run after the tags in a line have changed.")
2821 (defgroup org-properties nil
2822 "Options concerning properties in Org-mode."
2823 :tag "Org Properties"
2824 :group 'org)
2826 (defcustom org-property-format "%-10s %s"
2827 "How property key/value pairs should be formatted by `indent-line'.
2828 When `indent-line' hits a property definition, it will format the line
2829 according to this format, mainly to make sure that the values are
2830 lined-up with respect to each other."
2831 :group 'org-properties
2832 :type 'string)
2834 (defcustom org-use-property-inheritance nil
2835 "Non-nil means properties apply also for sublevels.
2837 This setting is chiefly used during property searches. Turning it on can
2838 cause significant overhead when doing a search, which is why it is not
2839 on by default.
2841 When nil, only the properties directly given in the current entry count.
2842 When t, every property is inherited. The value may also be a list of
2843 properties that should have inheritance, or a regular expression matching
2844 properties that should be inherited.
2846 However, note that some special properties use inheritance under special
2847 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2848 and the properties ending in \"_ALL\" when they are used as descriptor
2849 for valid values of a property.
2851 Note for programmers:
2852 When querying an entry with `org-entry-get', you can control if inheritance
2853 should be used. By default, `org-entry-get' looks only at the local
2854 properties. You can request inheritance by setting the inherit argument
2855 to t (to force inheritance) or to `selective' (to respect the setting
2856 in this variable)."
2857 :group 'org-properties
2858 :type '(choice
2859 (const :tag "Not" nil)
2860 (const :tag "Always" t)
2861 (repeat :tag "Specific properties" (string :tag "Property"))
2862 (regexp :tag "Properties matched by regexp")))
2864 (defun org-property-inherit-p (property)
2865 "Check if PROPERTY is one that should be inherited."
2866 (cond
2867 ((eq org-use-property-inheritance t) t)
2868 ((not org-use-property-inheritance) nil)
2869 ((stringp org-use-property-inheritance)
2870 (string-match org-use-property-inheritance property))
2871 ((listp org-use-property-inheritance)
2872 (member property org-use-property-inheritance))
2873 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2875 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2876 "The default column format, if no other format has been defined.
2877 This variable can be set on the per-file basis by inserting a line
2879 #+COLUMNS: %25ITEM ....."
2880 :group 'org-properties
2881 :type 'string)
2883 (defcustom org-columns-ellipses ".."
2884 "The ellipses to be used when a field in column view is truncated.
2885 When this is the empty string, as many characters as possible are shown,
2886 but then there will be no visual indication that the field has been truncated.
2887 When this is a string of length N, the last N characters of a truncated
2888 field are replaced by this string. If the column is narrower than the
2889 ellipses string, only part of the ellipses string will be shown."
2890 :group 'org-properties
2891 :type 'string)
2893 (defcustom org-columns-modify-value-for-display-function nil
2894 "Function that modifies values for display in column view.
2895 For example, it can be used to cut out a certain part from a time stamp.
2896 The function must take 2 arguments:
2898 column-title The title of the column (*not* the property name)
2899 value The value that should be modified.
2901 The function should return the value that should be displayed,
2902 or nil if the normal value should be used."
2903 :group 'org-properties
2904 :type 'function)
2906 (defcustom org-effort-property "Effort"
2907 "The property that is being used to keep track of effort estimates.
2908 Effort estimates given in this property need to have the format H:MM."
2909 :group 'org-properties
2910 :group 'org-progress
2911 :type '(string :tag "Property"))
2913 (defconst org-global-properties-fixed
2914 '(("VISIBILITY_ALL" . "folded children content all")
2915 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2916 "List of property/value pairs that can be inherited by any entry.
2918 These are fixed values, for the preset properties. The user variable
2919 that can be used to add to this list is `org-global-properties'.
2921 The entries in this list are cons cells where the car is a property
2922 name and cdr is a string with the value. If the value represents
2923 multiple items like an \"_ALL\" property, separate the items by
2924 spaces.")
2926 (defcustom org-global-properties nil
2927 "List of property/value pairs that can be inherited by any entry.
2929 This list will be combined with the constant `org-global-properties-fixed'.
2931 The entries in this list are cons cells where the car is a property
2932 name and cdr is a string with the value.
2934 You can set buffer-local values for the same purpose in the variable
2935 `org-file-properties' this by adding lines like
2937 #+PROPERTY: NAME VALUE"
2938 :group 'org-properties
2939 :type '(repeat
2940 (cons (string :tag "Property")
2941 (string :tag "Value"))))
2943 (defvar org-file-properties nil
2944 "List of property/value pairs that can be inherited by any entry.
2945 Valid for the current buffer.
2946 This variable is populated from #+PROPERTY lines.")
2947 (make-variable-buffer-local 'org-file-properties)
2949 (defgroup org-agenda nil
2950 "Options concerning agenda views in Org-mode."
2951 :tag "Org Agenda"
2952 :group 'org)
2954 (defvar org-category nil
2955 "Variable used by org files to set a category for agenda display.
2956 Such files should use a file variable to set it, for example
2958 # -*- mode: org; org-category: \"ELisp\"
2960 or contain a special line
2962 #+CATEGORY: ELisp
2964 If the file does not specify a category, then file's base name
2965 is used instead.")
2966 (make-variable-buffer-local 'org-category)
2967 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2969 (defcustom org-agenda-files nil
2970 "The files to be used for agenda display.
2971 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2972 \\[org-remove-file]. You can also use customize to edit the list.
2974 If an entry is a directory, all files in that directory that are matched by
2975 `org-agenda-file-regexp' will be part of the file list.
2977 If the value of the variable is not a list but a single file name, then
2978 the list of agenda files is actually stored and maintained in that file, one
2979 agenda file per line. In this file paths can be given relative to
2980 `org-directory'. Tilde expansion and environment variable substitution
2981 are also made."
2982 :group 'org-agenda
2983 :type '(choice
2984 (repeat :tag "List of files and directories" file)
2985 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2987 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2988 "Regular expression to match files for `org-agenda-files'.
2989 If any element in the list in that variable contains a directory instead
2990 of a normal file, all files in that directory that are matched by this
2991 regular expression will be included."
2992 :group 'org-agenda
2993 :type 'regexp)
2995 (defcustom org-agenda-text-search-extra-files nil
2996 "List of extra files to be searched by text search commands.
2997 These files will be search in addition to the agenda files by the
2998 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2999 Note that these files will only be searched for text search commands,
3000 not for the other agenda views like todo lists, tag searches or the weekly
3001 agenda. This variable is intended to list notes and possibly archive files
3002 that should also be searched by these two commands.
3003 In fact, if the first element in the list is the symbol `agenda-archives',
3004 than all archive files of all agenda files will be added to the search
3005 scope."
3006 :group 'org-agenda
3007 :type '(set :greedy t
3008 (const :tag "Agenda Archives" agenda-archives)
3009 (repeat :inline t (file))))
3011 (if (fboundp 'defvaralias)
3012 (defvaralias 'org-agenda-multi-occur-extra-files
3013 'org-agenda-text-search-extra-files))
3015 (defcustom org-agenda-skip-unavailable-files nil
3016 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3017 A nil value means to remove them, after a query, from the list."
3018 :group 'org-agenda
3019 :type 'boolean)
3021 (defcustom org-calendar-to-agenda-key [?c]
3022 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3023 The command `org-calendar-goto-agenda' will be bound to this key. The
3024 default is the character `c' because then `c' can be used to switch back and
3025 forth between agenda and calendar."
3026 :group 'org-agenda
3027 :type 'sexp)
3029 (defcustom org-calendar-agenda-action-key [?k]
3030 "The key to be installed in `calendar-mode-map' for agenda-action.
3031 The command `org-agenda-action' will be bound to this key. The
3032 default is the character `k' because we use the same key in the agenda."
3033 :group 'org-agenda
3034 :type 'sexp)
3036 (defcustom org-calendar-insert-diary-entry-key [?i]
3037 "The key to be installed in `calendar-mode-map' for adding diary entries.
3038 This option is irrelevant until `org-agenda-diary-file' has been configured
3039 to point to an Org-mode file. When that is the case, the command
3040 `org-agenda-diary-entry' will be bound to the key given here, by default
3041 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3042 if you want to continue doing this, you need to change this to a different
3043 key."
3044 :group 'org-agenda
3045 :type 'sexp)
3047 (defcustom org-agenda-diary-file 'diary-file
3048 "File to which to add new entries with the `i' key in agenda and calendar.
3049 When this is the symbol `diary-file', the functionality in the Emacs
3050 calendar will be used to add entries to the `diary-file'. But when this
3051 points to a file, `org-agenda-diary-entry' will be used instead."
3052 :group 'org-agenda
3053 :type '(choice
3054 (const :tag "The standard Emacs diary file" diary-file)
3055 (file :tag "Special Org file diary entries")))
3057 (eval-after-load "calendar"
3058 '(progn
3059 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3060 'org-calendar-goto-agenda)
3061 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3062 'org-agenda-action)
3063 (add-hook 'calendar-mode-hook
3064 (lambda ()
3065 (unless (eq org-agenda-diary-file 'diary-file)
3066 (define-key calendar-mode-map
3067 org-calendar-insert-diary-entry-key
3068 'org-agenda-diary-entry))))))
3070 (defgroup org-latex nil
3071 "Options for embedding LaTeX code into Org-mode."
3072 :tag "Org LaTeX"
3073 :group 'org)
3075 (defcustom org-format-latex-options
3076 '(:foreground default :background default :scale 1.0
3077 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
3078 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3079 "Options for creating images from LaTeX fragments.
3080 This is a property list with the following properties:
3081 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3082 `default' means use the foreground of the default face.
3083 :background the background color, or \"Transparent\".
3084 `default' means use the background of the default face.
3085 :scale a scaling factor for the size of the images.
3086 :html-foreground, :html-background, :html-scale
3087 the same numbers for HTML export.
3088 :matchers a list indicating which matchers should be used to
3089 find LaTeX fragments. Valid members of this list are:
3090 \"begin\" find environments
3091 \"$1\" find single characters surrounded by $.$
3092 \"$\" find math expressions surrounded by $...$
3093 \"$$\" find math expressions surrounded by $$....$$
3094 \"\\(\" find math expressions surrounded by \\(...\\)
3095 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3096 :group 'org-latex
3097 :type 'plist)
3099 (defcustom org-format-latex-signal-error t
3100 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3101 When nil, just push out a message."
3102 :group 'org-latex
3103 :type 'boolean)
3105 (defcustom org-format-latex-header "\\documentclass{article}
3106 \\usepackage[usenames]{color}
3107 \\usepackage{amsmath}
3108 \\usepackage[mathscr]{eucal}
3109 \\pagestyle{empty} % do not remove
3110 \[PACKAGES]
3111 \[DEFAULT-PACKAGES]
3112 % The settings below are copied from fullpage.sty
3113 \\setlength{\\textwidth}{\\paperwidth}
3114 \\addtolength{\\textwidth}{-3cm}
3115 \\setlength{\\oddsidemargin}{1.5cm}
3116 \\addtolength{\\oddsidemargin}{-2.54cm}
3117 \\setlength{\\evensidemargin}{\\oddsidemargin}
3118 \\setlength{\\textheight}{\\paperheight}
3119 \\addtolength{\\textheight}{-\\headheight}
3120 \\addtolength{\\textheight}{-\\headsep}
3121 \\addtolength{\\textheight}{-\\footskip}
3122 \\addtolength{\\textheight}{-3cm}
3123 \\setlength{\\topmargin}{1.5cm}
3124 \\addtolength{\\topmargin}{-2.54cm}"
3125 "The document header used for processing LaTeX fragments.
3126 It is imperative that this header make sure that no page number
3127 appears on the page. The package defined in the variables
3128 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3129 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3130 will be appended."
3131 :group 'org-latex
3132 :type 'string)
3134 (defvar org-format-latex-header-extra nil)
3136 (defun org-set-packages-alist (var val)
3137 "Set the packages alist and make sure it has 3 elements per entry."
3138 (set var (mapcar (lambda (x)
3139 (if (and (consp x) (= (length x) 2))
3140 (list (car x) (nth 1 x) t)
3142 val)))
3144 (defun org-get-packages-alist (var)
3146 "Get the packages alist and make sure it has 3 elements per entry."
3147 (mapcar (lambda (x)
3148 (if (and (consp x) (= (length x) 2))
3149 (list (car x) (nth 1 x) t)
3151 (default-value var)))
3153 ;; The following variables are defined here because is it also used
3154 ;; when formatting latex fragments. Originally it was part of the
3155 ;; LaTeX exporter, which is why the name includes "export".
3156 (defcustom org-export-latex-default-packages-alist
3157 '(("AUTO" "inputenc" t)
3158 ("T1" "fontenc" t)
3159 ("" "fixltx2e" nil)
3160 ("" "graphicx" t)
3161 ("" "longtable" nil)
3162 ("" "float" nil)
3163 ("" "wrapfig" nil)
3164 ("" "soul" t)
3165 ("" "t1enc" t)
3166 ("" "textcomp" t)
3167 ("" "marvosym" t)
3168 ("" "wasysym" t)
3169 ("" "latexsym" t)
3170 ("" "amssymb" t)
3171 ("" "hyperref" nil)
3172 "\\tolerance=1000"
3174 "Alist of default packages to be inserted in the header.
3175 Change this only if one of the packages here causes an incompatibility
3176 with another package you are using.
3177 The packages in this list are needed by one part or another of Org-mode
3178 to function properly.
3180 - inputenc, fontenc, t1enc: for basic font and character selection
3181 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3182 for interpreting the entities in `org-entities'. You can skip some of these
3183 packages if you don't use any of the symbols in it.
3184 - graphicx: for including images
3185 - float, wrapfig: for figure placement
3186 - longtable: for long tables
3187 - hyperref: for cross references
3189 Therefore you should not modify this variable unless you know what you
3190 are doing. The one reason to change it anyway is that you might be loading
3191 some other package that conflicts with one of the default packages.
3192 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3193 If SNIPPET-FLAG is t, the package also needs to be included when
3194 compiling LaTeX snippets into images for inclusion into HTML."
3195 :group 'org-export-latex
3196 :set 'org-set-packages-alist
3197 :get 'org-get-packages-alist
3198 :type '(repeat
3199 (choice
3200 (list :tag "options/package pair"
3201 (string :tag "options")
3202 (string :tag "package")
3203 (boolean :tag "Snippet"))
3204 (string :tag "A line of LaTeX"))))
3206 (defcustom org-export-latex-packages-alist nil
3207 "Alist of packages to be inserted in every LaTeX header.
3208 These will be inserted after `org-export-latex-default-packages-alist'.
3209 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3210 SNIPPET-FLAG, when t, indicates that this package is also needed when
3211 turning LaTeX snippets into images for inclusion into HTML.
3212 Make sure that you only list packages here which:
3213 - you want in every file
3214 - do not conflict with the default packages in
3215 `org-export-latex-default-packages-alist'
3216 - do not conflict with the setup in `org-format-latex-header'."
3217 :group 'org-export-latex
3218 :set 'org-set-packages-alist
3219 :get 'org-get-packages-alist
3220 :type '(repeat
3221 (choice
3222 (list :tag "options/package pair"
3223 (string :tag "options")
3224 (string :tag "package")
3225 (boolean :tag "Snippet"))
3226 (string :tag "A line of LaTeX"))))
3229 (defgroup org-appearance nil
3230 "Settings for Org-mode appearance."
3231 :tag "Org Appearance"
3232 :group 'org)
3234 (defcustom org-level-color-stars-only nil
3235 "Non-nil means fontify only the stars in each headline.
3236 When nil, the entire headline is fontified.
3237 Changing it requires restart of `font-lock-mode' to become effective
3238 also in regions already fontified."
3239 :group 'org-appearance
3240 :type 'boolean)
3242 (defcustom org-hide-leading-stars nil
3243 "Non-nil means hide the first N-1 stars in a headline.
3244 This works by using the face `org-hide' for these stars. This
3245 face is white for a light background, and black for a dark
3246 background. You may have to customize the face `org-hide' to
3247 make this work.
3248 Changing it requires restart of `font-lock-mode' to become effective
3249 also in regions already fontified.
3250 You may also set this on a per-file basis by adding one of the following
3251 lines to the buffer:
3253 #+STARTUP: hidestars
3254 #+STARTUP: showstars"
3255 :group 'org-appearance
3256 :type 'boolean)
3258 (defcustom org-hidden-keywords nil
3259 "List of keywords that should be hidden when typed in the org buffer.
3260 For example, add #+TITLE to this list in order to make the
3261 document title appear in the buffer without the initial #+TITLE:
3262 keyword."
3263 :group 'org-appearance
3264 :type '(set (const :tag "#+AUTHOR" author)
3265 (const :tag "#+DATE" date)
3266 (const :tag "#+EMAIL" email)
3267 (const :tag "#+TITLE" title)))
3269 (defcustom org-fontify-done-headline nil
3270 "Non-nil means change the face of a headline if it is marked DONE.
3271 Normally, only the TODO/DONE keyword indicates the state of a headline.
3272 When this is non-nil, the headline after the keyword is set to the
3273 `org-headline-done' as an additional indication."
3274 :group 'org-appearance
3275 :type 'boolean)
3277 (defcustom org-fontify-emphasized-text t
3278 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3279 Changing this variable requires a restart of Emacs to take effect."
3280 :group 'org-appearance
3281 :type 'boolean)
3283 (defcustom org-fontify-whole-heading-line nil
3284 "Non-nil means fontify the whole line for headings.
3285 This is useful when setting a background color for the
3286 org-level-* faces."
3287 :group 'org-appearance
3288 :type 'boolean)
3290 (defcustom org-highlight-latex-fragments-and-specials nil
3291 "Non-nil means fontify what is treated specially by the exporters."
3292 :group 'org-appearance
3293 :type 'boolean)
3295 (defcustom org-hide-emphasis-markers nil
3296 "Non-nil mean font-lock should hide the emphasis marker characters."
3297 :group 'org-appearance
3298 :type 'boolean)
3300 (defcustom org-pretty-entities nil
3301 "Non-nil means show entities as UTF8 characters.
3302 When nil, the \\name form remains in the buffer."
3303 :group 'org-appearance
3304 :type 'boolean)
3306 (defcustom org-pretty-entities-include-sub-superscripts t
3307 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3308 :group 'org-appearance
3309 :type 'boolean)
3311 (defvar org-emph-re nil
3312 "Regular expression for matching emphasis.
3313 After a match, the match groups contain these elements:
3314 1 The character before the proper match, or empty at beginning of line
3315 2 The proper match, including the leading and trailing markers
3316 3 The leading marker like * or /, indicating the type of highlighting
3317 4 The text between the emphasis markers, not including the markers
3318 5 The character after the match, empty at the end of a line")
3319 (defvar org-verbatim-re nil
3320 "Regular expression for matching verbatim text.")
3321 (defvar org-emphasis-regexp-components) ; defined just below
3322 (defvar org-emphasis-alist) ; defined just below
3323 (defun org-set-emph-re (var val)
3324 "Set variable and compute the emphasis regular expression."
3325 (set var val)
3326 (when (and (boundp 'org-emphasis-alist)
3327 (boundp 'org-emphasis-regexp-components)
3328 org-emphasis-alist org-emphasis-regexp-components)
3329 (let* ((e org-emphasis-regexp-components)
3330 (pre (car e))
3331 (post (nth 1 e))
3332 (border (nth 2 e))
3333 (body (nth 3 e))
3334 (nl (nth 4 e))
3335 (body1 (concat body "*?"))
3336 (markers (mapconcat 'car org-emphasis-alist ""))
3337 (vmarkers (mapconcat
3338 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3339 org-emphasis-alist "")))
3340 ;; make sure special characters appear at the right position in the class
3341 (if (string-match "\\^" markers)
3342 (setq markers (concat (replace-match "" t t markers) "^")))
3343 (if (string-match "-" markers)
3344 (setq markers (concat (replace-match "" t t markers) "-")))
3345 (if (string-match "\\^" vmarkers)
3346 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3347 (if (string-match "-" vmarkers)
3348 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3349 (if (> nl 0)
3350 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3351 (int-to-string nl) "\\}")))
3352 ;; Make the regexp
3353 (setq org-emph-re
3354 (concat "\\([" pre "]\\|^\\)"
3355 "\\("
3356 "\\([" markers "]\\)"
3357 "\\("
3358 "[^" border "]\\|"
3359 "[^" border "]"
3360 body1
3361 "[^" border "]"
3362 "\\)"
3363 "\\3\\)"
3364 "\\([" post "]\\|$\\)"))
3365 (setq org-verbatim-re
3366 (concat "\\([" pre "]\\|^\\)"
3367 "\\("
3368 "\\([" vmarkers "]\\)"
3369 "\\("
3370 "[^" border "]\\|"
3371 "[^" border "]"
3372 body1
3373 "[^" border "]"
3374 "\\)"
3375 "\\3\\)"
3376 "\\([" post "]\\|$\\)")))))
3378 (defcustom org-emphasis-regexp-components
3379 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3380 "Components used to build the regular expression for emphasis.
3381 This is a list with 6 entries. Terminology: In an emphasis string
3382 like \" *strong word* \", we call the initial space PREMATCH, the final
3383 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3384 and \"trong wor\" is the body. The different components in this variable
3385 specify what is allowed/forbidden in each part:
3387 pre Chars allowed as prematch. Beginning of line will be allowed too.
3388 post Chars allowed as postmatch. End of line will be allowed too.
3389 border The chars *forbidden* as border characters.
3390 body-regexp A regexp like \".\" to match a body character. Don't use
3391 non-shy groups here, and don't allow newline here.
3392 newline The maximum number of newlines allowed in an emphasis exp.
3394 Use customize to modify this, or restart Emacs after changing it."
3395 :group 'org-appearance
3396 :set 'org-set-emph-re
3397 :type '(list
3398 (sexp :tag "Allowed chars in pre ")
3399 (sexp :tag "Allowed chars in post ")
3400 (sexp :tag "Forbidden chars in border ")
3401 (sexp :tag "Regexp for body ")
3402 (integer :tag "number of newlines allowed")
3403 (option (boolean :tag "Please ignore this button"))))
3405 (defcustom org-emphasis-alist
3406 `(("*" bold "<b>" "</b>")
3407 ("/" italic "<i>" "</i>")
3408 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3409 ("=" org-code "<code>" "</code>" verbatim)
3410 ("~" org-verbatim "<code>" "</code>" verbatim)
3411 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3412 "<del>" "</del>")
3414 "Special syntax for emphasized text.
3415 Text starting and ending with a special character will be emphasized, for
3416 example *bold*, _underlined_ and /italic/. This variable sets the marker
3417 characters, the face to be used by font-lock for highlighting in Org-mode
3418 Emacs buffers, and the HTML tags to be used for this.
3419 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3420 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3421 Use customize to modify this, or restart Emacs after changing it."
3422 :group 'org-appearance
3423 :set 'org-set-emph-re
3424 :type '(repeat
3425 (list
3426 (string :tag "Marker character")
3427 (choice
3428 (face :tag "Font-lock-face")
3429 (plist :tag "Face property list"))
3430 (string :tag "HTML start tag")
3431 (string :tag "HTML end tag")
3432 (option (const verbatim)))))
3434 (defvar org-protecting-blocks
3435 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3436 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3437 This is needed for font-lock setup.")
3439 ;;; Miscellaneous options
3441 (defgroup org-completion nil
3442 "Completion in Org-mode."
3443 :tag "Org Completion"
3444 :group 'org)
3446 (defcustom org-completion-use-ido nil
3447 "Non-nil means use ido completion wherever possible.
3448 Note that `ido-mode' must be active for this variable to be relevant.
3449 If you decide to turn this variable on, you might well want to turn off
3450 `org-outline-path-complete-in-steps'.
3451 See also `org-completion-use-iswitchb'."
3452 :group 'org-completion
3453 :type 'boolean)
3455 (defcustom org-completion-use-iswitchb nil
3456 "Non-nil means use iswitchb completion wherever possible.
3457 Note that `iswitchb-mode' must be active for this variable to be relevant.
3458 If you decide to turn this variable on, you might well want to turn off
3459 `org-outline-path-complete-in-steps'.
3460 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3461 :group 'org-completion
3462 :type 'boolean)
3464 (defcustom org-completion-fallback-command 'hippie-expand
3465 "The expansion command called by \\[org-complete] in normal context.
3466 Normal means no org-mode-specific context."
3467 :group 'org-completion
3468 :type 'function)
3470 ;;; Functions and variables from their packages
3471 ;; Declared here to avoid compiler warnings
3473 ;; XEmacs only
3474 (defvar outline-mode-menu-heading)
3475 (defvar outline-mode-menu-show)
3476 (defvar outline-mode-menu-hide)
3477 (defvar zmacs-regions) ; XEmacs regions
3479 ;; Emacs only
3480 (defvar mark-active)
3482 ;; Various packages
3483 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3484 (declare-function calendar-forward-day "cal-move" (arg))
3485 (declare-function calendar-goto-date "cal-move" (date))
3486 (declare-function calendar-goto-today "cal-move" ())
3487 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3488 (defvar calc-embedded-close-formula)
3489 (defvar calc-embedded-open-formula)
3490 (declare-function cdlatex-tab "ext:cdlatex" ())
3491 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3492 (defvar font-lock-unfontify-region-function)
3493 (declare-function iswitchb-read-buffer "iswitchb"
3494 (prompt &optional default require-match start matches-set))
3495 (defvar iswitchb-temp-buflist)
3496 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3497 (defvar org-agenda-tags-todo-honor-ignore-options)
3498 (declare-function org-agenda-skip "org-agenda" ())
3499 (declare-function
3500 org-format-agenda-item "org-agenda"
3501 (extra txt &optional category tags dotime noprefix remove-re habitp))
3502 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3503 (declare-function org-agenda-change-all-lines "org-agenda"
3504 (newhead hdmarker &optional fixface just-this))
3505 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3506 (declare-function org-agenda-maybe-redo "org-agenda" ())
3507 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3508 (beg end))
3509 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3510 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3511 "org-agenda" (&optional end))
3512 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3513 (declare-function org-indent-mode "org-indent" (&optional arg))
3514 (declare-function parse-time-string "parse-time" (string))
3515 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3516 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3517 (defvar remember-data-file)
3518 (defvar texmathp-why)
3519 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3520 (declare-function table--at-cell-p "table" (position &optional object at-column))
3522 (defvar w3m-current-url)
3523 (defvar w3m-current-title)
3525 (defvar org-latex-regexps)
3527 ;;; Autoload and prepare some org modules
3529 ;; Some table stuff that needs to be defined here, because it is used
3530 ;; by the functions setting up org-mode or checking for table context.
3532 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3533 "Detects an org-type or table-type table.")
3534 (defconst org-table-line-regexp "^[ \t]*|"
3535 "Detects an org-type table line.")
3536 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3537 "Detects an org-type table line.")
3538 (defconst org-table-hline-regexp "^[ \t]*|-"
3539 "Detects an org-type table hline.")
3540 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3541 "Detects a table-type table hline.")
3542 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3543 "Searching from within a table (any type) this finds the first line
3544 outside the table.")
3546 ;; Autoload the functions in org-table.el that are needed by functions here.
3548 (eval-and-compile
3549 (org-autoload "org-table"
3550 '(org-table-align org-table-begin org-table-blank-field
3551 org-table-convert org-table-convert-region org-table-copy-down
3552 org-table-copy-region org-table-create
3553 org-table-create-or-convert-from-region
3554 org-table-create-with-table.el org-table-current-dline
3555 org-table-cut-region org-table-delete-column org-table-edit-field
3556 org-table-edit-formulas org-table-end org-table-eval-formula
3557 org-table-export org-table-field-info
3558 org-table-get-stored-formulas org-table-goto-column
3559 org-table-hline-and-move org-table-import org-table-insert-column
3560 org-table-insert-hline org-table-insert-row org-table-iterate
3561 org-table-justify-field-maybe org-table-kill-row
3562 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3563 org-table-move-column org-table-move-column-left
3564 org-table-move-column-right org-table-move-row
3565 org-table-move-row-down org-table-move-row-up
3566 org-table-next-field org-table-next-row org-table-paste-rectangle
3567 org-table-previous-field org-table-recalculate
3568 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3569 org-table-toggle-coordinate-overlays
3570 org-table-toggle-formula-debugger org-table-wrap-region
3571 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3572 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3573 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3575 (defun org-at-table-p (&optional table-type)
3576 "Return t if the cursor is inside an org-type table.
3577 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3578 (if org-enable-table-editor
3579 (save-excursion
3580 (beginning-of-line 1)
3581 (looking-at (if table-type org-table-any-line-regexp
3582 org-table-line-regexp)))
3583 nil))
3584 (defsubst org-table-p () (org-at-table-p))
3586 (defun org-at-table.el-p ()
3587 "Return t if and only if we are at a table.el table."
3588 (and (org-at-table-p 'any)
3589 (save-excursion
3590 (goto-char (org-table-begin 'any))
3591 (looking-at org-table1-hline-regexp))))
3592 (defun org-table-recognize-table.el ()
3593 "If there is a table.el table nearby, recognize it and move into it."
3594 (if org-table-tab-recognizes-table.el
3595 (if (org-at-table.el-p)
3596 (progn
3597 (beginning-of-line 1)
3598 (if (looking-at org-table-dataline-regexp)
3600 (if (looking-at org-table1-hline-regexp)
3601 (progn
3602 (beginning-of-line 2)
3603 (if (looking-at org-table-any-border-regexp)
3604 (beginning-of-line -1)))))
3605 (if (re-search-forward "|" (org-table-end t) t)
3606 (progn
3607 (require 'table)
3608 (if (table--at-cell-p (point))
3610 (message "recognizing table.el table...")
3611 (table-recognize-table)
3612 (message "recognizing table.el table...done")))
3613 (error "This should not happen..."))
3615 nil)
3616 nil))
3618 (defun org-at-table-hline-p ()
3619 "Return t if the cursor is inside a hline in a table."
3620 (if org-enable-table-editor
3621 (save-excursion
3622 (beginning-of-line 1)
3623 (looking-at org-table-hline-regexp))
3624 nil))
3626 (defvar org-table-clean-did-remove-column nil)
3628 (defun org-table-map-tables (function &optional quietly)
3629 "Apply FUNCTION to the start of all tables in the buffer."
3630 (save-excursion
3631 (save-restriction
3632 (widen)
3633 (goto-char (point-min))
3634 (while (re-search-forward org-table-any-line-regexp nil t)
3635 (unless quietly
3636 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3637 (beginning-of-line 1)
3638 (when (looking-at org-table-line-regexp)
3639 (save-excursion (funcall function))
3640 (or (looking-at org-table-line-regexp)
3641 (forward-char 1)))
3642 (re-search-forward org-table-any-border-regexp nil 1))))
3643 (unless quietly (message "Mapping tables: done")))
3645 ;; Declare and autoload functions from org-exp.el & Co
3647 (declare-function org-default-export-plist "org-exp")
3648 (declare-function org-infile-export-plist "org-exp")
3649 (declare-function org-get-current-options "org-exp")
3650 (eval-and-compile
3651 (org-autoload "org-exp"
3652 '(org-export org-export-visible
3653 org-insert-export-options-template
3654 org-table-clean-before-export))
3655 (org-autoload "org-ascii"
3656 '(org-export-as-ascii org-export-ascii-preprocess
3657 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3658 org-export-region-as-ascii))
3659 (org-autoload "org-latex"
3660 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3661 org-replace-region-by-latex org-export-region-as-latex
3662 org-export-as-latex org-export-as-pdf
3663 org-export-as-pdf-and-open))
3664 (org-autoload "org-html"
3665 '(org-export-as-html-and-open
3666 org-export-as-html-batch org-export-as-html-to-buffer
3667 org-replace-region-by-html org-export-region-as-html
3668 org-export-as-html))
3669 (org-autoload "org-docbook"
3670 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3671 org-replace-region-by-docbook org-export-region-as-docbook
3672 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3673 org-export-as-docbook))
3674 (org-autoload "org-icalendar"
3675 '(org-export-icalendar-this-file
3676 org-export-icalendar-all-agenda-files
3677 org-export-icalendar-combine-agenda-files))
3678 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3679 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3681 ;; Declare and autoload functions from org-agenda.el
3683 (eval-and-compile
3684 (org-autoload "org-agenda"
3685 '(org-agenda org-agenda-list org-search-view
3686 org-todo-list org-tags-view org-agenda-list-stuck-projects
3687 org-diary org-agenda-to-appt
3688 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3690 ;; Autoload org-remember
3692 (eval-and-compile
3693 (org-autoload "org-remember"
3694 '(org-remember-insinuate org-remember-annotation
3695 org-remember-apply-template org-remember org-remember-handler)))
3697 (eval-and-compile
3698 (org-autoload "org-capture"
3699 '(org-capture org-capture-insert-template-here
3700 org-capture-import-remember-templates)))
3702 ;; Autoload org-clock.el
3705 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3706 (beg end))
3707 (declare-function org-clock-update-mode-line "org-clock" ())
3708 (declare-function org-resolve-clocks "org-clock"
3709 (&optional also-non-dangling-p prompt last-valid))
3710 (defvar org-clock-start-time)
3711 (defvar org-clock-marker (make-marker)
3712 "Marker recording the last clock-in.")
3713 (defvar org-clock-hd-marker (make-marker)
3714 "Marker recording the last clock-in, but the headline position.")
3715 (defvar org-clock-heading ""
3716 "The heading of the current clock entry.")
3717 (defun org-clock-is-active ()
3718 "Return non-nil if clock is currently running.
3719 The return value is actually the clock marker."
3720 (marker-buffer org-clock-marker))
3722 (eval-and-compile
3723 (org-autoload
3724 "org-clock"
3725 '(org-clock-in org-clock-out org-clock-cancel
3726 org-clock-goto org-clock-sum org-clock-display
3727 org-clock-remove-overlays org-clock-report
3728 org-clocktable-shift org-dblock-write:clocktable
3729 org-get-clocktable org-resolve-clocks)))
3731 (defun org-clock-update-time-maybe ()
3732 "If this is a CLOCK line, update it and return t.
3733 Otherwise, return nil."
3734 (interactive)
3735 (save-excursion
3736 (beginning-of-line 1)
3737 (skip-chars-forward " \t")
3738 (when (looking-at org-clock-string)
3739 (let ((re (concat "[ \t]*" org-clock-string
3740 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3741 "\\([ \t]*=>.*\\)?\\)?"))
3742 ts te h m s neg)
3743 (cond
3744 ((not (looking-at re))
3745 nil)
3746 ((not (match-end 2))
3747 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3748 (> org-clock-marker (point))
3749 (<= org-clock-marker (point-at-eol)))
3750 ;; The clock is running here
3751 (setq org-clock-start-time
3752 (apply 'encode-time
3753 (org-parse-time-string (match-string 1))))
3754 (org-clock-update-mode-line)))
3756 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3757 (end-of-line 1)
3758 (setq ts (match-string 1)
3759 te (match-string 3))
3760 (setq s (- (org-float-time
3761 (apply 'encode-time (org-parse-time-string te)))
3762 (org-float-time
3763 (apply 'encode-time (org-parse-time-string ts))))
3764 neg (< s 0)
3765 s (abs s)
3766 h (floor (/ s 3600))
3767 s (- s (* 3600 h))
3768 m (floor (/ s 60))
3769 s (- s (* 60 s)))
3770 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3771 t))))))
3773 (defun org-check-running-clock ()
3774 "Check if the current buffer contains the running clock.
3775 If yes, offer to stop it and to save the buffer with the changes."
3776 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3777 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3778 (buffer-name))))
3779 (org-clock-out)
3780 (when (y-or-n-p "Save changed buffer?")
3781 (save-buffer))))
3783 (defun org-clocktable-try-shift (dir n)
3784 "Check if this line starts a clock table, if yes, shift the time block."
3785 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3786 (org-clocktable-shift dir n)))
3788 ;; Autoload org-timer.el
3790 (eval-and-compile
3791 (org-autoload
3792 "org-timer"
3793 '(org-timer-start org-timer org-timer-item
3794 org-timer-change-times-in-region
3795 org-timer-set-timer
3796 org-timer-reset-timers
3797 org-timer-show-remaining-time)))
3799 ;; Autoload org-feed.el
3801 (eval-and-compile
3802 (org-autoload
3803 "org-feed"
3804 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3807 ;; Autoload org-indent.el
3809 ;; Define the variable already here, to make sure we have it.
3810 (defvar org-indent-mode nil
3811 "Non-nil if Org-Indent mode is enabled.
3812 Use the command `org-indent-mode' to change this variable.")
3814 (eval-and-compile
3815 (org-autoload
3816 "org-indent"
3817 '(org-indent-mode)))
3819 ;; Autoload org-mobile.el
3821 (eval-and-compile
3822 (org-autoload
3823 "org-mobile"
3824 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3826 ;; Autoload archiving code
3827 ;; The stuff that is needed for cycling and tags has to be defined here.
3829 (defgroup org-archive nil
3830 "Options concerning archiving in Org-mode."
3831 :tag "Org Archive"
3832 :group 'org-structure)
3834 (defcustom org-archive-location "%s_archive::"
3835 "The location where subtrees should be archived.
3837 The value of this variable is a string, consisting of two parts,
3838 separated by a double-colon. The first part is a filename and
3839 the second part is a headline.
3841 When the filename is omitted, archiving happens in the same file.
3842 %s in the filename will be replaced by the current file
3843 name (without the directory part). Archiving to a different file
3844 is useful to keep archived entries from contributing to the
3845 Org-mode Agenda.
3847 The archived entries will be filed as subtrees of the specified
3848 headline. When the headline is omitted, the subtrees are simply
3849 filed away at the end of the file, as top-level entries. Also in
3850 the heading you can use %s to represent the file name, this can be
3851 useful when using the same archive for a number of different files.
3853 Here are a few examples:
3854 \"%s_archive::\"
3855 If the current file is Projects.org, archive in file
3856 Projects.org_archive, as top-level trees. This is the default.
3858 \"::* Archived Tasks\"
3859 Archive in the current file, under the top-level headline
3860 \"* Archived Tasks\".
3862 \"~/org/archive.org::\"
3863 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3865 \"~/org/archive.org::From %s\"
3866 Archive in file ~/org/archive.org (absolute path), under headlines
3867 \"From FILENAME\" where file name is the current file name.
3869 \"basement::** Finished Tasks\"
3870 Archive in file ./basement (relative path), as level 3 trees
3871 below the level 2 heading \"** Finished Tasks\".
3873 You may set this option on a per-file basis by adding to the buffer a
3874 line like
3876 #+ARCHIVE: basement::** Finished Tasks
3878 You may also define it locally for a subtree by setting an ARCHIVE property
3879 in the entry. If such a property is found in an entry, or anywhere up
3880 the hierarchy, it will be used."
3881 :group 'org-archive
3882 :type 'string)
3884 (defcustom org-archive-tag "ARCHIVE"
3885 "The tag that marks a subtree as archived.
3886 An archived subtree does not open during visibility cycling, and does
3887 not contribute to the agenda listings.
3888 After changing this, font-lock must be restarted in the relevant buffers to
3889 get the proper fontification."
3890 :group 'org-archive
3891 :group 'org-keywords
3892 :type 'string)
3894 (defcustom org-agenda-skip-archived-trees t
3895 "Non-nil means the agenda will skip any items located in archived trees.
3896 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3897 variable is no longer recommended, you should leave it at the value t.
3898 Instead, use the key `v' to cycle the archives-mode in the agenda."
3899 :group 'org-archive
3900 :group 'org-agenda-skip
3901 :type 'boolean)
3903 (defcustom org-columns-skip-archived-trees t
3904 "Non-nil means ignore archived trees when creating column view."
3905 :group 'org-archive
3906 :group 'org-properties
3907 :type 'boolean)
3909 (defcustom org-cycle-open-archived-trees nil
3910 "Non-nil means `org-cycle' will open archived trees.
3911 An archived tree is a tree marked with the tag ARCHIVE.
3912 When nil, archived trees will stay folded. You can still open them with
3913 normal outline commands like `show-all', but not with the cycling commands."
3914 :group 'org-archive
3915 :group 'org-cycle
3916 :type 'boolean)
3918 (defcustom org-sparse-tree-open-archived-trees nil
3919 "Non-nil means sparse tree construction shows matches in archived trees.
3920 When nil, matches in these trees are highlighted, but the trees are kept in
3921 collapsed state."
3922 :group 'org-archive
3923 :group 'org-sparse-trees
3924 :type 'boolean)
3926 (defun org-cycle-hide-archived-subtrees (state)
3927 "Re-hide all archived subtrees after a visibility state change."
3928 (when (and (not org-cycle-open-archived-trees)
3929 (not (memq state '(overview folded))))
3930 (save-excursion
3931 (let* ((globalp (memq state '(contents all)))
3932 (beg (if globalp (point-min) (point)))
3933 (end (if globalp (point-max) (org-end-of-subtree t))))
3934 (org-hide-archived-subtrees beg end)
3935 (goto-char beg)
3936 (if (looking-at (concat ".*:" org-archive-tag ":"))
3937 (message "%s" (substitute-command-keys
3938 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3940 (defun org-force-cycle-archived ()
3941 "Cycle subtree even if it is archived."
3942 (interactive)
3943 (setq this-command 'org-cycle)
3944 (let ((org-cycle-open-archived-trees t))
3945 (call-interactively 'org-cycle)))
3947 (defun org-hide-archived-subtrees (beg end)
3948 "Re-hide all archived subtrees after a visibility state change."
3949 (save-excursion
3950 (let* ((re (concat ":" org-archive-tag ":")))
3951 (goto-char beg)
3952 (while (re-search-forward re end t)
3953 (when (org-on-heading-p)
3954 (org-flag-subtree t)
3955 (org-end-of-subtree t))))))
3957 (defun org-flag-subtree (flag)
3958 (save-excursion
3959 (org-back-to-heading t)
3960 (outline-end-of-heading)
3961 (outline-flag-region (point)
3962 (progn (org-end-of-subtree t) (point))
3963 flag)))
3965 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3967 (eval-and-compile
3968 (org-autoload "org-archive"
3969 '(org-add-archive-files org-archive-subtree
3970 org-archive-to-archive-sibling org-toggle-archive-tag
3971 org-archive-subtree-default
3972 org-archive-subtree-default-with-confirmation)))
3974 ;; Autoload Column View Code
3976 (declare-function org-columns-number-to-string "org-colview")
3977 (declare-function org-columns-get-format-and-top-level "org-colview")
3978 (declare-function org-columns-compute "org-colview")
3980 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3981 '(org-columns-number-to-string org-columns-get-format-and-top-level
3982 org-columns-compute org-agenda-columns org-columns-remove-overlays
3983 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3985 ;; Autoload ID code
3987 (declare-function org-id-store-link "org-id")
3988 (declare-function org-id-locations-load "org-id")
3989 (declare-function org-id-locations-save "org-id")
3990 (defvar org-id-track-globally)
3991 (org-autoload "org-id"
3992 '(org-id-get-create org-id-new org-id-copy org-id-get
3993 org-id-get-with-outline-path-completion
3994 org-id-get-with-outline-drilling
3995 org-id-goto org-id-find org-id-store-link))
3997 ;; Autoload Plotting Code
3999 (org-autoload "org-plot"
4000 '(org-plot/gnuplot))
4002 ;;; Variables for pre-computed regular expressions, all buffer local
4004 (defvar org-drawer-regexp nil
4005 "Matches first line of a hidden block.")
4006 (make-variable-buffer-local 'org-drawer-regexp)
4007 (defvar org-todo-regexp nil
4008 "Matches any of the TODO state keywords.")
4009 (make-variable-buffer-local 'org-todo-regexp)
4010 (defvar org-not-done-regexp nil
4011 "Matches any of the TODO state keywords except the last one.")
4012 (make-variable-buffer-local 'org-not-done-regexp)
4013 (defvar org-not-done-heading-regexp nil
4014 "Matches a TODO headline that is not done.")
4015 (make-variable-buffer-local 'org-not-done-regexp)
4016 (defvar org-todo-line-regexp nil
4017 "Matches a headline and puts TODO state into group 2 if present.")
4018 (make-variable-buffer-local 'org-todo-line-regexp)
4019 (defvar org-complex-heading-regexp nil
4020 "Matches a headline and puts everything into groups:
4021 group 1: the stars
4022 group 2: The todo keyword, maybe
4023 group 3: Priority cookie
4024 group 4: True headline
4025 group 5: Tags")
4026 (make-variable-buffer-local 'org-complex-heading-regexp)
4027 (defvar org-complex-heading-regexp-format nil)
4028 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4029 (defvar org-todo-line-tags-regexp nil
4030 "Matches a headline and puts TODO state into group 2 if present.
4031 Also put tags into group 4 if tags are present.")
4032 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4033 (defvar org-nl-done-regexp nil
4034 "Matches newline followed by a headline with the DONE keyword.")
4035 (make-variable-buffer-local 'org-nl-done-regexp)
4036 (defvar org-looking-at-done-regexp nil
4037 "Matches the DONE keyword a point.")
4038 (make-variable-buffer-local 'org-looking-at-done-regexp)
4039 (defvar org-ds-keyword-length 12
4040 "Maximum length of the Deadline and SCHEDULED keywords.")
4041 (make-variable-buffer-local 'org-ds-keyword-length)
4042 (defvar org-deadline-regexp nil
4043 "Matches the DEADLINE keyword.")
4044 (make-variable-buffer-local 'org-deadline-regexp)
4045 (defvar org-deadline-time-regexp nil
4046 "Matches the DEADLINE keyword together with a time stamp.")
4047 (make-variable-buffer-local 'org-deadline-time-regexp)
4048 (defvar org-deadline-line-regexp nil
4049 "Matches the DEADLINE keyword and the rest of the line.")
4050 (make-variable-buffer-local 'org-deadline-line-regexp)
4051 (defvar org-scheduled-regexp nil
4052 "Matches the SCHEDULED keyword.")
4053 (make-variable-buffer-local 'org-scheduled-regexp)
4054 (defvar org-scheduled-time-regexp nil
4055 "Matches the SCHEDULED keyword together with a time stamp.")
4056 (make-variable-buffer-local 'org-scheduled-time-regexp)
4057 (defvar org-closed-time-regexp nil
4058 "Matches the CLOSED keyword together with a time stamp.")
4059 (make-variable-buffer-local 'org-closed-time-regexp)
4061 (defvar org-keyword-time-regexp nil
4062 "Matches any of the 4 keywords, together with the time stamp.")
4063 (make-variable-buffer-local 'org-keyword-time-regexp)
4064 (defvar org-keyword-time-not-clock-regexp nil
4065 "Matches any of the 3 keywords, together with the time stamp.")
4066 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4067 (defvar org-maybe-keyword-time-regexp nil
4068 "Matches a timestamp, possibly preceeded by a keyword.")
4069 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4070 (defvar org-planning-or-clock-line-re nil
4071 "Matches a line with planning or clock info.")
4072 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4073 (defvar org-all-time-keywords nil
4074 "List of time keywords.")
4075 (make-variable-buffer-local 'org-all-time-keywords)
4077 (defconst org-plain-time-of-day-regexp
4078 (concat
4079 "\\(\\<[012]?[0-9]"
4080 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4081 "\\(--?"
4082 "\\(\\<[012]?[0-9]"
4083 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4084 "\\)?")
4085 "Regular expression to match a plain time or time range.
4086 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4087 groups carry important information:
4088 0 the full match
4089 1 the first time, range or not
4090 8 the second time, if it is a range.")
4092 (defconst org-plain-time-extension-regexp
4093 (concat
4094 "\\(\\<[012]?[0-9]"
4095 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4096 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4097 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4098 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4099 groups carry important information:
4100 0 the full match
4101 7 hours of duration
4102 9 minutes of duration")
4104 (defconst org-stamp-time-of-day-regexp
4105 (concat
4106 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4107 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4108 "\\(--?"
4109 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4110 "Regular expression to match a timestamp time or time range.
4111 After a match, the following groups carry important information:
4112 0 the full match
4113 1 date plus weekday, for back referencing to make sure both times are on the same day
4114 2 the first time, range or not
4115 4 the second time, if it is a range.")
4117 (defconst org-startup-options
4118 '(("fold" org-startup-folded t)
4119 ("overview" org-startup-folded t)
4120 ("nofold" org-startup-folded nil)
4121 ("showall" org-startup-folded nil)
4122 ("showeverything" org-startup-folded showeverything)
4123 ("content" org-startup-folded content)
4124 ("indent" org-startup-indented t)
4125 ("noindent" org-startup-indented nil)
4126 ("hidestars" org-hide-leading-stars t)
4127 ("showstars" org-hide-leading-stars nil)
4128 ("odd" org-odd-levels-only t)
4129 ("oddeven" org-odd-levels-only nil)
4130 ("align" org-startup-align-all-tables t)
4131 ("noalign" org-startup-align-all-tables nil)
4132 ("customtime" org-display-custom-times t)
4133 ("logdone" org-log-done time)
4134 ("lognotedone" org-log-done note)
4135 ("nologdone" org-log-done nil)
4136 ("lognoteclock-out" org-log-note-clock-out t)
4137 ("nolognoteclock-out" org-log-note-clock-out nil)
4138 ("logrepeat" org-log-repeat state)
4139 ("lognoterepeat" org-log-repeat note)
4140 ("nologrepeat" org-log-repeat nil)
4141 ("logreschedule" org-log-reschedule time)
4142 ("lognotereschedule" org-log-reschedule note)
4143 ("nologreschedule" org-log-reschedule nil)
4144 ("logredeadline" org-log-redeadline time)
4145 ("lognoteredeadline" org-log-redeadline note)
4146 ("nologredeadline" org-log-redeadline nil)
4147 ("logrefile" org-log-refile time)
4148 ("lognoterefile" org-log-refile note)
4149 ("nologrefile" org-log-refile nil)
4150 ("fninline" org-footnote-define-inline t)
4151 ("nofninline" org-footnote-define-inline nil)
4152 ("fnlocal" org-footnote-section nil)
4153 ("fnauto" org-footnote-auto-label t)
4154 ("fnprompt" org-footnote-auto-label nil)
4155 ("fnconfirm" org-footnote-auto-label confirm)
4156 ("fnplain" org-footnote-auto-label plain)
4157 ("fnadjust" org-footnote-auto-adjust t)
4158 ("nofnadjust" org-footnote-auto-adjust nil)
4159 ("constcgs" constants-unit-system cgs)
4160 ("constSI" constants-unit-system SI)
4161 ("noptag" org-tag-persistent-alist nil)
4162 ("hideblocks" org-hide-block-startup t)
4163 ("nohideblocks" org-hide-block-startup nil)
4164 ("beamer" org-startup-with-beamer-mode t)
4165 ("entitiespretty" org-pretty-entities t)
4166 ("entitiesplain" org-pretty-entities nil))
4167 "Variable associated with STARTUP options for org-mode.
4168 Each element is a list of three items: The startup options as written
4169 in the #+STARTUP line, the corresponding variable, and the value to
4170 set this variable to if the option is found. An optional forth element PUSH
4171 means to push this value onto the list in the variable.")
4173 (defun org-set-regexps-and-options ()
4174 "Precompute regular expressions for current buffer."
4175 (when (org-mode-p)
4176 (org-set-local 'org-todo-kwd-alist nil)
4177 (org-set-local 'org-todo-key-alist nil)
4178 (org-set-local 'org-todo-key-trigger nil)
4179 (org-set-local 'org-todo-keywords-1 nil)
4180 (org-set-local 'org-done-keywords nil)
4181 (org-set-local 'org-todo-heads nil)
4182 (org-set-local 'org-todo-sets nil)
4183 (org-set-local 'org-todo-log-states nil)
4184 (org-set-local 'org-file-properties nil)
4185 (org-set-local 'org-file-tags nil)
4186 (let ((re (org-make-options-regexp
4187 '("CATEGORY" "TODO" "COLUMNS"
4188 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4189 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4190 "OPTIONS")
4191 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4192 (splitre "[ \t]+")
4193 (scripts org-use-sub-superscripts)
4194 kwds kws0 kwsa key log value cat arch tags const links hw dws
4195 tail sep kws1 prio props ftags drawers beamer-p
4196 ext-setup-or-nil setup-contents (start 0))
4197 (save-excursion
4198 (save-restriction
4199 (widen)
4200 (goto-char (point-min))
4201 (while (or (and ext-setup-or-nil
4202 (string-match re ext-setup-or-nil start)
4203 (setq start (match-end 0)))
4204 (and (setq ext-setup-or-nil nil start 0)
4205 (re-search-forward re nil t)))
4206 (setq key (upcase (match-string 1 ext-setup-or-nil))
4207 value (org-match-string-no-properties 2 ext-setup-or-nil))
4208 (if (stringp value) (setq value (org-trim value)))
4209 (cond
4210 ((equal key "CATEGORY")
4211 (setq cat value))
4212 ((member key '("SEQ_TODO" "TODO"))
4213 (push (cons 'sequence (org-split-string value splitre)) kwds))
4214 ((equal key "TYP_TODO")
4215 (push (cons 'type (org-split-string value splitre)) kwds))
4216 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4217 ;; general TODO-like setup
4218 (push (cons (intern (downcase (match-string 1 key)))
4219 (org-split-string value splitre)) kwds))
4220 ((equal key "TAGS")
4221 (setq tags (append tags (if tags '("\\n") nil)
4222 (org-split-string value splitre))))
4223 ((equal key "COLUMNS")
4224 (org-set-local 'org-columns-default-format value))
4225 ((equal key "LINK")
4226 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4227 (push (cons (match-string 1 value)
4228 (org-trim (match-string 2 value)))
4229 links)))
4230 ((equal key "PRIORITIES")
4231 (setq prio (org-split-string value " +")))
4232 ((equal key "PROPERTY")
4233 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4234 (push (cons (match-string 1 value) (match-string 2 value))
4235 props)))
4236 ((equal key "FILETAGS")
4237 (when (string-match "\\S-" value)
4238 (setq ftags
4239 (append
4240 ftags
4241 (apply 'append
4242 (mapcar (lambda (x) (org-split-string x ":"))
4243 (org-split-string value)))))))
4244 ((equal key "DRAWERS")
4245 (setq drawers (org-split-string value splitre)))
4246 ((equal key "CONSTANTS")
4247 (setq const (append const (org-split-string value splitre))))
4248 ((equal key "STARTUP")
4249 (let ((opts (org-split-string value splitre))
4250 l var val)
4251 (while (setq l (pop opts))
4252 (when (setq l (assoc l org-startup-options))
4253 (setq var (nth 1 l) val (nth 2 l))
4254 (if (not (nth 3 l))
4255 (set (make-local-variable var) val)
4256 (if (not (listp (symbol-value var)))
4257 (set (make-local-variable var) nil))
4258 (set (make-local-variable var) (symbol-value var))
4259 (add-to-list var val))))))
4260 ((equal key "ARCHIVE")
4261 (setq arch value)
4262 (remove-text-properties 0 (length arch)
4263 '(face t fontified t) arch))
4264 ((equal key "LATEX_CLASS")
4265 (setq beamer-p (equal value "beamer")))
4266 ((equal key "OPTIONS")
4267 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4268 (setq scripts (read (match-string 2 value)))))
4269 ((equal key "SETUPFILE")
4270 (setq setup-contents (org-file-contents
4271 (expand-file-name
4272 (org-remove-double-quotes value))
4273 'noerror))
4274 (if (not ext-setup-or-nil)
4275 (setq ext-setup-or-nil setup-contents start 0)
4276 (setq ext-setup-or-nil
4277 (concat (substring ext-setup-or-nil 0 start)
4278 "\n" setup-contents "\n"
4279 (substring ext-setup-or-nil start)))))
4280 ))))
4281 (org-set-local 'org-use-sub-superscripts scripts)
4282 (when cat
4283 (org-set-local 'org-category (intern cat))
4284 (push (cons "CATEGORY" cat) props))
4285 (when prio
4286 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4287 (setq prio (mapcar 'string-to-char prio))
4288 (org-set-local 'org-highest-priority (nth 0 prio))
4289 (org-set-local 'org-lowest-priority (nth 1 prio))
4290 (org-set-local 'org-default-priority (nth 2 prio)))
4291 (and props (org-set-local 'org-file-properties (nreverse props)))
4292 (and ftags (org-set-local 'org-file-tags
4293 (mapcar 'org-add-prop-inherited ftags)))
4294 (and drawers (org-set-local 'org-drawers drawers))
4295 (and arch (org-set-local 'org-archive-location arch))
4296 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4297 ;; Process the TODO keywords
4298 (unless kwds
4299 ;; Use the global values as if they had been given locally.
4300 (setq kwds (default-value 'org-todo-keywords))
4301 (if (stringp (car kwds))
4302 (setq kwds (list (cons org-todo-interpretation
4303 (default-value 'org-todo-keywords)))))
4304 (setq kwds (reverse kwds)))
4305 (setq kwds (nreverse kwds))
4306 (let (inter kws kw)
4307 (while (setq kws (pop kwds))
4308 (let ((kws (or
4309 (run-hook-with-args-until-success
4310 'org-todo-setup-filter-hook kws)
4311 kws)))
4312 (setq inter (pop kws) sep (member "|" kws)
4313 kws0 (delete "|" (copy-sequence kws))
4314 kwsa nil
4315 kws1 (mapcar
4316 (lambda (x)
4317 ;; 1 2
4318 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4319 (progn
4320 (setq kw (match-string 1 x)
4321 key (and (match-end 2) (match-string 2 x))
4322 log (org-extract-log-state-settings x))
4323 (push (cons kw (and key (string-to-char key))) kwsa)
4324 (and log (push log org-todo-log-states))
4326 (error "Invalid TODO keyword %s" x)))
4327 kws0)
4328 kwsa (if kwsa (append '((:startgroup))
4329 (nreverse kwsa)
4330 '((:endgroup))))
4331 hw (car kws1)
4332 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4333 tail (list inter hw (car dws) (org-last dws))))
4334 (add-to-list 'org-todo-heads hw 'append)
4335 (push kws1 org-todo-sets)
4336 (setq org-done-keywords (append org-done-keywords dws nil))
4337 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4338 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4339 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4340 (setq org-todo-sets (nreverse org-todo-sets)
4341 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4342 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4343 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4344 ;; Process the constants
4345 (when const
4346 (let (e cst)
4347 (while (setq e (pop const))
4348 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4349 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4350 (setq org-table-formula-constants-local cst)))
4352 ;; Process the tags.
4353 (when tags
4354 (let (e tgs)
4355 (while (setq e (pop tags))
4356 (cond
4357 ((equal e "{") (push '(:startgroup) tgs))
4358 ((equal e "}") (push '(:endgroup) tgs))
4359 ((equal e "\\n") (push '(:newline) tgs))
4360 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4361 (push (cons (match-string 1 e)
4362 (string-to-char (match-string 2 e)))
4363 tgs))
4364 (t (push (list e) tgs))))
4365 (org-set-local 'org-tag-alist nil)
4366 (while (setq e (pop tgs))
4367 (or (and (stringp (car e))
4368 (assoc (car e) org-tag-alist))
4369 (push e org-tag-alist)))))
4371 ;; Compute the regular expressions and other local variables
4372 (if (not org-done-keywords)
4373 (setq org-done-keywords (and org-todo-keywords-1
4374 (list (org-last org-todo-keywords-1)))))
4375 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4376 (length org-scheduled-string)
4377 (length org-clock-string)
4378 (length org-closed-string)))
4379 org-drawer-regexp
4380 (concat "^[ \t]*:\\("
4381 (mapconcat 'regexp-quote org-drawers "\\|")
4382 "\\):[ \t]*$")
4383 org-not-done-keywords
4384 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4385 org-todo-regexp
4386 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4387 "\\|") "\\)\\>")
4388 org-not-done-regexp
4389 (concat "\\<\\("
4390 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4391 "\\)\\>")
4392 org-not-done-heading-regexp
4393 (concat "^\\(\\*+\\)[ \t]+\\("
4394 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4395 "\\)\\>")
4396 org-todo-line-regexp
4397 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4398 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4399 "\\)\\>\\)?[ \t]*\\(.*\\)")
4400 org-complex-heading-regexp
4401 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4402 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4403 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4404 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4405 org-complex-heading-regexp-format
4406 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4407 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4408 "\\)\\>\\)?"
4409 "\\(?:[ \t]*\\(\\[#.\\]\\)\\)?"
4410 "\\(?:[ \t]*\\(?:\\[[0-9%%/]+\\]\\)\\)?" ;; stats cookie
4411 "[ \t]*\\(%s\\)"
4412 "\\(?:[ \t]*\\(?:\\[[0-9%%/]+\\]\\)\\)?" ;; stats cookie
4413 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4414 org-nl-done-regexp
4415 (concat "\n\\*+[ \t]+"
4416 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4417 "\\)" "\\>")
4418 org-todo-line-tags-regexp
4419 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4420 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4421 (org-re
4422 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4423 org-looking-at-done-regexp
4424 (concat "^" "\\(?:"
4425 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4426 "\\>")
4427 org-deadline-regexp (concat "\\<" org-deadline-string)
4428 org-deadline-time-regexp
4429 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4430 org-deadline-line-regexp
4431 (concat "\\<\\(" org-deadline-string "\\).*")
4432 org-scheduled-regexp
4433 (concat "\\<" org-scheduled-string)
4434 org-scheduled-time-regexp
4435 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4436 org-closed-time-regexp
4437 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4438 org-keyword-time-regexp
4439 (concat "\\<\\(" org-scheduled-string
4440 "\\|" org-deadline-string
4441 "\\|" org-closed-string
4442 "\\|" org-clock-string "\\)"
4443 " *[[<]\\([^]>]+\\)[]>]")
4444 org-keyword-time-not-clock-regexp
4445 (concat "\\<\\(" org-scheduled-string
4446 "\\|" org-deadline-string
4447 "\\|" org-closed-string
4448 "\\)"
4449 " *[[<]\\([^]>]+\\)[]>]")
4450 org-maybe-keyword-time-regexp
4451 (concat "\\(\\<\\(" org-scheduled-string
4452 "\\|" org-deadline-string
4453 "\\|" org-closed-string
4454 "\\|" org-clock-string "\\)\\)?"
4455 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4456 org-planning-or-clock-line-re
4457 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4458 "\\|" org-deadline-string
4459 "\\|" org-closed-string "\\|" org-clock-string
4460 "\\)\\>\\)")
4461 org-all-time-keywords
4462 (mapcar (lambda (w) (substring w 0 -1))
4463 (list org-scheduled-string org-deadline-string
4464 org-clock-string org-closed-string))
4466 (org-compute-latex-and-specials-regexp)
4467 (org-set-font-lock-defaults))))
4469 (defun org-file-contents (file &optional noerror)
4470 "Return the contents of FILE, as a string."
4471 (if (or (not file)
4472 (not (file-readable-p file)))
4473 (if noerror
4474 (progn
4475 (message "Cannot read file \"%s\"" file)
4476 (ding) (sit-for 2)
4478 (error "Cannot read file \"%s\"" file))
4479 (with-temp-buffer
4480 (insert-file-contents file)
4481 (buffer-string))))
4483 (defun org-extract-log-state-settings (x)
4484 "Extract the log state setting from a TODO keyword string.
4485 This will extract info from a string like \"WAIT(w@/!)\"."
4486 (let (kw key log1 log2)
4487 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4488 (setq kw (match-string 1 x)
4489 key (and (match-end 2) (match-string 2 x))
4490 log1 (and (match-end 3) (match-string 3 x))
4491 log2 (and (match-end 4) (match-string 4 x)))
4492 (and (or log1 log2)
4493 (list kw
4494 (and log1 (if (equal log1 "!") 'time 'note))
4495 (and log2 (if (equal log2 "!") 'time 'note)))))))
4497 (defun org-remove-keyword-keys (list)
4498 "Remove a pair of parenthesis at the end of each string in LIST."
4499 (mapcar (lambda (x)
4500 (if (string-match "(.*)$" x)
4501 (substring x 0 (match-beginning 0))
4503 list))
4505 (defun org-assign-fast-keys (alist)
4506 "Assign fast keys to a keyword-key alist.
4507 Respect keys that are already there."
4508 (let (new e (alt ?0))
4509 (while (setq e (pop alist))
4510 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4511 (cdr e)) ;; Key already assigned.
4512 (push e new)
4513 (let ((clist (string-to-list (downcase (car e))))
4514 (used (append new alist)))
4515 (when (= (car clist) ?@)
4516 (pop clist))
4517 (while (and clist (rassoc (car clist) used))
4518 (pop clist))
4519 (unless clist
4520 (while (rassoc alt used)
4521 (incf alt)))
4522 (push (cons (car e) (or (car clist) alt)) new))))
4523 (nreverse new)))
4525 ;;; Some variables used in various places
4527 (defvar org-window-configuration nil
4528 "Used in various places to store a window configuration.")
4529 (defvar org-selected-window nil
4530 "Used in various places to store a window configuration.")
4531 (defvar org-finish-function nil
4532 "Function to be called when `C-c C-c' is used.
4533 This is for getting out of special buffers like remember.")
4536 ;; FIXME: Occasionally check by commenting these, to make sure
4537 ;; no other functions uses these, forgetting to let-bind them.
4538 (defvar entry)
4539 (defvar last-state)
4540 (defvar date)
4542 ;; Defined somewhere in this file, but used before definition.
4543 (defvar org-entities) ;; defined in org-entities.el
4544 (defvar org-struct-menu)
4545 (defvar org-org-menu)
4546 (defvar org-tbl-menu)
4548 ;;;; Define the Org-mode
4550 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4551 (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."))
4554 ;; We use a before-change function to check if a table might need
4555 ;; an update.
4556 (defvar org-table-may-need-update t
4557 "Indicates that a table might need an update.
4558 This variable is set by `org-before-change-function'.
4559 `org-table-align' sets it back to nil.")
4560 (defun org-before-change-function (beg end)
4561 "Every change indicates that a table might need an update."
4562 (setq org-table-may-need-update t))
4563 (defvar org-mode-map)
4564 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4565 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4566 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4567 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4568 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4569 (defvar org-table-buffer-is-an nil)
4570 (defconst org-outline-regexp "\\*+ ")
4572 ;;;###autoload
4573 (define-derived-mode org-mode outline-mode "Org"
4574 "Outline-based notes management and organizer, alias
4575 \"Carsten's outline-mode for keeping track of everything.\"
4577 Org-mode develops organizational tasks around a NOTES file which
4578 contains information about projects as plain text. Org-mode is
4579 implemented on top of outline-mode, which is ideal to keep the content
4580 of large files well structured. It supports ToDo items, deadlines and
4581 time stamps, which magically appear in the diary listing of the Emacs
4582 calendar. Tables are easily created with a built-in table editor.
4583 Plain text URL-like links connect to websites, emails (VM), Usenet
4584 messages (Gnus), BBDB entries, and any files related to the project.
4585 For printing and sharing of notes, an Org-mode file (or a part of it)
4586 can be exported as a structured ASCII or HTML file.
4588 The following commands are available:
4590 \\{org-mode-map}"
4592 ;; Get rid of Outline menus, they are not needed
4593 ;; Need to do this here because define-derived-mode sets up
4594 ;; the keymap so late. Still, it is a waste to call this each time
4595 ;; we switch another buffer into org-mode.
4596 (if (featurep 'xemacs)
4597 (when (boundp 'outline-mode-menu-heading)
4598 ;; Assume this is Greg's port, it uses easymenu
4599 (easy-menu-remove outline-mode-menu-heading)
4600 (easy-menu-remove outline-mode-menu-show)
4601 (easy-menu-remove outline-mode-menu-hide))
4602 (define-key org-mode-map [menu-bar headings] 'undefined)
4603 (define-key org-mode-map [menu-bar hide] 'undefined)
4604 (define-key org-mode-map [menu-bar show] 'undefined))
4606 (org-load-modules-maybe)
4607 (easy-menu-add org-org-menu)
4608 (easy-menu-add org-tbl-menu)
4609 (org-install-agenda-files-menu)
4610 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4611 (add-to-invisibility-spec '(org-cwidth))
4612 (add-to-invisibility-spec '(org-hide-block . t))
4613 (when (featurep 'xemacs)
4614 (org-set-local 'line-move-ignore-invisible t))
4615 (org-set-local 'outline-regexp org-outline-regexp)
4616 (org-set-local 'outline-level 'org-outline-level)
4617 (when (and org-ellipsis
4618 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4619 (fboundp 'make-glyph-code))
4620 (unless org-display-table
4621 (setq org-display-table (make-display-table)))
4622 (set-display-table-slot
4623 org-display-table 4
4624 (vconcat (mapcar
4625 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4626 org-ellipsis)))
4627 (if (stringp org-ellipsis) org-ellipsis "..."))))
4628 (setq buffer-display-table org-display-table))
4629 (org-set-regexps-and-options)
4630 (when (and org-tag-faces (not org-tags-special-faces-re))
4631 ;; tag faces set outside customize.... force initialization.
4632 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4633 ;; Calc embedded
4634 (org-set-local 'calc-embedded-open-mode "# ")
4635 (modify-syntax-entry ?@ "w")
4636 (if org-startup-truncated (setq truncate-lines t))
4637 (org-set-local 'font-lock-unfontify-region-function
4638 'org-unfontify-region)
4639 ;; Activate before-change-function
4640 (org-set-local 'org-table-may-need-update t)
4641 (org-add-hook 'before-change-functions 'org-before-change-function nil
4642 'local)
4643 ;; Check for running clock before killing a buffer
4644 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4645 ;; Paragraphs and auto-filling
4646 (org-set-autofill-regexps)
4647 (setq indent-line-function 'org-indent-line-function)
4648 (org-update-radio-target-regexp)
4649 ;; Beginning/end of defun
4650 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
4651 (org-set-local 'end-of-defun-function 'org-end-of-defun)
4652 ;; Make sure dependence stuff works reliably, even for users who set it
4653 ;; too late :-(
4654 (if org-enforce-todo-dependencies
4655 (add-hook 'org-blocker-hook
4656 'org-block-todo-from-children-or-siblings-or-parent)
4657 (remove-hook 'org-blocker-hook
4658 'org-block-todo-from-children-or-siblings-or-parent))
4659 (if org-enforce-todo-checkbox-dependencies
4660 (add-hook 'org-blocker-hook
4661 'org-block-todo-from-checkboxes)
4662 (remove-hook 'org-blocker-hook
4663 'org-block-todo-from-checkboxes))
4665 ;; Comment characters
4666 (org-set-local 'comment-start "#")
4667 (org-set-local 'comment-padding " ")
4669 ;; Align options lines
4670 (org-set-local
4671 'align-mode-rules-list
4672 '((org-in-buffer-settings
4673 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4674 (modes . '(org-mode)))))
4676 ;; Imenu
4677 (org-set-local 'imenu-create-index-function
4678 'org-imenu-get-tree)
4680 ;; Make isearch reveal context
4681 (if (or (featurep 'xemacs)
4682 (not (boundp 'outline-isearch-open-invisible-function)))
4683 ;; Emacs 21 and XEmacs make use of the hook
4684 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4685 ;; Emacs 22 deals with this through a special variable
4686 (org-set-local 'outline-isearch-open-invisible-function
4687 (lambda (&rest ignore) (org-show-context 'isearch))))
4689 ;; Turn on org-beamer-mode?
4690 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4692 ;; If empty file that did not turn on org-mode automatically, make it to.
4693 (if (and org-insert-mode-line-in-empty-file
4694 (interactive-p)
4695 (= (point-min) (point-max)))
4696 (insert "# -*- mode: org -*-\n\n"))
4697 (unless org-inhibit-startup
4698 (when org-startup-align-all-tables
4699 (let ((bmp (buffer-modified-p)))
4700 (org-table-map-tables 'org-table-align 'quietly)
4701 (set-buffer-modified-p bmp)))
4702 (when org-startup-indented
4703 (require 'org-indent)
4704 (org-indent-mode 1))
4705 (unless org-inhibit-startup-visibility-stuff
4706 (org-set-startup-visibility))))
4708 (when (fboundp 'abbrev-table-put)
4709 (abbrev-table-put org-mode-abbrev-table
4710 :parents (list text-mode-abbrev-table)))
4712 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4714 (defun org-current-time ()
4715 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4716 (if (> (car org-time-stamp-rounding-minutes) 1)
4717 (let ((r (car org-time-stamp-rounding-minutes))
4718 (time (decode-time)))
4719 (apply 'encode-time
4720 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4721 (nthcdr 2 time))))
4722 (current-time)))
4724 ;;;; Font-Lock stuff, including the activators
4726 (defvar org-mouse-map (make-sparse-keymap))
4727 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
4728 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
4729 (when org-mouse-1-follows-link
4730 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4731 (when org-tab-follows-link
4732 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4733 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4735 (require 'font-lock)
4737 (defconst org-non-link-chars "]\t\n\r<>")
4738 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4739 "shell" "elisp" "doi"))
4740 (defvar org-link-types-re nil
4741 "Matches a link that has a url-like prefix like \"http:\"")
4742 (defvar org-link-re-with-space nil
4743 "Matches a link with spaces, optional angular brackets around it.")
4744 (defvar org-link-re-with-space2 nil
4745 "Matches a link with spaces, optional angular brackets around it.")
4746 (defvar org-link-re-with-space3 nil
4747 "Matches a link with spaces, only for internal part in bracket links.")
4748 (defvar org-angle-link-re nil
4749 "Matches link with angular brackets, spaces are allowed.")
4750 (defvar org-plain-link-re nil
4751 "Matches plain link, without spaces.")
4752 (defvar org-bracket-link-regexp nil
4753 "Matches a link in double brackets.")
4754 (defvar org-bracket-link-analytic-regexp nil
4755 "Regular expression used to analyze links.
4756 Here is what the match groups contain after a match:
4757 1: http:
4758 2: http
4759 3: path
4760 4: [desc]
4761 5: desc")
4762 (defvar org-bracket-link-analytic-regexp++ nil
4763 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4764 (defvar org-any-link-re nil
4765 "Regular expression matching any link.")
4767 (defcustom org-match-sexp-depth 3
4768 "Number of stacked braces for sub/superscript matching.
4769 This has to be set before loading org.el to be effective."
4770 :group 'org-export-translation ; ??????????????????????????/
4771 :type 'integer)
4773 (defun org-create-multibrace-regexp (left right n)
4774 "Create a regular expression which will match a balanced sexp.
4775 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
4776 as single character strings.
4777 The regexp returned will match the entire expression including the
4778 delimiters. It will also define a single group which contains the
4779 match except for the outermost delimiters. The maximum depth of
4780 stacked delimiters is N. Escaping delimiters is not possible."
4781 (let* ((nothing (concat "[^" left right "]*?"))
4782 (or "\\|")
4783 (re nothing)
4784 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
4785 (while (> n 1)
4786 (setq n (1- n)
4787 re (concat re or next)
4788 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
4789 (concat left "\\(" re "\\)" right)))
4791 (defvar org-match-substring-regexp
4792 (concat
4793 "\\([^\\]\\)\\([_^]\\)\\("
4794 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
4795 "\\|"
4796 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
4797 "\\|"
4798 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
4799 "The regular expression matching a sub- or superscript.")
4801 (defvar org-match-substring-with-braces-regexp
4802 (concat
4803 "\\([^\\]\\)\\([_^]\\)\\("
4804 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
4805 "\\)")
4806 "The regular expression matching a sub- or superscript, forcing braces.")
4808 (defun org-make-link-regexps ()
4809 "Update the link regular expressions.
4810 This should be called after the variable `org-link-types' has changed."
4811 (setq org-link-types-re
4812 (concat
4813 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
4814 org-link-re-with-space
4815 (concat
4816 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4817 "\\([^" org-non-link-chars " ]"
4818 "[^" org-non-link-chars "]*"
4819 "[^" org-non-link-chars " ]\\)>?")
4820 org-link-re-with-space2
4821 (concat
4822 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4823 "\\([^" org-non-link-chars " ]"
4824 "[^\t\n\r]*"
4825 "[^" org-non-link-chars " ]\\)>?")
4826 org-link-re-with-space3
4827 (concat
4828 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4829 "\\([^" org-non-link-chars " ]"
4830 "[^\t\n\r]*\\)")
4831 org-angle-link-re
4832 (concat
4833 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4834 "\\([^" org-non-link-chars " ]"
4835 "[^" org-non-link-chars "]*"
4836 "\\)>")
4837 org-plain-link-re
4838 (concat
4839 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4840 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4841 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4842 org-bracket-link-regexp
4843 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4844 org-bracket-link-analytic-regexp
4845 (concat
4846 "\\[\\["
4847 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
4848 "\\([^]]+\\)"
4849 "\\]"
4850 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4851 "\\]")
4852 org-bracket-link-analytic-regexp++
4853 (concat
4854 "\\[\\["
4855 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4856 "\\([^]]+\\)"
4857 "\\]"
4858 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4859 "\\]")
4860 org-any-link-re
4861 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4862 org-angle-link-re "\\)\\|\\("
4863 org-plain-link-re "\\)")))
4865 (org-make-link-regexps)
4867 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4868 "Regular expression for fast time stamp matching.")
4869 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4870 "Regular expression for fast time stamp matching.")
4871 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4872 "Regular expression matching time strings for analysis.
4873 This one does not require the space after the date, so it can be used
4874 on a string that terminates immediately after the date.")
4875 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4876 "Regular expression matching time strings for analysis.")
4877 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4878 "Regular expression matching time stamps, with groups.")
4879 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4880 "Regular expression matching time stamps (also [..]), with groups.")
4881 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4882 "Regular expression matching a time stamp range.")
4883 (defconst org-tr-regexp-both
4884 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4885 "Regular expression matching a time stamp range.")
4886 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4887 org-ts-regexp "\\)?")
4888 "Regular expression matching a time stamp or time stamp range.")
4889 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4890 org-ts-regexp-both "\\)?")
4891 "Regular expression matching a time stamp or time stamp range.
4892 The time stamps may be either active or inactive.")
4894 (defvar org-emph-face nil)
4896 (defun org-do-emphasis-faces (limit)
4897 "Run through the buffer and add overlays to links."
4898 (let (rtn a)
4899 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4900 (if (not (= (char-after (match-beginning 3))
4901 (char-after (match-beginning 4))))
4902 (progn
4903 (setq rtn t)
4904 (setq a (assoc (match-string 3) org-emphasis-alist))
4905 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4906 'face
4907 (nth 1 a))
4908 (and (nth 4 a)
4909 (org-remove-flyspell-overlays-in
4910 (match-beginning 0) (match-end 0)))
4911 (add-text-properties (match-beginning 2) (match-end 2)
4912 '(font-lock-multiline t org-emphasis t))
4913 (when org-hide-emphasis-markers
4914 (add-text-properties (match-end 4) (match-beginning 5)
4915 '(invisible org-link))
4916 (add-text-properties (match-beginning 3) (match-end 3)
4917 '(invisible org-link)))))
4918 (backward-char 1))
4919 rtn))
4921 (defun org-emphasize (&optional char)
4922 "Insert or change an emphasis, i.e. a font like bold or italic.
4923 If there is an active region, change that region to a new emphasis.
4924 If there is no region, just insert the marker characters and position
4925 the cursor between them.
4926 CHAR should be either the marker character, or the first character of the
4927 HTML tag associated with that emphasis. If CHAR is a space, the means
4928 to remove the emphasis of the selected region.
4929 If char is not given (for example in an interactive call) it
4930 will be prompted for."
4931 (interactive)
4932 (let ((eal org-emphasis-alist) e det
4933 (erc org-emphasis-regexp-components)
4934 (prompt "")
4935 (string "") beg end move tag c s)
4936 (if (org-region-active-p)
4937 (setq beg (region-beginning) end (region-end)
4938 string (buffer-substring beg end))
4939 (setq move t))
4941 (while (setq e (pop eal))
4942 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4943 c (aref tag 0))
4944 (push (cons c (string-to-char (car e))) det)
4945 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4946 (substring tag 1)))))
4947 (setq det (nreverse det))
4948 (unless char
4949 (message "%s" (concat "Emphasis marker or tag:" prompt))
4950 (setq char (read-char-exclusive)))
4951 (setq char (or (cdr (assoc char det)) char))
4952 (if (equal char ?\ )
4953 (setq s "" move nil)
4954 (unless (assoc (char-to-string char) org-emphasis-alist)
4955 (error "No such emphasis marker: \"%c\"" char))
4956 (setq s (char-to-string char)))
4957 (while (and (> (length string) 1)
4958 (equal (substring string 0 1) (substring string -1))
4959 (assoc (substring string 0 1) org-emphasis-alist))
4960 (setq string (substring string 1 -1)))
4961 (setq string (concat s string s))
4962 (if beg (delete-region beg end))
4963 (unless (or (bolp)
4964 (string-match (concat "[" (nth 0 erc) "\n]")
4965 (char-to-string (char-before (point)))))
4966 (insert " "))
4967 (unless (or (eobp)
4968 (string-match (concat "[" (nth 1 erc) "\n]")
4969 (char-to-string (char-after (point)))))
4970 (insert " ") (backward-char 1))
4971 (insert string)
4972 (and move (backward-char 1))))
4974 (defconst org-nonsticky-props
4975 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4977 (defsubst org-rear-nonsticky-at (pos)
4978 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4980 (defun org-activate-plain-links (limit)
4981 "Run through the buffer and add overlays to links."
4982 (catch 'exit
4983 (let (f)
4984 (if (re-search-forward org-plain-link-re limit t)
4985 (progn
4986 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4987 (setq f (get-text-property (match-beginning 0) 'face))
4988 (if (or (eq f 'org-tag)
4989 (and (listp f) (memq 'org-tag f)))
4991 (add-text-properties (match-beginning 0) (match-end 0)
4992 (list 'mouse-face 'highlight
4993 'face 'org-link
4994 'keymap org-mouse-map))
4995 (org-rear-nonsticky-at (match-end 0)))
4996 t)))))
4998 (defun org-activate-code (limit)
4999 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
5000 (progn
5001 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5002 (remove-text-properties (match-beginning 0) (match-end 0)
5003 '(display t invisible t intangible t))
5004 t)))
5006 (defun org-fontify-meta-lines-and-blocks (limit)
5007 "Fontify #+ lines and blocks, in the correct ways."
5008 (let ((case-fold-search t))
5009 (if (re-search-forward
5010 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
5011 limit t)
5012 (let ((beg (match-beginning 0))
5013 (beg1 (line-beginning-position 2))
5014 (dc1 (downcase (match-string 2)))
5015 (dc3 (downcase (match-string 3)))
5016 end end1 quoting block-type)
5017 (cond
5018 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5019 ;; a single line of backend-specific content
5020 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5021 (remove-text-properties (match-beginning 0) (match-end 0)
5022 '(display t invisible t intangible t))
5023 (add-text-properties (match-beginning 1) (match-end 3)
5024 '(font-lock-fontified t face org-meta-line))
5025 (add-text-properties (match-beginning 6) (match-end 6)
5026 '(font-lock-fontified t face org-block))
5028 ((and (match-end 4) (equal dc3 "begin"))
5029 ;; Truly a block
5030 (setq block-type (downcase (match-string 5))
5031 quoting (member block-type org-protecting-blocks))
5032 (when (re-search-forward
5033 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5034 nil t) ;; on purpose, we look further than LIMIT
5035 (setq end (match-end 0) end1 (1- (match-beginning 0)))
5036 (when quoting
5037 (remove-text-properties beg end
5038 '(display t invisible t intangible t)))
5039 (add-text-properties
5040 beg end
5041 '(font-lock-fontified t font-lock-multiline t))
5042 (add-text-properties beg beg1 '(face org-meta-line))
5043 (add-text-properties end1 end '(face org-meta-line))
5044 (cond
5045 (quoting
5046 (add-text-properties beg1 end1 '(face org-block)))
5047 ((not org-fontify-quote-and-verse-blocks))
5048 ((string= block-type "quote")
5049 (add-text-properties beg1 end1 '(face org-quote)))
5050 ((string= block-type "verse")
5051 (add-text-properties beg1 end1 '(face org-verse))))
5053 ((member dc1 '("title:" "author:" "email:" "date:"))
5054 (add-text-properties
5055 beg (match-end 3)
5056 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5057 '(font-lock-fontified t invisible t)
5058 '(font-lock-fontified t face org-document-info-keyword)))
5059 (add-text-properties
5060 (match-beginning 6) (match-end 6)
5061 (if (string-equal dc1 "title:")
5062 '(font-lock-fontified t face org-document-title)
5063 '(font-lock-fontified t face org-document-info))))
5064 ((not (member (char-after beg) '(?\ ?\t)))
5065 ;; just any other in-buffer setting, but not indented
5066 (add-text-properties
5067 beg (match-end 0)
5068 '(font-lock-fontified t face org-meta-line))
5070 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5071 "orgtbl:" "tblfm:" "tblname:" "result:"
5072 "results:" "source:" "srcname:" "call:"))
5073 (and (match-end 4) (equal dc3 "attr")))
5074 (add-text-properties
5075 beg (match-end 0)
5076 '(font-lock-fontified t face org-meta-line))
5078 ((member dc3 '(" " ""))
5079 (add-text-properties
5080 beg (match-end 0)
5081 '(font-lock-fontified t face font-lock-comment-face)))
5082 (t nil))))))
5084 (defun org-activate-angle-links (limit)
5085 "Run through the buffer and add overlays to links."
5086 (if (re-search-forward org-angle-link-re limit t)
5087 (progn
5088 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5089 (add-text-properties (match-beginning 0) (match-end 0)
5090 (list 'mouse-face 'highlight
5091 'keymap org-mouse-map))
5092 (org-rear-nonsticky-at (match-end 0))
5093 t)))
5095 (defun org-activate-footnote-links (limit)
5096 "Run through the buffer and add overlays to links."
5097 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
5098 limit t)
5099 (progn
5100 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5101 (add-text-properties (match-beginning 2) (match-end 2)
5102 (list 'mouse-face 'highlight
5103 'keymap org-mouse-map
5104 'help-echo
5105 (if (= (point-at-bol) (match-beginning 2))
5106 "Footnote definition"
5107 "Footnote reference")
5109 (org-rear-nonsticky-at (match-end 2))
5110 t)))
5112 (defun org-activate-bracket-links (limit)
5113 "Run through the buffer and add overlays to bracketed links."
5114 (if (re-search-forward org-bracket-link-regexp limit t)
5115 (let* ((help (concat "LINK: "
5116 (org-match-string-no-properties 1)))
5117 ;; FIXME: above we should remove the escapes.
5118 ;; but that requires another match, protecting match data,
5119 ;; a lot of overhead for font-lock.
5120 (ip (org-maybe-intangible
5121 (list 'invisible 'org-link
5122 'keymap org-mouse-map 'mouse-face 'highlight
5123 'font-lock-multiline t 'help-echo help)))
5124 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5125 'font-lock-multiline t 'help-echo help)))
5126 ;; We need to remove the invisible property here. Table narrowing
5127 ;; may have made some of this invisible.
5128 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5129 (remove-text-properties (match-beginning 0) (match-end 0)
5130 '(invisible nil))
5131 (if (match-end 3)
5132 (progn
5133 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5134 (org-rear-nonsticky-at (match-beginning 3))
5135 (add-text-properties (match-beginning 3) (match-end 3) vp)
5136 (org-rear-nonsticky-at (match-end 3))
5137 (add-text-properties (match-end 3) (match-end 0) ip)
5138 (org-rear-nonsticky-at (match-end 0)))
5139 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5140 (org-rear-nonsticky-at (match-beginning 1))
5141 (add-text-properties (match-beginning 1) (match-end 1) vp)
5142 (org-rear-nonsticky-at (match-end 1))
5143 (add-text-properties (match-end 1) (match-end 0) ip)
5144 (org-rear-nonsticky-at (match-end 0)))
5145 t)))
5147 (defun org-activate-dates (limit)
5148 "Run through the buffer and add overlays to dates."
5149 (if (re-search-forward org-tsr-regexp-both limit t)
5150 (progn
5151 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5152 (add-text-properties (match-beginning 0) (match-end 0)
5153 (list 'mouse-face 'highlight
5154 'keymap org-mouse-map))
5155 (org-rear-nonsticky-at (match-end 0))
5156 (when org-display-custom-times
5157 (if (match-end 3)
5158 (org-display-custom-time (match-beginning 3) (match-end 3)))
5159 (org-display-custom-time (match-beginning 1) (match-end 1)))
5160 t)))
5162 (defvar org-target-link-regexp nil
5163 "Regular expression matching radio targets in plain text.")
5164 (make-variable-buffer-local 'org-target-link-regexp)
5165 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5166 "Regular expression matching a link target.")
5167 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5168 "Regular expression matching a radio target.")
5169 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5170 "Regular expression matching any target.")
5172 (defun org-activate-target-links (limit)
5173 "Run through the buffer and add overlays to target matches."
5174 (when org-target-link-regexp
5175 (let ((case-fold-search t))
5176 (if (re-search-forward org-target-link-regexp limit t)
5177 (progn
5178 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5179 (add-text-properties (match-beginning 0) (match-end 0)
5180 (list 'mouse-face 'highlight
5181 'keymap org-mouse-map
5182 'help-echo "Radio target link"
5183 'org-linked-text t))
5184 (org-rear-nonsticky-at (match-end 0))
5185 t)))))
5187 (defun org-update-radio-target-regexp ()
5188 "Find all radio targets in this file and update the regular expression."
5189 (interactive)
5190 (when (memq 'radio org-activate-links)
5191 (setq org-target-link-regexp
5192 (org-make-target-link-regexp (org-all-targets 'radio)))
5193 (org-restart-font-lock)))
5195 (defun org-hide-wide-columns (limit)
5196 (let (s e)
5197 (setq s (text-property-any (point) (or limit (point-max))
5198 'org-cwidth t))
5199 (when s
5200 (setq e (next-single-property-change s 'org-cwidth))
5201 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5202 (goto-char e)
5203 t)))
5205 (defvar org-latex-and-specials-regexp nil
5206 "Regular expression for highlighting export special stuff.")
5207 (defvar org-match-substring-regexp)
5208 (defvar org-match-substring-with-braces-regexp)
5210 ;; This should be with the exporter code, but we also use if for font-locking
5211 (defconst org-export-html-special-string-regexps
5212 '(("\\\\-" . "&shy;")
5213 ("---\\([^-]\\)" . "&mdash;\\1")
5214 ("--\\([^-]\\)" . "&ndash;\\1")
5215 ("\\.\\.\\." . "&hellip;"))
5216 "Regular expressions for special string conversion.")
5219 (defun org-compute-latex-and-specials-regexp ()
5220 "Compute regular expression for stuff treated specially by exporters."
5221 (if (not org-highlight-latex-fragments-and-specials)
5222 (org-set-local 'org-latex-and-specials-regexp nil)
5223 (require 'org-exp)
5224 (let*
5225 ((matchers (plist-get org-format-latex-options :matchers))
5226 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5227 org-latex-regexps)))
5228 (org-export-allow-BIND nil)
5229 (options (org-combine-plists (org-default-export-plist)
5230 (org-infile-export-plist)))
5231 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5232 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5233 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5234 (org-export-html-expand (plist-get options :expand-quoted-html))
5235 (org-export-with-special-strings (plist-get options :special-strings))
5236 (re-sub
5237 (cond
5238 ((equal org-export-with-sub-superscripts '{})
5239 (list org-match-substring-with-braces-regexp))
5240 (org-export-with-sub-superscripts
5241 (list org-match-substring-regexp))
5242 (t nil)))
5243 (re-latex
5244 (if org-export-with-LaTeX-fragments
5245 (mapcar (lambda (x) (nth 1 x)) latexs)))
5246 (re-macros
5247 (if org-export-with-TeX-macros
5248 (list (concat "\\\\"
5249 (regexp-opt
5250 (append
5252 (delq nil
5253 (mapcar 'car-safe
5254 (append org-entities-user
5255 org-entities)))
5256 (if (boundp 'org-latex-entities)
5257 (mapcar (lambda (x)
5258 (or (car-safe x) x))
5259 org-latex-entities)
5260 nil))
5261 'words))) ; FIXME
5263 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5264 (re-special (if org-export-with-special-strings
5265 (mapcar (lambda (x) (car x))
5266 org-export-html-special-string-regexps)))
5267 (re-rest
5268 (delq nil
5269 (list
5270 (if org-export-html-expand "@<[^>\n]+>")
5271 ))))
5272 (org-set-local
5273 'org-latex-and-specials-regexp
5274 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5275 re-rest) "\\|")))))
5277 (defun org-do-latex-and-special-faces (limit)
5278 "Run through the buffer and add overlays to links."
5279 (when org-latex-and-specials-regexp
5280 (let (rtn d)
5281 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5282 limit t))
5283 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5284 'face))
5285 '(org-code org-verbatim underline)))
5286 (progn
5287 (setq rtn t
5288 d (cond ((member (char-after (1+ (match-beginning 0)))
5289 '(?_ ?^)) 1)
5290 (t 0)))
5291 (font-lock-prepend-text-property
5292 (+ d (match-beginning 0)) (match-end 0)
5293 'face 'org-latex-and-export-specials)
5294 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5295 '(font-lock-multiline t)))))
5296 rtn)))
5298 (defun org-restart-font-lock ()
5299 "Restart font-lock-mode, to force refontification."
5300 (when (and (boundp 'font-lock-mode) font-lock-mode)
5301 (font-lock-mode -1)
5302 (font-lock-mode 1)))
5304 (defun org-all-targets (&optional radio)
5305 "Return a list of all targets in this file.
5306 With optional argument RADIO, only find radio targets."
5307 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5308 rtn)
5309 (save-excursion
5310 (goto-char (point-min))
5311 (while (re-search-forward re nil t)
5312 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5313 rtn)))
5315 (defun org-make-target-link-regexp (targets)
5316 "Make regular expression matching all strings in TARGETS.
5317 The regular expression finds the targets also if there is a line break
5318 between words."
5319 (and targets
5320 (concat
5321 "\\<\\("
5322 (mapconcat
5323 (lambda (x)
5324 (while (string-match " +" x)
5325 (setq x (replace-match "\\s-+" t t x)))
5327 targets
5328 "\\|")
5329 "\\)\\>")))
5331 (defun org-activate-tags (limit)
5332 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5333 (progn
5334 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5335 (add-text-properties (match-beginning 1) (match-end 1)
5336 (list 'mouse-face 'highlight
5337 'keymap org-mouse-map))
5338 (org-rear-nonsticky-at (match-end 1))
5339 t)))
5341 (defun org-outline-level ()
5342 "Compute the outline level of the heading at point.
5343 This function assumes that the cursor is at the beginning of a line matched
5344 by outline-regexp. Otherwise it returns garbage.
5345 If this is called at a normal headline, the level is the number of stars.
5346 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
5347 For plain list items, if they are matched by `outline-regexp', this returns
5348 1000 plus the line indentation."
5349 (save-excursion
5350 (looking-at outline-regexp)
5351 (if (match-beginning 1)
5352 (+ (org-get-string-indentation (match-string 1)) 1000)
5353 (1- (- (match-end 0) (match-beginning 0))))))
5355 (defvar org-font-lock-keywords nil)
5357 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5358 "Regular expression matching a property line.")
5360 (defvar org-font-lock-hook nil
5361 "Functions to be called for special font lock stuff.")
5363 (defun org-font-lock-hook (limit)
5364 (run-hook-with-args 'org-font-lock-hook limit))
5366 (defun org-set-font-lock-defaults ()
5367 (let* ((em org-fontify-emphasized-text)
5368 (lk org-activate-links)
5369 (org-font-lock-extra-keywords
5370 (list
5371 ;; Call the hook
5372 '(org-font-lock-hook)
5373 ;; Headlines
5374 `(,(if org-fontify-whole-heading-line
5375 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5376 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5377 (1 (org-get-level-face 1))
5378 (2 (org-get-level-face 2))
5379 (3 (org-get-level-face 3)))
5380 ;; Table lines
5381 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5382 (1 'org-table t))
5383 ;; Table internals
5384 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5385 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5386 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5387 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
5388 ;; Drawers
5389 (list org-drawer-regexp '(0 'org-special-keyword t))
5390 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5391 ;; Properties
5392 (list org-property-re
5393 '(1 'org-special-keyword t)
5394 '(3 'org-property-value t))
5395 ;; Links
5396 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5397 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5398 (if (memq 'plain lk) '(org-activate-plain-links))
5399 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5400 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5401 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5402 (if (memq 'footnote lk) '(org-activate-footnote-links
5403 (2 'org-footnote t)))
5404 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5405 '(org-hide-wide-columns (0 nil append))
5406 ;; TODO lines
5407 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
5408 '(1 (org-get-todo-face 1) t))
5409 ;; DONE
5410 (if org-fontify-done-headline
5411 (list (concat "^[*]+ +\\<\\("
5412 (mapconcat 'regexp-quote org-done-keywords "\\|")
5413 "\\)\\(.*\\)")
5414 '(2 'org-headline-done t))
5415 nil)
5416 ;; Priorities
5417 '(org-font-lock-add-priority-faces)
5418 ;; Tags
5419 '(org-font-lock-add-tag-faces)
5420 ;; Special keywords
5421 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5422 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5423 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5424 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5425 ;; Emphasis
5426 (if em
5427 (if (featurep 'xemacs)
5428 '(org-do-emphasis-faces (0 nil append))
5429 '(org-do-emphasis-faces)))
5430 ;; Checkboxes
5431 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5432 2 'org-checkbox prepend)
5433 (if org-provide-checkbox-statistics
5434 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5435 (0 (org-get-checkbox-statistics-face) t)))
5436 ;; Description list items
5437 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
5438 2 'bold prepend)
5439 ;; ARCHIVEd headings
5440 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5441 '(1 'org-archived prepend))
5442 ;; Specials
5443 '(org-do-latex-and-special-faces)
5444 '(org-fontify-entities)
5445 '(org-raise-scripts)
5446 ;; Code
5447 '(org-activate-code (1 'org-code t))
5448 ;; COMMENT
5449 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5450 "\\|" org-quote-string "\\)\\>")
5451 '(1 'org-special-keyword t))
5452 '("^#.*" (0 'font-lock-comment-face t))
5453 ;; Blocks and meta lines
5454 '(org-fontify-meta-lines-and-blocks)
5456 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5457 ;; Now set the full font-lock-keywords
5458 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5459 (org-set-local 'font-lock-defaults
5460 '(org-font-lock-keywords t nil nil backward-paragraph))
5461 (kill-local-variable 'font-lock-keywords) nil))
5463 (defun org-toggle-pretty-entities ()
5464 "Toggle the compostion display of entities as UTF8 characters."
5465 (interactive)
5466 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5467 (org-restart-font-lock)
5468 (if org-pretty-entities
5469 (message "Entities are displayed as UTF8 characers")
5470 (save-restriction
5471 (widen)
5472 (decompose-region (point-min) (point-max))
5473 (message "Entities are displayed plain"))))
5475 (defun org-fontify-entities (limit)
5476 "Find an entity to fontify."
5477 (let (ee)
5478 (when org-pretty-entities
5479 (catch 'match
5480 (while (re-search-forward
5481 "\\\\\\([a-zA-Z][a-zA-Z0-9]*\\)\\($\\|[^[:alnum:]\n]\\)"
5482 limit t)
5483 (if (and (not (org-in-indented-comment-line))
5484 (setq ee (org-entity-get (match-string 1)))
5485 (= (length (nth 6 ee)) 1))
5486 (progn
5487 (add-text-properties
5488 (match-beginning 0) (match-end 1)
5489 (list 'font-lock-fontified t))
5490 (compose-region (match-beginning 0) (match-end 1)
5491 (nth 6 ee) nil)
5492 (backward-char 1)
5493 (throw 'match t))))
5494 nil))))
5496 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5497 "Fontify string S like in Org-mode"
5498 (with-temp-buffer
5499 (insert s)
5500 (let ((org-odd-levels-only odd-levels))
5501 (org-mode)
5502 (font-lock-fontify-buffer)
5503 (buffer-string))))
5505 (defvar org-m nil)
5506 (defvar org-l nil)
5507 (defvar org-f nil)
5508 (defun org-get-level-face (n)
5509 "Get the right face for match N in font-lock matching of headlines."
5510 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5511 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5512 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5513 (cond
5514 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5515 ((eq n 2) org-f)
5516 (t (if org-level-color-stars-only nil org-f))))
5518 (defun org-get-todo-face (kwd)
5519 "Get the right face for a TODO keyword KWD.
5520 If KWD is a number, get the corresponding match group."
5521 (if (numberp kwd) (setq kwd (match-string kwd)))
5522 (or (org-face-from-face-or-color
5523 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5524 (and (member kwd org-done-keywords) 'org-done)
5525 'org-todo))
5527 (defun org-face-from-face-or-color (context inherit face-or-color)
5528 "Create a face list that inherits INHERIT, but sets the foreground color.
5529 When FACE-OR-COLOR is not a string, just return it."
5530 (if (stringp face-or-color)
5531 (list :inherit inherit
5532 (cdr (assoc context org-faces-easy-properties))
5533 face-or-color)
5534 face-or-color))
5536 (defun org-font-lock-add-tag-faces (limit)
5537 "Add the special tag faces."
5538 (when (and org-tag-faces org-tags-special-faces-re)
5539 (while (re-search-forward org-tags-special-faces-re limit t)
5540 (add-text-properties (match-beginning 1) (match-end 1)
5541 (list 'face (org-get-tag-face 1)
5542 'font-lock-fontified t))
5543 (backward-char 1))))
5545 (defun org-font-lock-add-priority-faces (limit)
5546 "Add the special priority faces."
5547 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5548 (add-text-properties
5549 (match-beginning 0) (match-end 0)
5550 (list 'face (or (org-face-from-face-or-color
5551 'priority 'org-special-keyword
5552 (cdr (assoc (char-after (match-beginning 1))
5553 org-priority-faces)))
5554 'org-special-keyword)
5555 'font-lock-fontified t))))
5557 (defun org-get-tag-face (kwd)
5558 "Get the right face for a TODO keyword KWD.
5559 If KWD is a number, get the corresponding match group."
5560 (if (numberp kwd) (setq kwd (match-string kwd)))
5561 (or (org-face-from-face-or-color
5562 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5563 'org-tag))
5565 (defun org-unfontify-region (beg end &optional maybe_loudly)
5566 "Remove fontification and activation overlays from links."
5567 (font-lock-default-unfontify-region beg end)
5568 (let* ((buffer-undo-list t)
5569 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5570 (inhibit-modification-hooks t)
5571 deactivate-mark buffer-file-name buffer-file-truename)
5572 (decompose-region beg end)
5573 (remove-text-properties
5574 beg end
5575 (if org-indent-mode
5576 ;; also remove line-prefix and wrap-prefix properties
5577 '(mouse-face t keymap t org-linked-text t
5578 invisible t intangible t
5579 line-prefix t wrap-prefix t
5580 org-no-flyspell t org-emphasis t)
5581 '(mouse-face t keymap t org-linked-text t
5582 invisible t intangible t
5583 org-no-flyspell t org-emphasis t)))
5584 (org-remove-font-lock-display-properties beg end)))
5586 (defconst org-script-display '(((raise -0.3) (height 0.7))
5587 ((raise 0.3) (height 0.7))
5588 ((raise -0.5))
5589 ((raise 0.5)))
5590 "Display properties for showing superscripts and subscripts.")
5592 (defun org-remove-font-lock-display-properties (beg end)
5593 "Remove specific display properties that have been added by font lock.
5594 The will remove the raise properties that are used to show superscripts
5595 and subscriipts."
5596 (let (next prop)
5597 (while (< beg end)
5598 (setq next (next-single-property-change beg 'display nil end)
5599 prop (get-text-property beg 'display))
5600 (if (member prop org-script-display)
5601 (put-text-property beg next 'display nil))
5602 (setq beg next))))
5604 (defun org-raise-scripts (limit)
5605 "Add raise properties to sub/superscripts."
5606 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
5607 (if (re-search-forward
5608 (if (eq org-use-sub-superscripts t)
5609 org-match-substring-regexp
5610 org-match-substring-with-braces-regexp)
5611 limit t)
5612 (let* ((pos (point)) table-p comment-p
5613 (mpos (match-beginning 3))
5614 (emph-p (get-text-property mpos 'org-emphasis))
5615 (link-p (get-text-property mpos 'mouse-face))
5616 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
5617 (goto-char (point-at-bol))
5618 (setq table-p (org-looking-at-p org-table-dataline-regexp)
5619 comment-p (org-looking-at-p "[ \t]*#"))
5620 (goto-char pos)
5621 (if (or comment-p emph-p link-p keyw-p)
5623 (put-text-property (match-beginning 3) (match-end 0)
5624 'display
5625 (if (equal (char-after (match-beginning 2)) ?^)
5626 (nth (if table-p 3 1) org-script-display)
5627 (nth (if table-p 2 0) org-script-display)))
5628 (add-text-properties (match-beginning 2) (match-end 2)
5629 (list 'invisible t
5630 'org-dwidth t 'org-dwidth-n 1))
5631 (if (and (eq (char-after (match-beginning 3)) ?{)
5632 (eq (char-before (match-end 3)) ?}))
5633 (progn
5634 (add-text-properties
5635 (match-beginning 3) (1+ (match-beginning 3))
5636 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
5637 (add-text-properties
5638 (1- (match-end 3)) (match-end 3)
5639 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
5640 t)))))
5642 ;;;; Visibility cycling, including org-goto and indirect buffer
5644 ;;; Cycling
5646 (defvar org-cycle-global-status nil)
5647 (make-variable-buffer-local 'org-cycle-global-status)
5648 (defvar org-cycle-subtree-status nil)
5649 (make-variable-buffer-local 'org-cycle-subtree-status)
5651 ;;;###autoload
5653 (defvar org-inlinetask-min-level)
5655 (defun org-cycle (&optional arg)
5656 "TAB-action and visibility cycling for Org-mode.
5658 This is the command invoked in Org-mode by the TAB key. Its main purpose
5659 is outline visibility cycling, but it also invokes other actions
5660 in special contexts.
5662 - When this function is called with a prefix argument, rotate the entire
5663 buffer through 3 states (global cycling)
5664 1. OVERVIEW: Show only top-level headlines.
5665 2. CONTENTS: Show all headlines of all levels, but no body text.
5666 3. SHOW ALL: Show everything.
5667 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5668 determined by the variable `org-startup-folded', and by any VISIBILITY
5669 properties in the buffer.
5670 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5671 including any drawers.
5673 - When inside a table, re-align the table and move to the next field.
5675 - When point is at the beginning of a headline, rotate the subtree started
5676 by this line through 3 different states (local cycling)
5677 1. FOLDED: Only the main headline is shown.
5678 2. CHILDREN: The main headline and the direct children are shown.
5679 From this state, you can move to one of the children
5680 and zoom in further.
5681 3. SUBTREE: Show the entire subtree, including body text.
5682 If there is no subtree, switch directly from CHILDREN to FOLDED.
5684 - When point is at the beginning of an empty headline and the variable
5685 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5686 of the headline by demoting and promoting it to likely levels. This
5687 speeds up creation document structure by presing TAB once or several
5688 times right after creating a new headline.
5690 - When there is a numeric prefix, go up to a heading with level ARG, do
5691 a `show-subtree' and return to the previous cursor position. If ARG
5692 is negative, go up that many levels.
5694 - When point is not at the beginning of a headline, execute the global
5695 binding for TAB, which is re-indenting the line. See the option
5696 `org-cycle-emulate-tab' for details.
5698 - Special case: if point is at the beginning of the buffer and there is
5699 no headline in line 1, this function will act as if called with prefix arg.
5700 But only if also the variable `org-cycle-global-at-bob' is t."
5701 (interactive "P")
5702 (org-load-modules-maybe)
5703 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5704 (and org-cycle-level-after-item/entry-creation
5705 (or (org-cycle-level)
5706 (org-cycle-item-indentation))))
5707 (let* ((limit-level
5708 (or org-cycle-max-level
5709 (and (boundp 'org-inlinetask-min-level)
5710 org-inlinetask-min-level
5711 (1- org-inlinetask-min-level))))
5712 (nstars (and limit-level
5713 (if org-odd-levels-only
5714 (and limit-level (1- (* limit-level 2)))
5715 limit-level)))
5716 (outline-regexp
5717 (cond
5718 ((not (org-mode-p)) outline-regexp)
5719 ((or (eq org-cycle-include-plain-lists 'integrate)
5720 (and org-cycle-include-plain-lists (org-at-item-p)))
5721 (concat "\\(?:\\*"
5722 (if nstars (format "\\{1,%d\\}" nstars) "+")
5723 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5724 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5725 (bob-special (and org-cycle-global-at-bob (bobp)
5726 (not (looking-at outline-regexp))))
5727 (org-cycle-hook
5728 (if bob-special
5729 (delq 'org-optimize-window-after-visibility-change
5730 (copy-sequence org-cycle-hook))
5731 org-cycle-hook))
5732 (pos (point)))
5734 (if (or bob-special (equal arg '(4)))
5735 ;; special case: use global cycling
5736 (setq arg t))
5738 (cond
5740 ((equal arg '(16))
5741 (org-set-startup-visibility)
5742 (message "Startup visibility, plus VISIBILITY properties"))
5744 ((equal arg '(64))
5745 (show-all)
5746 (message "Entire buffer visible, including drawers"))
5748 ((org-at-table-p 'any)
5749 ;; Enter the table or move to the next field in the table
5750 (if (org-at-table.el-p)
5751 (message "Use C-c ' to edit table.el tables")
5752 (if arg (org-table-edit-field t)
5753 (org-table-justify-field-maybe)
5754 (call-interactively 'org-table-next-field))))
5756 ((run-hook-with-args-until-success
5757 'org-tab-after-check-for-table-hook))
5759 ((eq arg t) ;; Global cycling
5760 (org-cycle-internal-global))
5762 ((and org-drawers org-drawer-regexp
5763 (save-excursion
5764 (beginning-of-line 1)
5765 (looking-at org-drawer-regexp)))
5766 ;; Toggle block visibility
5767 (org-flag-drawer
5768 (not (get-char-property (match-end 0) 'invisible))))
5770 ((integerp arg)
5771 ;; Show-subtree, ARG levels up from here.
5772 (save-excursion
5773 (org-back-to-heading)
5774 (outline-up-heading (if (< arg 0) (- arg)
5775 (- (funcall outline-level) arg)))
5776 (org-show-subtree)))
5778 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5779 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5781 (org-cycle-internal-local))
5783 ;; TAB emulation and template completion
5784 (buffer-read-only (org-back-to-heading))
5786 ((run-hook-with-args-until-success
5787 'org-tab-after-check-for-cycling-hook))
5789 ((org-try-structure-completion))
5791 ((org-try-cdlatex-tab))
5793 ((run-hook-with-args-until-success
5794 'org-tab-before-tab-emulation-hook))
5796 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5797 (or (not (bolp))
5798 (not (looking-at outline-regexp))))
5799 (call-interactively (global-key-binding "\t")))
5801 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5802 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5803 (or (and (eq org-cycle-emulate-tab 'white)
5804 (= (match-end 0) (point-at-eol)))
5805 (and (eq org-cycle-emulate-tab 'whitestart)
5806 (>= (match-end 0) pos))))
5808 (eq org-cycle-emulate-tab t))
5809 (call-interactively (global-key-binding "\t")))
5811 (t (save-excursion
5812 (org-back-to-heading)
5813 (org-cycle)))))))
5815 (defun org-cycle-internal-global ()
5816 "Do the global cycling action."
5817 (cond
5818 ((and (eq last-command this-command)
5819 (eq org-cycle-global-status 'overview))
5820 ;; We just created the overview - now do table of contents
5821 ;; This can be slow in very large buffers, so indicate action
5822 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5823 (message "CONTENTS...")
5824 (org-content)
5825 (message "CONTENTS...done")
5826 (setq org-cycle-global-status 'contents)
5827 (run-hook-with-args 'org-cycle-hook 'contents))
5829 ((and (eq last-command this-command)
5830 (eq org-cycle-global-status 'contents))
5831 ;; We just showed the table of contents - now show everything
5832 (run-hook-with-args 'org-pre-cycle-hook 'all)
5833 (show-all)
5834 (message "SHOW ALL")
5835 (setq org-cycle-global-status 'all)
5836 (run-hook-with-args 'org-cycle-hook 'all))
5839 ;; Default action: go to overview
5840 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5841 (org-overview)
5842 (message "OVERVIEW")
5843 (setq org-cycle-global-status 'overview)
5844 (run-hook-with-args 'org-cycle-hook 'overview))))
5846 (defun org-cycle-internal-local ()
5847 "Do the local cycling action."
5848 (org-back-to-heading)
5849 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5850 ;; First, some boundaries
5851 (save-excursion
5852 (org-back-to-heading)
5853 (setq level (funcall outline-level))
5854 (save-excursion
5855 (beginning-of-line 2)
5856 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5857 ; XEmacs does not have `next-single-char-property-change'
5858 ; I'm not sure about Emacs 21.
5859 (while (and (not (eobp)) ;; this is like `next-line'
5860 (get-char-property (1- (point)) 'invisible))
5861 (beginning-of-line 2))
5862 (while (and (not (eobp)) ;; this is like `next-line'
5863 (get-char-property (1- (point)) 'invisible))
5864 (goto-char (next-single-char-property-change (point) 'invisible))
5865 (and (eolp) (beginning-of-line 2))))
5866 (setq eol (point)))
5867 (outline-end-of-heading) (setq eoh (point))
5868 (save-excursion
5869 (outline-next-heading)
5870 (setq has-children (and (org-at-heading-p t)
5871 (> (funcall outline-level) level))))
5872 (org-end-of-subtree t)
5873 (unless (eobp)
5874 (skip-chars-forward " \t\n")
5875 (beginning-of-line 1) ; in case this is an item
5877 (setq eos (if (eobp) (point) (1- (point)))))
5878 ;; Find out what to do next and set `this-command'
5879 (cond
5880 ((= eos eoh)
5881 ;; Nothing is hidden behind this heading
5882 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5883 (message "EMPTY ENTRY")
5884 (setq org-cycle-subtree-status nil)
5885 (save-excursion
5886 (goto-char eos)
5887 (outline-next-heading)
5888 (if (org-invisible-p) (org-flag-heading nil))))
5889 ((and (or (>= eol eos)
5890 (not (string-match "\\S-" (buffer-substring eol eos))))
5891 (or has-children
5892 (not (setq children-skipped
5893 org-cycle-skip-children-state-if-no-children))))
5894 ;; Entire subtree is hidden in one line: children view
5895 (run-hook-with-args 'org-pre-cycle-hook 'children)
5896 (org-show-entry)
5897 (show-children)
5898 (message "CHILDREN")
5899 (save-excursion
5900 (goto-char eos)
5901 (outline-next-heading)
5902 (if (org-invisible-p) (org-flag-heading nil)))
5903 (setq org-cycle-subtree-status 'children)
5904 (run-hook-with-args 'org-cycle-hook 'children))
5905 ((or children-skipped
5906 (and (eq last-command this-command)
5907 (eq org-cycle-subtree-status 'children)))
5908 ;; We just showed the children, or no children are there,
5909 ;; now show everything.
5910 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5911 (org-show-subtree)
5912 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5913 (setq org-cycle-subtree-status 'subtree)
5914 (run-hook-with-args 'org-cycle-hook 'subtree))
5916 ;; Default action: hide the subtree.
5917 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5918 (hide-subtree)
5919 (message "FOLDED")
5920 (setq org-cycle-subtree-status 'folded)
5921 (run-hook-with-args 'org-cycle-hook 'folded)))))
5923 ;;;###autoload
5924 (defun org-global-cycle (&optional arg)
5925 "Cycle the global visibility. For details see `org-cycle'.
5926 With C-u prefix arg, switch to startup visibility.
5927 With a numeric prefix, show all headlines up to that level."
5928 (interactive "P")
5929 (let ((org-cycle-include-plain-lists
5930 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5931 (cond
5932 ((integerp arg)
5933 (show-all)
5934 (hide-sublevels arg)
5935 (setq org-cycle-global-status 'contents))
5936 ((equal arg '(4))
5937 (org-set-startup-visibility)
5938 (message "Startup visibility, plus VISIBILITY properties."))
5940 (org-cycle '(4))))))
5942 (defun org-set-startup-visibility ()
5943 "Set the visibility required by startup options and properties."
5944 (cond
5945 ((eq org-startup-folded t)
5946 (org-cycle '(4)))
5947 ((eq org-startup-folded 'content)
5948 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5949 (org-cycle '(4)) (org-cycle '(4)))))
5950 (unless (eq org-startup-folded 'showeverything)
5951 (if org-hide-block-startup (org-hide-block-all))
5952 (org-set-visibility-according-to-property 'no-cleanup)
5953 (org-cycle-hide-archived-subtrees 'all)
5954 (org-cycle-hide-drawers 'all)
5955 (org-cycle-show-empty-lines t)))
5957 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5958 "Switch subtree visibilities according to :VISIBILITY: property."
5959 (interactive)
5960 (let (org-show-entry-below state)
5961 (save-excursion
5962 (goto-char (point-min))
5963 (while (re-search-forward
5964 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5965 nil t)
5966 (setq state (match-string 1))
5967 (save-excursion
5968 (org-back-to-heading t)
5969 (hide-subtree)
5970 (org-reveal)
5971 (cond
5972 ((equal state '("fold" "folded"))
5973 (hide-subtree))
5974 ((equal state "children")
5975 (org-show-hidden-entry)
5976 (show-children))
5977 ((equal state "content")
5978 (save-excursion
5979 (save-restriction
5980 (org-narrow-to-subtree)
5981 (org-content))))
5982 ((member state '("all" "showall"))
5983 (show-subtree)))))
5984 (unless no-cleanup
5985 (org-cycle-hide-archived-subtrees 'all)
5986 (org-cycle-hide-drawers 'all)
5987 (org-cycle-show-empty-lines 'all)))))
5989 (defun org-overview ()
5990 "Switch to overview mode, showing only top-level headlines.
5991 Really, this shows all headlines with level equal or greater than the level
5992 of the first headline in the buffer. This is important, because if the
5993 first headline is not level one, then (hide-sublevels 1) gives confusing
5994 results."
5995 (interactive)
5996 (let ((level (save-excursion
5997 (goto-char (point-min))
5998 (if (re-search-forward (concat "^" outline-regexp) nil t)
5999 (progn
6000 (goto-char (match-beginning 0))
6001 (funcall outline-level))))))
6002 (and level (hide-sublevels level))))
6004 (defun org-content (&optional arg)
6005 "Show all headlines in the buffer, like a table of contents.
6006 With numerical argument N, show content up to level N."
6007 (interactive "P")
6008 (save-excursion
6009 ;; Visit all headings and show their offspring
6010 (and (integerp arg) (org-overview))
6011 (goto-char (point-max))
6012 (catch 'exit
6013 (while (and (progn (condition-case nil
6014 (outline-previous-visible-heading 1)
6015 (error (goto-char (point-min))))
6017 (looking-at outline-regexp))
6018 (if (integerp arg)
6019 (show-children (1- arg))
6020 (show-branches))
6021 (if (bobp) (throw 'exit nil))))))
6024 (defun org-optimize-window-after-visibility-change (state)
6025 "Adjust the window after a change in outline visibility.
6026 This function is the default value of the hook `org-cycle-hook'."
6027 (when (get-buffer-window (current-buffer))
6028 (cond
6029 ((eq state 'content) nil)
6030 ((eq state 'all) nil)
6031 ((eq state 'folded) nil)
6032 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6033 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6035 (defun org-remove-empty-overlays-at (pos)
6036 "Remove outline overlays that do not contain non-white stuff."
6037 (mapc
6038 (lambda (o)
6039 (and (eq 'outline (overlay-get o 'invisible))
6040 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6041 (overlay-end o))))
6042 (delete-overlay o)))
6043 (overlays-at pos)))
6045 (defun org-clean-visibility-after-subtree-move ()
6046 "Fix visibility issues after moving a subtree."
6047 ;; First, find a reasonable region to look at:
6048 ;; Start two siblings above, end three below
6049 (let* ((beg (save-excursion
6050 (and (org-get-last-sibling)
6051 (org-get-last-sibling))
6052 (point)))
6053 (end (save-excursion
6054 (and (org-get-next-sibling)
6055 (org-get-next-sibling)
6056 (org-get-next-sibling))
6057 (if (org-at-heading-p)
6058 (point-at-eol)
6059 (point))))
6060 (level (looking-at "\\*+"))
6061 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6062 (save-excursion
6063 (save-restriction
6064 (narrow-to-region beg end)
6065 (when re
6066 ;; Properly fold already folded siblings
6067 (goto-char (point-min))
6068 (while (re-search-forward re nil t)
6069 (if (and (not (org-invisible-p))
6070 (save-excursion
6071 (goto-char (point-at-eol)) (org-invisible-p)))
6072 (hide-entry))))
6073 (org-cycle-show-empty-lines 'overview)
6074 (org-cycle-hide-drawers 'overview)))))
6076 (defun org-cycle-show-empty-lines (state)
6077 "Show empty lines above all visible headlines.
6078 The region to be covered depends on STATE when called through
6079 `org-cycle-hook'. Lisp program can use t for STATE to get the
6080 entire buffer covered. Note that an empty line is only shown if there
6081 are at least `org-cycle-separator-lines' empty lines before the headline."
6082 (when (not (= org-cycle-separator-lines 0))
6083 (save-excursion
6084 (let* ((n (abs org-cycle-separator-lines))
6085 (re (cond
6086 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6087 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6088 (t (let ((ns (number-to-string (- n 2))))
6089 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6090 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6091 beg end b e)
6092 (cond
6093 ((memq state '(overview contents t))
6094 (setq beg (point-min) end (point-max)))
6095 ((memq state '(children folded))
6096 (setq beg (point) end (progn (org-end-of-subtree t t)
6097 (beginning-of-line 2)
6098 (point)))))
6099 (when beg
6100 (goto-char beg)
6101 (while (re-search-forward re end t)
6102 (unless (get-char-property (match-end 1) 'invisible)
6103 (setq e (match-end 1))
6104 (if (< org-cycle-separator-lines 0)
6105 (setq b (save-excursion
6106 (goto-char (match-beginning 0))
6107 (org-back-over-empty-lines)
6108 (if (save-excursion
6109 (goto-char (max (point-min) (1- (point))))
6110 (org-on-heading-p))
6111 (1- (point))
6112 (point))))
6113 (setq b (match-beginning 1)))
6114 (outline-flag-region b e nil)))))))
6115 ;; Never hide empty lines at the end of the file.
6116 (save-excursion
6117 (goto-char (point-max))
6118 (outline-previous-heading)
6119 (outline-end-of-heading)
6120 (if (and (looking-at "[ \t\n]+")
6121 (= (match-end 0) (point-max)))
6122 (outline-flag-region (point) (match-end 0) nil))))
6124 (defun org-show-empty-lines-in-parent ()
6125 "Move to the parent and re-show empty lines before visible headlines."
6126 (save-excursion
6127 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6128 (org-cycle-show-empty-lines context))))
6130 (defun org-files-list ()
6131 "Return `org-agenda-files' list, plus all open org-mode files.
6132 This is useful for operations that need to scan all of a user's
6133 open and agenda-wise Org files."
6134 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6135 (dolist (buf (buffer-list))
6136 (with-current-buffer buf
6137 (if (and (eq major-mode 'org-mode) (buffer-file-name))
6138 (let ((file (expand-file-name (buffer-file-name))))
6139 (unless (member file files)
6140 (push file files))))))
6141 files))
6143 (defsubst org-entry-beginning-position ()
6144 "Return the beginning position of the current entry."
6145 (save-excursion (outline-back-to-heading t) (point)))
6147 (defsubst org-entry-end-position ()
6148 "Return the end position of the current entry."
6149 (save-excursion (outline-next-heading) (point)))
6151 (defun org-cycle-hide-drawers (state)
6152 "Re-hide all drawers after a visibility state change."
6153 (when (and (org-mode-p)
6154 (not (memq state '(overview folded contents))))
6155 (save-excursion
6156 (let* ((globalp (memq state '(contents all)))
6157 (beg (if globalp (point-min) (point)))
6158 (end (if globalp (point-max)
6159 (if (eq state 'children)
6160 (save-excursion (outline-next-heading) (point))
6161 (org-end-of-subtree t)))))
6162 (goto-char beg)
6163 (while (re-search-forward org-drawer-regexp end t)
6164 (org-flag-drawer t))))))
6166 (defun org-flag-drawer (flag)
6167 (save-excursion
6168 (beginning-of-line 1)
6169 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6170 (let ((b (match-end 0))
6171 (outline-regexp org-outline-regexp))
6172 (if (re-search-forward
6173 "^[ \t]*:END:"
6174 (save-excursion (outline-next-heading) (point)) t)
6175 (outline-flag-region b (point-at-eol) flag)
6176 (error ":END: line missing at position %s" b))))))
6178 (defun org-subtree-end-visible-p ()
6179 "Is the end of the current subtree visible?"
6180 (pos-visible-in-window-p
6181 (save-excursion (org-end-of-subtree t) (point))))
6183 (defun org-first-headline-recenter (&optional N)
6184 "Move cursor to the first headline and recenter the headline.
6185 Optional argument N means put the headline into the Nth line of the window."
6186 (goto-char (point-min))
6187 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
6188 (beginning-of-line)
6189 (recenter (prefix-numeric-value N))))
6191 ;;; Saving and restoring visibility
6193 (defun org-outline-overlay-data (&optional use-markers)
6194 "Return a list of the locations of all outline overlays.
6195 The are overlays with the `invisible' property value `outline'.
6196 The return valus is a list of cons cells, with start and stop
6197 positions for each overlay.
6198 If USE-MARKERS is set, return the positions as markers."
6199 (let (beg end)
6200 (save-excursion
6201 (save-restriction
6202 (widen)
6203 (delq nil
6204 (mapcar (lambda (o)
6205 (when (eq (overlay-get o 'invisible) 'outline)
6206 (setq beg (overlay-start o)
6207 end (overlay-end o))
6208 (and beg end (> end beg)
6209 (if use-markers
6210 (cons (move-marker (make-marker) beg)
6211 (move-marker (make-marker) end))
6212 (cons beg end)))))
6213 (overlays-in (point-min) (point-max))))))))
6215 (defun org-set-outline-overlay-data (data)
6216 "Create visibility overlays for all positions in DATA.
6217 DATA should have been made by `org-outline-overlay-data'."
6218 (let (o)
6219 (save-excursion
6220 (save-restriction
6221 (widen)
6222 (show-all)
6223 (mapc (lambda (c)
6224 (setq o (make-overlay (car c) (cdr c)))
6225 (overlay-put o 'invisible 'outline))
6226 data)))))
6228 (defmacro org-save-outline-visibility (use-markers &rest body)
6229 "Save and restore outline visibility around BODY.
6230 If USE-MARKERS is non-nil, use markers for the positions.
6231 This means that the buffer may change while running BODY,
6232 but it also means that the buffer should stay alive
6233 during the operation, because otherwise all these markers will
6234 point nowhere."
6235 (declare (indent 1))
6236 `(let ((data (org-outline-overlay-data ,use-markers)))
6237 (unwind-protect
6238 (progn
6239 ,@body
6240 (org-set-outline-overlay-data data))
6241 (when ,use-markers
6242 (mapc (lambda (c)
6243 (and (markerp (car c)) (move-marker (car c) nil))
6244 (and (markerp (cdr c)) (move-marker (cdr c) nil)))
6245 data)))))
6248 ;;; Folding of blocks
6250 (defconst org-block-regexp
6252 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
6253 "Regular expression for hiding blocks.")
6255 (defvar org-hide-block-overlays nil
6256 "Overlays hiding blocks.")
6257 (make-variable-buffer-local 'org-hide-block-overlays)
6259 (defun org-block-map (function &optional start end)
6260 "Call func at the head of all source blocks in the current
6261 buffer. Optional arguments START and END can be used to limit
6262 the range."
6263 (let ((start (or start (point-min)))
6264 (end (or end (point-max))))
6265 (save-excursion
6266 (goto-char start)
6267 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6268 (save-excursion
6269 (save-match-data
6270 (goto-char (match-beginning 0))
6271 (funcall function)))))))
6273 (defun org-hide-block-toggle-all ()
6274 "Toggle the visibility of all blocks in the current buffer."
6275 (org-block-map #'org-hide-block-toggle))
6277 (defun org-hide-block-all ()
6278 "Fold all blocks in the current buffer."
6279 (interactive)
6280 (org-show-block-all)
6281 (org-block-map #'org-hide-block-toggle-maybe))
6283 (defun org-show-block-all ()
6284 "Unfold all blocks in the current buffer."
6285 (interactive)
6286 (mapc 'delete-overlay org-hide-block-overlays)
6287 (setq org-hide-block-overlays nil))
6289 (defun org-hide-block-toggle-maybe ()
6290 "Toggle visibility of block at point."
6291 (interactive)
6292 (let ((case-fold-search t))
6293 (if (save-excursion
6294 (beginning-of-line 1)
6295 (looking-at org-block-regexp))
6296 (progn (org-hide-block-toggle)
6297 t) ;; to signal that we took action
6298 nil))) ;; to signal that we did not
6300 (defun org-hide-block-toggle (&optional force)
6301 "Toggle the visibility of the current block."
6302 (interactive)
6303 (save-excursion
6304 (beginning-of-line)
6305 (if (re-search-forward org-block-regexp nil t)
6306 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6307 (end (match-end 0)) ;; end of entire body
6309 (if (memq t (mapcar (lambda (overlay)
6310 (eq (overlay-get overlay 'invisible)
6311 'org-hide-block))
6312 (overlays-at start)))
6313 (if (or (not force) (eq force 'off))
6314 (mapc (lambda (ov)
6315 (when (member ov org-hide-block-overlays)
6316 (setq org-hide-block-overlays
6317 (delq ov org-hide-block-overlays)))
6318 (when (eq (overlay-get ov 'invisible)
6319 'org-hide-block)
6320 (delete-overlay ov)))
6321 (overlays-at start)))
6322 (setq ov (make-overlay start end))
6323 (overlay-put ov 'invisible 'org-hide-block)
6324 ;; make the block accessible to isearch
6325 (overlay-put
6326 ov 'isearch-open-invisible
6327 (lambda (ov)
6328 (when (member ov org-hide-block-overlays)
6329 (setq org-hide-block-overlays
6330 (delq ov org-hide-block-overlays)))
6331 (when (eq (overlay-get ov 'invisible)
6332 'org-hide-block)
6333 (delete-overlay ov))))
6334 (push ov org-hide-block-overlays)))
6335 (error "Not looking at a source block"))))
6337 ;; org-tab-after-check-for-cycling-hook
6338 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6339 ;; Remove overlays when changing major mode
6340 (add-hook 'org-mode-hook
6341 (lambda () (org-add-hook 'change-major-mode-hook
6342 'org-show-block-all 'append 'local)))
6344 ;;; Org-goto
6346 (defvar org-goto-window-configuration nil)
6347 (defvar org-goto-marker nil)
6348 (defvar org-goto-map
6349 (let ((map (make-sparse-keymap)))
6350 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6351 (while (setq cmd (pop cmds))
6352 (substitute-key-definition cmd cmd map global-map)))
6353 (suppress-keymap map)
6354 (org-defkey map "\C-m" 'org-goto-ret)
6355 (org-defkey map [(return)] 'org-goto-ret)
6356 (org-defkey map [(left)] 'org-goto-left)
6357 (org-defkey map [(right)] 'org-goto-right)
6358 (org-defkey map [(control ?g)] 'org-goto-quit)
6359 (org-defkey map "\C-i" 'org-cycle)
6360 (org-defkey map [(tab)] 'org-cycle)
6361 (org-defkey map [(down)] 'outline-next-visible-heading)
6362 (org-defkey map [(up)] 'outline-previous-visible-heading)
6363 (if org-goto-auto-isearch
6364 (if (fboundp 'define-key-after)
6365 (define-key-after map [t] 'org-goto-local-auto-isearch)
6366 nil)
6367 (org-defkey map "q" 'org-goto-quit)
6368 (org-defkey map "n" 'outline-next-visible-heading)
6369 (org-defkey map "p" 'outline-previous-visible-heading)
6370 (org-defkey map "f" 'outline-forward-same-level)
6371 (org-defkey map "b" 'outline-backward-same-level)
6372 (org-defkey map "u" 'outline-up-heading))
6373 (org-defkey map "/" 'org-occur)
6374 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6375 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6376 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6377 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6378 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6379 map))
6381 (defconst org-goto-help
6382 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6383 RET=jump to location [Q]uit and return to previous location
6384 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6386 (defvar org-goto-start-pos) ; dynamically scoped parameter
6388 ;; FIXME: Docstring does not mention both interfaces
6389 (defun org-goto (&optional alternative-interface)
6390 "Look up a different location in the current file, keeping current visibility.
6392 When you want look-up or go to a different location in a document, the
6393 fastest way is often to fold the entire buffer and then dive into the tree.
6394 This method has the disadvantage, that the previous location will be folded,
6395 which may not be what you want.
6397 This command works around this by showing a copy of the current buffer
6398 in an indirect buffer, in overview mode. You can dive into the tree in
6399 that copy, use org-occur and incremental search to find a location.
6400 When pressing RET or `Q', the command returns to the original buffer in
6401 which the visibility is still unchanged. After RET is will also jump to
6402 the location selected in the indirect buffer and expose the
6403 the headline hierarchy above."
6404 (interactive "P")
6405 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6406 (org-refile-use-outline-path t)
6407 (org-refile-target-verify-function nil)
6408 (interface
6409 (if (not alternative-interface)
6410 org-goto-interface
6411 (if (eq org-goto-interface 'outline)
6412 'outline-path-completion
6413 'outline)))
6414 (org-goto-start-pos (point))
6415 (selected-point
6416 (if (eq interface 'outline)
6417 (car (org-get-location (current-buffer) org-goto-help))
6418 (nth 3 (org-refile-get-location "Goto: ")))))
6419 (if selected-point
6420 (progn
6421 (org-mark-ring-push org-goto-start-pos)
6422 (goto-char selected-point)
6423 (if (or (org-invisible-p) (org-invisible-p2))
6424 (org-show-context 'org-goto)))
6425 (message "Quit"))))
6427 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6428 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6429 (defvar org-goto-local-auto-isearch-map) ; defined below
6431 (defun org-get-location (buf help)
6432 "Let the user select a location in the Org-mode buffer BUF.
6433 This function uses a recursive edit. It returns the selected position
6434 or nil."
6435 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6436 (isearch-hide-immediately nil)
6437 (isearch-search-fun-function
6438 (lambda () 'org-goto-local-search-headings))
6439 (org-goto-selected-point org-goto-exit-command)
6440 (pop-up-frames nil)
6441 (special-display-buffer-names nil)
6442 (special-display-regexps nil)
6443 (special-display-function nil))
6444 (save-excursion
6445 (save-window-excursion
6446 (delete-other-windows)
6447 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6448 (switch-to-buffer
6449 (condition-case nil
6450 (make-indirect-buffer (current-buffer) "*org-goto*")
6451 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6452 (with-output-to-temp-buffer "*Help*"
6453 (princ help))
6454 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6455 (setq buffer-read-only nil)
6456 (let ((org-startup-truncated t)
6457 (org-startup-folded nil)
6458 (org-startup-align-all-tables nil))
6459 (org-mode)
6460 (org-overview))
6461 (setq buffer-read-only t)
6462 (if (and (boundp 'org-goto-start-pos)
6463 (integer-or-marker-p org-goto-start-pos))
6464 (let ((org-show-hierarchy-above t)
6465 (org-show-siblings t)
6466 (org-show-following-heading t))
6467 (goto-char org-goto-start-pos)
6468 (and (org-invisible-p) (org-show-context)))
6469 (goto-char (point-min)))
6470 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6471 (message "Select location and press RET")
6472 (use-local-map org-goto-map)
6473 (recursive-edit)
6475 (kill-buffer "*org-goto*")
6476 (cons org-goto-selected-point org-goto-exit-command)))
6478 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6479 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6480 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6481 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6483 (defun org-goto-local-search-headings (string bound noerror)
6484 "Search and make sure that any matches are in headlines."
6485 (catch 'return
6486 (while (if isearch-forward
6487 (search-forward string bound noerror)
6488 (search-backward string bound noerror))
6489 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6490 (and (member :headline context)
6491 (not (member :tags context))))
6492 (throw 'return (point))))))
6494 (defun org-goto-local-auto-isearch ()
6495 "Start isearch."
6496 (interactive)
6497 (goto-char (point-min))
6498 (let ((keys (this-command-keys)))
6499 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6500 (isearch-mode t)
6501 (isearch-process-search-char (string-to-char keys)))))
6503 (defun org-goto-ret (&optional arg)
6504 "Finish `org-goto' by going to the new location."
6505 (interactive "P")
6506 (setq org-goto-selected-point (point)
6507 org-goto-exit-command 'return)
6508 (throw 'exit nil))
6510 (defun org-goto-left ()
6511 "Finish `org-goto' by going to the new location."
6512 (interactive)
6513 (if (org-on-heading-p)
6514 (progn
6515 (beginning-of-line 1)
6516 (setq org-goto-selected-point (point)
6517 org-goto-exit-command 'left)
6518 (throw 'exit nil))
6519 (error "Not on a heading")))
6521 (defun org-goto-right ()
6522 "Finish `org-goto' by going to the new location."
6523 (interactive)
6524 (if (org-on-heading-p)
6525 (progn
6526 (setq org-goto-selected-point (point)
6527 org-goto-exit-command 'right)
6528 (throw 'exit nil))
6529 (error "Not on a heading")))
6531 (defun org-goto-quit ()
6532 "Finish `org-goto' without cursor motion."
6533 (interactive)
6534 (setq org-goto-selected-point nil)
6535 (setq org-goto-exit-command 'quit)
6536 (throw 'exit nil))
6538 ;;; Indirect buffer display of subtrees
6540 (defvar org-indirect-dedicated-frame nil
6541 "This is the frame being used for indirect tree display.")
6542 (defvar org-last-indirect-buffer nil)
6544 (defun org-tree-to-indirect-buffer (&optional arg)
6545 "Create indirect buffer and narrow it to current subtree.
6546 With numerical prefix ARG, go up to this level and then take that tree.
6547 If ARG is negative, go up that many levels.
6548 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6549 indirect buffer previously made with this command, to avoid proliferation of
6550 indirect buffers. However, when you call the command with a `C-u' prefix, or
6551 when `org-indirect-buffer-display' is `new-frame', the last buffer
6552 is kept so that you can work with several indirect buffers at the same time.
6553 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6554 requests that a new frame be made for the new buffer, so that the dedicated
6555 frame is not changed."
6556 (interactive "P")
6557 (let ((cbuf (current-buffer))
6558 (cwin (selected-window))
6559 (pos (point))
6560 beg end level heading ibuf)
6561 (save-excursion
6562 (org-back-to-heading t)
6563 (when (numberp arg)
6564 (setq level (org-outline-level))
6565 (if (< arg 0) (setq arg (+ level arg)))
6566 (while (> (setq level (org-outline-level)) arg)
6567 (outline-up-heading 1 t)))
6568 (setq beg (point)
6569 heading (org-get-heading))
6570 (org-end-of-subtree t t)
6571 (if (org-on-heading-p) (backward-char 1))
6572 (setq end (point)))
6573 (if (and (buffer-live-p org-last-indirect-buffer)
6574 (not (eq org-indirect-buffer-display 'new-frame))
6575 (not arg))
6576 (kill-buffer org-last-indirect-buffer))
6577 (setq ibuf (org-get-indirect-buffer cbuf)
6578 org-last-indirect-buffer ibuf)
6579 (cond
6580 ((or (eq org-indirect-buffer-display 'new-frame)
6581 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6582 (select-frame (make-frame))
6583 (delete-other-windows)
6584 (switch-to-buffer ibuf)
6585 (org-set-frame-title heading))
6586 ((eq org-indirect-buffer-display 'dedicated-frame)
6587 (raise-frame
6588 (select-frame (or (and org-indirect-dedicated-frame
6589 (frame-live-p org-indirect-dedicated-frame)
6590 org-indirect-dedicated-frame)
6591 (setq org-indirect-dedicated-frame (make-frame)))))
6592 (delete-other-windows)
6593 (switch-to-buffer ibuf)
6594 (org-set-frame-title (concat "Indirect: " heading)))
6595 ((eq org-indirect-buffer-display 'current-window)
6596 (switch-to-buffer ibuf))
6597 ((eq org-indirect-buffer-display 'other-window)
6598 (pop-to-buffer ibuf))
6599 (t (error "Invalid value")))
6600 (if (featurep 'xemacs)
6601 (save-excursion (org-mode) (turn-on-font-lock)))
6602 (narrow-to-region beg end)
6603 (show-all)
6604 (goto-char pos)
6605 (and (window-live-p cwin) (select-window cwin))))
6607 (defun org-get-indirect-buffer (&optional buffer)
6608 (setq buffer (or buffer (current-buffer)))
6609 (let ((n 1) (base (buffer-name buffer)) bname)
6610 (while (buffer-live-p
6611 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6612 (setq n (1+ n)))
6613 (condition-case nil
6614 (make-indirect-buffer buffer bname 'clone)
6615 (error (make-indirect-buffer buffer bname)))))
6617 (defun org-set-frame-title (title)
6618 "Set the title of the current frame to the string TITLE."
6619 ;; FIXME: how to name a single frame in XEmacs???
6620 (unless (featurep 'xemacs)
6621 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6623 ;;;; Structure editing
6625 ;;; Inserting headlines
6627 (defun org-previous-line-empty-p ()
6628 (save-excursion
6629 (and (not (bobp))
6630 (or (beginning-of-line 0) t)
6631 (save-match-data
6632 (looking-at "[ \t]*$")))))
6634 (defun org-insert-heading (&optional force-heading invisible-ok)
6635 "Insert a new heading or item with same depth at point.
6636 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6637 If point is at the beginning of a headline, insert a sibling before the
6638 current headline. If point is not at the beginning, do not split the line,
6639 but create the new headline after the current line.
6640 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6641 This is important for non-interactive uses of the command."
6642 (interactive "P")
6643 (if (or (= (buffer-size) 0)
6644 (and (not (save-excursion (and (ignore-errors (org-back-to-heading invisible-ok))
6645 (org-on-heading-p))))
6646 (not (org-in-item-p))))
6647 (insert "\n* ")
6648 (when (or force-heading (not (org-insert-item)))
6649 (let* ((empty-line-p nil)
6650 (head (save-excursion
6651 (condition-case nil
6652 (progn
6653 (org-back-to-heading invisible-ok)
6654 (setq empty-line-p (org-previous-line-empty-p))
6655 (match-string 0))
6656 (error "*"))))
6657 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6658 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6659 pos hide-previous previous-pos)
6660 (cond
6661 ((and (org-on-heading-p) (bolp)
6662 (or (bobp)
6663 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6664 ;; insert before the current line
6665 (open-line (if blank 2 1)))
6666 ((and (bolp)
6667 (not org-insert-heading-respect-content)
6668 (or (bobp)
6669 (save-excursion
6670 (backward-char 1) (not (org-invisible-p)))))
6671 ;; insert right here
6672 nil)
6674 ;; somewhere in the line
6675 (save-excursion
6676 (setq previous-pos (point-at-bol))
6677 (end-of-line)
6678 (setq hide-previous (org-invisible-p)))
6679 (and org-insert-heading-respect-content (org-show-subtree))
6680 (let ((split
6681 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6682 (save-excursion
6683 (let ((p (point)))
6684 (goto-char (point-at-bol))
6685 (and (looking-at org-complex-heading-regexp)
6686 (> p (match-beginning 4)))))))
6687 tags pos)
6688 (cond
6689 (org-insert-heading-respect-content
6690 (org-end-of-subtree nil t)
6691 (or (bolp) (newline))
6692 (or (org-previous-line-empty-p)
6693 (and blank (newline)))
6694 (open-line 1))
6695 ((org-on-heading-p)
6696 (when hide-previous
6697 (show-children)
6698 (org-show-entry))
6699 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6700 (setq tags (and (match-end 2) (match-string 2)))
6701 (and (match-end 1)
6702 (delete-region (match-beginning 1) (match-end 1)))
6703 (setq pos (point-at-bol))
6704 (or split (end-of-line 1))
6705 (delete-horizontal-space)
6706 (if (string-match "\\`\\*+\\'"
6707 (buffer-substring (point-at-bol) (point)))
6708 (insert " "))
6709 (newline (if blank 2 1))
6710 (when tags
6711 (save-excursion
6712 (goto-char pos)
6713 (end-of-line 1)
6714 (insert " " tags)
6715 (org-set-tags nil 'align))))
6717 (or split (end-of-line 1))
6718 (newline (if blank 2 1)))))))
6719 (insert head) (just-one-space)
6720 (setq pos (point))
6721 (end-of-line 1)
6722 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6723 (when (and org-insert-heading-respect-content hide-previous)
6724 (save-excursion
6725 (goto-char previous-pos)
6726 (hide-subtree)))
6727 (run-hooks 'org-insert-heading-hook)))))
6729 (defun org-get-heading (&optional no-tags)
6730 "Return the heading of the current entry, without the stars."
6731 (save-excursion
6732 (org-back-to-heading t)
6733 (if (looking-at
6734 (if no-tags
6735 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6736 "\\*+[ \t]+\\([^\r\n]*\\)"))
6737 (match-string 1) "")))
6739 (defun org-heading-components ()
6740 "Return the components of the current heading.
6741 This is a list with the following elements:
6742 - the level as an integer
6743 - the reduced level, different if `org-odd-levels-only' is set.
6744 - the TODO keyword, or nil
6745 - the priority character, like ?A, or nil if no priority is given
6746 - the headline text itself, or the tags string if no headline text
6747 - the tags string, or nil."
6748 (save-excursion
6749 (org-back-to-heading t)
6750 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6751 (list (length (match-string 1))
6752 (org-reduced-level (length (match-string 1)))
6753 (org-match-string-no-properties 2)
6754 (and (match-end 3) (aref (match-string 3) 2))
6755 (org-match-string-no-properties 4)
6756 (org-match-string-no-properties 5)))))
6758 (defun org-get-entry ()
6759 "Get the entry text, after heading, entire subtree."
6760 (save-excursion
6761 (org-back-to-heading t)
6762 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6764 (defun org-insert-heading-after-current ()
6765 "Insert a new heading with same level as current, after current subtree."
6766 (interactive)
6767 (org-back-to-heading)
6768 (org-insert-heading)
6769 (org-move-subtree-down)
6770 (end-of-line 1))
6772 (defun org-insert-heading-respect-content ()
6773 (interactive)
6774 (let ((org-insert-heading-respect-content t))
6775 (org-insert-heading t)))
6777 (defun org-insert-todo-heading-respect-content (&optional force-state)
6778 (interactive "P")
6779 (let ((org-insert-heading-respect-content t))
6780 (org-insert-todo-heading force-state t)))
6782 (defun org-insert-todo-heading (arg &optional force-heading)
6783 "Insert a new heading with the same level and TODO state as current heading.
6784 If the heading has no TODO state, or if the state is DONE, use the first
6785 state (TODO by default). Also with prefix arg, force first state."
6786 (interactive "P")
6787 (when (or force-heading (not (org-insert-item 'checkbox)))
6788 (org-insert-heading force-heading)
6789 (save-excursion
6790 (org-back-to-heading)
6791 (outline-previous-heading)
6792 (looking-at org-todo-line-regexp))
6793 (let*
6794 ((new-mark-x
6795 (if (or arg
6796 (not (match-beginning 2))
6797 (member (match-string 2) org-done-keywords))
6798 (car org-todo-keywords-1)
6799 (match-string 2)))
6800 (new-mark
6802 (run-hook-with-args-until-success
6803 'org-todo-get-default-hook new-mark-x nil)
6804 new-mark-x)))
6805 (beginning-of-line 1)
6806 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6807 (if org-treat-insert-todo-heading-as-state-change
6808 (org-todo new-mark)
6809 (insert new-mark " "))))
6810 (when org-provide-todo-statistics
6811 (org-update-parent-todo-statistics))))
6813 (defun org-insert-subheading (arg)
6814 "Insert a new subheading and demote it.
6815 Works for outline headings and for plain lists alike."
6816 (interactive "P")
6817 (org-insert-heading arg)
6818 (cond
6819 ((org-on-heading-p) (org-do-demote))
6820 ((org-at-item-p) (org-indent-item 1))))
6822 (defun org-insert-todo-subheading (arg)
6823 "Insert a new subheading with TODO keyword or checkbox and demote it.
6824 Works for outline headings and for plain lists alike."
6825 (interactive "P")
6826 (org-insert-todo-heading arg)
6827 (cond
6828 ((org-on-heading-p) (org-do-demote))
6829 ((org-at-item-p) (org-indent-item 1))))
6831 ;;; Promotion and Demotion
6833 (defvar org-after-demote-entry-hook nil
6834 "Hook run after an entry has been demoted.
6835 The cursor will be at the beginning of the entry.
6836 When a subtree is being demoted, the hook will be called for each node.")
6838 (defvar org-after-promote-entry-hook nil
6839 "Hook run after an entry has been promoted.
6840 The cursor will be at the beginning of the entry.
6841 When a subtree is being promoted, the hook will be called for each node.")
6843 (defun org-promote-subtree ()
6844 "Promote the entire subtree.
6845 See also `org-promote'."
6846 (interactive)
6847 (save-excursion
6848 (org-map-tree 'org-promote))
6849 (org-fix-position-after-promote))
6851 (defun org-demote-subtree ()
6852 "Demote the entire subtree. See `org-demote'.
6853 See also `org-promote'."
6854 (interactive)
6855 (save-excursion
6856 (org-map-tree 'org-demote))
6857 (org-fix-position-after-promote))
6860 (defun org-do-promote ()
6861 "Promote the current heading higher up the tree.
6862 If the region is active in `transient-mark-mode', promote all headings
6863 in the region."
6864 (interactive)
6865 (save-excursion
6866 (if (org-region-active-p)
6867 (org-map-region 'org-promote (region-beginning) (region-end))
6868 (org-promote)))
6869 (org-fix-position-after-promote))
6871 (defun org-do-demote ()
6872 "Demote the current heading lower down the tree.
6873 If the region is active in `transient-mark-mode', demote all headings
6874 in the region."
6875 (interactive)
6876 (save-excursion
6877 (if (org-region-active-p)
6878 (org-map-region 'org-demote (region-beginning) (region-end))
6879 (org-demote)))
6880 (org-fix-position-after-promote))
6882 (defun org-fix-position-after-promote ()
6883 "Make sure that after pro/demotion cursor position is right."
6884 (let ((pos (point)))
6885 (when (save-excursion
6886 (beginning-of-line 1)
6887 (looking-at org-todo-line-regexp)
6888 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6889 (cond ((eobp) (insert " "))
6890 ((eolp) (insert " "))
6891 ((equal (char-after) ?\ ) (forward-char 1))))))
6893 (defun org-current-level ()
6894 "Return the level of the current entry, or nil if before the first headline.
6895 The level is the number of stars at the beginning of the headline."
6896 (save-excursion
6897 (condition-case nil
6898 (progn
6899 (org-back-to-heading t)
6900 (funcall outline-level))
6901 (error nil))))
6903 (defun org-get-previous-line-level ()
6904 "Return the outline depth of the last headline before the current line.
6905 Returns 0 for the first headline in the buffer, and nil if before the
6906 first headline."
6907 (let ((current-level (org-current-level))
6908 (prev-level (when (> (line-number-at-pos) 1)
6909 (save-excursion
6910 (beginning-of-line 0)
6911 (org-current-level)))))
6912 (cond ((null current-level) nil) ; Before first headline
6913 ((null prev-level) 0) ; At first headline
6914 (prev-level))))
6916 (defun org-reduced-level (l)
6917 "Compute the effective level of a heading.
6918 This takes into account the setting of `org-odd-levels-only'."
6919 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6921 (defun org-level-increment ()
6922 "Return the number of stars that will be added or removed at a
6923 time to headlines when structure editing, based on the value of
6924 `org-odd-levels-only'."
6925 (if org-odd-levels-only 2 1))
6927 (defun org-get-valid-level (level &optional change)
6928 "Rectify a level change under the influence of `org-odd-levels-only'
6929 LEVEL is a current level, CHANGE is by how much the level should be
6930 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6931 even level numbers will become the next higher odd number."
6932 (if org-odd-levels-only
6933 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6934 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6935 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6936 (max 1 (+ level (or change 0)))))
6938 (if (boundp 'define-obsolete-function-alias)
6939 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6940 (define-obsolete-function-alias 'org-get-legal-level
6941 'org-get-valid-level)
6942 (define-obsolete-function-alias 'org-get-legal-level
6943 'org-get-valid-level "23.1")))
6945 (defun org-promote ()
6946 "Promote the current heading higher up the tree.
6947 If the region is active in `transient-mark-mode', promote all headings
6948 in the region."
6949 (org-back-to-heading t)
6950 (let* ((level (save-match-data (funcall outline-level)))
6951 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6952 (diff (abs (- level (length up-head) -1))))
6953 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6954 (replace-match up-head nil t)
6955 ;; Fixup tag positioning
6956 (and org-auto-align-tags (org-set-tags nil t))
6957 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6958 (run-hooks 'org-after-promote-entry-hook)))
6960 (defun org-demote ()
6961 "Demote the current heading lower down the tree.
6962 If the region is active in `transient-mark-mode', demote all headings
6963 in the region."
6964 (org-back-to-heading t)
6965 (let* ((level (save-match-data (funcall outline-level)))
6966 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6967 (diff (abs (- level (length down-head) -1))))
6968 (replace-match down-head nil t)
6969 ;; Fixup tag positioning
6970 (and org-auto-align-tags (org-set-tags nil t))
6971 (if org-adapt-indentation (org-fixup-indentation diff))
6972 (run-hooks 'org-after-demote-entry-hook)))
6974 (defun org-cycle-level ()
6975 "Cycle the level of an empty headline through possible states.
6976 This goes first to child, then to parent, level, then up the hierarchy.
6977 After top level, it switches back to sibling level."
6978 (interactive)
6979 (let ((org-adapt-indentation nil))
6980 (when (org-point-at-end-of-empty-headline)
6981 (setq this-command 'org-cycle-level) ; Only needed for caching
6982 (let ((cur-level (org-current-level))
6983 (prev-level (org-get-previous-line-level)))
6984 (cond
6985 ;; If first headline in file, promote to top-level.
6986 ((= prev-level 0)
6987 (loop repeat (/ (- cur-level 1) (org-level-increment))
6988 do (org-do-promote)))
6989 ;; If same level as prev, demote one.
6990 ((= prev-level cur-level)
6991 (org-do-demote))
6992 ;; If parent is top-level, promote to top level if not already.
6993 ((= prev-level 1)
6994 (loop repeat (/ (- cur-level 1) (org-level-increment))
6995 do (org-do-promote)))
6996 ;; If top-level, return to prev-level.
6997 ((= cur-level 1)
6998 (loop repeat (/ (- prev-level 1) (org-level-increment))
6999 do (org-do-demote)))
7000 ;; If less than prev-level, promote one.
7001 ((< cur-level prev-level)
7002 (org-do-promote))
7003 ;; If deeper than prev-level, promote until higher than
7004 ;; prev-level.
7005 ((> cur-level prev-level)
7006 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7007 do (org-do-promote))))
7008 t))))
7010 (defun org-map-tree (fun)
7011 "Call FUN for every heading underneath the current one."
7012 (org-back-to-heading)
7013 (let ((level (funcall outline-level)))
7014 (save-excursion
7015 (funcall fun)
7016 (while (and (progn
7017 (outline-next-heading)
7018 (> (funcall outline-level) level))
7019 (not (eobp)))
7020 (funcall fun)))))
7022 (defun org-map-region (fun beg end)
7023 "Call FUN for every heading between BEG and END."
7024 (let ((org-ignore-region t))
7025 (save-excursion
7026 (setq end (copy-marker end))
7027 (goto-char beg)
7028 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
7029 (< (point) end))
7030 (funcall fun))
7031 (while (and (progn
7032 (outline-next-heading)
7033 (< (point) end))
7034 (not (eobp)))
7035 (funcall fun)))))
7037 (defun org-fixup-indentation (diff)
7038 "Change the indentation in the current entry by DIFF
7039 However, if any line in the current entry has no indentation, or if it
7040 would end up with no indentation after the change, nothing at all is done."
7041 (save-excursion
7042 (let ((end (save-excursion (outline-next-heading)
7043 (point-marker)))
7044 (prohibit (if (> diff 0)
7045 "^\\S-"
7046 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7047 col)
7048 (unless (save-excursion (end-of-line 1)
7049 (re-search-forward prohibit end t))
7050 (while (and (< (point) end)
7051 (re-search-forward "^[ \t]+" end t))
7052 (goto-char (match-end 0))
7053 (setq col (current-column))
7054 (if (< diff 0) (replace-match ""))
7055 (org-indent-to-column (+ diff col))))
7056 (move-marker end nil))))
7058 (defun org-convert-to-odd-levels ()
7059 "Convert an org-mode file with all levels allowed to one with odd levels.
7060 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7061 level 5 etc."
7062 (interactive)
7063 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7064 (let ((outline-regexp org-outline-regexp)
7065 (outline-level 'org-outline-level)
7066 (org-odd-levels-only nil) n)
7067 (save-excursion
7068 (goto-char (point-min))
7069 (while (re-search-forward "^\\*\\*+ " nil t)
7070 (setq n (- (length (match-string 0)) 2))
7071 (while (>= (setq n (1- n)) 0)
7072 (org-demote))
7073 (end-of-line 1))))))
7075 (defun org-convert-to-oddeven-levels ()
7076 "Convert an org-mode file with only odd levels to one with odd and even levels.
7077 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
7078 section with an even level, conversion would destroy the structure of the file. An error
7079 is signaled in this case."
7080 (interactive)
7081 (goto-char (point-min))
7082 ;; First check if there are no even levels
7083 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7084 (org-show-context t)
7085 (error "Not all levels are odd in this file. Conversion not possible"))
7086 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7087 (let ((outline-regexp org-outline-regexp)
7088 (outline-level 'org-outline-level)
7089 (org-odd-levels-only nil) n)
7090 (save-excursion
7091 (goto-char (point-min))
7092 (while (re-search-forward "^\\*\\*+ " nil t)
7093 (setq n (/ (1- (length (match-string 0))) 2))
7094 (while (>= (setq n (1- n)) 0)
7095 (org-promote))
7096 (end-of-line 1))))))
7098 (defun org-tr-level (n)
7099 "Make N odd if required."
7100 (if org-odd-levels-only (1+ (/ n 2)) n))
7102 ;;; Vertical tree motion, cutting and pasting of subtrees
7104 (defun org-move-subtree-up (&optional arg)
7105 "Move the current subtree up past ARG headlines of the same level."
7106 (interactive "p")
7107 (org-move-subtree-down (- (prefix-numeric-value arg))))
7109 (defun org-move-subtree-down (&optional arg)
7110 "Move the current subtree down past ARG headlines of the same level."
7111 (interactive "p")
7112 (setq arg (prefix-numeric-value arg))
7113 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7114 'org-get-last-sibling))
7115 (ins-point (make-marker))
7116 (cnt (abs arg))
7117 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7118 ;; Select the tree
7119 (org-back-to-heading)
7120 (setq beg0 (point))
7121 (save-excursion
7122 (setq ne-beg (org-back-over-empty-lines))
7123 (setq beg (point)))
7124 (save-match-data
7125 (save-excursion (outline-end-of-heading)
7126 (setq folded (org-invisible-p)))
7127 (outline-end-of-subtree))
7128 (outline-next-heading)
7129 (setq ne-end (org-back-over-empty-lines))
7130 (setq end (point))
7131 (goto-char beg0)
7132 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7133 ;; include less whitespace
7134 (save-excursion
7135 (goto-char beg)
7136 (forward-line (- ne-beg ne-end))
7137 (setq beg (point))))
7138 ;; Find insertion point, with error handling
7139 (while (> cnt 0)
7140 (or (and (funcall movfunc) (looking-at outline-regexp))
7141 (progn (goto-char beg0)
7142 (error "Cannot move past superior level or buffer limit")))
7143 (setq cnt (1- cnt)))
7144 (if (> arg 0)
7145 ;; Moving forward - still need to move over subtree
7146 (progn (org-end-of-subtree t t)
7147 (save-excursion
7148 (org-back-over-empty-lines)
7149 (or (bolp) (newline)))))
7150 (setq ne-ins (org-back-over-empty-lines))
7151 (move-marker ins-point (point))
7152 (setq txt (buffer-substring beg end))
7153 (org-save-markers-in-region beg end)
7154 (delete-region beg end)
7155 (org-remove-empty-overlays-at beg)
7156 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7157 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7158 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7159 (let ((bbb (point)))
7160 (insert-before-markers txt)
7161 (org-reinstall-markers-in-region bbb)
7162 (move-marker ins-point bbb))
7163 (or (bolp) (insert "\n"))
7164 (setq ins-end (point))
7165 (goto-char ins-point)
7166 (org-skip-whitespace)
7167 (when (and (< arg 0)
7168 (org-first-sibling-p)
7169 (> ne-ins ne-beg))
7170 ;; Move whitespace back to beginning
7171 (save-excursion
7172 (goto-char ins-end)
7173 (let ((kill-whole-line t))
7174 (kill-line (- ne-ins ne-beg)) (point)))
7175 (insert (make-string (- ne-ins ne-beg) ?\n)))
7176 (move-marker ins-point nil)
7177 (if folded
7178 (hide-subtree)
7179 (org-show-entry)
7180 (show-children)
7181 (org-cycle-hide-drawers 'children))
7182 (org-clean-visibility-after-subtree-move)))
7184 (defvar org-subtree-clip ""
7185 "Clipboard for cut and paste of subtrees.
7186 This is actually only a copy of the kill, because we use the normal kill
7187 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7189 (defvar org-subtree-clip-folded nil
7190 "Was the last copied subtree folded?
7191 This is used to fold the tree back after pasting.")
7193 (defun org-cut-subtree (&optional n)
7194 "Cut the current subtree into the clipboard.
7195 With prefix arg N, cut this many sequential subtrees.
7196 This is a short-hand for marking the subtree and then cutting it."
7197 (interactive "p")
7198 (org-copy-subtree n 'cut))
7200 (defun org-copy-subtree (&optional n cut force-store-markers)
7201 "Cut the current subtree into the clipboard.
7202 With prefix arg N, cut this many sequential subtrees.
7203 This is a short-hand for marking the subtree and then copying it.
7204 If CUT is non-nil, actually cut the subtree.
7205 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7206 of some markers in the region, even if CUT is non-nil. This is
7207 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7208 (interactive "p")
7209 (let (beg end folded (beg0 (point)))
7210 (if (interactive-p)
7211 (org-back-to-heading nil) ; take what looks like a subtree
7212 (org-back-to-heading t)) ; take what is really there
7213 (org-back-over-empty-lines)
7214 (setq beg (point))
7215 (skip-chars-forward " \t\r\n")
7216 (save-match-data
7217 (save-excursion (outline-end-of-heading)
7218 (setq folded (org-invisible-p)))
7219 (condition-case nil
7220 (org-forward-same-level (1- n) t)
7221 (error nil))
7222 (org-end-of-subtree t t))
7223 (org-back-over-empty-lines)
7224 (setq end (point))
7225 (goto-char beg0)
7226 (when (> end beg)
7227 (setq org-subtree-clip-folded folded)
7228 (when (or cut force-store-markers)
7229 (org-save-markers-in-region beg end))
7230 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7231 (setq org-subtree-clip (current-kill 0))
7232 (message "%s: Subtree(s) with %d characters"
7233 (if cut "Cut" "Copied")
7234 (length org-subtree-clip)))))
7236 (defun org-paste-subtree (&optional level tree for-yank)
7237 "Paste the clipboard as a subtree, with modification of headline level.
7238 The entire subtree is promoted or demoted in order to match a new headline
7239 level.
7241 If the cursor is at the beginning of a headline, the same level as
7242 that headline is used to paste the tree
7244 If not, the new level is derived from the *visible* headings
7245 before and after the insertion point, and taken to be the inferior headline
7246 level of the two. So if the previous visible heading is level 3 and the
7247 next is level 4 (or vice versa), level 4 will be used for insertion.
7248 This makes sure that the subtree remains an independent subtree and does
7249 not swallow low level entries.
7251 You can also force a different level, either by using a numeric prefix
7252 argument, or by inserting the heading marker by hand. For example, if the
7253 cursor is after \"*****\", then the tree will be shifted to level 5.
7255 If optional TREE is given, use this text instead of the kill ring.
7257 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7258 move back over whitespace before inserting, and move point to the end of
7259 the inserted text when done."
7260 (interactive "P")
7261 (setq tree (or tree (and kill-ring (current-kill 0))))
7262 (unless (org-kill-is-subtree-p tree)
7263 (error "%s"
7264 (substitute-command-keys
7265 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7266 (let* ((visp (not (org-invisible-p)))
7267 (txt tree)
7268 (^re (concat "^\\(" outline-regexp "\\)"))
7269 (re (concat "\\(" outline-regexp "\\)"))
7270 (^re_ (concat "\\(\\*+\\)[ \t]*"))
7272 (old-level (if (string-match ^re txt)
7273 (- (match-end 0) (match-beginning 0) 1)
7274 -1))
7275 (force-level (cond (level (prefix-numeric-value level))
7276 ((and (looking-at "[ \t]*$")
7277 (string-match
7278 ^re_ (buffer-substring
7279 (point-at-bol) (point))))
7280 (- (match-end 1) (match-beginning 1)))
7281 ((and (bolp)
7282 (looking-at org-outline-regexp))
7283 (- (match-end 0) (point) 1))
7284 (t nil)))
7285 (previous-level (save-excursion
7286 (condition-case nil
7287 (progn
7288 (outline-previous-visible-heading 1)
7289 (if (looking-at re)
7290 (- (match-end 0) (match-beginning 0) 1)
7292 (error 1))))
7293 (next-level (save-excursion
7294 (condition-case nil
7295 (progn
7296 (or (looking-at outline-regexp)
7297 (outline-next-visible-heading 1))
7298 (if (looking-at re)
7299 (- (match-end 0) (match-beginning 0) 1)
7301 (error 1))))
7302 (new-level (or force-level (max previous-level next-level)))
7303 (shift (if (or (= old-level -1)
7304 (= new-level -1)
7305 (= old-level new-level))
7307 (- new-level old-level)))
7308 (delta (if (> shift 0) -1 1))
7309 (func (if (> shift 0) 'org-demote 'org-promote))
7310 (org-odd-levels-only nil)
7311 beg end newend)
7312 ;; Remove the forced level indicator
7313 (if force-level
7314 (delete-region (point-at-bol) (point)))
7315 ;; Paste
7316 (beginning-of-line 1)
7317 (unless for-yank (org-back-over-empty-lines))
7318 (setq beg (point))
7319 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7320 (insert-before-markers txt)
7321 (unless (string-match "\n\\'" txt) (insert "\n"))
7322 (setq newend (point))
7323 (org-reinstall-markers-in-region beg)
7324 (setq end (point))
7325 (goto-char beg)
7326 (skip-chars-forward " \t\n\r")
7327 (setq beg (point))
7328 (if (and (org-invisible-p) visp)
7329 (save-excursion (outline-show-heading)))
7330 ;; Shift if necessary
7331 (unless (= shift 0)
7332 (save-restriction
7333 (narrow-to-region beg end)
7334 (while (not (= shift 0))
7335 (org-map-region func (point-min) (point-max))
7336 (setq shift (+ delta shift)))
7337 (goto-char (point-min))
7338 (setq newend (point-max))))
7339 (when (or (interactive-p) for-yank)
7340 (message "Clipboard pasted as level %d subtree" new-level))
7341 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7342 kill-ring
7343 (eq org-subtree-clip (current-kill 0))
7344 org-subtree-clip-folded)
7345 ;; The tree was folded before it was killed/copied
7346 (hide-subtree))
7347 (and for-yank (goto-char newend))))
7349 (defun org-kill-is-subtree-p (&optional txt)
7350 "Check if the current kill is an outline subtree, or a set of trees.
7351 Returns nil if kill does not start with a headline, or if the first
7352 headline level is not the largest headline level in the tree.
7353 So this will actually accept several entries of equal levels as well,
7354 which is OK for `org-paste-subtree'.
7355 If optional TXT is given, check this string instead of the current kill."
7356 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7357 (start-level (and kill
7358 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
7359 org-outline-regexp "\\)")
7360 kill)
7361 (- (match-end 2) (match-beginning 2) 1)))
7362 (re (concat "^" org-outline-regexp))
7363 (start (1+ (or (match-beginning 2) -1))))
7364 (if (not start-level)
7365 (progn
7366 nil) ;; does not even start with a heading
7367 (catch 'exit
7368 (while (setq start (string-match re kill (1+ start)))
7369 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7370 (throw 'exit nil)))
7371 t))))
7373 (defvar org-markers-to-move nil
7374 "Markers that should be moved with a cut-and-paste operation.
7375 Those markers are stored together with their positions relative to
7376 the start of the region.")
7378 (defun org-save-markers-in-region (beg end)
7379 "Check markers in region.
7380 If these markers are between BEG and END, record their position relative
7381 to BEG, so that after moving the block of text, we can put the markers back
7382 into place.
7383 This function gets called just before an entry or tree gets cut from the
7384 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7385 called immediately, to move the markers with the entries."
7386 (setq org-markers-to-move nil)
7387 (when (featurep 'org-clock)
7388 (org-clock-save-markers-for-cut-and-paste beg end))
7389 (when (featurep 'org-agenda)
7390 (org-agenda-save-markers-for-cut-and-paste beg end)))
7392 (defun org-check-and-save-marker (marker beg end)
7393 "Check if MARKER is between BEG and END.
7394 If yes, remember the marker and the distance to BEG."
7395 (when (and (marker-buffer marker)
7396 (equal (marker-buffer marker) (current-buffer)))
7397 (if (and (>= marker beg) (< marker end))
7398 (push (cons marker (- marker beg)) org-markers-to-move))))
7400 (defun org-reinstall-markers-in-region (beg)
7401 "Move all remembered markers to their position relative to BEG."
7402 (mapc (lambda (x)
7403 (move-marker (car x) (+ beg (cdr x))))
7404 org-markers-to-move)
7405 (setq org-markers-to-move nil))
7407 (defun org-narrow-to-subtree ()
7408 "Narrow buffer to the current subtree."
7409 (interactive)
7410 (save-excursion
7411 (save-match-data
7412 (narrow-to-region
7413 (progn (org-back-to-heading t) (point))
7414 (progn (org-end-of-subtree t t)
7415 (if (org-on-heading-p) (backward-char 1))
7416 (point))))))
7418 (eval-when-compile
7419 (defvar org-property-drawer-re))
7421 (defun org-clone-subtree-with-time-shift (n &optional shift)
7422 "Clone the task (subtree) at point N times.
7423 The clones will be inserted as siblings.
7425 In interactive use, the user will be prompted for the number of
7426 clones to be produced, and for a time SHIFT, which may be a
7427 repeater as used in time stamps, for example `+3d'.
7429 When a valid repeater is given and the entry contains any time
7430 stamps, the clones will become a sequence in time, with time
7431 stamps in the subtree shifted for each clone produced. If SHIFT
7432 is nil or the empty string, time stamps will be left alone. The
7433 ID property of the original subtree is removed.
7435 If the original subtree did contain time stamps with a repeater,
7436 the following will happen:
7437 - the repeater will be removed in each clone
7438 - an additional clone will be produced, with the current, unshifted
7439 date(s) in the entry.
7440 - the original entry will be placed *after* all the clones, with
7441 repeater intact.
7442 - the start days in the repeater in the original entry will be shifted
7443 to past the last clone.
7444 I this way you can spell out a number of instances of a repeating task,
7445 and still retain the repeater to cover future instances of the task."
7446 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7447 (let (beg end template task idprop
7448 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7449 (if (not (and (integerp n) (> n 0)))
7450 (error "Invalid number of replications %s" n))
7451 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7452 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7453 shift)))
7454 (error "Invalid shift specification %s" shift))
7455 (when doshift
7456 (setq shift-n (string-to-number (match-string 1 shift))
7457 shift-what (cdr (assoc (match-string 2 shift)
7458 '(("d" . day) ("w" . week)
7459 ("m" . month) ("y" . year))))))
7460 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7461 (setq nmin 1 nmax n)
7462 (org-back-to-heading t)
7463 (setq beg (point))
7464 (setq idprop (org-entry-get nil "ID"))
7465 (org-end-of-subtree t t)
7466 (or (bolp) (insert "\n"))
7467 (setq end (point))
7468 (setq template (buffer-substring beg end))
7469 (when (and doshift
7470 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7471 (delete-region beg end)
7472 (setq end beg)
7473 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7474 (goto-char end)
7475 (loop for n from nmin to nmax do
7476 ;; prepare clone
7477 (with-temp-buffer
7478 (insert template)
7479 (org-mode)
7480 (goto-char (point-min))
7481 (and idprop (if org-clone-delete-id
7482 (org-entry-delete nil "ID")
7483 (org-id-get-create t)))
7484 (while (re-search-forward org-property-drawer-re nil t)
7485 (org-remove-empty-drawer-at "PROPERTIES" (point)))
7486 (goto-char (point-min))
7487 (when doshift
7488 (while (re-search-forward org-ts-regexp-both nil t)
7489 (org-timestamp-change (* n shift-n) shift-what))
7490 (unless (= n n-no-remove)
7491 (goto-char (point-min))
7492 (while (re-search-forward org-ts-regexp nil t)
7493 (save-excursion
7494 (goto-char (match-beginning 0))
7495 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7496 (delete-region (match-beginning 1) (match-end 1)))))))
7497 (setq task (buffer-string)))
7498 (insert task))
7499 (goto-char beg)))
7501 ;;; Outline Sorting
7503 (defun org-sort (with-case)
7504 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
7505 Optional argument WITH-CASE means sort case-sensitively.
7506 With a double prefix argument, also remove duplicate entries."
7507 (interactive "P")
7508 (if (org-at-table-p)
7509 (org-call-with-arg 'org-table-sort-lines with-case)
7510 (org-call-with-arg 'org-sort-entries-or-items with-case)))
7512 (defun org-sort-remove-invisible (s)
7513 (remove-text-properties 0 (length s) org-rm-props s)
7514 (while (string-match org-bracket-link-regexp s)
7515 (setq s (replace-match (if (match-end 2)
7516 (match-string 3 s)
7517 (match-string 1 s)) t t s)))
7520 (defvar org-priority-regexp) ; defined later in the file
7522 (defvar org-after-sorting-entries-or-items-hook nil
7523 "Hook that is run after a bunch of entries or items have been sorted.
7524 When children are sorted, the cursor is in the parent line when this
7525 hook gets called. When a region or a plain list is sorted, the cursor
7526 will be in the first entry of the sorted region/list.")
7528 (defun org-sort-entries-or-items
7529 (&optional with-case sorting-type getkey-func compare-func property)
7530 "Sort entries on a certain level of an outline tree, or plain list items.
7531 If there is an active region, the entries in the region are sorted.
7532 Else, if the cursor is before the first entry, sort the top-level items.
7533 Else, the children of the entry at point are sorted.
7534 If the cursor is at the first item in a plain list, the list items will be
7535 sorted.
7537 Sorting can be alphabetically, numerically, by date/time as given by
7538 a time stamp, by a property or by priority.
7540 The command prompts for the sorting type unless it has been given to the
7541 function through the SORTING-TYPE argument, which needs to be a character,
7542 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7543 precise meaning of each character:
7545 n Numerically, by converting the beginning of the entry/item to a number.
7546 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7547 t By date/time, either the first active time stamp in the entry, or, if
7548 none exist, by the first inactive one.
7549 In items, only the first line will be checked.
7550 s By the scheduled date/time.
7551 d By deadline date/time.
7552 c By creation time, which is assumed to be the first inactive time stamp
7553 at the beginning of a line.
7554 p By priority according to the cookie.
7555 r By the value of a property.
7557 Capital letters will reverse the sort order.
7559 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7560 called with point at the beginning of the record. It must return either
7561 a string or a number that should serve as the sorting key for that record.
7563 Comparing entries ignores case by default. However, with an optional argument
7564 WITH-CASE, the sorting considers case as well."
7565 (interactive "P")
7566 (let ((case-func (if with-case 'identity 'downcase))
7567 start beg end stars re re2
7568 txt what tmp plain-list-p)
7569 ;; Find beginning and end of region to sort
7570 (cond
7571 ((org-region-active-p)
7572 ;; we will sort the region
7573 (setq end (region-end)
7574 what "region")
7575 (goto-char (region-beginning))
7576 (if (not (org-on-heading-p)) (outline-next-heading))
7577 (setq start (point)))
7578 ((org-at-item-p)
7579 ;; we will sort this plain list
7580 (org-beginning-of-item-list) (setq start (point))
7581 (org-end-of-item-list)
7582 (or (bolp) (insert "\n"))
7583 (setq end (point))
7584 (goto-char start)
7585 (setq plain-list-p t
7586 what "plain list"))
7587 ((or (org-on-heading-p)
7588 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7589 ;; we will sort the children of the current headline
7590 (org-back-to-heading)
7591 (setq start (point)
7592 end (progn (org-end-of-subtree t t)
7593 (or (bolp) (insert "\n"))
7594 (org-back-over-empty-lines)
7595 (point))
7596 what "children")
7597 (goto-char start)
7598 (show-subtree)
7599 (outline-next-heading))
7601 ;; we will sort the top-level entries in this file
7602 (goto-char (point-min))
7603 (or (org-on-heading-p) (outline-next-heading))
7604 (setq start (point))
7605 (goto-char (point-max))
7606 (beginning-of-line 1)
7607 (when (looking-at ".*?\\S-")
7608 ;; File ends in a non-white line
7609 (end-of-line 1)
7610 (insert "\n"))
7611 (setq end (point-max))
7612 (setq what "top-level")
7613 (goto-char start)
7614 (show-all)))
7616 (setq beg (point))
7617 (if (>= beg end) (error "Nothing to sort"))
7619 (unless plain-list-p
7620 (looking-at "\\(\\*+\\)")
7621 (setq stars (match-string 1)
7622 re (concat "^" (regexp-quote stars) " +")
7623 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7624 txt (buffer-substring beg end))
7625 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7626 (if (and (not (equal stars "*")) (string-match re2 txt))
7627 (error "Region to sort contains a level above the first entry")))
7629 (unless sorting-type
7630 (message
7631 (if plain-list-p
7632 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7633 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7634 [t]ime [s]cheduled [d]eadline [c]reated
7635 A/N/T/S/D/C/P/O/F means reversed:")
7636 what)
7637 (setq sorting-type (read-char-exclusive))
7639 (and (= (downcase sorting-type) ?f)
7640 (setq getkey-func
7641 (org-icompleting-read "Sort using function: "
7642 obarray 'fboundp t nil nil))
7643 (setq getkey-func (intern getkey-func)))
7645 (and (= (downcase sorting-type) ?r)
7646 (setq property
7647 (org-icompleting-read "Property: "
7648 (mapcar 'list (org-buffer-property-keys t))
7649 nil t))))
7651 (message "Sorting entries...")
7653 (save-restriction
7654 (narrow-to-region start end)
7656 (let ((dcst (downcase sorting-type))
7657 (case-fold-search nil)
7658 (now (current-time)))
7659 (sort-subr
7660 (/= dcst sorting-type)
7661 ;; This function moves to the beginning character of the "record" to
7662 ;; be sorted.
7663 (if plain-list-p
7664 (lambda nil
7665 (if (org-at-item-p) t (goto-char (point-max))))
7666 (lambda nil
7667 (if (re-search-forward re nil t)
7668 (goto-char (match-beginning 0))
7669 (goto-char (point-max)))))
7670 ;; This function moves to the last character of the "record" being
7671 ;; sorted.
7672 (if plain-list-p
7673 'org-end-of-item
7674 (lambda nil
7675 (save-match-data
7676 (condition-case nil
7677 (outline-forward-same-level 1)
7678 (error
7679 (goto-char (point-max)))))))
7681 ;; This function returns the value that gets sorted against.
7682 (if plain-list-p
7683 (lambda nil
7684 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7685 (cond
7686 ((= dcst ?n)
7687 (string-to-number (buffer-substring (match-end 0)
7688 (point-at-eol))))
7689 ((= dcst ?a)
7690 (buffer-substring (match-end 0) (point-at-eol)))
7691 ((= dcst ?t)
7692 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
7693 (re-search-forward org-ts-regexp-both
7694 (point-at-eol) t))
7695 (org-time-string-to-seconds (match-string 0))
7696 (org-float-time now)))
7697 ((= dcst ?f)
7698 (if getkey-func
7699 (progn
7700 (setq tmp (funcall getkey-func))
7701 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7702 tmp)
7703 (error "Invalid key function `%s'" getkey-func)))
7704 (t (error "Invalid sorting type `%c'" sorting-type)))))
7705 (lambda nil
7706 (cond
7707 ((= dcst ?n)
7708 (if (looking-at org-complex-heading-regexp)
7709 (string-to-number (match-string 4))
7710 nil))
7711 ((= dcst ?a)
7712 (if (looking-at org-complex-heading-regexp)
7713 (funcall case-func (match-string 4))
7714 nil))
7715 ((= dcst ?t)
7716 (let ((end (save-excursion (outline-next-heading) (point))))
7717 (if (or (re-search-forward org-ts-regexp end t)
7718 (re-search-forward org-ts-regexp-both end t))
7719 (org-time-string-to-seconds (match-string 0))
7720 (org-float-time now))))
7721 ((= dcst ?c)
7722 (let ((end (save-excursion (outline-next-heading) (point))))
7723 (if (re-search-forward
7724 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7725 end t)
7726 (org-time-string-to-seconds (match-string 0))
7727 (org-float-time now))))
7728 ((= dcst ?s)
7729 (let ((end (save-excursion (outline-next-heading) (point))))
7730 (if (re-search-forward org-scheduled-time-regexp end t)
7731 (org-time-string-to-seconds (match-string 1))
7732 (org-float-time now))))
7733 ((= dcst ?d)
7734 (let ((end (save-excursion (outline-next-heading) (point))))
7735 (if (re-search-forward org-deadline-time-regexp end t)
7736 (org-time-string-to-seconds (match-string 1))
7737 (org-float-time now))))
7738 ((= dcst ?p)
7739 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7740 (string-to-char (match-string 2))
7741 org-default-priority))
7742 ((= dcst ?r)
7743 (or (org-entry-get nil property) ""))
7744 ((= dcst ?o)
7745 (if (looking-at org-complex-heading-regexp)
7746 (- 9999 (length (member (match-string 2)
7747 org-todo-keywords-1)))))
7748 ((= dcst ?f)
7749 (if getkey-func
7750 (progn
7751 (setq tmp (funcall getkey-func))
7752 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7753 tmp)
7754 (error "Invalid key function `%s'" getkey-func)))
7755 (t (error "Invalid sorting type `%c'" sorting-type)))))
7757 (cond
7758 ((= dcst ?a) 'string<)
7759 ((= dcst ?f) compare-func)
7760 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7761 (t nil)))))
7762 (run-hooks 'org-after-sorting-entries-or-items-hook)
7763 (message "Sorting entries...done")))
7765 (defun org-do-sort (table what &optional with-case sorting-type)
7766 "Sort TABLE of WHAT according to SORTING-TYPE.
7767 The user will be prompted for the SORTING-TYPE if the call to this
7768 function does not specify it. WHAT is only for the prompt, to indicate
7769 what is being sorted. The sorting key will be extracted from
7770 the car of the elements of the table.
7771 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7772 (unless sorting-type
7773 (message
7774 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7775 what)
7776 (setq sorting-type (read-char-exclusive)))
7777 (let ((dcst (downcase sorting-type))
7778 extractfun comparefun)
7779 ;; Define the appropriate functions
7780 (cond
7781 ((= dcst ?n)
7782 (setq extractfun 'string-to-number
7783 comparefun (if (= dcst sorting-type) '< '>)))
7784 ((= dcst ?a)
7785 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7786 (lambda(x) (downcase (org-sort-remove-invisible x))))
7787 comparefun (if (= dcst sorting-type)
7788 'string<
7789 (lambda (a b) (and (not (string< a b))
7790 (not (string= a b)))))))
7791 ((= dcst ?t)
7792 (setq extractfun
7793 (lambda (x)
7794 (if (or (string-match org-ts-regexp x)
7795 (string-match org-ts-regexp-both x))
7796 (org-float-time
7797 (org-time-string-to-time (match-string 0 x)))
7799 comparefun (if (= dcst sorting-type) '< '>)))
7800 (t (error "Invalid sorting type `%c'" sorting-type)))
7802 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7803 table)
7804 (lambda (a b) (funcall comparefun (car a) (car b))))))
7807 ;;; The orgstruct minor mode
7809 ;; Define a minor mode which can be used in other modes in order to
7810 ;; integrate the org-mode structure editing commands.
7812 ;; This is really a hack, because the org-mode structure commands use
7813 ;; keys which normally belong to the major mode. Here is how it
7814 ;; works: The minor mode defines all the keys necessary to operate the
7815 ;; structure commands, but wraps the commands into a function which
7816 ;; tests if the cursor is currently at a headline or a plain list
7817 ;; item. If that is the case, the structure command is used,
7818 ;; temporarily setting many Org-mode variables like regular
7819 ;; expressions for filling etc. However, when any of those keys is
7820 ;; used at a different location, function uses `key-binding' to look
7821 ;; up if the key has an associated command in another currently active
7822 ;; keymap (minor modes, major mode, global), and executes that
7823 ;; command. There might be problems if any of the keys is otherwise
7824 ;; used as a prefix key.
7826 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7827 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7828 ;; addresses this by checking explicitly for both bindings.
7830 (defvar orgstruct-mode-map (make-sparse-keymap)
7831 "Keymap for the minor `orgstruct-mode'.")
7833 (defvar org-local-vars nil
7834 "List of local variables, for use by `orgstruct-mode'")
7836 ;;;###autoload
7837 (define-minor-mode orgstruct-mode
7838 "Toggle the minor mode `orgstruct-mode'.
7839 This mode is for using Org-mode structure commands in other
7840 modes. The following keys behave as if Org-mode were active, if
7841 the cursor is on a headline, or on a plain list item (both as
7842 defined by Org-mode).
7844 M-up Move entry/item up
7845 M-down Move entry/item down
7846 M-left Promote
7847 M-right Demote
7848 M-S-up Move entry/item up
7849 M-S-down Move entry/item down
7850 M-S-left Promote subtree
7851 M-S-right Demote subtree
7852 M-q Fill paragraph and items like in Org-mode
7853 C-c ^ Sort entries
7854 C-c - Cycle list bullet
7855 TAB Cycle item visibility
7856 M-RET Insert new heading/item
7857 S-M-RET Insert new TODO heading / Checkbox item
7858 C-c C-c Set tags / toggle checkbox"
7859 nil " OrgStruct" nil
7860 (org-load-modules-maybe)
7861 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7863 ;;;###autoload
7864 (defun turn-on-orgstruct ()
7865 "Unconditionally turn on `orgstruct-mode'."
7866 (orgstruct-mode 1))
7868 (defun orgstruct++-mode (&optional arg)
7869 "Toggle `orgstruct-mode', the enhanced version of it.
7870 In addition to setting orgstruct-mode, this also exports all indentation
7871 and autofilling variables from org-mode into the buffer. It will also
7872 recognize item context in multiline items.
7873 Note that turning off orgstruct-mode will *not* remove the
7874 indentation/paragraph settings. This can only be done by refreshing the
7875 major mode, for example with \\[normal-mode]."
7876 (interactive "P")
7877 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7878 (if (< arg 1)
7879 (orgstruct-mode -1)
7880 (orgstruct-mode 1)
7881 (let (var val)
7882 (mapc
7883 (lambda (x)
7884 (when (string-match
7885 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7886 (symbol-name (car x)))
7887 (setq var (car x) val (nth 1 x))
7888 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7889 org-local-vars)
7890 (org-set-local 'orgstruct-is-++ t))))
7892 (defvar orgstruct-is-++ nil
7893 "Is orgstruct-mode in ++ version in the current-buffer?")
7894 (make-variable-buffer-local 'orgstruct-is-++)
7896 ;;;###autoload
7897 (defun turn-on-orgstruct++ ()
7898 "Unconditionally turn on `orgstruct++-mode'."
7899 (orgstruct++-mode 1))
7901 (defun orgstruct-error ()
7902 "Error when there is no default binding for a structure key."
7903 (interactive)
7904 (error "This key has no function outside structure elements"))
7906 (defun orgstruct-setup ()
7907 "Setup orgstruct keymaps."
7908 (let ((nfunc 0)
7909 (bindings
7910 (list
7911 '([(meta up)] org-metaup)
7912 '([(meta down)] org-metadown)
7913 '([(meta left)] org-metaleft)
7914 '([(meta right)] org-metaright)
7915 '([(meta shift up)] org-shiftmetaup)
7916 '([(meta shift down)] org-shiftmetadown)
7917 '([(meta shift left)] org-shiftmetaleft)
7918 '([(meta shift right)] org-shiftmetaright)
7919 '([?\e (up)] org-metaup)
7920 '([?\e (down)] org-metadown)
7921 '([?\e (left)] org-metaleft)
7922 '([?\e (right)] org-metaright)
7923 '([?\e (shift up)] org-shiftmetaup)
7924 '([?\e (shift down)] org-shiftmetadown)
7925 '([?\e (shift left)] org-shiftmetaleft)
7926 '([?\e (shift right)] org-shiftmetaright)
7927 '([(shift up)] org-shiftup)
7928 '([(shift down)] org-shiftdown)
7929 '([(shift left)] org-shiftleft)
7930 '([(shift right)] org-shiftright)
7931 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7932 '("\M-q" fill-paragraph)
7933 '("\C-c^" org-sort)
7934 '("\C-c-" org-cycle-list-bullet)))
7935 elt key fun cmd)
7936 (while (setq elt (pop bindings))
7937 (setq nfunc (1+ nfunc))
7938 (setq key (org-key (car elt))
7939 fun (nth 1 elt)
7940 cmd (orgstruct-make-binding fun nfunc key))
7941 (org-defkey orgstruct-mode-map key cmd))
7943 ;; Special treatment needed for TAB and RET
7944 (org-defkey orgstruct-mode-map [(tab)]
7945 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7946 (org-defkey orgstruct-mode-map "\C-i"
7947 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7949 (org-defkey orgstruct-mode-map "\M-\C-m"
7950 (orgstruct-make-binding 'org-insert-heading 105
7951 "\M-\C-m" [(meta return)]))
7952 (org-defkey orgstruct-mode-map [(meta return)]
7953 (orgstruct-make-binding 'org-insert-heading 106
7954 [(meta return)] "\M-\C-m"))
7956 (org-defkey orgstruct-mode-map [(shift meta return)]
7957 (orgstruct-make-binding 'org-insert-todo-heading 107
7958 [(meta return)] "\M-\C-m"))
7960 (org-defkey orgstruct-mode-map "\e\C-m"
7961 (orgstruct-make-binding 'org-insert-heading 108
7962 "\e\C-m" [?\e (return)]))
7963 (org-defkey orgstruct-mode-map [?\e (return)]
7964 (orgstruct-make-binding 'org-insert-heading 109
7965 [?\e (return)] "\e\C-m"))
7966 (org-defkey orgstruct-mode-map [?\e (shift return)]
7967 (orgstruct-make-binding 'org-insert-todo-heading 110
7968 [?\e (return)] "\e\C-m"))
7970 (unless org-local-vars
7971 (setq org-local-vars (org-get-local-variables)))
7975 (defun orgstruct-make-binding (fun n &rest keys)
7976 "Create a function for binding in the structure minor mode.
7977 FUN is the command to call inside a table. N is used to create a unique
7978 command name. KEYS are keys that should be checked in for a command
7979 to execute outside of tables."
7980 (eval
7981 (list 'defun
7982 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7983 '(arg)
7984 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7985 "Outside of structure, run the binding of `"
7986 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7987 "'.")
7988 '(interactive "p")
7989 (list 'if
7990 `(org-context-p 'headline 'item
7991 (and orgstruct-is-++
7992 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7993 'item-body))
7994 (list 'org-run-like-in-org-mode (list 'quote fun))
7995 (list 'let '(orgstruct-mode)
7996 (list 'call-interactively
7997 (append '(or)
7998 (mapcar (lambda (k)
7999 (list 'key-binding k))
8000 keys)
8001 '('orgstruct-error))))))))
8003 (defun org-context-p (&rest contexts)
8004 "Check if local context is any of CONTEXTS.
8005 Possible values in the list of contexts are `table', `headline', and `item'."
8006 (let ((pos (point)))
8007 (goto-char (point-at-bol))
8008 (prog1 (or (and (memq 'table contexts)
8009 (looking-at "[ \t]*|"))
8010 (and (memq 'headline contexts)
8011 ;;????????? (looking-at "\\*+"))
8012 (looking-at outline-regexp))
8013 (and (memq 'item contexts)
8014 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8015 (and (memq 'item-body contexts)
8016 (org-in-item-p)))
8017 (goto-char pos))))
8019 (defun org-get-local-variables ()
8020 "Return a list of all local variables in an org-mode buffer."
8021 (let (varlist)
8022 (with-current-buffer (get-buffer-create "*Org tmp*")
8023 (erase-buffer)
8024 (org-mode)
8025 (setq varlist (buffer-local-variables)))
8026 (kill-buffer "*Org tmp*")
8027 (delq nil
8028 (mapcar
8029 (lambda (x)
8030 (setq x
8031 (if (symbolp x)
8032 (list x)
8033 (list (car x) (list 'quote (cdr x)))))
8034 (if (string-match
8035 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8036 (symbol-name (car x)))
8037 x nil))
8038 varlist))))
8040 ;;;###autoload
8041 (defun org-run-like-in-org-mode (cmd)
8042 "Run a command, pretending that the current buffer is in Org-mode.
8043 This will temporarily bind local variables that are typically bound in
8044 Org-mode to the values they have in Org-mode, and then interactively
8045 call CMD."
8046 (org-load-modules-maybe)
8047 (unless org-local-vars
8048 (setq org-local-vars (org-get-local-variables)))
8049 (eval (list 'let org-local-vars
8050 (list 'call-interactively (list 'quote cmd)))))
8052 ;;;; Archiving
8054 (defun org-get-category (&optional pos)
8055 "Get the category applying to position POS."
8056 (get-text-property (or pos (point)) 'org-category))
8058 (defun org-refresh-category-properties ()
8059 "Refresh category text properties in the buffer."
8060 (let ((def-cat (cond
8061 ((null org-category)
8062 (if buffer-file-name
8063 (file-name-sans-extension
8064 (file-name-nondirectory buffer-file-name))
8065 "???"))
8066 ((symbolp org-category) (symbol-name org-category))
8067 (t org-category)))
8068 beg end cat pos optionp)
8069 (org-unmodified
8070 (save-excursion
8071 (save-restriction
8072 (widen)
8073 (goto-char (point-min))
8074 (put-text-property (point) (point-max) 'org-category def-cat)
8075 (while (re-search-forward
8076 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8077 (setq pos (match-end 0)
8078 optionp (equal (char-after (match-beginning 0)) ?#)
8079 cat (org-trim (match-string 2)))
8080 (if optionp
8081 (setq beg (point-at-bol) end (point-max))
8082 (org-back-to-heading t)
8083 (setq beg (point) end (org-end-of-subtree t t)))
8084 (put-text-property beg end 'org-category cat)
8085 (goto-char pos)))))))
8088 ;;;; Link Stuff
8090 ;;; Link abbreviations
8092 (defun org-link-expand-abbrev (link)
8093 "Apply replacements as defined in `org-link-abbrev-alist."
8094 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
8095 (let* ((key (match-string 1 link))
8096 (as (or (assoc key org-link-abbrev-alist-local)
8097 (assoc key org-link-abbrev-alist)))
8098 (tag (and (match-end 2) (match-string 3 link)))
8099 rpl)
8100 (if (not as)
8101 link
8102 (setq rpl (cdr as))
8103 (cond
8104 ((symbolp rpl) (funcall rpl tag))
8105 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8106 ((string-match "%h" rpl)
8107 (replace-match (url-hexify-string (or tag "")) t t rpl))
8108 (t (concat rpl tag)))))
8109 link))
8111 ;;; Storing and inserting links
8113 (defvar org-insert-link-history nil
8114 "Minibuffer history for links inserted with `org-insert-link'.")
8116 (defvar org-stored-links nil
8117 "Contains the links stored with `org-store-link'.")
8119 (defvar org-store-link-plist nil
8120 "Plist with info about the most recently link created with `org-store-link'.")
8122 (defvar org-link-protocols nil
8123 "Link protocols added to Org-mode using `org-add-link-type'.")
8125 (defvar org-store-link-functions nil
8126 "List of functions that are called to create and store a link.
8127 Each function will be called in turn until one returns a non-nil
8128 value. Each function should check if it is responsible for creating
8129 this link (for example by looking at the major mode).
8130 If not, it must exit and return nil.
8131 If yes, it should return a non-nil value after a calling
8132 `org-store-link-props' with a list of properties and values.
8133 Special properties are:
8135 :type The link prefix. like \"http\". This must be given.
8136 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8137 This is obligatory as well.
8138 :description Optional default description for the second pair
8139 of brackets in an Org-mode link. The user can still change
8140 this when inserting this link into an Org-mode buffer.
8142 In addition to these, any additional properties can be specified
8143 and then used in remember templates.")
8145 (defun org-add-link-type (type &optional follow export)
8146 "Add TYPE to the list of `org-link-types'.
8147 Re-compute all regular expressions depending on `org-link-types'
8149 FOLLOW and EXPORT are two functions.
8151 FOLLOW should take the link path as the single argument and do whatever
8152 is necessary to follow the link, for example find a file or display
8153 a mail message.
8155 EXPORT should format the link path for export to one of the export formats.
8156 It should be a function accepting three arguments:
8158 path the path of the link, the text after the prefix (like \"http:\")
8159 desc the description of the link, if any, nil if there was no description
8160 format the export format, a symbol like `html' or `latex'.
8162 The function may use the FORMAT information to return different values
8163 depending on the format. The return value will be put literally into
8164 the exported file.
8165 Org-mode has a built-in default for exporting links. If you are happy with
8166 this default, there is no need to define an export function for the link
8167 type. For a simple example of an export function, see `org-bbdb.el'."
8168 (add-to-list 'org-link-types type t)
8169 (org-make-link-regexps)
8170 (if (assoc type org-link-protocols)
8171 (setcdr (assoc type org-link-protocols) (list follow export))
8172 (push (list type follow export) org-link-protocols)))
8174 (defvar org-agenda-buffer-name)
8176 ;;;###autoload
8177 (defun org-store-link (arg)
8178 "\\<org-mode-map>Store an org-link to the current location.
8179 This link is added to `org-stored-links' and can later be inserted
8180 into an org-buffer with \\[org-insert-link].
8182 For some link types, a prefix arg is interpreted:
8183 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8184 For file links, arg negates `org-context-in-file-links'."
8185 (interactive "P")
8186 (org-load-modules-maybe)
8187 (setq org-store-link-plist nil) ; reset
8188 (let ((outline-regexp (org-get-limited-outline-regexp))
8189 link cpltxt desc description search txt custom-id)
8190 (cond
8192 ((run-hook-with-args-until-success 'org-store-link-functions)
8193 (setq link (plist-get org-store-link-plist :link)
8194 desc (or (plist-get org-store-link-plist :description) link)))
8196 ((equal (buffer-name) "*Org Edit Src Example*")
8197 (let (label gc)
8198 (while (or (not label)
8199 (save-excursion
8200 (save-restriction
8201 (widen)
8202 (goto-char (point-min))
8203 (re-search-forward
8204 (regexp-quote (format org-coderef-label-format label))
8205 nil t))))
8206 (when label (message "Label exists already") (sit-for 2))
8207 (setq label (read-string "Code line label: " label)))
8208 (end-of-line 1)
8209 (setq link (format org-coderef-label-format label))
8210 (setq gc (- 79 (length link)))
8211 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8212 (insert link)
8213 (setq link (concat "(" label ")") desc nil)))
8215 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8216 ;; We are in the agenda, link to referenced location
8217 (let ((m (or (get-text-property (point) 'org-hd-marker)
8218 (get-text-property (point) 'org-marker))))
8219 (when m
8220 (org-with-point-at m
8221 (if (interactive-p)
8222 (call-interactively 'org-store-link)
8223 (org-store-link nil))))))
8225 ((eq major-mode 'calendar-mode)
8226 (let ((cd (calendar-cursor-to-date)))
8227 (setq link
8228 (format-time-string
8229 (car org-time-stamp-formats)
8230 (apply 'encode-time
8231 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8232 nil nil nil))))
8233 (org-store-link-props :type "calendar" :date cd)))
8235 ((eq major-mode 'w3-mode)
8236 (setq cpltxt (if (and (buffer-name)
8237 (not (string-match "Untitled" (buffer-name))))
8238 (buffer-name)
8239 (url-view-url t))
8240 link (org-make-link (url-view-url t)))
8241 (org-store-link-props :type "w3" :url (url-view-url t)))
8243 ((eq major-mode 'w3m-mode)
8244 (setq cpltxt (or w3m-current-title w3m-current-url)
8245 link (org-make-link w3m-current-url))
8246 (org-store-link-props :type "w3m" :url (url-view-url t)))
8248 ((setq search (run-hook-with-args-until-success
8249 'org-create-file-search-functions))
8250 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8251 "::" search))
8252 (setq cpltxt (or description link)))
8254 ((eq major-mode 'image-mode)
8255 (setq cpltxt (concat "file:"
8256 (abbreviate-file-name buffer-file-name))
8257 link (org-make-link cpltxt))
8258 (org-store-link-props :type "image" :file buffer-file-name))
8260 ((eq major-mode 'dired-mode)
8261 ;; link to the file in the current line
8262 (let ((file (dired-get-filename nil t)))
8263 (setq file (if file
8264 (abbreviate-file-name
8265 (expand-file-name (dired-get-filename nil t)))
8266 ;; otherwise, no file so use current directory.
8267 default-directory))
8268 (setq cpltxt (concat "file:" file)
8269 link (org-make-link cpltxt))))
8271 ((and buffer-file-name (org-mode-p))
8272 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
8273 (cond
8274 ((org-in-regexp "<<\\(.*?\\)>>")
8275 (setq cpltxt
8276 (concat "file:"
8277 (abbreviate-file-name buffer-file-name)
8278 "::" (match-string 1))
8279 link (org-make-link cpltxt)))
8280 ((and (featurep 'org-id)
8281 (or (eq org-link-to-org-use-id t)
8282 (and (eq org-link-to-org-use-id 'create-if-interactive)
8283 (interactive-p))
8284 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
8285 (interactive-p)
8286 (not custom-id))
8287 (and org-link-to-org-use-id
8288 (condition-case nil
8289 (org-entry-get nil "ID")
8290 (error nil)))))
8291 ;; We can make a link using the ID.
8292 (setq link (condition-case nil
8293 (prog1 (org-id-store-link)
8294 (setq desc (plist-get org-store-link-plist
8295 :description)))
8296 (error
8297 ;; probably before first headline, link to file only
8298 (concat "file:"
8299 (abbreviate-file-name buffer-file-name))))))
8301 ;; Just link to current headline
8302 (setq cpltxt (concat "file:"
8303 (abbreviate-file-name buffer-file-name)))
8304 ;; Add a context search string
8305 (when (org-xor org-context-in-file-links arg)
8306 (setq txt (cond
8307 ((org-on-heading-p) nil)
8308 ((org-region-active-p)
8309 (buffer-substring (region-beginning) (region-end)))
8310 (t nil)))
8311 (when (or (null txt) (string-match "\\S-" txt))
8312 (setq cpltxt
8313 (concat cpltxt "::"
8314 (condition-case nil
8315 (org-make-org-heading-search-string txt)
8316 (error "")))
8317 desc (or (nth 4 (ignore-errors
8318 (org-heading-components))) "NONE"))))
8319 (if (string-match "::\\'" cpltxt)
8320 (setq cpltxt (substring cpltxt 0 -2)))
8321 (setq link (org-make-link cpltxt)))))
8323 ((buffer-file-name (buffer-base-buffer))
8324 ;; Just link to this file here.
8325 (setq cpltxt (concat "file:"
8326 (abbreviate-file-name
8327 (buffer-file-name (buffer-base-buffer)))))
8328 ;; Add a context string
8329 (when (org-xor org-context-in-file-links arg)
8330 (setq txt (if (org-region-active-p)
8331 (buffer-substring (region-beginning) (region-end))
8332 (buffer-substring (point-at-bol) (point-at-eol))))
8333 ;; Only use search option if there is some text.
8334 (when (string-match "\\S-" txt)
8335 (setq cpltxt
8336 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8337 desc "NONE")))
8338 (setq link (org-make-link cpltxt)))
8340 ((interactive-p)
8341 (error "Cannot link to a buffer which is not visiting a file"))
8343 (t (setq link nil)))
8345 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8346 (setq link (or link cpltxt)
8347 desc (or desc cpltxt))
8348 (if (equal desc "NONE") (setq desc nil))
8350 (if (and (or (interactive-p) executing-kbd-macro) link)
8351 (progn
8352 (setq org-stored-links
8353 (cons (list link desc) org-stored-links))
8354 (message "Stored: %s" (or desc link))
8355 (when custom-id
8356 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8357 "::#" custom-id))
8358 (setq org-stored-links
8359 (cons (list link desc) org-stored-links))))
8360 (and link (org-make-link-string link desc)))))
8362 (defun org-store-link-props (&rest plist)
8363 "Store link properties, extract names and addresses."
8364 (let (x adr)
8365 (when (setq x (plist-get plist :from))
8366 (setq adr (mail-extract-address-components x))
8367 (setq plist (plist-put plist :fromname (car adr)))
8368 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8369 (when (setq x (plist-get plist :to))
8370 (setq adr (mail-extract-address-components x))
8371 (setq plist (plist-put plist :toname (car adr)))
8372 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8373 (let ((from (plist-get plist :from))
8374 (to (plist-get plist :to)))
8375 (when (and from to org-from-is-user-regexp)
8376 (setq plist
8377 (plist-put plist :fromto
8378 (if (string-match org-from-is-user-regexp from)
8379 (concat "to %t")
8380 (concat "from %f"))))))
8381 (setq org-store-link-plist plist))
8383 (defun org-add-link-props (&rest plist)
8384 "Add these properties to the link property list."
8385 (let (key value)
8386 (while plist
8387 (setq key (pop plist) value (pop plist))
8388 (setq org-store-link-plist
8389 (plist-put org-store-link-plist key value)))))
8391 (defun org-email-link-description (&optional fmt)
8392 "Return the description part of an email link.
8393 This takes information from `org-store-link-plist' and formats it
8394 according to FMT (default from `org-email-link-description-format')."
8395 (setq fmt (or fmt org-email-link-description-format))
8396 (let* ((p org-store-link-plist)
8397 (to (plist-get p :toaddress))
8398 (from (plist-get p :fromaddress))
8399 (table
8400 (list
8401 (cons "%c" (plist-get p :fromto))
8402 (cons "%F" (plist-get p :from))
8403 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8404 (cons "%T" (plist-get p :to))
8405 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8406 (cons "%s" (plist-get p :subject))
8407 (cons "%m" (plist-get p :message-id)))))
8408 (when (string-match "%c" fmt)
8409 ;; Check if the user wrote this message
8410 (if (and org-from-is-user-regexp from to
8411 (save-match-data (string-match org-from-is-user-regexp from)))
8412 (setq fmt (replace-match "to %t" t t fmt))
8413 (setq fmt (replace-match "from %f" t t fmt))))
8414 (org-replace-escapes fmt table)))
8416 (defun org-make-org-heading-search-string (&optional string heading)
8417 "Make search string for STRING or current headline."
8418 (interactive)
8419 (let ((s (or string (org-get-heading))))
8420 (unless (and string (not heading))
8421 ;; We are using a headline, clean up garbage in there.
8422 (if (string-match org-todo-regexp s)
8423 (setq s (replace-match "" t t s)))
8424 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
8425 (setq s (replace-match "" t t s)))
8426 (setq s (org-trim s))
8427 (if (string-match (concat "^\\(" org-quote-string "\\|"
8428 org-comment-string "\\)") s)
8429 (setq s (replace-match "" t t s)))
8430 (while (string-match org-ts-regexp s)
8431 (setq s (replace-match "" t t s))))
8432 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
8433 (setq s (replace-match " " t t s)))
8434 (or string (setq s (concat "*" s))) ; Add * for headlines
8435 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8437 (defun org-make-link (&rest strings)
8438 "Concatenate STRINGS."
8439 (apply 'concat strings))
8441 (defun org-make-link-string (link &optional description)
8442 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8443 (unless (string-match "\\S-" link)
8444 (error "Empty link"))
8445 (when (and description
8446 (stringp description)
8447 (not (string-match "\\S-" description)))
8448 (setq description nil))
8449 (when (stringp description)
8450 ;; Remove brackets from the description, they are fatal.
8451 (while (string-match "\\[" description)
8452 (setq description (replace-match "{" t t description)))
8453 (while (string-match "\\]" description)
8454 (setq description (replace-match "}" t t description))))
8455 (when (equal (org-link-escape link) description)
8456 ;; No description needed, it is identical
8457 (setq description nil))
8458 (when (and (not description)
8459 (not (equal link (org-link-escape link))))
8460 (setq description (org-extract-attributes link)))
8461 (concat "[[" (org-link-escape link) "]"
8462 (if description (concat "[" description "]") "")
8463 "]"))
8465 (defconst org-link-escape-chars
8466 '((?\ . "%20")
8467 (?\[ . "%5B")
8468 (?\] . "%5D")
8469 (?\340 . "%E0") ; `a
8470 (?\342 . "%E2") ; ^a
8471 (?\347 . "%E7") ; ,c
8472 (?\350 . "%E8") ; `e
8473 (?\351 . "%E9") ; 'e
8474 (?\352 . "%EA") ; ^e
8475 (?\356 . "%EE") ; ^i
8476 (?\364 . "%F4") ; ^o
8477 (?\371 . "%F9") ; `u
8478 (?\373 . "%FB") ; ^u
8479 (?\; . "%3B")
8480 ;; (?? . "%3F")
8481 (?= . "%3D")
8482 (?+ . "%2B")
8484 "Association list of escapes for some characters problematic in links.
8485 This is the list that is used for internal purposes.")
8487 (defvar org-url-encoding-use-url-hexify nil)
8489 (defconst org-link-escape-chars-browser
8490 '((?\ . "%20")) ; 32 for the SPC char
8491 "Association list of escapes for some characters problematic in links.
8492 This is the list that is used before handing over to the browser.")
8494 (defun org-link-escape (text &optional table)
8495 "Escape characters in TEXT that are problematic for links."
8496 (if (and org-url-encoding-use-url-hexify (not table))
8497 (url-hexify-string text)
8498 (setq table (or table org-link-escape-chars))
8499 (when text
8500 (let ((re (mapconcat (lambda (x) (regexp-quote
8501 (char-to-string (car x))))
8502 table "\\|")))
8503 (while (string-match re text)
8504 (setq text
8505 (replace-match
8506 (cdr (assoc (string-to-char (match-string 0 text))
8507 table))
8508 t t text)))
8509 text))))
8511 (defun org-link-unescape (text &optional table)
8512 "Reverse the action of `org-link-escape'."
8513 (if (and org-url-encoding-use-url-hexify (not table))
8514 (url-unhex-string text)
8515 (setq table (or table org-link-escape-chars))
8516 (when text
8517 (let ((case-fold-search t)
8518 (re (mapconcat (lambda (x) (regexp-quote (downcase (cdr x))))
8519 table "\\|")))
8520 (while (string-match re text)
8521 (setq text
8522 (replace-match
8523 (char-to-string (car (rassoc (upcase (match-string 0 text))
8524 table)))
8525 t t text)))
8526 text))))
8528 (defun org-xor (a b)
8529 "Exclusive or."
8530 (if a (not b) b))
8532 (defun org-fixup-message-id-for-http (s)
8533 "Replace special characters in a message id, so it can be used in an http query."
8534 (when (string-match "%" s)
8535 (setq s (mapconcat (lambda (c)
8536 (if (eq c ?%)
8537 "%25"
8538 (char-to-string c)))
8539 s "")))
8540 (while (string-match "<" s)
8541 (setq s (replace-match "%3C" t t s)))
8542 (while (string-match ">" s)
8543 (setq s (replace-match "%3E" t t s)))
8544 (while (string-match "@" s)
8545 (setq s (replace-match "%40" t t s)))
8548 ;;;###autoload
8549 (defun org-insert-link-global ()
8550 "Insert a link like Org-mode does.
8551 This command can be called in any mode to insert a link in Org-mode syntax."
8552 (interactive)
8553 (org-load-modules-maybe)
8554 (org-run-like-in-org-mode 'org-insert-link))
8556 (defun org-insert-link (&optional complete-file link-location)
8557 "Insert a link. At the prompt, enter the link.
8559 Completion can be used to insert any of the link protocol prefixes like
8560 http or ftp in use.
8562 The history can be used to select a link previously stored with
8563 `org-store-link'. When the empty string is entered (i.e. if you just
8564 press RET at the prompt), the link defaults to the most recently
8565 stored link. As SPC triggers completion in the minibuffer, you need to
8566 use M-SPC or C-q SPC to force the insertion of a space character.
8568 You will also be prompted for a description, and if one is given, it will
8569 be displayed in the buffer instead of the link.
8571 If there is already a link at point, this command will allow you to edit link
8572 and description parts.
8574 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
8575 be selected using completion. The path to the file will be relative to the
8576 current directory if the file is in the current directory or a subdirectory.
8577 Otherwise, the link will be the absolute path as completed in the minibuffer
8578 \(i.e. normally ~/path/to/file). You can configure this behavior using the
8579 option `org-link-file-path-type'.
8581 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
8582 the current directory or below.
8584 With three \\[universal-argument] prefixes, negate the meaning of
8585 `org-keep-stored-link-after-insertion'.
8587 If `org-make-link-description-function' is non-nil, this function will be
8588 called with the link target, and the result will be the default
8589 link description.
8591 If the LINK-LOCATION parameter is non-nil, this value will be
8592 used as the link location instead of reading one interactively."
8593 (interactive "P")
8594 (let* ((wcf (current-window-configuration))
8595 (region (if (org-region-active-p)
8596 (buffer-substring (region-beginning) (region-end))))
8597 (remove (and region (list (region-beginning) (region-end))))
8598 (desc region)
8599 tmphist ; byte-compile incorrectly complains about this
8600 (link link-location)
8601 entry file all-prefixes)
8602 (cond
8603 (link-location) ; specified by arg, just use it.
8604 ((org-in-regexp org-bracket-link-regexp 1)
8605 ;; We do have a link at point, and we are going to edit it.
8606 (setq remove (list (match-beginning 0) (match-end 0)))
8607 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8608 (setq link (read-string "Link: "
8609 (org-link-unescape
8610 (org-match-string-no-properties 1)))))
8611 ((or (org-in-regexp org-angle-link-re)
8612 (org-in-regexp org-plain-link-re))
8613 ;; Convert to bracket link
8614 (setq remove (list (match-beginning 0) (match-end 0))
8615 link (read-string "Link: "
8616 (org-remove-angle-brackets (match-string 0)))))
8617 ((member complete-file '((4) (16)))
8618 ;; Completing read for file names.
8619 (setq link (org-file-complete-link complete-file)))
8621 ;; Read link, with completion for stored links.
8622 (with-output-to-temp-buffer "*Org Links*"
8623 (princ "Insert a link.
8624 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8625 (when org-stored-links
8626 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8627 (princ (mapconcat
8628 (lambda (x)
8629 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8630 (reverse org-stored-links) "\n"))))
8631 (let ((cw (selected-window)))
8632 (select-window (get-buffer-window "*Org Links*" 'visible))
8633 (setq truncate-lines t)
8634 (unless (pos-visible-in-window-p (point-max))
8635 (org-fit-window-to-buffer))
8636 (and (window-live-p cw) (select-window cw)))
8637 ;; Fake a link history, containing the stored links.
8638 (setq tmphist (append (mapcar 'car org-stored-links)
8639 org-insert-link-history))
8640 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8641 (mapcar 'car org-link-abbrev-alist)
8642 org-link-types))
8643 (unwind-protect
8644 (progn
8645 (setq link
8646 (let ((org-completion-use-ido nil)
8647 (org-completion-use-iswitchb nil))
8648 (org-completing-read
8649 "Link: "
8650 (append
8651 (mapcar (lambda (x) (list (concat x ":")))
8652 all-prefixes)
8653 (mapcar 'car org-stored-links))
8654 nil nil nil
8655 'tmphist
8656 (car (car org-stored-links)))))
8657 (if (not (string-match "\\S-" link))
8658 (error "No link selected"))
8659 (if (or (member link all-prefixes)
8660 (and (equal ":" (substring link -1))
8661 (member (substring link 0 -1) all-prefixes)
8662 (setq link (substring link 0 -1))))
8663 (setq link (org-link-try-special-completion link))))
8664 (set-window-configuration wcf)
8665 (kill-buffer "*Org Links*"))
8666 (setq entry (assoc link org-stored-links))
8667 (or entry (push link org-insert-link-history))
8668 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8669 (not org-keep-stored-link-after-insertion))
8670 (setq org-stored-links (delq (assoc link org-stored-links)
8671 org-stored-links)))
8672 (setq desc (or desc (nth 1 entry)))))
8674 (if (string-match org-plain-link-re link)
8675 ;; URL-like link, normalize the use of angular brackets.
8676 (setq link (org-make-link (org-remove-angle-brackets link))))
8678 ;; Check if we are linking to the current file with a search option
8679 ;; If yes, simplify the link by using only the search option.
8680 (when (and buffer-file-name
8681 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8682 (let* ((path (match-string 1 link))
8683 (case-fold-search nil)
8684 (search (match-string 2 link)))
8685 (save-match-data
8686 (if (equal (file-truename buffer-file-name) (file-truename path))
8687 ;; We are linking to this same file, with a search option
8688 (setq link search)))))
8690 ;; Check if we can/should use a relative path. If yes, simplify the link
8691 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8692 (let* ((type (match-string 1 link))
8693 (path (match-string 2 link))
8694 (origpath path)
8695 (case-fold-search nil))
8696 (cond
8697 ((or (eq org-link-file-path-type 'absolute)
8698 (equal complete-file '(16)))
8699 (setq path (abbreviate-file-name (expand-file-name path))))
8700 ((eq org-link-file-path-type 'noabbrev)
8701 (setq path (expand-file-name path)))
8702 ((eq org-link-file-path-type 'relative)
8703 (setq path (file-relative-name path)))
8705 (save-match-data
8706 (if (string-match (concat "^" (regexp-quote
8707 (expand-file-name
8708 (file-name-as-directory
8709 default-directory))))
8710 (expand-file-name path))
8711 ;; We are linking a file with relative path name.
8712 (setq path (substring (expand-file-name path)
8713 (match-end 0)))
8714 (setq path (abbreviate-file-name (expand-file-name path)))))))
8715 (setq link (concat type path))
8716 (if (equal desc origpath)
8717 (setq desc path))))
8719 (if org-make-link-description-function
8720 (setq desc (funcall org-make-link-description-function link desc)))
8722 (setq desc (read-string "Description: " desc))
8723 (unless (string-match "\\S-" desc) (setq desc nil))
8724 (if remove (apply 'delete-region remove))
8725 (insert (org-make-link-string link desc))))
8727 (defun org-link-try-special-completion (type)
8728 "If there is completion support for link type TYPE, offer it."
8729 (let ((fun (intern (concat "org-" type "-complete-link"))))
8730 (if (functionp fun)
8731 (funcall fun)
8732 (read-string "Link (no completion support): " (concat type ":")))))
8734 (defun org-file-complete-link (&optional arg)
8735 "Create a file link using completion."
8736 (let (file link)
8737 (setq file (read-file-name "File: "))
8738 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8739 (pwd1 (file-name-as-directory (abbreviate-file-name
8740 (expand-file-name ".")))))
8741 (cond
8742 ((equal arg '(16))
8743 (setq link (org-make-link
8744 "file:"
8745 (abbreviate-file-name (expand-file-name file)))))
8746 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8747 (setq link (org-make-link "file:" (match-string 1 file))))
8748 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8749 (expand-file-name file))
8750 (setq link (org-make-link
8751 "file:" (match-string 1 (expand-file-name file)))))
8752 (t (setq link (org-make-link "file:" file)))))
8753 link))
8755 (defun org-completing-read (&rest args)
8756 "Completing-read with SPACE being a normal character."
8757 (let ((minibuffer-local-completion-map
8758 (copy-keymap minibuffer-local-completion-map)))
8759 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8760 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8761 (apply 'org-icompleting-read args)))
8763 (defun org-completing-read-no-i (&rest args)
8764 (let (org-completion-use-ido org-completion-use-iswitchb)
8765 (apply 'org-completing-read args)))
8767 (defun org-iswitchb-completing-read (prompt choices &rest args)
8768 "Use iswitch as a completing-read replacement to choose from choices.
8769 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8770 from."
8771 (let* ((iswitchb-use-virtual-buffers nil)
8772 (iswitchb-make-buflist-hook
8773 (lambda ()
8774 (setq iswitchb-temp-buflist choices))))
8775 (iswitchb-read-buffer prompt)))
8777 (defun org-icompleting-read (&rest args)
8778 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8779 (org-without-partial-completion
8780 (if (and org-completion-use-ido
8781 (fboundp 'ido-completing-read)
8782 (boundp 'ido-mode) ido-mode
8783 (listp (second args)))
8784 (let ((ido-enter-matching-directory nil))
8785 (apply 'ido-completing-read (concat (car args))
8786 (if (consp (car (nth 1 args)))
8787 (mapcar (lambda (x) (car x)) (nth 1 args))
8788 (nth 1 args))
8789 (cddr args)))
8790 (if (and org-completion-use-iswitchb
8791 (boundp 'iswitchb-mode) iswitchb-mode
8792 (listp (second args)))
8793 (apply 'org-iswitchb-completing-read (concat (car args))
8794 (if (consp (car (nth 1 args)))
8795 (mapcar (lambda (x) (car x)) (nth 1 args))
8796 (nth 1 args))
8797 (cddr args))
8798 (apply 'completing-read args)))))
8800 (defun org-extract-attributes (s)
8801 "Extract the attributes cookie from a string and set as text property."
8802 (let (a attr (start 0) key value)
8803 (save-match-data
8804 (when (string-match "{{\\([^}]+\\)}}$" s)
8805 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8806 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8807 (setq key (match-string 1 a) value (match-string 2 a)
8808 start (match-end 0)
8809 attr (plist-put attr (intern key) value))))
8810 (org-add-props s nil 'org-attr attr))
8813 (defun org-extract-attributes-from-string (tag)
8814 (let (key value attr)
8815 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8816 (setq key (match-string 1 tag) value (match-string 2 tag)
8817 tag (replace-match "" t t tag)
8818 attr (plist-put attr (intern key) value)))
8819 (cons tag attr)))
8821 (defun org-attributes-to-string (plist)
8822 "Format a property list into an HTML attribute list."
8823 (let ((s "") key value)
8824 (while plist
8825 (setq key (pop plist) value (pop plist))
8826 (and value
8827 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8830 ;;; Opening/following a link
8832 (defvar org-link-search-failed nil)
8834 (defvar org-open-link-functions nil
8835 "Hook for functions finding a plain text link.
8836 These functions must take a single argument, the link content.
8837 They will be called for links that look like [[link text][description]]
8838 when LINK TEXT does not have a protocol like \"http:\" and does not look
8839 like a filename (e.g. \"./blue.png\").
8841 These functions will be called *before* Org attempts to resolve the
8842 link by doing text searches in the current buffer - so if you want a
8843 link \"[[target]]\" to still find \"<<target>>\", your function should
8844 handle this as a special case.
8846 When the function does handle the link, it must return a non-nil value.
8847 If it decides that it is not responsible for this link, it must return
8848 nil to indicate that that Org-mode can continue with other options
8849 like exact and fuzzy text search.")
8851 (defun org-next-link ()
8852 "Move forward to the next link.
8853 If the link is in hidden text, expose it."
8854 (interactive)
8855 (when (and org-link-search-failed (eq this-command last-command))
8856 (goto-char (point-min))
8857 (message "Link search wrapped back to beginning of buffer"))
8858 (setq org-link-search-failed nil)
8859 (let* ((pos (point))
8860 (ct (org-context))
8861 (a (assoc :link ct)))
8862 (if a (goto-char (nth 2 a)))
8863 (if (re-search-forward org-any-link-re nil t)
8864 (progn
8865 (goto-char (match-beginning 0))
8866 (if (org-invisible-p) (org-show-context)))
8867 (goto-char pos)
8868 (setq org-link-search-failed t)
8869 (error "No further link found"))))
8871 (defun org-previous-link ()
8872 "Move backward to the previous link.
8873 If the link is in hidden text, expose it."
8874 (interactive)
8875 (when (and org-link-search-failed (eq this-command last-command))
8876 (goto-char (point-max))
8877 (message "Link search wrapped back to end of buffer"))
8878 (setq org-link-search-failed nil)
8879 (let* ((pos (point))
8880 (ct (org-context))
8881 (a (assoc :link ct)))
8882 (if a (goto-char (nth 1 a)))
8883 (if (re-search-backward org-any-link-re nil t)
8884 (progn
8885 (goto-char (match-beginning 0))
8886 (if (org-invisible-p) (org-show-context)))
8887 (goto-char pos)
8888 (setq org-link-search-failed t)
8889 (error "No further link found"))))
8891 (defun org-translate-link (s)
8892 "Translate a link string if a translation function has been defined."
8893 (if (and org-link-translation-function
8894 (fboundp org-link-translation-function)
8895 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8896 (progn
8897 (setq s (funcall org-link-translation-function
8898 (match-string 1) (match-string 2)))
8899 (concat (car s) ":" (cdr s)))
8902 (defun org-translate-link-from-planner (type path)
8903 "Translate a link from Emacs Planner syntax so that Org can follow it.
8904 This is still an experimental function, your mileage may vary."
8905 (cond
8906 ((member type '("http" "https" "news" "ftp"))
8907 ;; standard Internet links are the same.
8908 nil)
8909 ((and (equal type "irc") (string-match "^//" path))
8910 ;; Planner has two / at the beginning of an irc link, we have 1.
8911 ;; We should have zero, actually....
8912 (setq path (substring path 1)))
8913 ((and (equal type "lisp") (string-match "^/" path))
8914 ;; Planner has a slash, we do not.
8915 (setq type "elisp" path (substring path 1)))
8916 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8917 ;; A typical message link. Planner has the id after the final slash,
8918 ;; we separate it with a hash mark
8919 (setq path (concat (match-string 1 path) "#"
8920 (org-remove-angle-brackets (match-string 2 path)))))
8922 (cons type path))
8924 (defun org-find-file-at-mouse (ev)
8925 "Open file link or URL at mouse."
8926 (interactive "e")
8927 (mouse-set-point ev)
8928 (org-open-at-point 'in-emacs))
8930 (defun org-open-at-mouse (ev)
8931 "Open file link or URL at mouse."
8932 (interactive "e")
8933 (mouse-set-point ev)
8934 (if (eq major-mode 'org-agenda-mode)
8935 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8936 (org-open-at-point))
8938 (defvar org-window-config-before-follow-link nil
8939 "The window configuration before following a link.
8940 This is saved in case the need arises to restore it.")
8942 (defvar org-open-link-marker (make-marker)
8943 "Marker pointing to the location where `org-open-at-point; was called.")
8945 ;;;###autoload
8946 (defun org-open-at-point-global ()
8947 "Follow a link like Org-mode does.
8948 This command can be called in any mode to follow a link that has
8949 Org-mode syntax."
8950 (interactive)
8951 (org-run-like-in-org-mode 'org-open-at-point))
8953 ;;;###autoload
8954 (defun org-open-link-from-string (s &optional arg reference-buffer)
8955 "Open a link in the string S, as if it was in Org-mode."
8956 (interactive "sLink: \nP")
8957 (let ((reference-buffer (or reference-buffer (current-buffer))))
8958 (with-temp-buffer
8959 (let ((org-inhibit-startup t))
8960 (org-mode)
8961 (insert s)
8962 (goto-char (point-min))
8963 (when reference-buffer
8964 (setq org-link-abbrev-alist-local
8965 (with-current-buffer reference-buffer
8966 org-link-abbrev-alist-local)))
8967 (org-open-at-point arg reference-buffer)))))
8969 (defun org-open-at-point (&optional in-emacs reference-buffer)
8970 "Open link at or after point.
8971 If there is no link at point, this function will search forward up to
8972 the end of the current line.
8973 Normally, files will be opened by an appropriate application. If the
8974 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8975 With a double prefix argument, try to open outside of Emacs, in the
8976 application the system uses for this file type."
8977 (interactive "P")
8978 ;; if in a code block, then open the block's results
8979 (unless (call-interactively #'org-babel-open-src-block-result)
8980 (org-load-modules-maybe)
8981 (move-marker org-open-link-marker (point))
8982 (setq org-window-config-before-follow-link (current-window-configuration))
8983 (org-remove-occur-highlights nil nil t)
8984 (cond
8985 ((and (org-on-heading-p)
8986 (not (org-in-regexp
8987 (concat org-plain-link-re "\\|"
8988 org-bracket-link-regexp "\\|"
8989 org-angle-link-re "\\|"
8990 "[ \t]:[^ \t\n]+:[ \t]*$")))
8991 (not (get-text-property (point) 'org-linked-text)))
8992 (or (org-offer-links-in-entry in-emacs)
8993 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8994 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8995 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8996 (org-footnote-action))
8998 (let (type path link line search (pos (point)))
8999 (catch 'match
9000 (save-excursion
9001 (skip-chars-forward "^]\n\r")
9002 (when (org-in-regexp org-bracket-link-regexp 1)
9003 (setq link (org-extract-attributes
9004 (org-link-unescape (org-match-string-no-properties 1))))
9005 (while (string-match " *\n *" link)
9006 (setq link (replace-match " " t t link)))
9007 (setq link (org-link-expand-abbrev link))
9008 (cond
9009 ((or (file-name-absolute-p link)
9010 (string-match "^\\.\\.?/" link))
9011 (setq type "file" path link))
9012 ((string-match org-link-re-with-space3 link)
9013 (setq type (match-string 1 link) path (match-string 2 link)))
9014 (t (setq type "thisfile" path link)))
9015 (throw 'match t)))
9017 (when (get-text-property (point) 'org-linked-text)
9018 (setq type "thisfile"
9019 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9020 (1+ (point)) (point))
9021 path (buffer-substring
9022 (previous-single-property-change pos 'org-linked-text)
9023 (next-single-property-change pos 'org-linked-text)))
9024 (throw 'match t))
9026 (save-excursion
9027 (when (or (org-in-regexp org-angle-link-re)
9028 (org-in-regexp org-plain-link-re))
9029 (setq type (match-string 1) path (match-string 2))
9030 (throw 'match t)))
9031 (save-excursion
9032 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
9033 (setq type "tags"
9034 path (match-string 1))
9035 (while (string-match ":" path)
9036 (setq path (replace-match "+" t t path)))
9037 (throw 'match t)))
9038 (when (org-in-regexp "<\\([^><\n]+\\)>")
9039 (setq type "tree-match"
9040 path (match-string 1))
9041 (throw 'match t)))
9042 (unless path
9043 (error "No link found"))
9045 ;; switch back to reference buffer
9046 ;; needed when if called in a temporary buffer through
9047 ;; org-open-link-from-string
9048 (with-current-buffer (or reference-buffer (current-buffer))
9050 ;; Remove any trailing spaces in path
9051 (if (string-match " +\\'" path)
9052 (setq path (replace-match "" t t path)))
9053 (if (and org-link-translation-function
9054 (fboundp org-link-translation-function))
9055 ;; Check if we need to translate the link
9056 (let ((tmp (funcall org-link-translation-function type path)))
9057 (setq type (car tmp) path (cdr tmp))))
9059 (cond
9061 ((assoc type org-link-protocols)
9062 (funcall (nth 1 (assoc type org-link-protocols)) path))
9064 ((equal type "mailto")
9065 (let ((cmd (car org-link-mailto-program))
9066 (args (cdr org-link-mailto-program)) args1
9067 (address path) (subject "") a)
9068 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9069 (setq address (match-string 1 path)
9070 subject (org-link-escape (match-string 2 path))))
9071 (while args
9072 (cond
9073 ((not (stringp (car args))) (push (pop args) args1))
9074 (t (setq a (pop args))
9075 (if (string-match "%a" a)
9076 (setq a (replace-match address t t a)))
9077 (if (string-match "%s" a)
9078 (setq a (replace-match subject t t a)))
9079 (push a args1))))
9080 (apply cmd (nreverse args1))))
9082 ((member type '("http" "https" "ftp" "news"))
9083 (browse-url (concat type ":" (org-link-escape
9084 path org-link-escape-chars-browser))))
9086 ((string= type "doi")
9087 (browse-url (concat "http://dx.doi.org/"
9088 (org-link-escape
9089 path org-link-escape-chars-browser))))
9091 ((member type '("message"))
9092 (browse-url (concat type ":" path)))
9094 ((string= type "tags")
9095 (org-tags-view in-emacs path))
9097 ((string= type "tree-match")
9098 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9100 ((string= type "file")
9101 (if (string-match "::\\([0-9]+\\)\\'" path)
9102 (setq line (string-to-number (match-string 1 path))
9103 path (substring path 0 (match-beginning 0)))
9104 (if (string-match "::\\(.+\\)\\'" path)
9105 (setq search (match-string 1 path)
9106 path (substring path 0 (match-beginning 0)))))
9107 (if (string-match "[*?{]" (file-name-nondirectory path))
9108 (dired path)
9109 (org-open-file path in-emacs line search)))
9111 ((string= type "news")
9112 (require 'org-gnus)
9113 (org-gnus-follow-link path))
9115 ((string= type "shell")
9116 (let ((cmd path))
9117 (if (or (not org-confirm-shell-link-function)
9118 (funcall org-confirm-shell-link-function
9119 (format "Execute \"%s\" in shell? "
9120 (org-add-props cmd nil
9121 'face 'org-warning))))
9122 (progn
9123 (message "Executing %s" cmd)
9124 (shell-command cmd))
9125 (error "Abort"))))
9127 ((string= type "elisp")
9128 (let ((cmd path))
9129 (if (or (not org-confirm-elisp-link-function)
9130 (funcall org-confirm-elisp-link-function
9131 (format "Execute \"%s\" as elisp? "
9132 (org-add-props cmd nil
9133 'face 'org-warning))))
9134 (message "%s => %s" cmd
9135 (if (equal (string-to-char cmd) ?\()
9136 (eval (read cmd))
9137 (call-interactively (read cmd))))
9138 (error "Abort"))))
9140 ((and (string= type "thisfile")
9141 (run-hook-with-args-until-success
9142 'org-open-link-functions path)))
9144 ((string= type "thisfile")
9145 (if in-emacs
9146 (switch-to-buffer-other-window
9147 (org-get-buffer-for-internal-link (current-buffer)))
9148 (org-mark-ring-push))
9149 (let ((cmd `(org-link-search
9150 ,path
9151 ,(cond ((equal in-emacs '(4)) 'occur)
9152 ((equal in-emacs '(16)) 'org-occur)
9153 (t nil))
9154 ,pos)))
9155 (condition-case nil (eval cmd)
9156 (error (progn (widen) (eval cmd))))))
9159 (browse-url-at-point)))))))
9160 (move-marker org-open-link-marker nil)
9161 (run-hook-with-args 'org-follow-link-hook)))
9163 (defun org-offer-links-in-entry (&optional nth zero)
9164 "Offer links in the current entry and follow the selected link.
9165 If there is only one link, follow it immediately as well.
9166 If NTH is an integer, immediately pick the NTH link found.
9167 If ZERO is a string, check also this string for a link, and if
9168 there is one, offer it as link number zero."
9169 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9170 "\\(" org-angle-link-re "\\)\\|"
9171 "\\(" org-plain-link-re "\\)"))
9172 (cnt ?0)
9173 (in-emacs (if (integerp nth) nil nth))
9174 have-zero end links link c)
9175 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9176 (push (match-string 0 zero) links)
9177 (setq cnt (1- cnt) have-zero t))
9178 (save-excursion
9179 (org-back-to-heading t)
9180 (setq end (save-excursion (outline-next-heading) (point)))
9181 (while (re-search-forward re end t)
9182 (push (match-string 0) links))
9183 (setq links (org-uniquify (reverse links))))
9185 (cond
9186 ((null links)
9187 (message "No links"))
9188 ((equal (length links) 1)
9189 (setq link (list (car links))))
9190 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9191 (setq link (nth (if have-zero nth (1- nth)) links)))
9192 (t ; we have to select a link
9193 (save-excursion
9194 (save-window-excursion
9195 (delete-other-windows)
9196 (with-output-to-temp-buffer "*Select Link*"
9197 (mapc (lambda (l)
9198 (if (not (string-match org-bracket-link-regexp l))
9199 (princ (format "[%c] %s\n" (incf cnt)
9200 (org-remove-angle-brackets l)))
9201 (if (match-end 3)
9202 (princ (format "[%c] %s (%s)\n" (incf cnt)
9203 (match-string 3 l) (match-string 1 l)))
9204 (princ (format "[%c] %s\n" (incf cnt)
9205 (match-string 1 l))))))
9206 links))
9207 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9208 (message "Select link to open, RET to open all:")
9209 (setq c (read-char-exclusive))
9210 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9211 (when (equal c ?q) (error "Abort"))
9212 (if (equal c ?\C-m)
9213 (setq link links)
9214 (setq nth (- c ?0))
9215 (if have-zero (setq nth (1+ nth)))
9216 (unless (and (integerp nth) (>= (length links) nth))
9217 (error "Invalid link selection"))
9218 (setq link (list (nth (1- nth) links))))))
9219 (if link
9220 (let ((buf (current-buffer)))
9221 (dolist (l link)
9222 (org-open-link-from-string l in-emacs buf))
9224 nil)))
9226 ;; Add special file links that specify the way of opening
9228 (org-add-link-type "file+sys" 'org-open-file-with-system)
9229 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9230 (defun org-open-file-with-system (path)
9231 "Open file at PATH using the system way of opeing it."
9232 (org-open-file path 'system))
9233 (defun org-open-file-with-emacs (path)
9234 "Open file at PATH in emacs."
9235 (org-open-file path 'emacs))
9236 (defun org-remove-file-link-modifiers ()
9237 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9238 (goto-char (point-min))
9239 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9240 (org-if-unprotected
9241 (replace-match "file:" t t))))
9242 (eval-after-load "org-exp"
9243 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9244 'org-remove-file-link-modifiers))
9246 ;;;; Time estimates
9248 (defun org-get-effort (&optional pom)
9249 "Get the effort estimate for the current entry."
9250 (org-entry-get pom org-effort-property))
9252 ;;; File search
9254 (defvar org-create-file-search-functions nil
9255 "List of functions to construct the right search string for a file link.
9256 These functions are called in turn with point at the location to
9257 which the link should point.
9259 A function in the hook should first test if it would like to
9260 handle this file type, for example by checking the major-mode or
9261 the file extension. If it decides not to handle this file, it
9262 should just return nil to give other functions a chance. If it
9263 does handle the file, it must return the search string to be used
9264 when following the link. The search string will be part of the
9265 file link, given after a double colon, and `org-open-at-point'
9266 will automatically search for it. If special measures must be
9267 taken to make the search successful, another function should be
9268 added to the companion hook `org-execute-file-search-functions',
9269 which see.
9271 A function in this hook may also use `setq' to set the variable
9272 `description' to provide a suggestion for the descriptive text to
9273 be used for this link when it gets inserted into an Org-mode
9274 buffer with \\[org-insert-link].")
9276 (defvar org-execute-file-search-functions nil
9277 "List of functions to execute a file search triggered by a link.
9279 Functions added to this hook must accept a single argument, the
9280 search string that was part of the file link, the part after the
9281 double colon. The function must first check if it would like to
9282 handle this search, for example by checking the major-mode or the
9283 file extension. If it decides not to handle this search, it
9284 should just return nil to give other functions a chance. If it
9285 does handle the search, it must return a non-nil value to keep
9286 other functions from trying.
9288 Each function can access the current prefix argument through the
9289 variable `current-prefix-argument'. Note that a single prefix is
9290 used to force opening a link in Emacs, so it may be good to only
9291 use a numeric or double prefix to guide the search function.
9293 In case this is needed, a function in this hook can also restore
9294 the window configuration before `org-open-at-point' was called using:
9296 (set-window-configuration org-window-config-before-follow-link)")
9298 (defun org-link-search (s &optional type avoid-pos)
9299 "Search for a link search option.
9300 If S is surrounded by forward slashes, it is interpreted as a
9301 regular expression. In org-mode files, this will create an `org-occur'
9302 sparse tree. In ordinary files, `occur' will be used to list matches.
9303 If the current buffer is in `dired-mode', grep will be used to search
9304 in all files. If AVOID-POS is given, ignore matches near that position."
9305 (let ((case-fold-search t)
9306 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9307 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9308 (append '(("") (" ") ("\t") ("\n"))
9309 org-emphasis-alist)
9310 "\\|") "\\)"))
9311 (pos (point))
9312 (pre nil) (post nil)
9313 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9314 (cond
9315 ;; First check if there are any special
9316 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9317 ;; Now try the builtin stuff
9318 ((and (equal (string-to-char s0) ?#)
9319 (> (length s0) 1)
9320 (save-excursion
9321 (goto-char (point-min))
9322 (and
9323 (re-search-forward
9324 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9325 (setq type 'dedicated
9326 pos (match-beginning 0))))
9327 ;; There is an exact target for this
9328 (goto-char pos)
9329 (org-back-to-heading t)))
9330 ((save-excursion
9331 (goto-char (point-min))
9332 (and
9333 (re-search-forward
9334 (concat "<<" (regexp-quote s0) ">>") nil t)
9335 (setq type 'dedicated
9336 pos (match-beginning 0))))
9337 ;; There is an exact target for this
9338 (goto-char pos))
9339 ((and (string-match "^(\\(.*\\))$" s0)
9340 (save-excursion
9341 (goto-char (point-min))
9342 (and
9343 (re-search-forward
9344 (concat "[^[]" (regexp-quote
9345 (format org-coderef-label-format
9346 (match-string 1 s0))))
9347 nil t)
9348 (setq type 'dedicated
9349 pos (1+ (match-beginning 0))))))
9350 ;; There is a coderef target for this
9351 (goto-char pos))
9352 ((string-match "^/\\(.*\\)/$" s)
9353 ;; A regular expression
9354 (cond
9355 ((org-mode-p)
9356 (org-occur (match-string 1 s)))
9357 ;;((eq major-mode 'dired-mode)
9358 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9359 (t (org-do-occur (match-string 1 s)))))
9361 ;; A normal search strings
9362 (when (equal (string-to-char s) ?*)
9363 ;; Anchor on headlines, post may include tags.
9364 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9365 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
9366 s (substring s 1)))
9367 (remove-text-properties
9368 0 (length s)
9369 '(face nil mouse-face nil keymap nil fontified nil) s)
9370 ;; Make a series of regular expressions to find a match
9371 (setq words (org-split-string s "[ \n\r\t]+")
9373 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9374 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9375 "\\)" markers)
9376 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9377 re2a (concat "[ \t\r\n]" re2a_)
9378 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9379 re4 (concat "[^a-zA-Z_]" re4_)
9381 re1 (concat pre re2 post)
9382 re3 (concat pre (if pre re4_ re4) post)
9383 re5 (concat pre ".*" re4)
9384 re2 (concat pre re2)
9385 re2a (concat pre (if pre re2a_ re2a))
9386 re4 (concat pre (if pre re4_ re4))
9387 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9388 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9389 re5 "\\)"
9391 (cond
9392 ((eq type 'org-occur) (org-occur reall))
9393 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9394 (t (goto-char (point-min))
9395 (setq type 'fuzzy)
9396 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9397 (org-search-not-self 1 re1 nil t)
9398 (org-search-not-self 1 re2 nil t)
9399 (org-search-not-self 1 re2a nil t)
9400 (org-search-not-self 1 re3 nil t)
9401 (org-search-not-self 1 re4 nil t)
9402 (org-search-not-self 1 re5 nil t)
9404 (goto-char (match-beginning 1))
9405 (goto-char pos)
9406 (error "No match")))))
9408 ;; Normal string-search
9409 (goto-char (point-min))
9410 (if (search-forward s nil t)
9411 (goto-char (match-beginning 0))
9412 (error "No match"))))
9413 (and (org-mode-p) (org-show-context 'link-search))
9414 type))
9416 (defun org-search-not-self (group &rest args)
9417 "Execute `re-search-forward', but only accept matches that do not
9418 enclose the position of `org-open-link-marker'."
9419 (let ((m org-open-link-marker))
9420 (catch 'exit
9421 (while (apply 're-search-forward args)
9422 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9423 (goto-char (match-end group))
9424 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9425 (> (match-beginning 0) (marker-position m))
9426 (< (match-end 0) (marker-position m)))
9427 (save-match-data
9428 (or (not (org-in-regexp
9429 org-bracket-link-analytic-regexp 1))
9430 (not (match-end 4)) ; no description
9431 (and (<= (match-beginning 4) (point))
9432 (>= (match-end 4) (point))))))
9433 (throw 'exit (point))))))))
9435 (defun org-get-buffer-for-internal-link (buffer)
9436 "Return a buffer to be used for displaying the link target of internal links."
9437 (cond
9438 ((not org-display-internal-link-with-indirect-buffer)
9439 buffer)
9440 ((string-match "(Clone)$" (buffer-name buffer))
9441 (message "Buffer is already a clone, not making another one")
9442 ;; we also do not modify visibility in this case
9443 buffer)
9444 (t ; make a new indirect buffer for displaying the link
9445 (let* ((bn (buffer-name buffer))
9446 (ibn (concat bn "(Clone)"))
9447 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9448 (with-current-buffer ib (org-overview))
9449 ib))))
9451 (defun org-do-occur (regexp &optional cleanup)
9452 "Call the Emacs command `occur'.
9453 If CLEANUP is non-nil, remove the printout of the regular expression
9454 in the *Occur* buffer. This is useful if the regex is long and not useful
9455 to read."
9456 (occur regexp)
9457 (when cleanup
9458 (let ((cwin (selected-window)) win beg end)
9459 (when (setq win (get-buffer-window "*Occur*"))
9460 (select-window win))
9461 (goto-char (point-min))
9462 (when (re-search-forward "match[a-z]+" nil t)
9463 (setq beg (match-end 0))
9464 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9465 (setq end (1- (match-beginning 0)))))
9466 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9467 (goto-char (point-min))
9468 (select-window cwin))))
9470 ;;; The mark ring for links jumps
9472 (defvar org-mark-ring nil
9473 "Mark ring for positions before jumps in Org-mode.")
9474 (defvar org-mark-ring-last-goto nil
9475 "Last position in the mark ring used to go back.")
9476 ;; Fill and close the ring
9477 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9478 (loop for i from 1 to org-mark-ring-length do
9479 (push (make-marker) org-mark-ring))
9480 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9481 org-mark-ring)
9483 (defun org-mark-ring-push (&optional pos buffer)
9484 "Put the current position or POS into the mark ring and rotate it."
9485 (interactive)
9486 (setq pos (or pos (point)))
9487 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9488 (move-marker (car org-mark-ring)
9489 (or pos (point))
9490 (or buffer (current-buffer)))
9491 (message "%s"
9492 (substitute-command-keys
9493 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9495 (defun org-mark-ring-goto (&optional n)
9496 "Jump to the previous position in the mark ring.
9497 With prefix arg N, jump back that many stored positions. When
9498 called several times in succession, walk through the entire ring.
9499 Org-mode commands jumping to a different position in the current file,
9500 or to another Org-mode file, automatically push the old position
9501 onto the ring."
9502 (interactive "p")
9503 (let (p m)
9504 (if (eq last-command this-command)
9505 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9506 (setq p org-mark-ring))
9507 (setq org-mark-ring-last-goto p)
9508 (setq m (car p))
9509 (switch-to-buffer (marker-buffer m))
9510 (goto-char m)
9511 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9513 (defun org-remove-angle-brackets (s)
9514 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9515 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9517 (defun org-add-angle-brackets (s)
9518 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9519 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9521 (defun org-remove-double-quotes (s)
9522 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9523 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
9526 ;;; Following specific links
9528 (defun org-follow-timestamp-link ()
9529 (cond
9530 ((org-at-date-range-p t)
9531 (let ((org-agenda-start-on-weekday)
9532 (t1 (match-string 1))
9533 (t2 (match-string 2)))
9534 (setq t1 (time-to-days (org-time-string-to-time t1))
9535 t2 (time-to-days (org-time-string-to-time t2)))
9536 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9537 ((org-at-timestamp-p t)
9538 (org-agenda-list nil (time-to-days (org-time-string-to-time
9539 (substring (match-string 1) 0 10)))
9541 (t (error "This should not happen"))))
9544 ;;; Following file links
9545 (defvar org-wait nil)
9546 (defun org-open-file (path &optional in-emacs line search)
9547 "Open the file at PATH.
9548 First, this expands any special file name abbreviations. Then the
9549 configuration variable `org-file-apps' is checked if it contains an
9550 entry for this file type, and if yes, the corresponding command is launched.
9552 If no application is found, Emacs simply visits the file.
9554 With optional prefix argument IN-EMACS, Emacs will visit the file.
9555 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
9556 and to use an external application to visit the file.
9558 Optional LINE specifies a line to go to, optional SEARCH a string
9559 to search for. If LINE or SEARCH is given, the file will be
9560 opened in Emacs, unless an entry from org-file-apps that makes
9561 use of groups in a regexp matches.
9562 If the file does not exist, an error is thrown."
9563 (let* ((file (if (equal path "")
9564 buffer-file-name
9565 (substitute-in-file-name (expand-file-name path))))
9566 (file-apps (append org-file-apps (org-default-apps)))
9567 (apps (org-remove-if
9568 'org-file-apps-entry-match-against-dlink-p file-apps))
9569 (apps-dlink (org-remove-if-not
9570 'org-file-apps-entry-match-against-dlink-p file-apps))
9571 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9572 (dirp (if remp nil (file-directory-p file)))
9573 (file (if (and dirp org-open-directory-means-index-dot-org)
9574 (concat (file-name-as-directory file) "index.org")
9575 file))
9576 (a-m-a-p (assq 'auto-mode apps))
9577 (dfile (downcase file))
9578 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
9579 (link (cond ((and (eq line nil)
9580 (eq search nil))
9581 file)
9582 (line
9583 (concat file "::" (number-to-string line)))
9584 (search
9585 (concat file "::" search))))
9586 (dlink (downcase link))
9587 (old-buffer (current-buffer))
9588 (old-pos (point))
9589 (old-mode major-mode)
9590 ext cmd link-match-data)
9591 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9592 (setq ext (match-string 1 dfile))
9593 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9594 (setq ext (match-string 1 dfile))))
9595 (cond
9596 ((member in-emacs '((16) system))
9597 (setq cmd (cdr (assoc 'system apps))))
9598 (in-emacs (setq cmd 'emacs))
9600 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9601 (and dirp (cdr (assoc 'directory apps)))
9602 ; first, try matching against apps-dlink
9603 ; if we get a match here, store the match data for later
9604 (let ((match (assoc-default dlink apps-dlink
9605 'string-match)))
9606 (if match
9607 (progn (setq link-match-data (match-data))
9608 match)
9609 (progn (setq in-emacs (or in-emacs line search))
9610 nil))) ; if we have no match in apps-dlink,
9611 ; always open the file in emacs if line or search
9612 ; is given (for backwards compatibility)
9613 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
9614 'string-match)
9615 (cdr (assoc ext apps))
9616 (cdr (assoc t apps))))))
9617 (when (eq cmd 'system)
9618 (setq cmd (cdr (assoc 'system apps))))
9619 (when (eq cmd 'default)
9620 (setq cmd (cdr (assoc t apps))))
9621 (when (eq cmd 'mailcap)
9622 (require 'mailcap)
9623 (mailcap-parse-mailcaps)
9624 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9625 (command (mailcap-mime-info mime-type)))
9626 (if (stringp command)
9627 (setq cmd command)
9628 (setq cmd 'emacs))))
9629 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
9630 (not (file-exists-p file))
9631 (not org-open-non-existing-files))
9632 (error "No such file: %s" file))
9633 (cond
9634 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9635 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9636 (while (string-match "['\"]%s['\"]" cmd)
9637 (setq cmd (replace-match "%s" t t cmd)))
9638 (while (string-match "%s" cmd)
9639 (setq cmd (replace-match
9640 (save-match-data
9641 (shell-quote-argument
9642 (convert-standard-filename file)))
9643 t t cmd)))
9645 ;; Replace "%1", "%2" etc. in command with group matches from regex
9646 (save-match-data
9647 (let ((match-index 1)
9648 (number-of-groups (- (/ (length link-match-data) 2) 1)))
9649 (set-match-data link-match-data)
9650 (while (<= match-index number-of-groups)
9651 (let ((regex (concat "%" (number-to-string match-index)))
9652 (replace-with (match-string match-index dlink)))
9653 (while (string-match regex cmd)
9654 (setq cmd (replace-match replace-with t t cmd))))
9655 (setq match-index (+ match-index 1)))))
9657 (save-window-excursion
9658 (start-process-shell-command cmd nil cmd)
9659 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9661 ((or (stringp cmd)
9662 (eq cmd 'emacs))
9663 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9664 (widen)
9665 (if line (org-goto-line line)
9666 (if search (org-link-search search))))
9667 ((consp cmd)
9668 (let ((file (convert-standard-filename file)))
9669 (save-match-data
9670 (set-match-data link-match-data)
9671 (eval cmd))))
9672 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9673 (and (org-mode-p) (eq old-mode 'org-mode)
9674 (or (not (equal old-buffer (current-buffer)))
9675 (not (equal old-pos (point))))
9676 (org-mark-ring-push old-pos old-buffer))))
9678 (defun org-file-apps-entry-match-against-dlink-p (entry)
9679 "This function returns non-nil if `entry' uses a regular
9680 expression which should be matched against the whole link by
9681 org-open-file.
9683 It assumes that is the case when the entry uses a regular
9684 expression which has at least one grouping construct and the
9685 action is either a lisp form or a command string containing
9686 '%1', i.e. using at least one subexpression match as a
9687 parameter."
9688 (let ((selector (car entry))
9689 (action (cdr entry)))
9690 (if (stringp selector)
9691 (and (> (regexp-opt-depth selector) 0)
9692 (or (and (stringp action)
9693 (string-match "%[0-9]" action))
9694 (consp action)))
9695 nil)))
9697 (defun org-default-apps ()
9698 "Return the default applications for this operating system."
9699 (cond
9700 ((eq system-type 'darwin)
9701 org-file-apps-defaults-macosx)
9702 ((eq system-type 'windows-nt)
9703 org-file-apps-defaults-windowsnt)
9704 (t org-file-apps-defaults-gnu)))
9706 (defun org-apps-regexp-alist (list &optional add-auto-mode)
9707 "Convert extensions to regular expressions in the cars of LIST.
9708 Also, weed out any non-string entries, because the return value is used
9709 only for regexp matching.
9710 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
9711 point to the symbol `emacs', indicating that the file should
9712 be opened in Emacs."
9713 (append
9714 (delq nil
9715 (mapcar (lambda (x)
9716 (if (not (stringp (car x)))
9718 (if (string-match "\\W" (car x))
9720 (cons (concat "\\." (car x) "\\'") (cdr x)))))
9721 list))
9722 (if add-auto-mode
9723 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
9725 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
9726 (defun org-file-remote-p (file)
9727 "Test whether FILE specifies a location on a remote system.
9728 Return non-nil if the location is indeed remote.
9730 For example, the filename \"/user@host:/foo\" specifies a location
9731 on the system \"/user@host:\"."
9732 (cond ((fboundp 'file-remote-p)
9733 (file-remote-p file))
9734 ((fboundp 'tramp-handle-file-remote-p)
9735 (tramp-handle-file-remote-p file))
9736 ((and (boundp 'ange-ftp-name-format)
9737 (string-match (car ange-ftp-name-format) file))
9739 (t nil)))
9742 ;;;; Refiling
9744 (defun org-get-org-file ()
9745 "Read a filename, with default directory `org-directory'."
9746 (let ((default (or org-default-notes-file remember-data-file)))
9747 (read-file-name (format "File name [%s]: " default)
9748 (file-name-as-directory org-directory)
9749 default)))
9751 (defun org-notes-order-reversed-p ()
9752 "Check if the current file should receive notes in reversed order."
9753 (cond
9754 ((not org-reverse-note-order) nil)
9755 ((eq t org-reverse-note-order) t)
9756 ((not (listp org-reverse-note-order)) nil)
9757 (t (catch 'exit
9758 (let ((all org-reverse-note-order)
9759 entry)
9760 (while (setq entry (pop all))
9761 (if (string-match (car entry) buffer-file-name)
9762 (throw 'exit (cdr entry))))
9763 nil)))))
9765 (defvar org-refile-target-table nil
9766 "The list of refile targets, created by `org-refile'.")
9768 (defvar org-agenda-new-buffers nil
9769 "Buffers created to visit agenda files.")
9771 (defvar org-refile-cache nil
9772 "Cache for refile targets.")
9775 (defvar org-refile-markers nil
9776 "All the markers used for caching refile locations.")
9778 (defun org-refile-marker (pos)
9779 "Get a new refile marker, but only if caching is in use."
9780 (if (not org-refile-use-cache)
9782 (let ((m (make-marker)))
9783 (move-marker m pos)
9784 (push m org-refile-markers)
9785 m)))
9787 (defun org-refile-cache-clear ()
9788 "Clear the refile cache and disable all the markers."
9789 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
9790 (setq org-refile-markers nil)
9791 (setq org-refile-cache nil)
9792 (message "Refile cache has been cleared"))
9794 (defun org-refile-cache-check-set (set)
9795 "Check if all the markers in the cache still have live buffers."
9796 (let (marker)
9797 (catch 'exit
9798 (while (and set (setq marker (nth 3 (pop set))))
9799 ;; if org-refile-use-outline-path is 'file, marker may be nil
9800 (when (and marker (null (marker-buffer marker)))
9801 (message "not found") (sit-for 3)
9802 (throw 'exit nil)))
9803 t)))
9805 (defun org-refile-cache-put (set &rest identifiers)
9806 "Push the refile targets SET into the cache, under IDENTIFIERS."
9807 (let* ((key (sha1 (prin1-to-string identifiers)))
9808 (entry (assoc key org-refile-cache)))
9809 (if entry
9810 (setcdr entry set)
9811 (push (cons key set) org-refile-cache))))
9813 (defun org-refile-cache-get (&rest identifiers)
9814 "Retrieve the cached value for refile targets given by IDENTIFIERS."
9815 (cond
9816 ((not org-refile-cache) nil)
9817 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
9819 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
9820 org-refile-cache))))
9821 (and set (org-refile-cache-check-set set) set)))))
9823 (defun org-get-refile-targets (&optional default-buffer)
9824 "Produce a table with refile targets."
9825 (let ((case-fold-search nil)
9826 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
9827 (entries (or org-refile-targets '((nil . (:level . 1)))))
9828 targets tgs txt re files f desc descre fast-path-p level pos0)
9829 (message "Getting targets...")
9830 (with-current-buffer (or default-buffer (current-buffer))
9831 (while (setq entry (pop entries))
9832 (setq files (car entry) desc (cdr entry))
9833 (setq fast-path-p nil)
9834 (cond
9835 ((null files) (setq files (list (current-buffer))))
9836 ((eq files 'org-agenda-files)
9837 (setq files (org-agenda-files 'unrestricted)))
9838 ((and (symbolp files) (fboundp files))
9839 (setq files (funcall files)))
9840 ((and (symbolp files) (boundp files))
9841 (setq files (symbol-value files))))
9842 (if (stringp files) (setq files (list files)))
9843 (cond
9844 ((eq (car desc) :tag)
9845 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
9846 ((eq (car desc) :todo)
9847 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
9848 ((eq (car desc) :regexp)
9849 (setq descre (cdr desc)))
9850 ((eq (car desc) :level)
9851 (setq descre (concat "^\\*\\{" (number-to-string
9852 (if org-odd-levels-only
9853 (1- (* 2 (cdr desc)))
9854 (cdr desc)))
9855 "\\}[ \t]")))
9856 ((eq (car desc) :maxlevel)
9857 (setq fast-path-p t)
9858 (setq descre (concat "^\\*\\{1," (number-to-string
9859 (if org-odd-levels-only
9860 (1- (* 2 (cdr desc)))
9861 (cdr desc)))
9862 "\\}[ \t]")))
9863 (t (error "Bad refiling target description %s" desc)))
9864 (while (setq f (pop files))
9865 (with-current-buffer
9866 (if (bufferp f) f (org-get-agenda-file-buffer f))
9868 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
9869 (progn
9870 (if (bufferp f) (setq f (buffer-file-name
9871 (buffer-base-buffer f))))
9872 (setq f (and f (expand-file-name f)))
9873 (if (eq org-refile-use-outline-path 'file)
9874 (push (list (file-name-nondirectory f) f nil nil) tgs))
9875 (save-excursion
9876 (save-restriction
9877 (widen)
9878 (goto-char (point-min))
9879 (while (re-search-forward descre nil t)
9880 (goto-char (setq pos0 (point-at-bol)))
9881 (catch 'next
9882 (when org-refile-target-verify-function
9883 (save-match-data
9884 (or (funcall org-refile-target-verify-function)
9885 (throw 'next t))))
9886 (when (looking-at org-complex-heading-regexp)
9887 (setq level (org-reduced-level
9888 (- (match-end 1) (match-beginning 1)))
9889 txt (org-link-display-format (match-string 4))
9890 re (concat "^" (regexp-quote
9891 (buffer-substring
9892 (match-beginning 1)
9893 (match-end 4)))))
9894 (if (match-end 5) (setq re (concat
9895 re "[ \t]+"
9896 (regexp-quote
9897 (match-string 5)))))
9898 (setq re (concat re "[ \t]*$"))
9899 (when org-refile-use-outline-path
9900 (setq txt (mapconcat
9901 'org-protect-slash
9902 (append
9903 (if (eq org-refile-use-outline-path
9904 'file)
9905 (list (file-name-nondirectory
9906 (buffer-file-name
9907 (buffer-base-buffer))))
9908 (if (eq org-refile-use-outline-path
9909 'full-file-path)
9910 (list (buffer-file-name
9911 (buffer-base-buffer)))))
9912 (org-get-outline-path fast-path-p
9913 level txt)
9914 (list txt))
9915 "/")))
9916 (push (list txt f re (org-refile-marker (point)))
9917 tgs)))
9918 (when (= (point) pos0)
9919 ;; verification function has not moved point
9920 (goto-char (point-at-eol))))))))
9921 (when org-refile-use-cache
9922 (org-refile-cache-put tgs (buffer-file-name) descre))
9923 (setq targets (append tgs targets))
9924 ))))
9925 (message "Getting targets...done")
9926 (nreverse targets)))
9928 (defun org-protect-slash (s)
9929 (while (string-match "/" s)
9930 (setq s (replace-match "\\" t t s)))
9933 (defvar org-olpa (make-vector 20 nil))
9935 (defun org-get-outline-path (&optional fastp level heading)
9936 "Return the outline path to the current entry, as a list.
9938 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
9939 routine which makes outline path derivations for an entire file,
9940 avoiding backtracing. Refile target collection makes use of that."
9941 (if fastp
9942 (progn
9943 (if (> level 19)
9944 (error "Outline path failure, more than 19 levels."))
9945 (loop for i from level upto 19 do
9946 (aset org-olpa i nil))
9947 (prog1
9948 (delq nil (append org-olpa nil))
9949 (aset org-olpa level heading)))
9950 (let (rtn case-fold-search)
9951 (save-excursion
9952 (save-restriction
9953 (widen)
9954 (while (org-up-heading-safe)
9955 (when (looking-at org-complex-heading-regexp)
9956 (push (org-match-string-no-properties 4) rtn)))
9957 rtn)))))
9959 (defun org-format-outline-path (path &optional width prefix)
9960 "Format the outlie path PATH for display.
9961 Width is the maximum number of characters that is available.
9962 Prefix is a prefix to be included in the returned string,
9963 such as the file name."
9964 (setq width (or width 79))
9965 (if prefix (setq width (- width (length prefix))))
9966 (if (not path)
9967 (or prefix "")
9968 (let* ((nsteps (length path))
9969 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9970 (maxwidth (if (<= total-width width)
9971 10000 ;; everything fits
9972 ;; we need to shorten the level headings
9973 (/ (- width nsteps) nsteps)))
9974 (org-odd-levels-only nil)
9975 (n 0)
9976 (total (1+ (length prefix))))
9977 (setq maxwidth (max maxwidth 10))
9978 (concat prefix
9979 (mapconcat
9980 (lambda (h)
9981 (setq n (1+ n))
9982 (if (and (= n nsteps) (< maxwidth 10000))
9983 (setq maxwidth (- total-width total)))
9984 (if (< (length h) maxwidth)
9985 (progn (setq total (+ total (length h) 1)) h)
9986 (setq h (substring h 0 (- maxwidth 2))
9987 total (+ total maxwidth 1))
9988 (if (string-match "[ \t]+\\'" h)
9989 (setq h (substring h 0 (match-beginning 0))))
9990 (setq h (concat h "..")))
9991 (org-add-props h nil 'face
9992 (nth (% (1- n) org-n-level-faces)
9993 org-level-faces))
9995 path "/")))))
9997 (defun org-display-outline-path (&optional file current)
9998 "Display the current outline path in the echo area."
9999 (interactive "P")
10000 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10001 (case-fold-search nil)
10002 (path (and (org-mode-p) (org-get-outline-path))))
10003 (if current (setq path (append path
10004 (save-excursion
10005 (org-back-to-heading t)
10006 (if (looking-at org-complex-heading-regexp)
10007 (list (match-string 4)))))))
10008 (message "%s"
10009 (org-format-outline-path
10010 path
10011 (1- (frame-width))
10012 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10014 (defvar org-refile-history nil
10015 "History for refiling operations.")
10017 (defvar org-after-refile-insert-hook nil
10018 "Hook run after `org-refile' has inserted its stuff at the new location.
10019 Note that this is still *before* the stuff will be removed from
10020 the *old* location.")
10022 (defvar org-capture-last-stored-marker)
10023 (defun org-refile (&optional goto default-buffer rfloc)
10024 "Move the entry at point to another heading.
10025 The list of target headings is compiled using the information in
10026 `org-refile-targets', which see. This list is created before each use
10027 and will therefore always be up-to-date.
10029 At the target location, the entry is filed as a subitem of the target heading.
10030 Depending on `org-reverse-note-order', the new subitem will either be the
10031 first or the last subitem.
10033 If there is an active region, all entries in that region will be moved.
10034 However, the region must fulfil the requirement that the first heading
10035 is the first one sets the top-level of the moved text - at most siblings
10036 below it are allowed.
10038 With prefix arg GOTO, the command will only visit the target location,
10039 not actually move anything.
10040 With a double prefix `C-u C-u', go to the location where the last refiling
10041 operation has put the subtree.
10042 With a prefix argument of `2', refile to the running clock.
10044 RFLOC can be a refile location obtained in a different way.
10046 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10048 If you are using target caching (see `org-refile-use-cache'),
10049 You have to clear the target cache in order to find new targets.
10050 This can be done with a 0 prefix: `C-0 C-c C-w'"
10051 (interactive "P")
10052 (if (member goto '(0 (64)))
10053 (org-refile-cache-clear)
10054 (let* ((cbuf (current-buffer))
10055 (regionp (org-region-active-p))
10056 (region-start (and regionp (region-beginning)))
10057 (region-end (and regionp (region-end)))
10058 (region-length (and regionp (- region-end region-start)))
10059 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10060 pos it nbuf file re level reversed)
10061 (setq last-command nil)
10062 (when regionp
10063 (goto-char region-start)
10064 (or (bolp) (goto-char (point-at-bol)))
10065 (setq region-start (point))
10066 (unless (org-kill-is-subtree-p
10067 (buffer-substring region-start region-end))
10068 (error "The region is not a (sequence of) subtree(s)")))
10069 (if (equal goto '(16))
10070 (org-refile-goto-last-stored)
10071 (when (or
10072 (and (equal goto 2)
10073 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10074 (prog1
10075 (setq it (list (or org-clock-heading "running clock")
10076 (buffer-file-name
10077 (marker-buffer org-clock-hd-marker))
10079 (marker-position org-clock-hd-marker)))
10080 (setq goto nil)))
10081 (setq it (or rfloc
10082 (save-excursion
10083 (org-refile-get-location
10084 (if goto "Goto: " "Refile to: ") default-buffer
10085 org-refile-allow-creating-parent-nodes)))))
10086 (setq file (nth 1 it)
10087 re (nth 2 it)
10088 pos (nth 3 it))
10089 (if (and (not goto)
10091 (equal (buffer-file-name) file)
10092 (if regionp
10093 (and (>= pos region-start)
10094 (<= pos region-end))
10095 (and (>= pos (point))
10096 (< pos (save-excursion
10097 (org-end-of-subtree t t))))))
10098 (error "Cannot refile to position inside the tree or region"))
10100 (setq nbuf (or (find-buffer-visiting file)
10101 (find-file-noselect file)))
10102 (if goto
10103 (progn
10104 (switch-to-buffer nbuf)
10105 (goto-char pos)
10106 (org-show-context 'org-goto))
10107 (if regionp
10108 (progn
10109 (org-kill-new (buffer-substring region-start region-end))
10110 (org-save-markers-in-region region-start region-end))
10111 (org-copy-subtree 1 nil t))
10112 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10113 (find-file-noselect file)))
10114 (setq reversed (org-notes-order-reversed-p))
10115 (save-excursion
10116 (save-restriction
10117 (widen)
10118 (if pos
10119 (progn
10120 (goto-char pos)
10121 (looking-at outline-regexp)
10122 (setq level (org-get-valid-level (funcall outline-level) 1))
10123 (goto-char
10124 (if reversed
10125 (or (outline-next-heading) (point-max))
10126 (or (save-excursion (org-get-next-sibling))
10127 (org-end-of-subtree t t)
10128 (point-max)))))
10129 (setq level 1)
10130 (if (not reversed)
10131 (goto-char (point-max))
10132 (goto-char (point-min))
10133 (or (outline-next-heading) (goto-char (point-max)))))
10134 (if (not (bolp)) (newline))
10135 (org-paste-subtree level)
10136 (when org-log-refile
10137 (org-add-log-setup 'refile nil nil 'findpos
10138 org-log-refile)
10139 (unless (eq org-log-refile 'note)
10140 (save-excursion (org-add-log-note))))
10141 (and org-auto-align-tags (org-set-tags nil t))
10142 (bookmark-set "org-refile-last-stored")
10143 ;; If we are refiling for capture, make sure that the
10144 ;; last-capture pointers point here
10145 (when (org-bound-and-true-p org-refile-for-capture)
10146 (bookmark-set "org-capture-last-stored-marker")
10147 (move-marker org-capture-last-stored-marker (point)))
10148 (if (fboundp 'deactivate-mark) (deactivate-mark))
10149 (run-hooks 'org-after-refile-insert-hook))))
10150 (if regionp
10151 (delete-region (point) (+ (point) region-length))
10152 (org-cut-subtree))
10153 (when (featurep 'org-inlinetask)
10154 (org-inlinetask-remove-END-maybe))
10155 (setq org-markers-to-move nil)
10156 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10158 (defun org-refile-goto-last-stored ()
10159 "Go to the location where the last refile was stored."
10160 (interactive)
10161 (bookmark-jump "org-refile-last-stored")
10162 (message "This is the location of the last refile"))
10164 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
10165 "Prompt the user for a refile location, using PROMPT."
10166 (let ((org-refile-targets org-refile-targets)
10167 (org-refile-use-outline-path org-refile-use-outline-path))
10168 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
10169 (unless org-refile-target-table
10170 (error "No refile targets"))
10171 (let* ((cbuf (current-buffer))
10172 (partial-completion-mode nil)
10173 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10174 (cfunc (if (and org-refile-use-outline-path
10175 org-outline-path-complete-in-steps)
10176 'org-olpath-completing-read
10177 'org-icompleting-read))
10178 (extra (if org-refile-use-outline-path "/" ""))
10179 (filename (and cfn (expand-file-name cfn)))
10180 (tbl (mapcar
10181 (lambda (x)
10182 (if (and (not (member org-refile-use-outline-path
10183 '(file full-file-path)))
10184 (not (equal filename (nth 1 x))))
10185 (cons (concat (car x) extra " ("
10186 (file-name-nondirectory (nth 1 x)) ")")
10187 (cdr x))
10188 (cons (concat (car x) extra) (cdr x))))
10189 org-refile-target-table))
10190 (completion-ignore-case t)
10191 pa answ parent-target child parent old-hist)
10192 (setq old-hist org-refile-history)
10193 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10194 nil 'org-refile-history))
10195 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10196 (if pa
10197 (progn
10198 (when (or (not org-refile-history)
10199 (not (eq old-hist org-refile-history))
10200 (not (equal (car pa) (car org-refile-history))))
10201 (setq org-refile-history
10202 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10203 org-refile-history
10204 (cdr org-refile-history))))
10205 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10206 (pop org-refile-history)))
10208 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10209 (progn
10210 (setq parent (match-string 1 answ)
10211 child (match-string 2 answ))
10212 (setq parent-target (or (assoc parent tbl)
10213 (assoc (concat parent "/") tbl)))
10214 (when (and parent-target
10215 (or (eq new-nodes t)
10216 (and (eq new-nodes 'confirm)
10217 (y-or-n-p (format "Create new node \"%s\"? "
10218 child)))))
10219 (org-refile-new-child parent-target child)))
10220 (error "Invalid target location")))))
10222 (defun org-refile-new-child (parent-target child)
10223 "Use refile target PARENT-TARGET to add new CHILD below it."
10224 (unless parent-target
10225 (error "Cannot find parent for new node"))
10226 (let ((file (nth 1 parent-target))
10227 (pos (nth 3 parent-target))
10228 level)
10229 (with-current-buffer (or (find-buffer-visiting file)
10230 (find-file-noselect file))
10231 (save-excursion
10232 (save-restriction
10233 (widen)
10234 (if pos
10235 (goto-char pos)
10236 (goto-char (point-max))
10237 (if (not (bolp)) (newline)))
10238 (when (looking-at outline-regexp)
10239 (setq level (funcall outline-level))
10240 (org-end-of-subtree t t))
10241 (org-back-over-empty-lines)
10242 (insert "\n" (make-string
10243 (if pos (org-get-valid-level level 1) 1) ?*)
10244 " " child "\n")
10245 (beginning-of-line 0)
10246 (list (concat (car parent-target) "/" child) file "" (point)))))))
10248 (defun org-olpath-completing-read (prompt collection &rest args)
10249 "Read an outline path like a file name."
10250 (let ((thetable collection)
10251 (org-completion-use-ido nil) ; does not work with ido.
10252 (org-completion-use-iswitchb nil)) ; or iswitchb
10253 (apply
10254 'org-icompleting-read prompt
10255 (lambda (string predicate &optional flag)
10256 (let (rtn r f (l (length string)))
10257 (cond
10258 ((eq flag nil)
10259 ;; try completion
10260 (try-completion string thetable))
10261 ((eq flag t)
10262 ;; all-completions
10263 (setq rtn (all-completions string thetable predicate))
10264 (mapcar
10265 (lambda (x)
10266 (setq r (substring x l))
10267 (if (string-match " ([^)]*)$" x)
10268 (setq f (match-string 0 x))
10269 (setq f ""))
10270 (if (string-match "/" r)
10271 (concat string (substring r 0 (match-end 0)) f)
10273 rtn))
10274 ((eq flag 'lambda)
10275 ;; exact match?
10276 (assoc string thetable)))
10278 args)))
10280 ;;;; Dynamic blocks
10282 (defun org-find-dblock (name)
10283 "Find the first dynamic block with name NAME in the buffer.
10284 If not found, stay at current position and return nil."
10285 (let (pos)
10286 (save-excursion
10287 (goto-char (point-min))
10288 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
10289 nil t)
10290 (match-beginning 0))))
10291 (if pos (goto-char pos))
10292 pos))
10294 (defconst org-dblock-start-re
10295 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10296 "Matches the start line of a dynamic block, with parameters.")
10298 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10299 "Matches the end of a dynamic block.")
10301 (defun org-create-dblock (plist)
10302 "Create a dynamic block section, with parameters taken from PLIST.
10303 PLIST must contain a :name entry which is used as name of the block."
10304 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10305 (end-of-line 1)
10306 (newline))
10307 (let ((col (current-column))
10308 (name (plist-get plist :name)))
10309 (insert "#+BEGIN: " name)
10310 (while plist
10311 (if (eq (car plist) :name)
10312 (setq plist (cddr plist))
10313 (insert " " (prin1-to-string (pop plist)))))
10314 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10315 (beginning-of-line -2)))
10317 (defun org-prepare-dblock ()
10318 "Prepare dynamic block for refresh.
10319 This empties the block, puts the cursor at the insert position and returns
10320 the property list including an extra property :name with the block name."
10321 (unless (looking-at org-dblock-start-re)
10322 (error "Not at a dynamic block"))
10323 (let* ((begdel (1+ (match-end 0)))
10324 (name (org-no-properties (match-string 1)))
10325 (params (append (list :name name)
10326 (read (concat "(" (match-string 3) ")")))))
10327 (save-excursion
10328 (beginning-of-line 1)
10329 (skip-chars-forward " \t")
10330 (setq params (plist-put params :indentation-column (current-column))))
10331 (unless (re-search-forward org-dblock-end-re nil t)
10332 (error "Dynamic block not terminated"))
10333 (setq params
10334 (append params
10335 (list :content (buffer-substring
10336 begdel (match-beginning 0)))))
10337 (delete-region begdel (match-beginning 0))
10338 (goto-char begdel)
10339 (open-line 1)
10340 params))
10342 (defun org-map-dblocks (&optional command)
10343 "Apply COMMAND to all dynamic blocks in the current buffer.
10344 If COMMAND is not given, use `org-update-dblock'."
10345 (let ((cmd (or command 'org-update-dblock)))
10346 (save-excursion
10347 (goto-char (point-min))
10348 (while (re-search-forward org-dblock-start-re nil t)
10349 (goto-char (match-beginning 0))
10350 (save-excursion
10351 (condition-case nil
10352 (funcall cmd)
10353 (error (message "Error during update of dynamic block"))))
10354 (unless (re-search-forward org-dblock-end-re nil t)
10355 (error "Dynamic block not terminated"))))))
10357 (defun org-dblock-update (&optional arg)
10358 "User command for updating dynamic blocks.
10359 Update the dynamic block at point. With prefix ARG, update all dynamic
10360 blocks in the buffer."
10361 (interactive "P")
10362 (if arg
10363 (org-update-all-dblocks)
10364 (or (looking-at org-dblock-start-re)
10365 (org-beginning-of-dblock))
10366 (org-update-dblock)))
10368 (defun org-update-dblock ()
10369 "Update the dynamic block at point
10370 This means to empty the block, parse for parameters and then call
10371 the correct writing function."
10372 (save-window-excursion
10373 (let* ((pos (point))
10374 (line (org-current-line))
10375 (params (org-prepare-dblock))
10376 (name (plist-get params :name))
10377 (indent (plist-get params :indentation-column))
10378 (cmd (intern (concat "org-dblock-write:" name))))
10379 (message "Updating dynamic block `%s' at line %d..." name line)
10380 (funcall cmd params)
10381 (message "Updating dynamic block `%s' at line %d...done" name line)
10382 (goto-char pos)
10383 (when (and indent (> indent 0))
10384 (setq indent (make-string indent ?\ ))
10385 (save-excursion
10386 (org-beginning-of-dblock)
10387 (forward-line 1)
10388 (while (not (looking-at org-dblock-end-re))
10389 (insert indent)
10390 (beginning-of-line 2))
10391 (when (looking-at org-dblock-end-re)
10392 (and (looking-at "[ \t]+")
10393 (replace-match ""))
10394 (insert indent)))))))
10396 (defun org-beginning-of-dblock ()
10397 "Find the beginning of the dynamic block at point.
10398 Error if there is no such block at point."
10399 (let ((pos (point))
10400 beg)
10401 (end-of-line 1)
10402 (if (and (re-search-backward org-dblock-start-re nil t)
10403 (setq beg (match-beginning 0))
10404 (re-search-forward org-dblock-end-re nil t)
10405 (> (match-end 0) pos))
10406 (goto-char beg)
10407 (goto-char pos)
10408 (error "Not in a dynamic block"))))
10410 (defun org-update-all-dblocks ()
10411 "Update all dynamic blocks in the buffer.
10412 This function can be used in a hook."
10413 (when (org-mode-p)
10414 (org-map-dblocks 'org-update-dblock)))
10417 ;;;; Completion
10419 (defconst org-additional-option-like-keywords
10420 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
10421 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
10422 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
10423 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX"
10424 "BEGIN:" "END:"
10425 "ORGTBL" "TBLFM:" "TBLNAME:"
10426 "BEGIN_EXAMPLE" "END_EXAMPLE"
10427 "BEGIN_QUOTE" "END_QUOTE"
10428 "BEGIN_VERSE" "END_VERSE"
10429 "BEGIN_CENTER" "END_CENTER"
10430 "BEGIN_SRC" "END_SRC"
10431 "CATEGORY" "COLUMNS"
10432 "CAPTION" "LABEL"
10433 "SETUPFILE"
10434 "BIND"
10435 "MACRO"))
10437 (defcustom org-structure-template-alist
10439 ("s" "#+begin_src ?\n\n#+end_src"
10440 "<src lang=\"?\">\n\n</src>")
10441 ("e" "#+begin_example\n?\n#+end_example"
10442 "<example>\n?\n</example>")
10443 ("q" "#+begin_quote\n?\n#+end_quote"
10444 "<quote>\n?\n</quote>")
10445 ("v" "#+begin_verse\n?\n#+end_verse"
10446 "<verse>\n?\n/verse>")
10447 ("c" "#+begin_center\n?\n#+end_center"
10448 "<center>\n?\n/center>")
10449 ("l" "#+begin_latex\n?\n#+end_latex"
10450 "<literal style=\"latex\">\n?\n</literal>")
10451 ("L" "#+latex: "
10452 "<literal style=\"latex\">?</literal>")
10453 ("h" "#+begin_html\n?\n#+end_html"
10454 "<literal style=\"html\">\n?\n</literal>")
10455 ("H" "#+html: "
10456 "<literal style=\"html\">?</literal>")
10457 ("a" "#+begin_ascii\n?\n#+end_ascii")
10458 ("A" "#+ascii: ")
10459 ("i" "#+include %file ?"
10460 "<include file=%file markup=\"?\">")
10462 "Structure completion elements.
10463 This is a list of abbreviation keys and values. The value gets inserted
10464 if you type `<' followed by the key and then press the completion key,
10465 usually `M-TAB'. %file will be replaced by a file name after prompting
10466 for the file using completion.
10467 There are two templates for each key, the first uses the original Org syntax,
10468 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
10469 the default when the /org-mtags.el/ module has been loaded. See also the
10470 variable `org-mtags-prefer-muse-templates'.
10471 This is an experimental feature, it is undecided if it is going to stay in."
10472 :group 'org-completion
10473 :type '(repeat
10474 (string :tag "Key")
10475 (string :tag "Template")
10476 (string :tag "Muse Template")))
10478 (defun org-try-structure-completion ()
10479 "Try to complete a structure template before point.
10480 This looks for strings like \"<e\" on an otherwise empty line and
10481 expands them."
10482 (let ((l (buffer-substring (point-at-bol) (point)))
10484 (when (and (looking-at "[ \t]*$")
10485 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
10486 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
10487 (org-complete-expand-structure-template (+ -1 (point-at-bol)
10488 (match-beginning 1)) a)
10489 t)))
10491 (defun org-complete-expand-structure-template (start cell)
10492 "Expand a structure template."
10493 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
10494 (rpl (nth (if musep 2 1) cell))
10495 (ind ""))
10496 (delete-region start (point))
10497 (when (string-match "\\`#\\+" rpl)
10498 (cond
10499 ((bolp))
10500 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
10501 (setq ind (buffer-substring (point-at-bol) (point))))
10502 (t (newline))))
10503 (setq start (point))
10504 (if (string-match "%file" rpl)
10505 (setq rpl (replace-match
10506 (concat
10507 "\""
10508 (save-match-data
10509 (abbreviate-file-name (read-file-name "Include file: ")))
10510 "\"")
10511 t t rpl)))
10512 (setq rpl (mapconcat 'identity (split-string rpl "\n")
10513 (concat "\n" ind)))
10514 (insert rpl)
10515 (if (re-search-backward "\\?" start t) (delete-char 1))))
10518 (defun org-complete (&optional arg)
10519 "Perform completion on word at point.
10520 At the beginning of a headline, this completes TODO keywords as given in
10521 `org-todo-keywords'.
10522 If the current word is preceded by a backslash, completes the TeX symbols
10523 that are supported for HTML support.
10524 If the current word is preceded by \"#+\", completes special words for
10525 setting file options.
10526 In the line after \"#+STARTUP:, complete valid keywords.\"
10527 At all other locations, this simply calls the value of
10528 `org-completion-fallback-command'."
10529 (interactive "P")
10530 (org-without-partial-completion
10531 (catch 'exit
10532 (let* ((a nil)
10533 (end (point))
10534 (beg1 (save-excursion
10535 (skip-chars-backward (org-re "[:alnum:]_@"))
10536 (point)))
10537 (beg (save-excursion
10538 (skip-chars-backward "a-zA-Z0-9_:$")
10539 (point)))
10540 (confirm (lambda (x) (stringp (car x))))
10541 (searchhead (equal (char-before beg) ?*))
10542 (struct
10543 (when (and (member (char-before beg1) '(?. ?<))
10544 (setq a (assoc (buffer-substring beg1 (point))
10545 org-structure-template-alist)))
10546 (org-complete-expand-structure-template (1- beg1) a)
10547 (throw 'exit t)))
10548 (tag (and (equal (char-before beg1) ?:)
10549 (equal (char-after (point-at-bol)) ?*)))
10550 (prop (and (equal (char-before beg1) ?:)
10551 (not (equal (char-after (point-at-bol)) ?*))))
10552 (texp (equal (char-before beg) ?\\))
10553 (link (equal (char-before beg) ?\[))
10554 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
10555 beg)
10556 "#+"))
10557 (startup (string-match "^#\\+STARTUP:.*"
10558 (buffer-substring (point-at-bol) (point))))
10559 (completion-ignore-case opt)
10560 (type nil)
10561 (tbl nil)
10562 (table (cond
10563 (opt
10564 (setq type :opt)
10565 (require 'org-exp)
10566 (append
10567 (delq nil
10568 (mapcar
10569 (lambda (x)
10570 (if (string-match
10571 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
10572 (cons (match-string 2 x)
10573 (match-string 1 x))))
10574 (org-split-string (org-get-current-options) "\n")))
10575 (mapcar 'list org-additional-option-like-keywords)))
10576 (startup
10577 (setq type :startup)
10578 org-startup-options)
10579 (link (append org-link-abbrev-alist-local
10580 org-link-abbrev-alist))
10581 (texp
10582 (setq type :tex)
10583 (append org-entities-user org-entities))
10584 ((string-match "\\`\\*+[ \t]+\\'"
10585 (buffer-substring (point-at-bol) beg))
10586 (setq type :todo)
10587 (mapcar 'list org-todo-keywords-1))
10588 (searchhead
10589 (setq type :searchhead)
10590 (save-excursion
10591 (goto-char (point-min))
10592 (while (re-search-forward org-todo-line-regexp nil t)
10593 (push (list
10594 (org-make-org-heading-search-string
10595 (match-string 3) t))
10596 tbl)))
10597 tbl)
10598 (tag (setq type :tag beg beg1)
10599 (or org-tag-alist (org-get-buffer-tags)))
10600 (prop (setq type :prop beg beg1)
10601 (mapcar 'list (org-buffer-property-keys nil t t)))
10602 (t (progn
10603 (call-interactively org-completion-fallback-command)
10604 (throw 'exit nil)))))
10605 (pattern (buffer-substring-no-properties beg end))
10606 (completion (try-completion pattern table confirm)))
10607 (cond ((eq completion t)
10608 (if (not (assoc (upcase pattern) table))
10609 (message "Already complete")
10610 (if (and (equal type :opt)
10611 (not (member (car (assoc (upcase pattern) table))
10612 org-additional-option-like-keywords)))
10613 (insert (substring (cdr (assoc (upcase pattern) table))
10614 (length pattern)))
10615 (if (memq type '(:tag :prop)) (insert ":")))))
10616 ((null completion)
10617 (message "Can't find completion for \"%s\"" pattern)
10618 (ding))
10619 ((not (string= pattern completion))
10620 (delete-region beg end)
10621 (if (string-match " +$" completion)
10622 (setq completion (replace-match "" t t completion)))
10623 (insert completion)
10624 (if (get-buffer-window "*Completions*")
10625 (delete-window (get-buffer-window "*Completions*")))
10626 (if (assoc completion table)
10627 (if (eq type :todo) (insert " ")
10628 (if (memq type '(:tag :prop)) (insert ":"))))
10629 (if (and (equal type :opt) (assoc completion table))
10630 (message "%s" (substitute-command-keys
10631 "Press \\[org-complete] again to insert example settings"))))
10633 (message "Making completion list...")
10634 (let ((list (sort (all-completions pattern table confirm)
10635 'string<)))
10636 (with-output-to-temp-buffer "*Completions*"
10637 (condition-case nil
10638 ;; Protection needed for XEmacs and emacs 21
10639 (display-completion-list list pattern)
10640 (error (display-completion-list list)))))
10641 (message "Making completion list...%s" "done")))))))
10643 ;;;; TODO, DEADLINE, Comments
10645 (defun org-toggle-comment ()
10646 "Change the COMMENT state of an entry."
10647 (interactive)
10648 (save-excursion
10649 (org-back-to-heading)
10650 (let (case-fold-search)
10651 (if (looking-at (concat outline-regexp
10652 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10653 (replace-match "" t t nil 1)
10654 (if (looking-at outline-regexp)
10655 (progn
10656 (goto-char (match-end 0))
10657 (insert org-comment-string " ")))))))
10659 (defvar org-last-todo-state-is-todo nil
10660 "This is non-nil when the last TODO state change led to a TODO state.
10661 If the last change removed the TODO tag or switched to DONE, then
10662 this is nil.")
10664 (defvar org-setting-tags nil) ; dynamically skipped
10666 (defun org-parse-local-options (string var)
10667 "Parse STRING for startup setting relevant for variable VAR."
10668 (let ((rtn (symbol-value var))
10669 e opts)
10670 (save-match-data
10671 (if (or (not string) (not (string-match "\\S-" string)))
10673 (setq opts (delq nil (mapcar (lambda (x)
10674 (setq e (assoc x org-startup-options))
10675 (if (eq (nth 1 e) var) e nil))
10676 (org-split-string string "[ \t]+"))))
10677 (if (not opts)
10679 (setq rtn nil)
10680 (while (setq e (pop opts))
10681 (if (not (nth 3 e))
10682 (setq rtn (nth 2 e))
10683 (if (not (listp rtn)) (setq rtn nil))
10684 (push (nth 2 e) rtn)))
10685 rtn)))))
10687 (defvar org-todo-setup-filter-hook nil
10688 "Hook for functions that pre-filter todo specs.
10690 Each function takes a todo spec and returns either `nil' or the spec
10691 transformed into canonical form." )
10693 (defvar org-todo-get-default-hook nil
10694 "Hook for functions that get a default item for todo.
10696 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
10697 `nil' or a string to be used for the todo mark." )
10699 (defvar org-agenda-headline-snapshot-before-repeat)
10701 (defun org-todo (&optional arg)
10702 "Change the TODO state of an item.
10703 The state of an item is given by a keyword at the start of the heading,
10704 like
10705 *** TODO Write paper
10706 *** DONE Call mom
10708 The different keywords are specified in the variable `org-todo-keywords'.
10709 By default the available states are \"TODO\" and \"DONE\".
10710 So for this example: when the item starts with TODO, it is changed to DONE.
10711 When it starts with DONE, the DONE is removed. And when neither TODO nor
10712 DONE are present, add TODO at the beginning of the heading.
10714 With C-u prefix arg, use completion to determine the new state.
10715 With numeric prefix arg, switch to that state.
10716 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
10717 With a triple C-u prefix, circumvent any state blocking.
10719 For calling through lisp, arg is also interpreted in the following way:
10720 'none -> empty state
10721 \"\"(empty string) -> switch to empty state
10722 'done -> switch to DONE
10723 'nextset -> switch to the next set of keywords
10724 'previousset -> switch to the previous set of keywords
10725 \"WAITING\" -> switch to the specified keyword, but only if it
10726 really is a member of `org-todo-keywords'."
10727 (interactive "P")
10728 (if (equal arg '(16)) (setq arg 'nextset))
10729 (let ((org-blocker-hook org-blocker-hook)
10730 (case-fold-search nil))
10731 (when (equal arg '(64))
10732 (setq arg nil org-blocker-hook nil))
10733 (when (and org-blocker-hook
10734 (or org-inhibit-blocking
10735 (org-entry-get nil "NOBLOCKING")))
10736 (setq org-blocker-hook nil))
10737 (save-excursion
10738 (catch 'exit
10739 (org-back-to-heading t)
10740 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
10741 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
10742 (looking-at " *"))
10743 (let* ((match-data (match-data))
10744 (startpos (point-at-bol))
10745 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
10746 (org-log-done org-log-done)
10747 (org-log-repeat org-log-repeat)
10748 (org-todo-log-states org-todo-log-states)
10749 (this (match-string 1))
10750 (hl-pos (match-beginning 0))
10751 (head (org-get-todo-sequence-head this))
10752 (ass (assoc head org-todo-kwd-alist))
10753 (interpret (nth 1 ass))
10754 (done-word (nth 3 ass))
10755 (final-done-word (nth 4 ass))
10756 (last-state (or this ""))
10757 (completion-ignore-case t)
10758 (member (member this org-todo-keywords-1))
10759 (tail (cdr member))
10760 (state (cond
10761 ((and org-todo-key-trigger
10762 (or (and (equal arg '(4))
10763 (eq org-use-fast-todo-selection 'prefix))
10764 (and (not arg) org-use-fast-todo-selection
10765 (not (eq org-use-fast-todo-selection
10766 'prefix)))))
10767 ;; Use fast selection
10768 (org-fast-todo-selection))
10769 ((and (equal arg '(4))
10770 (or (not org-use-fast-todo-selection)
10771 (not org-todo-key-trigger)))
10772 ;; Read a state with completion
10773 (org-icompleting-read
10774 "State: " (mapcar (lambda(x) (list x))
10775 org-todo-keywords-1)
10776 nil t))
10777 ((eq arg 'right)
10778 (if this
10779 (if tail (car tail) nil)
10780 (car org-todo-keywords-1)))
10781 ((eq arg 'left)
10782 (if (equal member org-todo-keywords-1)
10784 (if this
10785 (nth (- (length org-todo-keywords-1)
10786 (length tail) 2)
10787 org-todo-keywords-1)
10788 (org-last org-todo-keywords-1))))
10789 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10790 (setq arg nil))) ; hack to fall back to cycling
10791 (arg
10792 ;; user or caller requests a specific state
10793 (cond
10794 ((equal arg "") nil)
10795 ((eq arg 'none) nil)
10796 ((eq arg 'done) (or done-word (car org-done-keywords)))
10797 ((eq arg 'nextset)
10798 (or (car (cdr (member head org-todo-heads)))
10799 (car org-todo-heads)))
10800 ((eq arg 'previousset)
10801 (let ((org-todo-heads (reverse org-todo-heads)))
10802 (or (car (cdr (member head org-todo-heads)))
10803 (car org-todo-heads))))
10804 ((car (member arg org-todo-keywords-1)))
10805 ((stringp arg)
10806 (error "State `%s' not valid in this file" arg))
10807 ((nth (1- (prefix-numeric-value arg))
10808 org-todo-keywords-1))))
10809 ((null member) (or head (car org-todo-keywords-1)))
10810 ((equal this final-done-word) nil) ;; -> make empty
10811 ((null tail) nil) ;; -> first entry
10812 ((memq interpret '(type priority))
10813 (if (eq this-command last-command)
10814 (car tail)
10815 (if (> (length tail) 0)
10816 (or done-word (car org-done-keywords))
10817 nil)))
10819 (car tail))))
10820 (state (or
10821 (run-hook-with-args-until-success
10822 'org-todo-get-default-hook state last-state)
10823 state))
10824 (next (if state (concat " " state " ") " "))
10825 (change-plist (list :type 'todo-state-change :from this :to state
10826 :position startpos))
10827 dolog now-done-p)
10828 (when org-blocker-hook
10829 (setq org-last-todo-state-is-todo
10830 (not (member this org-done-keywords)))
10831 (unless (save-excursion
10832 (save-match-data
10833 (run-hook-with-args-until-failure
10834 'org-blocker-hook change-plist)))
10835 (if (interactive-p)
10836 (error "TODO state change from %s to %s blocked" this state)
10837 ;; fail silently
10838 (message "TODO state change from %s to %s blocked" this state)
10839 (throw 'exit nil))))
10840 (store-match-data match-data)
10841 (replace-match next t t)
10842 (unless (pos-visible-in-window-p hl-pos)
10843 (message "TODO state changed to %s" (org-trim next)))
10844 (unless head
10845 (setq head (org-get-todo-sequence-head state)
10846 ass (assoc head org-todo-kwd-alist)
10847 interpret (nth 1 ass)
10848 done-word (nth 3 ass)
10849 final-done-word (nth 4 ass)))
10850 (when (memq arg '(nextset previousset))
10851 (message "Keyword-Set %d/%d: %s"
10852 (- (length org-todo-sets) -1
10853 (length (memq (assoc state org-todo-sets) org-todo-sets)))
10854 (length org-todo-sets)
10855 (mapconcat 'identity (assoc state org-todo-sets) " ")))
10856 (setq org-last-todo-state-is-todo
10857 (not (member state org-done-keywords)))
10858 (setq now-done-p (and (member state org-done-keywords)
10859 (not (member this org-done-keywords))))
10860 (and logging (org-local-logging logging))
10861 (when (and (or org-todo-log-states org-log-done)
10862 (not (eq org-inhibit-logging t))
10863 (not (memq arg '(nextset previousset))))
10864 ;; we need to look at recording a time and note
10865 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
10866 (nth 2 (assoc this org-todo-log-states))))
10867 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
10868 (setq dolog 'time))
10869 (when (and state
10870 (member state org-not-done-keywords)
10871 (not (member this org-not-done-keywords)))
10872 ;; This is now a todo state and was not one before
10873 ;; If there was a CLOSED time stamp, get rid of it.
10874 (org-add-planning-info nil nil 'closed))
10875 (when (and now-done-p org-log-done)
10876 ;; It is now done, and it was not done before
10877 (org-add-planning-info 'closed (org-current-time))
10878 (if (and (not dolog) (eq 'note org-log-done))
10879 (org-add-log-setup 'done state this 'findpos 'note)))
10880 (when (and state dolog)
10881 ;; This is a non-nil state, and we need to log it
10882 (org-add-log-setup 'state state this 'findpos dolog)))
10883 ;; Fixup tag positioning
10884 (org-todo-trigger-tag-changes state)
10885 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
10886 (when org-provide-todo-statistics
10887 (org-update-parent-todo-statistics))
10888 (run-hooks 'org-after-todo-state-change-hook)
10889 (if (and arg (not (member state org-done-keywords)))
10890 (setq head (org-get-todo-sequence-head state)))
10891 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
10892 ;; Do we need to trigger a repeat?
10893 (when now-done-p
10894 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
10895 ;; This is for the agenda, take a snapshot of the headline.
10896 (save-match-data
10897 (setq org-agenda-headline-snapshot-before-repeat
10898 (org-get-heading))))
10899 (org-auto-repeat-maybe state))
10900 ;; Fixup cursor location if close to the keyword
10901 (if (and (outline-on-heading-p)
10902 (not (bolp))
10903 (save-excursion (beginning-of-line 1)
10904 (looking-at org-todo-line-regexp))
10905 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
10906 (progn
10907 (goto-char (or (match-end 2) (match-end 1)))
10908 (and (looking-at " ") (just-one-space))))
10909 (when org-trigger-hook
10910 (save-excursion
10911 (run-hook-with-args 'org-trigger-hook change-plist))))))))
10913 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
10914 "Block turning an entry into a TODO, using the hierarchy.
10915 This checks whether the current task should be blocked from state
10916 changes. Such blocking occurs when:
10918 1. The task has children which are not all in a completed state.
10920 2. A task has a parent with the property :ORDERED:, and there
10921 are siblings prior to the current task with incomplete
10922 status.
10924 3. The parent of the task is blocked because it has siblings that should
10925 be done first, or is child of a block grandparent TODO entry."
10927 (if (not org-enforce-todo-dependencies)
10928 t ; if locally turned off don't block
10929 (catch 'dont-block
10930 ;; If this is not a todo state change, or if this entry is already DONE,
10931 ;; do not block
10932 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10933 (member (plist-get change-plist :from)
10934 (cons 'done org-done-keywords))
10935 (member (plist-get change-plist :to)
10936 (cons 'todo org-not-done-keywords))
10937 (not (plist-get change-plist :to)))
10938 (throw 'dont-block t))
10939 ;; If this task has children, and any are undone, it's blocked
10940 (save-excursion
10941 (org-back-to-heading t)
10942 (let ((this-level (funcall outline-level)))
10943 (outline-next-heading)
10944 (let ((child-level (funcall outline-level)))
10945 (while (and (not (eobp))
10946 (> child-level this-level))
10947 ;; this todo has children, check whether they are all
10948 ;; completed
10949 (if (and (not (org-entry-is-done-p))
10950 (org-entry-is-todo-p))
10951 (throw 'dont-block nil))
10952 (outline-next-heading)
10953 (setq child-level (funcall outline-level))))))
10954 ;; Otherwise, if the task's parent has the :ORDERED: property, and
10955 ;; any previous siblings are undone, it's blocked
10956 (save-excursion
10957 (org-back-to-heading t)
10958 (let* ((pos (point))
10959 (parent-pos (and (org-up-heading-safe) (point))))
10960 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10961 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
10962 (forward-line 1)
10963 (re-search-forward org-not-done-heading-regexp pos t))
10964 (throw 'dont-block nil)) ; block, there is an older sibling not done.
10965 ;; Search further up the hierarchy, to see if an anchestor is blocked
10966 (while t
10967 (goto-char parent-pos)
10968 (if (not (looking-at org-not-done-heading-regexp))
10969 (throw 'dont-block t)) ; do not block, parent is not a TODO
10970 (setq pos (point))
10971 (setq parent-pos (and (org-up-heading-safe) (point)))
10972 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10973 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
10974 (forward-line 1)
10975 (re-search-forward org-not-done-heading-regexp pos t))
10976 (throw 'dont-block nil)))))))) ; block, older sibling not done.
10978 (defcustom org-track-ordered-property-with-tag nil
10979 "Should the ORDERED property also be shown as a tag?
10980 The ORDERED property decides if an entry should require subtasks to be
10981 completed in sequence. Since a property is not very visible, setting
10982 this option means that toggling the ORDERED property with the command
10983 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10984 not relevant for the behavior, but it makes things more visible.
10986 Note that toggling the tag with tags commands will not change the property
10987 and therefore not influence behavior!
10989 This can be t, meaning the tag ORDERED should be used, It can also be a
10990 string to select a different tag for this task."
10991 :group 'org-todo
10992 :type '(choice
10993 (const :tag "No tracking" nil)
10994 (const :tag "Track with ORDERED tag" t)
10995 (string :tag "Use other tag")))
10997 (defun org-toggle-ordered-property ()
10998 "Toggle the ORDERED property of the current entry.
10999 For better visibility, you can track the value of this property with a tag.
11000 See variable `org-track-ordered-property-with-tag'."
11001 (interactive)
11002 (let* ((t1 org-track-ordered-property-with-tag)
11003 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11004 (save-excursion
11005 (org-back-to-heading)
11006 (if (org-entry-get nil "ORDERED")
11007 (progn
11008 (org-delete-property "ORDERED")
11009 (and tag (org-toggle-tag tag 'off))
11010 (message "Subtasks can be completed in arbitrary order"))
11011 (org-entry-put nil "ORDERED" "t")
11012 (and tag (org-toggle-tag tag 'on))
11013 (message "Subtasks must be completed in sequence")))))
11015 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11016 (defun org-block-todo-from-checkboxes (change-plist)
11017 "Block turning an entry into a TODO, using checkboxes.
11018 This checks whether the current task should be blocked from state
11019 changes because there are unchecked boxes in this entry."
11020 (if (not org-enforce-todo-checkbox-dependencies)
11021 t ; if locally turned off don't block
11022 (catch 'dont-block
11023 ;; If this is not a todo state change, or if this entry is already DONE,
11024 ;; do not block
11025 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11026 (member (plist-get change-plist :from)
11027 (cons 'done org-done-keywords))
11028 (member (plist-get change-plist :to)
11029 (cons 'todo org-not-done-keywords))
11030 (not (plist-get change-plist :to)))
11031 (throw 'dont-block t))
11032 ;; If this task has checkboxes that are not checked, it's blocked
11033 (save-excursion
11034 (org-back-to-heading t)
11035 (let ((beg (point)) end)
11036 (outline-next-heading)
11037 (setq end (point))
11038 (goto-char beg)
11039 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
11040 end t)
11041 (progn
11042 (if (boundp 'org-blocked-by-checkboxes)
11043 (setq org-blocked-by-checkboxes t))
11044 (throw 'dont-block nil)))))
11045 t))) ; do not block
11047 (defun org-entry-blocked-p ()
11048 "Is the current entry blocked?"
11049 (if (org-entry-get nil "NOBLOCKING")
11050 nil ;; Never block this entry
11051 (not
11052 (run-hook-with-args-until-failure
11053 'org-blocker-hook
11054 (list :type 'todo-state-change
11055 :position (point)
11056 :from 'todo
11057 :to 'done)))))
11059 (defun org-update-statistics-cookies (all)
11060 "Update the statistics cookie, either from TODO or from checkboxes.
11061 This should be called with the cursor in a line with a statistics cookie."
11062 (interactive "P")
11063 (if all
11064 (progn
11065 (org-update-checkbox-count 'all)
11066 (org-map-entries 'org-update-parent-todo-statistics))
11067 (if (not (org-on-heading-p))
11068 (org-update-checkbox-count)
11069 (let ((pos (move-marker (make-marker) (point)))
11070 end l1 l2)
11071 (ignore-errors (org-back-to-heading t))
11072 (if (not (org-on-heading-p))
11073 (org-update-checkbox-count)
11074 (setq l1 (org-outline-level))
11075 (setq end (save-excursion
11076 (outline-next-heading)
11077 (if (org-on-heading-p) (setq l2 (org-outline-level)))
11078 (point)))
11079 (if (and (save-excursion
11080 (re-search-forward
11081 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11082 (not (save-excursion (re-search-forward
11083 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11084 (org-update-checkbox-count)
11085 (if (and l2 (> l2 l1))
11086 (progn
11087 (goto-char end)
11088 (org-update-parent-todo-statistics))
11089 (goto-char pos)
11090 (beginning-of-line 1)
11091 (while (re-search-forward
11092 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11093 (point-at-eol) t)
11094 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11095 (goto-char pos)
11096 (move-marker pos nil)))))
11098 (defvar org-entry-property-inherited-from) ;; defined below
11099 (defun org-update-parent-todo-statistics ()
11100 "Update any statistics cookie in the parent of the current headline.
11101 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11102 the entire subtree and this will travel up the hierarchy and update
11103 statistics everywhere."
11104 (interactive)
11105 (let* ((lim 0) prop
11106 (recursive (or (not org-hierarchical-todo-statistics)
11107 (string-match
11108 "\\<recursive\\>"
11109 (or (setq prop (org-entry-get
11110 nil "COOKIE_DATA" 'inherit)) ""))))
11111 (lim (or (and prop (marker-position
11112 org-entry-property-inherited-from))
11113 lim))
11114 (first t)
11115 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11116 level ltoggle l1 new ndel
11117 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
11118 (catch 'exit
11119 (save-excursion
11120 (beginning-of-line 1)
11121 (if (org-at-heading-p)
11122 (setq ltoggle (funcall outline-level))
11123 (error "This should not happen"))
11124 (while (and (setq level (org-up-heading-safe))
11125 (or recursive first)
11126 (>= (point) lim))
11127 (setq first nil cookie-present nil)
11128 (unless (and level
11129 (not (string-match
11130 "\\<checkbox\\>"
11131 (downcase
11132 (or (org-entry-get
11133 nil "COOKIE_DATA")
11134 "")))))
11135 (throw 'exit nil))
11136 (while (re-search-forward box-re (point-at-eol) t)
11137 (setq cnt-all 0 cnt-done 0 cookie-present t)
11138 (setq is-percent (match-end 2))
11139 (save-match-data
11140 (unless (outline-next-heading) (throw 'exit nil))
11141 (while (and (looking-at org-complex-heading-regexp)
11142 (> (setq l1 (length (match-string 1))) level))
11143 (setq kwd (and (or recursive (= l1 ltoggle))
11144 (match-string 2)))
11145 (if (or (eq org-provide-todo-statistics 'all-headlines)
11146 (and (listp org-provide-todo-statistics)
11147 (or (member kwd org-provide-todo-statistics)
11148 (member kwd org-done-keywords))))
11149 (setq cnt-all (1+ cnt-all))
11150 (if (eq org-provide-todo-statistics t)
11151 (and kwd (setq cnt-all (1+ cnt-all)))))
11152 (and (member kwd org-done-keywords)
11153 (setq cnt-done (1+ cnt-done)))
11154 (outline-next-heading)))
11155 (setq new
11156 (if is-percent
11157 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11158 (format "[%d/%d]" cnt-done cnt-all))
11159 ndel (- (match-end 0) (match-beginning 0)))
11160 (goto-char (match-beginning 0))
11161 (insert new)
11162 (delete-region (point) (+ (point) ndel)))
11163 (when cookie-present
11164 (run-hook-with-args 'org-after-todo-statistics-hook
11165 cnt-done (- cnt-all cnt-done))))))
11166 (run-hooks 'org-todo-statistics-hook)))
11168 (defvar org-after-todo-statistics-hook nil
11169 "Hook that is called after a TODO statistics cookie has been updated.
11170 Each function is called with two arguments: the number of not-done entries
11171 and the number of done entries.
11173 For example, the following function, when added to this hook, will switch
11174 an entry to DONE when all children are done, and back to TODO when new
11175 entries are set to a TODO status. Note that this hook is only called
11176 when there is a statistics cookie in the headline!
11178 (defun org-summary-todo (n-done n-not-done)
11179 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11180 (let (org-log-done org-log-states) ; turn off logging
11181 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11184 (defvar org-todo-statistics-hook nil
11185 "Hook that is run whenever Org thinks TODO statistics should be updated.
11186 This hook runs even if there is no statistics cookie present, in which case
11187 `org-after-todo-statistics-hook' would not run.")
11189 (defun org-todo-trigger-tag-changes (state)
11190 "Apply the changes defined in `org-todo-state-tags-triggers'."
11191 (let ((l org-todo-state-tags-triggers)
11192 changes)
11193 (when (or (not state) (equal state ""))
11194 (setq changes (append changes (cdr (assoc "" l)))))
11195 (when (and (stringp state) (> (length state) 0))
11196 (setq changes (append changes (cdr (assoc state l)))))
11197 (when (member state org-not-done-keywords)
11198 (setq changes (append changes (cdr (assoc 'todo l)))))
11199 (when (member state org-done-keywords)
11200 (setq changes (append changes (cdr (assoc 'done l)))))
11201 (dolist (c changes)
11202 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11204 (defun org-local-logging (value)
11205 "Get logging settings from a property VALUE."
11206 (let* (words w a)
11207 ;; directly set the variables, they are already local.
11208 (setq org-log-done nil
11209 org-log-repeat nil
11210 org-todo-log-states nil)
11211 (setq words (org-split-string value))
11212 (while (setq w (pop words))
11213 (cond
11214 ((setq a (assoc w org-startup-options))
11215 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11216 (set (nth 1 a) (nth 2 a))))
11217 ((setq a (org-extract-log-state-settings w))
11218 (and (member (car a) org-todo-keywords-1)
11219 (push a org-todo-log-states)))))))
11221 (defun org-get-todo-sequence-head (kwd)
11222 "Return the head of the TODO sequence to which KWD belongs.
11223 If KWD is not set, check if there is a text property remembering the
11224 right sequence."
11225 (let (p)
11226 (cond
11227 ((not kwd)
11228 (or (get-text-property (point-at-bol) 'org-todo-head)
11229 (progn
11230 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11231 nil (point-at-eol)))
11232 (get-text-property p 'org-todo-head))))
11233 ((not (member kwd org-todo-keywords-1))
11234 (car org-todo-keywords-1))
11235 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11237 (defun org-fast-todo-selection ()
11238 "Fast TODO keyword selection with single keys.
11239 Returns the new TODO keyword, or nil if no state change should occur."
11240 (let* ((fulltable org-todo-key-alist)
11241 (done-keywords org-done-keywords) ;; needed for the faces.
11242 (maxlen (apply 'max (mapcar
11243 (lambda (x)
11244 (if (stringp (car x)) (string-width (car x)) 0))
11245 fulltable)))
11246 (expert nil)
11247 (fwidth (+ maxlen 3 1 3))
11248 (ncol (/ (- (window-width) 4) fwidth))
11249 tg cnt e c tbl
11250 groups ingroup)
11251 (save-excursion
11252 (save-window-excursion
11253 (if expert
11254 (set-buffer (get-buffer-create " *Org todo*"))
11255 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11256 (erase-buffer)
11257 (org-set-local 'org-done-keywords done-keywords)
11258 (setq tbl fulltable cnt 0)
11259 (while (setq e (pop tbl))
11260 (cond
11261 ((equal e '(:startgroup))
11262 (push '() groups) (setq ingroup t)
11263 (when (not (= cnt 0))
11264 (setq cnt 0)
11265 (insert "\n"))
11266 (insert "{ "))
11267 ((equal e '(:endgroup))
11268 (setq ingroup nil cnt 0)
11269 (insert "}\n"))
11270 ((equal e '(:newline))
11271 (when (not (= cnt 0))
11272 (setq cnt 0)
11273 (insert "\n")
11274 (setq e (car tbl))
11275 (while (equal (car tbl) '(:newline))
11276 (insert "\n")
11277 (setq tbl (cdr tbl)))))
11279 (setq tg (car e) c (cdr e))
11280 (if ingroup (push tg (car groups)))
11281 (setq tg (org-add-props tg nil 'face
11282 (org-get-todo-face tg)))
11283 (if (and (= cnt 0) (not ingroup)) (insert " "))
11284 (insert "[" c "] " tg (make-string
11285 (- fwidth 4 (length tg)) ?\ ))
11286 (when (= (setq cnt (1+ cnt)) ncol)
11287 (insert "\n")
11288 (if ingroup (insert " "))
11289 (setq cnt 0)))))
11290 (insert "\n")
11291 (goto-char (point-min))
11292 (if (not expert) (org-fit-window-to-buffer))
11293 (message "[a-z..]:Set [SPC]:clear")
11294 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11295 (cond
11296 ((or (= c ?\C-g)
11297 (and (= c ?q) (not (rassoc c fulltable))))
11298 (setq quit-flag t))
11299 ((= c ?\ ) nil)
11300 ((setq e (rassoc c fulltable) tg (car e))
11302 (t (setq quit-flag t)))))))
11304 (defun org-entry-is-todo-p ()
11305 (member (org-get-todo-state) org-not-done-keywords))
11307 (defun org-entry-is-done-p ()
11308 (member (org-get-todo-state) org-done-keywords))
11310 (defun org-get-todo-state ()
11311 (save-excursion
11312 (org-back-to-heading t)
11313 (and (looking-at org-todo-line-regexp)
11314 (match-end 2)
11315 (match-string 2))))
11317 (defun org-at-date-range-p (&optional inactive-ok)
11318 "Is the cursor inside a date range?"
11319 (interactive)
11320 (save-excursion
11321 (catch 'exit
11322 (let ((pos (point)))
11323 (skip-chars-backward "^[<\r\n")
11324 (skip-chars-backward "<[")
11325 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11326 (>= (match-end 0) pos)
11327 (throw 'exit t))
11328 (skip-chars-backward "^<[\r\n")
11329 (skip-chars-backward "<[")
11330 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11331 (>= (match-end 0) pos)
11332 (throw 'exit t)))
11333 nil)))
11335 (defun org-get-repeat (&optional tagline)
11336 "Check if there is a deadline/schedule with repeater in this entry."
11337 (save-match-data
11338 (save-excursion
11339 (org-back-to-heading t)
11340 (and (re-search-forward (if tagline
11341 (concat tagline "\\s-*" org-repeat-re)
11342 org-repeat-re)
11343 (org-entry-end-position) t)
11344 (match-string-no-properties 1)))))
11346 (defvar org-last-changed-timestamp)
11347 (defvar org-last-inserted-timestamp)
11348 (defvar org-log-post-message)
11349 (defvar org-log-note-purpose)
11350 (defvar org-log-note-how)
11351 (defvar org-log-note-extra)
11352 (defun org-auto-repeat-maybe (done-word)
11353 "Check if the current headline contains a repeated deadline/schedule.
11354 If yes, set TODO state back to what it was and change the base date
11355 of repeating deadline/scheduled time stamps to new date.
11356 This function is run automatically after each state change to a DONE state."
11357 ;; last-state is dynamically scoped into this function
11358 (let* ((repeat (org-get-repeat))
11359 (aa (assoc last-state org-todo-kwd-alist))
11360 (interpret (nth 1 aa))
11361 (head (nth 2 aa))
11362 (whata '(("d" . day) ("m" . month) ("y" . year)))
11363 (msg "Entry repeats: ")
11364 (org-log-done nil)
11365 (org-todo-log-states nil)
11366 (nshiftmax 10) (nshift 0)
11367 re type n what ts time to-state)
11368 (when repeat
11369 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11370 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11371 org-todo-repeat-to-state))
11372 (unless (and to-state (member to-state org-todo-keywords-1))
11373 (setq to-state (if (eq interpret 'type) last-state head)))
11374 (org-todo to-state)
11375 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11376 (org-entry-put nil "LAST_REPEAT" (format-time-string
11377 (org-time-stamp-format t t))))
11378 (when org-log-repeat
11379 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11380 (memq 'org-add-log-note post-command-hook))
11381 ;; OK, we are already setup for some record
11382 (if (eq org-log-repeat 'note)
11383 ;; make sure we take a note, not only a time stamp
11384 (setq org-log-note-how 'note))
11385 ;; Set up for taking a record
11386 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11387 last-state
11388 'findpos org-log-repeat)))
11389 (org-back-to-heading t)
11390 (org-add-planning-info nil nil 'closed)
11391 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11392 org-deadline-time-regexp "\\)\\|\\("
11393 org-ts-regexp "\\)"))
11394 (while (re-search-forward
11395 re (save-excursion (outline-next-heading) (point)) t)
11396 (setq type (if (match-end 1) org-scheduled-string
11397 (if (match-end 3) org-deadline-string "Plain:"))
11398 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11399 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11400 (setq n (string-to-number (match-string 2 ts))
11401 what (match-string 3 ts))
11402 (if (equal what "w") (setq n (* n 7) what "d"))
11403 ;; Preparation, see if we need to modify the start date for the change
11404 (when (match-end 1)
11405 (setq time (save-match-data (org-time-string-to-time ts)))
11406 (cond
11407 ((equal (match-string 1 ts) ".")
11408 ;; Shift starting date to today
11409 (org-timestamp-change
11410 (- (time-to-days (current-time)) (time-to-days time))
11411 'day))
11412 ((equal (match-string 1 ts) "+")
11413 (while (or (= nshift 0)
11414 (<= (time-to-days time) (time-to-days (current-time))))
11415 (when (= (incf nshift) nshiftmax)
11416 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11417 (error "Abort")))
11418 (org-timestamp-change n (cdr (assoc what whata)))
11419 (org-at-timestamp-p t)
11420 (setq ts (match-string 1))
11421 (setq time (save-match-data (org-time-string-to-time ts))))
11422 (org-timestamp-change (- n) (cdr (assoc what whata)))
11423 ;; rematch, so that we have everything in place for the real shift
11424 (org-at-timestamp-p t)
11425 (setq ts (match-string 1))
11426 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11427 (org-timestamp-change n (cdr (assoc what whata)))
11428 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11429 (setq org-log-post-message msg)
11430 (message "%s" msg))))
11432 (defun org-show-todo-tree (arg)
11433 "Make a compact tree which shows all headlines marked with TODO.
11434 The tree will show the lines where the regexp matches, and all higher
11435 headlines above the match.
11436 With a \\[universal-argument] prefix, prompt for a regexp to match.
11437 With a numeric prefix N, construct a sparse tree for the Nth element
11438 of `org-todo-keywords-1'."
11439 (interactive "P")
11440 (let ((case-fold-search nil)
11441 (kwd-re
11442 (cond ((null arg) org-not-done-regexp)
11443 ((equal arg '(4))
11444 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11445 (mapcar 'list org-todo-keywords-1))))
11446 (concat "\\("
11447 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11448 "\\)\\>")))
11449 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11450 (regexp-quote (nth (1- (prefix-numeric-value arg))
11451 org-todo-keywords-1)))
11452 (t (error "Invalid prefix argument: %s" arg)))))
11453 (message "%d TODO entries found"
11454 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
11456 (defun org-deadline (&optional remove time)
11457 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11458 With argument REMOVE, remove any deadline from the item.
11459 When TIME is set, it should be an internal time specification, and the
11460 scheduling will use the corresponding date."
11461 (interactive "P")
11462 (let* ((old-date (org-entry-get nil "DEADLINE"))
11463 (repeater (and old-date
11464 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
11465 (match-string 1 old-date))))
11466 (if remove
11467 (progn
11468 (when (and old-date org-log-redeadline)
11469 (org-add-log-setup 'deldeadline nil old-date 'findpos
11470 org-log-redeadline))
11471 (org-remove-timestamp-with-keyword org-deadline-string)
11472 (message "Item no longer has a deadline."))
11473 (org-add-planning-info 'deadline time 'closed)
11474 (when (and old-date org-log-redeadline
11475 (not (equal old-date
11476 (substring org-last-inserted-timestamp 1 -1))))
11477 (org-add-log-setup 'redeadline nil old-date 'findpos
11478 org-log-redeadline))
11479 (when repeater
11480 (save-excursion
11481 (org-back-to-heading t)
11482 (when (re-search-forward (concat org-deadline-string " "
11483 org-last-inserted-timestamp)
11484 (save-excursion
11485 (outline-next-heading) (point)) t)
11486 (goto-char (1- (match-end 0)))
11487 (insert " " repeater)
11488 (setq org-last-inserted-timestamp
11489 (concat (substring org-last-inserted-timestamp 0 -1)
11490 " " repeater
11491 (substring org-last-inserted-timestamp -1))))))
11492 (message "Deadline on %s" org-last-inserted-timestamp))))
11494 (defun org-schedule (&optional remove time)
11495 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11496 With argument REMOVE, remove any scheduling date from the item.
11497 When TIME is set, it should be an internal time specification, and the
11498 scheduling will use the corresponding date."
11499 (interactive "P")
11500 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11501 (repeater (and old-date
11502 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
11503 (match-string 1 old-date))))
11504 (if remove
11505 (progn
11506 (when (and old-date org-log-reschedule)
11507 (org-add-log-setup 'delschedule nil old-date 'findpos
11508 org-log-reschedule))
11509 (org-remove-timestamp-with-keyword org-scheduled-string)
11510 (message "Item is no longer scheduled."))
11511 (org-add-planning-info 'scheduled time 'closed)
11512 (when (and old-date org-log-reschedule
11513 (not (equal old-date
11514 (substring org-last-inserted-timestamp 1 -1))))
11515 (org-add-log-setup 'reschedule nil old-date 'findpos
11516 org-log-reschedule))
11517 (when repeater
11518 (save-excursion
11519 (org-back-to-heading t)
11520 (when (re-search-forward (concat org-scheduled-string " "
11521 org-last-inserted-timestamp)
11522 (save-excursion
11523 (outline-next-heading) (point)) t)
11524 (goto-char (1- (match-end 0)))
11525 (insert " " repeater)
11526 (setq org-last-inserted-timestamp
11527 (concat (substring org-last-inserted-timestamp 0 -1)
11528 " " repeater
11529 (substring org-last-inserted-timestamp -1))))))
11530 (message "Scheduled to %s" org-last-inserted-timestamp))))
11532 (defun org-get-scheduled-time (pom &optional inherit)
11533 "Get the scheduled time as a time tuple, of a format suitable
11534 for calling org-schedule with, or if there is no scheduling,
11535 returns nil."
11536 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
11537 (when time
11538 (apply 'encode-time (org-parse-time-string time)))))
11540 (defun org-get-deadline-time (pom &optional inherit)
11541 "Get the deadine as a time tuple, of a format suitable for
11542 calling org-deadline with, or if there is no scheduling, returns
11543 nil."
11544 (let ((time (org-entry-get pom "DEADLINE" inherit)))
11545 (when time
11546 (apply 'encode-time (org-parse-time-string time)))))
11548 (defun org-remove-timestamp-with-keyword (keyword)
11549 "Remove all time stamps with KEYWORD in the current entry."
11550 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
11551 beg)
11552 (save-excursion
11553 (org-back-to-heading t)
11554 (setq beg (point))
11555 (outline-next-heading)
11556 (while (re-search-backward re beg t)
11557 (replace-match "")
11558 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
11559 (equal (char-before) ?\ ))
11560 (backward-delete-char 1)
11561 (if (string-match "^[ \t]*$" (buffer-substring
11562 (point-at-bol) (point-at-eol)))
11563 (delete-region (point-at-bol)
11564 (min (point-max) (1+ (point-at-eol))))))))))
11566 (defun org-add-planning-info (what &optional time &rest remove)
11567 "Insert new timestamp with keyword in the line directly after the headline.
11568 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11569 If non is given, the user is prompted for a date.
11570 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11571 be removed."
11572 (interactive)
11573 (let (org-time-was-given org-end-time-was-given ts
11574 end default-time default-input)
11576 (catch 'exit
11577 (when (and (not time) (memq what '(scheduled deadline)))
11578 ;; Try to get a default date/time from existing timestamp
11579 (save-excursion
11580 (org-back-to-heading t)
11581 (setq end (save-excursion (outline-next-heading) (point)))
11582 (when (re-search-forward (if (eq what 'scheduled)
11583 org-scheduled-time-regexp
11584 org-deadline-time-regexp)
11585 end t)
11586 (setq ts (match-string 1)
11587 default-time
11588 (apply 'encode-time (org-parse-time-string ts))
11589 default-input (and ts (org-get-compact-tod ts))))))
11590 (when what
11591 ;; If necessary, get the time from the user
11592 (setq time (or time (org-read-date nil 'to-time nil nil
11593 default-time default-input))))
11595 (when (and org-insert-labeled-timestamps-at-point
11596 (member what '(scheduled deadline)))
11597 (insert
11598 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11599 (org-insert-time-stamp time org-time-was-given
11600 nil nil nil (list org-end-time-was-given))
11601 (setq what nil))
11602 (save-excursion
11603 (save-restriction
11604 (let (col list elt ts buffer-invisibility-spec)
11605 (org-back-to-heading t)
11606 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11607 (goto-char (match-end 1))
11608 (setq col (current-column))
11609 (goto-char (match-end 0))
11610 (if (eobp) (insert "\n") (forward-char 1))
11611 (when (and (not what)
11612 (not (looking-at
11613 (concat "[ \t]*"
11614 org-keyword-time-not-clock-regexp))))
11615 ;; Nothing to add, nothing to remove...... :-)
11616 (throw 'exit nil))
11617 (if (and (not (looking-at outline-regexp))
11618 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11619 "[^\r\n]*"))
11620 (not (equal (match-string 1) org-clock-string)))
11621 (narrow-to-region (match-beginning 0) (match-end 0))
11622 (insert-before-markers "\n")
11623 (backward-char 1)
11624 (narrow-to-region (point) (point))
11625 (and org-adapt-indentation (org-indent-to-column col)))
11626 ;; Check if we have to remove something.
11627 (setq list (cons what remove))
11628 (while list
11629 (setq elt (pop list))
11630 (goto-char (point-min))
11631 (when (or (and (eq elt 'scheduled)
11632 (re-search-forward org-scheduled-time-regexp nil t))
11633 (and (eq elt 'deadline)
11634 (re-search-forward org-deadline-time-regexp nil t))
11635 (and (eq elt 'closed)
11636 (re-search-forward org-closed-time-regexp nil t)))
11637 (replace-match "")
11638 (if (looking-at "--+<[^>]+>") (replace-match ""))
11639 (skip-chars-backward " ")
11640 (if (looking-at " +") (replace-match ""))))
11641 (goto-char (point-max))
11642 (and org-adapt-indentation (bolp) (org-indent-to-column col))
11643 (when what
11644 (insert
11645 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
11646 (cond ((eq what 'scheduled) org-scheduled-string)
11647 ((eq what 'deadline) org-deadline-string)
11648 ((eq what 'closed) org-closed-string))
11649 " ")
11650 (setq ts (org-insert-time-stamp
11651 time
11652 (or org-time-was-given
11653 (and (eq what 'closed) org-log-done-with-time))
11654 (eq what 'closed)
11655 nil nil (list org-end-time-was-given)))
11656 (end-of-line 1))
11657 (goto-char (point-min))
11658 (widen)
11659 (if (and (looking-at "[ \t]*\n")
11660 (equal (char-before) ?\n))
11661 (delete-region (1- (point)) (point-at-eol)))
11662 ts))))))
11664 (defvar org-log-note-marker (make-marker))
11665 (defvar org-log-note-purpose nil)
11666 (defvar org-log-note-state nil)
11667 (defvar org-log-note-previous-state nil)
11668 (defvar org-log-note-how nil)
11669 (defvar org-log-note-extra nil)
11670 (defvar org-log-note-window-configuration nil)
11671 (defvar org-log-note-return-to (make-marker))
11672 (defvar org-log-post-message nil
11673 "Message to be displayed after a log note has been stored.
11674 The auto-repeater uses this.")
11676 (defun org-add-note ()
11677 "Add a note to the current entry.
11678 This is done in the same way as adding a state change note."
11679 (interactive)
11680 (org-add-log-setup 'note nil nil 'findpos nil))
11682 (defvar org-property-end-re)
11683 (defun org-add-log-setup (&optional purpose state prev-state
11684 findpos how &optional extra)
11685 "Set up the post command hook to take a note.
11686 If this is about to TODO state change, the new state is expected in STATE.
11687 When FINDPOS is non-nil, find the correct position for the note in
11688 the current entry. If not, assume that it can be inserted at point.
11689 HOW is an indicator what kind of note should be created.
11690 EXTRA is additional text that will be inserted into the notes buffer."
11691 (let* ((org-log-into-drawer (org-log-into-drawer))
11692 (drawer (cond ((stringp org-log-into-drawer)
11693 org-log-into-drawer)
11694 (org-log-into-drawer "LOGBOOK")
11695 (t nil))))
11696 (save-restriction
11697 (save-excursion
11698 (when findpos
11699 (org-back-to-heading t)
11700 (narrow-to-region (point) (save-excursion
11701 (outline-next-heading) (point)))
11702 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11703 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11704 "[^\r\n]*\\)?"))
11705 (goto-char (match-end 0))
11706 (cond
11707 (drawer
11708 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
11709 nil t)
11710 (progn
11711 (goto-char (match-end 0))
11712 (or org-log-states-order-reversed
11713 (and (re-search-forward org-property-end-re nil t)
11714 (goto-char (1- (match-beginning 0))))))
11715 (insert "\n:" drawer ":\n:END:")
11716 (beginning-of-line 0)
11717 (org-indent-line-function)
11718 (beginning-of-line 2)
11719 (org-indent-line-function)
11720 (end-of-line 0)))
11721 ((and org-log-state-notes-insert-after-drawers
11722 (save-excursion
11723 (forward-line) (looking-at org-drawer-regexp)))
11724 (forward-line)
11725 (while (looking-at org-drawer-regexp)
11726 (goto-char (match-end 0))
11727 (re-search-forward org-property-end-re (point-max) t)
11728 (forward-line))
11729 (forward-line -1)))
11730 (unless org-log-states-order-reversed
11731 (and (= (char-after) ?\n) (forward-char 1))
11732 (org-skip-over-state-notes)
11733 (skip-chars-backward " \t\n\r")))
11734 (move-marker org-log-note-marker (point))
11735 (setq org-log-note-purpose purpose
11736 org-log-note-state state
11737 org-log-note-previous-state prev-state
11738 org-log-note-how how
11739 org-log-note-extra extra)
11740 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
11742 (defun org-skip-over-state-notes ()
11743 "Skip past the list of State notes in an entry."
11744 (if (looking-at "\n[ \t]*- State") (forward-char 1))
11745 (while (looking-at "[ \t]*- State")
11746 (condition-case nil
11747 (org-next-item)
11748 (error (org-end-of-item)))))
11750 (defun org-add-log-note (&optional purpose)
11751 "Pop up a window for taking a note, and add this note later at point."
11752 (remove-hook 'post-command-hook 'org-add-log-note)
11753 (setq org-log-note-window-configuration (current-window-configuration))
11754 (delete-other-windows)
11755 (move-marker org-log-note-return-to (point))
11756 (switch-to-buffer (marker-buffer org-log-note-marker))
11757 (goto-char org-log-note-marker)
11758 (org-switch-to-buffer-other-window "*Org Note*")
11759 (erase-buffer)
11760 (if (memq org-log-note-how '(time state))
11761 (let (current-prefix-arg) (org-store-log-note))
11762 (let ((org-inhibit-startup t)) (org-mode))
11763 (insert (format "# Insert note for %s.
11764 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
11765 (cond
11766 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11767 ((eq org-log-note-purpose 'done) "closed todo item")
11768 ((eq org-log-note-purpose 'state)
11769 (format "state change from \"%s\" to \"%s\""
11770 (or org-log-note-previous-state "")
11771 (or org-log-note-state "")))
11772 ((eq org-log-note-purpose 'reschedule)
11773 "rescheduling")
11774 ((eq org-log-note-purpose 'delschedule)
11775 "no longer scheduled")
11776 ((eq org-log-note-purpose 'redeadline)
11777 "changing deadline")
11778 ((eq org-log-note-purpose 'deldeadline)
11779 "removing deadline")
11780 ((eq org-log-note-purpose 'refile)
11781 "refiling")
11782 ((eq org-log-note-purpose 'note)
11783 "this entry")
11784 (t (error "This should not happen")))))
11785 (if org-log-note-extra (insert org-log-note-extra))
11786 (org-set-local 'org-finish-function 'org-store-log-note)))
11788 (defvar org-note-abort nil) ; dynamically scoped
11789 (defun org-store-log-note ()
11790 "Finish taking a log note, and insert it to where it belongs."
11791 (let ((txt (buffer-string))
11792 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11793 lines ind)
11794 (kill-buffer (current-buffer))
11795 (while (string-match "\\`#.*\n[ \t\n]*" txt)
11796 (setq txt (replace-match "" t t txt)))
11797 (if (string-match "\\s-+\\'" txt)
11798 (setq txt (replace-match "" t t txt)))
11799 (setq lines (org-split-string txt "\n"))
11800 (when (and note (string-match "\\S-" note))
11801 (setq note
11802 (org-replace-escapes
11803 note
11804 (list (cons "%u" (user-login-name))
11805 (cons "%U" user-full-name)
11806 (cons "%t" (format-time-string
11807 (org-time-stamp-format 'long 'inactive)
11808 (current-time)))
11809 (cons "%T" (format-time-string
11810 (org-time-stamp-format 'long nil)
11811 (current-time)))
11812 (cons "%s" (if org-log-note-state
11813 (concat "\"" org-log-note-state "\"")
11814 ""))
11815 (cons "%S" (if org-log-note-previous-state
11816 (concat "\"" org-log-note-previous-state "\"")
11817 "\"\"")))))
11818 (if lines (setq note (concat note " \\\\")))
11819 (push note lines))
11820 (when (or current-prefix-arg org-note-abort)
11821 (when org-log-into-drawer
11822 (org-remove-empty-drawer-at
11823 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
11824 org-log-note-marker))
11825 (setq lines nil))
11826 (when lines
11827 (with-current-buffer (marker-buffer org-log-note-marker)
11828 (save-excursion
11829 (goto-char org-log-note-marker)
11830 (move-marker org-log-note-marker nil)
11831 (end-of-line 1)
11832 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
11833 (insert "- " (pop lines))
11834 (org-indent-line-function)
11835 (beginning-of-line 1)
11836 (looking-at "[ \t]*")
11837 (setq ind (concat (match-string 0) " "))
11838 (end-of-line 1)
11839 (while lines (insert "\n" ind (pop lines)))
11840 (message "Note stored")
11841 (org-back-to-heading t)
11842 (org-cycle-hide-drawers 'children)))))
11843 (set-window-configuration org-log-note-window-configuration)
11844 (with-current-buffer (marker-buffer org-log-note-return-to)
11845 (goto-char org-log-note-return-to))
11846 (move-marker org-log-note-return-to nil)
11847 (and org-log-post-message (message "%s" org-log-post-message)))
11849 (defun org-remove-empty-drawer-at (drawer pos)
11850 "Remove an empty drawer DRAWER at position POS.
11851 POS may also be a marker."
11852 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
11853 (save-excursion
11854 (save-restriction
11855 (widen)
11856 (goto-char pos)
11857 (if (org-in-regexp
11858 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
11859 (replace-match ""))))))
11861 (defun org-sparse-tree (&optional arg)
11862 "Create a sparse tree, prompt for the details.
11863 This command can create sparse trees. You first need to select the type
11864 of match used to create the tree:
11866 t Show all TODO entries.
11867 T Show entries with a specific TODO keyword.
11868 m Show entries selected by a tags/property match.
11869 p Enter a property name and its value (both with completion on existing
11870 names/values) and show entries with that property.
11871 / Show entries matching a regular expression (`r' can be used as well)
11872 d Show deadlines due within `org-deadline-warning-days'.
11873 b Show deadlines and scheduled items before a date.
11874 a Show deadlines and scheduled items after a date."
11875 (interactive "P")
11876 (let (ans kwd value)
11877 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty [d]eadlines\n [b]efore-date [a]fter-date")
11878 (setq ans (read-char-exclusive))
11879 (cond
11880 ((equal ans ?d)
11881 (call-interactively 'org-check-deadlines))
11882 ((equal ans ?b)
11883 (call-interactively 'org-check-before-date))
11884 ((equal ans ?a)
11885 (call-interactively 'org-check-after-date))
11886 ((equal ans ?t)
11887 (org-show-todo-tree nil))
11888 ((equal ans ?T)
11889 (org-show-todo-tree '(4)))
11890 ((member ans '(?T ?m))
11891 (call-interactively 'org-match-sparse-tree))
11892 ((member ans '(?p ?P))
11893 (setq kwd (org-icompleting-read "Property: "
11894 (mapcar 'list (org-buffer-property-keys))))
11895 (setq value (org-icompleting-read "Value: "
11896 (mapcar 'list (org-property-values kwd))))
11897 (unless (string-match "\\`{.*}\\'" value)
11898 (setq value (concat "\"" value "\"")))
11899 (org-match-sparse-tree arg (concat kwd "=" value)))
11900 ((member ans '(?r ?R ?/))
11901 (call-interactively 'org-occur))
11902 (t (error "No such sparse tree command \"%c\"" ans)))))
11904 (defvar org-occur-highlights nil
11905 "List of overlays used for occur matches.")
11906 (make-variable-buffer-local 'org-occur-highlights)
11907 (defvar org-occur-parameters nil
11908 "Parameters of the active org-occur calls.
11909 This is a list, each call to org-occur pushes as cons cell,
11910 containing the regular expression and the callback, onto the list.
11911 The list can contain several entries if `org-occur' has been called
11912 several time with the KEEP-PREVIOUS argument. Otherwise, this list
11913 will only contain one set of parameters. When the highlights are
11914 removed (for example with `C-c C-c', or with the next edit (depending
11915 on `org-remove-highlights-with-change'), this variable is emptied
11916 as well.")
11917 (make-variable-buffer-local 'org-occur-parameters)
11919 (defun org-occur (regexp &optional keep-previous callback)
11920 "Make a compact tree which shows all matches of REGEXP.
11921 The tree will show the lines where the regexp matches, and all higher
11922 headlines above the match. It will also show the heading after the match,
11923 to make sure editing the matching entry is easy.
11924 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11925 call to `org-occur' will be kept, to allow stacking of calls to this
11926 command.
11927 If CALLBACK is non-nil, it is a function which is called to confirm
11928 that the match should indeed be shown."
11929 (interactive "sRegexp: \nP")
11930 (when (equal regexp "")
11931 (error "Regexp cannot be empty"))
11932 (unless keep-previous
11933 (org-remove-occur-highlights nil nil t))
11934 (push (cons regexp callback) org-occur-parameters)
11935 (let ((cnt 0))
11936 (save-excursion
11937 (goto-char (point-min))
11938 (if (or (not keep-previous) ; do not want to keep
11939 (not org-occur-highlights)) ; no previous matches
11940 ;; hide everything
11941 (org-overview))
11942 (while (re-search-forward regexp nil t)
11943 (when (or (not callback)
11944 (save-match-data (funcall callback)))
11945 (setq cnt (1+ cnt))
11946 (when org-highlight-sparse-tree-matches
11947 (org-highlight-new-match (match-beginning 0) (match-end 0)))
11948 (org-show-context 'occur-tree))))
11949 (when org-remove-highlights-with-change
11950 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11951 nil 'local))
11952 (unless org-sparse-tree-open-archived-trees
11953 (org-hide-archived-subtrees (point-min) (point-max)))
11954 (run-hooks 'org-occur-hook)
11955 (if (interactive-p)
11956 (message "%d match(es) for regexp %s" cnt regexp))
11957 cnt))
11959 (defun org-show-context (&optional key)
11960 "Make sure point and context are visible.
11961 How much context is shown depends upon the variables
11962 `org-show-hierarchy-above', `org-show-following-heading'. and
11963 `org-show-siblings'."
11964 (let ((heading-p (org-on-heading-p t))
11965 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11966 (following-p (org-get-alist-option org-show-following-heading key))
11967 (entry-p (org-get-alist-option org-show-entry-below key))
11968 (siblings-p (org-get-alist-option org-show-siblings key)))
11969 (catch 'exit
11970 ;; Show heading or entry text
11971 (if (and heading-p (not entry-p))
11972 (org-flag-heading nil) ; only show the heading
11973 (and (or entry-p (org-invisible-p) (org-invisible-p2))
11974 (org-show-hidden-entry))) ; show entire entry
11975 (when following-p
11976 ;; Show next sibling, or heading below text
11977 (save-excursion
11978 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11979 (org-flag-heading nil))))
11980 (when siblings-p (org-show-siblings))
11981 (when hierarchy-p
11982 ;; show all higher headings, possibly with siblings
11983 (save-excursion
11984 (while (and (condition-case nil
11985 (progn (org-up-heading-all 1) t)
11986 (error nil))
11987 (not (bobp)))
11988 (org-flag-heading nil)
11989 (when siblings-p (org-show-siblings))))))))
11991 (defvar org-reveal-start-hook nil
11992 "Hook run before revealing a location.")
11994 (defun org-reveal (&optional siblings)
11995 "Show current entry, hierarchy above it, and the following headline.
11996 This can be used to show a consistent set of context around locations
11997 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
11998 not t for the search context.
12000 With optional argument SIBLINGS, on each level of the hierarchy all
12001 siblings are shown. This repairs the tree structure to what it would
12002 look like when opened with hierarchical calls to `org-cycle'.
12003 With double optional argument `C-u C-u', go to the parent and show the
12004 entire tree."
12005 (interactive "P")
12006 (run-hooks 'org-reveal-start-hook)
12007 (let ((org-show-hierarchy-above t)
12008 (org-show-following-heading t)
12009 (org-show-siblings (if siblings t org-show-siblings)))
12010 (org-show-context nil))
12011 (when (equal siblings '(16))
12012 (save-excursion
12013 (when (org-up-heading-safe)
12014 (org-show-subtree)
12015 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12017 (defun org-highlight-new-match (beg end)
12018 "Highlight from BEG to END and mark the highlight is an occur headline."
12019 (let ((ov (make-overlay beg end)))
12020 (overlay-put ov 'face 'secondary-selection)
12021 (push ov org-occur-highlights)))
12023 (defun org-remove-occur-highlights (&optional beg end noremove)
12024 "Remove the occur highlights from the buffer.
12025 BEG and END are ignored. If NOREMOVE is nil, remove this function
12026 from the `before-change-functions' in the current buffer."
12027 (interactive)
12028 (unless org-inhibit-highlight-removal
12029 (mapc 'delete-overlay org-occur-highlights)
12030 (setq org-occur-highlights nil)
12031 (setq org-occur-parameters nil)
12032 (unless noremove
12033 (remove-hook 'before-change-functions
12034 'org-remove-occur-highlights 'local))))
12036 ;;;; Priorities
12038 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12039 "Regular expression matching the priority indicator.")
12041 (defvar org-remove-priority-next-time nil)
12043 (defun org-priority-up ()
12044 "Increase the priority of the current item."
12045 (interactive)
12046 (org-priority 'up))
12048 (defun org-priority-down ()
12049 "Decrease the priority of the current item."
12050 (interactive)
12051 (org-priority 'down))
12053 (defun org-priority (&optional action)
12054 "Change the priority of an item by ARG.
12055 ACTION can be `set', `up', `down', or a character."
12056 (interactive)
12057 (unless org-enable-priority-commands
12058 (error "Priority commands are disabled"))
12059 (setq action (or action 'set))
12060 (let (current new news have remove)
12061 (save-excursion
12062 (org-back-to-heading t)
12063 (if (looking-at org-priority-regexp)
12064 (setq current (string-to-char (match-string 2))
12065 have t)
12066 (setq current org-default-priority))
12067 (cond
12068 ((eq action 'remove)
12069 (setq remove t new ?\ ))
12070 ((or (eq action 'set)
12071 (if (featurep 'xemacs) (characterp action) (integerp action)))
12072 (if (not (eq action 'set))
12073 (setq new action)
12074 (message "Priority %c-%c, SPC to remove: "
12075 org-highest-priority org-lowest-priority)
12076 (setq new (read-char-exclusive)))
12077 (if (and (= (upcase org-highest-priority) org-highest-priority)
12078 (= (upcase org-lowest-priority) org-lowest-priority))
12079 (setq new (upcase new)))
12080 (cond ((equal new ?\ ) (setq remove t))
12081 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12082 (error "Priority must be between `%c' and `%c'"
12083 org-highest-priority org-lowest-priority))))
12084 ((eq action 'up)
12085 (if (and (not have) (eq last-command this-command))
12086 (setq new org-lowest-priority)
12087 (setq new (if (and org-priority-start-cycle-with-default (not have))
12088 org-default-priority (1- current)))))
12089 ((eq action 'down)
12090 (if (and (not have) (eq last-command this-command))
12091 (setq new org-highest-priority)
12092 (setq new (if (and org-priority-start-cycle-with-default (not have))
12093 org-default-priority (1+ current)))))
12094 (t (error "Invalid action")))
12095 (if (or (< (upcase new) org-highest-priority)
12096 (> (upcase new) org-lowest-priority))
12097 (setq remove t))
12098 (setq news (format "%c" new))
12099 (if have
12100 (if remove
12101 (replace-match "" t t nil 1)
12102 (replace-match news t t nil 2))
12103 (if remove
12104 (error "No priority cookie found in line")
12105 (let ((case-fold-search nil))
12106 (looking-at org-todo-line-regexp))
12107 (if (match-end 2)
12108 (progn
12109 (goto-char (match-end 2))
12110 (insert " [#" news "]"))
12111 (goto-char (match-beginning 3))
12112 (insert "[#" news "] "))))
12113 (org-preserve-lc (org-set-tags nil 'align)))
12114 (if remove
12115 (message "Priority removed")
12116 (message "Priority of current item set to %s" news))))
12118 (defun org-get-priority (s)
12119 "Find priority cookie and return priority."
12120 (save-match-data
12121 (if (not (string-match org-priority-regexp s))
12122 (* 1000 (- org-lowest-priority org-default-priority))
12123 (* 1000 (- org-lowest-priority
12124 (string-to-char (match-string 2 s)))))))
12126 ;;;; Tags
12128 (defvar org-agenda-archives-mode)
12129 (defvar org-map-continue-from nil
12130 "Position from where mapping should continue.
12131 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
12133 (defvar org-scanner-tags nil
12134 "The current tag list while the tags scanner is running.")
12135 (defvar org-trust-scanner-tags nil
12136 "Should `org-get-tags-at' use the tags fro the scanner.
12137 This is for internal dynamical scoping only.
12138 When this is non-nil, the function `org-get-tags-at' will return the value
12139 of `org-scanner-tags' instead of building the list by itself. This
12140 can lead to large speed-ups when the tags scanner is used in a file with
12141 many entries, and when the list of tags is retrieved, for example to
12142 obtain a list of properties. Building the tags list for each entry in such
12143 a file becomes an N^2 operation - but with this variable set, it scales
12144 as N.")
12146 (defun org-scan-tags (action matcher &optional todo-only)
12147 "Scan headline tags with inheritance and produce output ACTION.
12149 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12150 or `agenda' to produce an entry list for an agenda view. It can also be
12151 a Lisp form or a function that should be called at each matched headline, in
12152 this case the return value is a list of all return values from these calls.
12154 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12155 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12156 only lines with a TODO keyword are included in the output."
12157 (require 'org-agenda)
12158 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
12159 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12160 (org-re
12161 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
12162 (props (list 'face 'default
12163 'done-face 'org-agenda-done
12164 'undone-face 'default
12165 'mouse-face 'highlight
12166 'org-not-done-regexp org-not-done-regexp
12167 'org-todo-regexp org-todo-regexp
12168 'help-echo
12169 (format "mouse-2 or RET jump to org file %s"
12170 (abbreviate-file-name
12171 (or (buffer-file-name (buffer-base-buffer))
12172 (buffer-name (buffer-base-buffer)))))))
12173 (case-fold-search nil)
12174 (org-map-continue-from nil)
12175 lspos tags tags-list
12176 (tags-alist (list (cons 0 org-file-tags)))
12177 (llast 0) rtn rtn1 level category i txt
12178 todo marker entry priority)
12179 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12180 (setq action (list 'lambda nil action)))
12181 (save-excursion
12182 (goto-char (point-min))
12183 (when (eq action 'sparse-tree)
12184 (org-overview)
12185 (org-remove-occur-highlights))
12186 (while (re-search-forward re nil t)
12187 (catch :skip
12188 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12189 tags (if (match-end 4) (org-match-string-no-properties 4)))
12190 (goto-char (setq lspos (match-beginning 0)))
12191 (setq level (org-reduced-level (funcall outline-level))
12192 category (org-get-category))
12193 (setq i llast llast level)
12194 ;; remove tag lists from same and sublevels
12195 (while (>= i level)
12196 (when (setq entry (assoc i tags-alist))
12197 (setq tags-alist (delete entry tags-alist)))
12198 (setq i (1- i)))
12199 ;; add the next tags
12200 (when tags
12201 (setq tags (org-split-string tags ":")
12202 tags-alist
12203 (cons (cons level tags) tags-alist)))
12204 ;; compile tags for current headline
12205 (setq tags-list
12206 (if org-use-tag-inheritance
12207 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12208 tags)
12209 org-scanner-tags tags-list)
12210 (when org-use-tag-inheritance
12211 (setcdr (car tags-alist)
12212 (mapcar (lambda (x)
12213 (setq x (copy-sequence x))
12214 (org-add-prop-inherited x))
12215 (cdar tags-alist))))
12216 (when (and tags org-use-tag-inheritance
12217 (or (not (eq t org-use-tag-inheritance))
12218 org-tags-exclude-from-inheritance))
12219 ;; selective inheritance, remove uninherited ones
12220 (setcdr (car tags-alist)
12221 (org-remove-uniherited-tags (cdar tags-alist))))
12222 (when (and (or (not todo-only)
12223 (and (member todo org-not-done-keywords)
12224 (or (not org-agenda-tags-todo-honor-ignore-options)
12225 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12226 (let ((case-fold-search t)) (eval matcher))
12228 (not (member org-archive-tag tags-list))
12229 ;; we have an archive tag, should we use this anyway?
12230 (or (not org-agenda-skip-archived-trees)
12231 (and (eq action 'agenda) org-agenda-archives-mode))))
12232 (unless (eq action 'sparse-tree) (org-agenda-skip))
12234 ;; select this headline
12236 (cond
12237 ((eq action 'sparse-tree)
12238 (and org-highlight-sparse-tree-matches
12239 (org-get-heading) (match-end 0)
12240 (org-highlight-new-match
12241 (match-beginning 0) (match-beginning 1)))
12242 (org-show-context 'tags-tree))
12243 ((eq action 'agenda)
12244 (setq txt (org-format-agenda-item
12246 (concat
12247 (if (eq org-tags-match-list-sublevels 'indented)
12248 (make-string (1- level) ?.) "")
12249 (org-get-heading))
12250 category
12251 tags-list
12253 priority (org-get-priority txt))
12254 (goto-char lspos)
12255 (setq marker (org-agenda-new-marker))
12256 (org-add-props txt props
12257 'org-marker marker 'org-hd-marker marker 'org-category category
12258 'todo-state todo
12259 'priority priority 'type "tagsmatch")
12260 (push txt rtn))
12261 ((functionp action)
12262 (setq org-map-continue-from nil)
12263 (save-excursion
12264 (setq rtn1 (funcall action))
12265 (push rtn1 rtn)))
12266 (t (error "Invalid action")))
12268 ;; if we are to skip sublevels, jump to end of subtree
12269 (unless org-tags-match-list-sublevels
12270 (org-end-of-subtree t)
12271 (backward-char 1))))
12272 ;; Get the correct position from where to continue
12273 (if org-map-continue-from
12274 (goto-char org-map-continue-from)
12275 (and (= (point) lspos) (end-of-line 1)))))
12276 (when (and (eq action 'sparse-tree)
12277 (not org-sparse-tree-open-archived-trees))
12278 (org-hide-archived-subtrees (point-min) (point-max)))
12279 (nreverse rtn)))
12281 (defun org-remove-uniherited-tags (tags)
12282 "Remove all tags that are not inherited from the list TAGS."
12283 (cond
12284 ((eq org-use-tag-inheritance t)
12285 (if org-tags-exclude-from-inheritance
12286 (org-delete-all org-tags-exclude-from-inheritance tags)
12287 tags))
12288 ((not org-use-tag-inheritance) nil)
12289 ((stringp org-use-tag-inheritance)
12290 (delq nil (mapcar
12291 (lambda (x)
12292 (if (and (string-match org-use-tag-inheritance x)
12293 (not (member x org-tags-exclude-from-inheritance)))
12294 x nil))
12295 tags)))
12296 ((listp org-use-tag-inheritance)
12297 (delq nil (mapcar
12298 (lambda (x)
12299 (if (member x org-use-tag-inheritance) x nil))
12300 tags)))))
12302 (defvar todo-only) ;; dynamically scoped
12304 (defun org-match-sparse-tree (&optional todo-only match)
12305 "Create a sparse tree according to tags string MATCH.
12306 MATCH can contain positive and negative selection of tags, like
12307 \"+WORK+URGENT-WITHBOSS\".
12308 If optional argument TODO-ONLY is non-nil, only select lines that are
12309 also TODO lines."
12310 (interactive "P")
12311 (org-prepare-agenda-buffers (list (current-buffer)))
12312 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12314 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12316 (defvar org-cached-props nil)
12317 (defun org-cached-entry-get (pom property)
12318 (if (or (eq t org-use-property-inheritance)
12319 (and (stringp org-use-property-inheritance)
12320 (string-match org-use-property-inheritance property))
12321 (and (listp org-use-property-inheritance)
12322 (member property org-use-property-inheritance)))
12323 ;; Caching is not possible, check it directly
12324 (org-entry-get pom property 'inherit)
12325 ;; Get all properties, so that we can do complicated checks easily
12326 (cdr (assoc property (or org-cached-props
12327 (setq org-cached-props
12328 (org-entry-properties pom)))))))
12330 (defun org-global-tags-completion-table (&optional files)
12331 "Return the list of all tags in all agenda buffer/files."
12332 (save-excursion
12333 (org-uniquify
12334 (delq nil
12335 (apply 'append
12336 (mapcar
12337 (lambda (file)
12338 (set-buffer (find-file-noselect file))
12339 (append (org-get-buffer-tags)
12340 (mapcar (lambda (x) (if (stringp (car-safe x))
12341 (list (car-safe x)) nil))
12342 org-tag-alist)))
12343 (if (and files (car files))
12344 files
12345 (org-agenda-files))))))))
12347 (defun org-make-tags-matcher (match)
12348 "Create the TAGS//TODO matcher form for the selection string MATCH."
12349 ;; todo-only is scoped dynamically into this function, and the function
12350 ;; may change it if the matcher asks for it.
12351 (unless match
12352 ;; Get a new match request, with completion
12353 (let ((org-last-tags-completion-table
12354 (org-global-tags-completion-table)))
12355 (setq match (org-completing-read-no-i
12356 "Match: " 'org-tags-completion-function nil nil nil
12357 'org-tags-history))))
12359 ;; Parse the string and create a lisp form
12360 (let ((match0 match)
12361 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
12362 minus tag mm
12363 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12364 orterms term orlist re-p str-p level-p level-op time-p
12365 prop-p pn pv po cat-p gv rest)
12366 (if (string-match "/+" match)
12367 ;; match contains also a todo-matching request
12368 (progn
12369 (setq tagsmatch (substring match 0 (match-beginning 0))
12370 todomatch (substring match (match-end 0)))
12371 (if (string-match "^!" todomatch)
12372 (setq todo-only t todomatch (substring todomatch 1)))
12373 (if (string-match "^\\s-*$" todomatch)
12374 (setq todomatch nil)))
12375 ;; only matching tags
12376 (setq tagsmatch match todomatch nil))
12378 ;; Make the tags matcher
12379 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12380 (setq tagsmatcher t)
12381 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12382 (while (setq term (pop orterms))
12383 (while (and (equal (substring term -1) "\\") orterms)
12384 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12385 (while (string-match re term)
12386 (setq rest (substring term (match-end 0))
12387 minus (and (match-end 1)
12388 (equal (match-string 1 term) "-"))
12389 tag (match-string 2 term)
12390 re-p (equal (string-to-char tag) ?{)
12391 level-p (match-end 4)
12392 prop-p (match-end 5)
12393 mm (cond
12394 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12395 (level-p
12396 (setq level-op (org-op-to-function (match-string 3 term)))
12397 `(,level-op level ,(string-to-number
12398 (match-string 4 term))))
12399 (prop-p
12400 (setq pn (match-string 5 term)
12401 po (match-string 6 term)
12402 pv (match-string 7 term)
12403 cat-p (equal pn "CATEGORY")
12404 re-p (equal (string-to-char pv) ?{)
12405 str-p (equal (string-to-char pv) ?\")
12406 time-p (save-match-data
12407 (string-match "^\"[[<].*[]>]\"$" pv))
12408 pv (if (or re-p str-p) (substring pv 1 -1) pv))
12409 (if time-p (setq pv (org-matcher-time pv)))
12410 (setq po (org-op-to-function po (if time-p 'time str-p)))
12411 (cond
12412 ((equal pn "CATEGORY")
12413 (setq gv '(get-text-property (point) 'org-category)))
12414 ((equal pn "TODO")
12415 (setq gv 'todo))
12417 (setq gv `(org-cached-entry-get nil ,pn))))
12418 (if re-p
12419 (if (eq po 'org<>)
12420 `(not (string-match ,pv (or ,gv "")))
12421 `(string-match ,pv (or ,gv "")))
12422 (if str-p
12423 `(,po (or ,gv "") ,pv)
12424 `(,po (string-to-number (or ,gv ""))
12425 ,(string-to-number pv) ))))
12426 (t `(member ,tag tags-list)))
12427 mm (if minus (list 'not mm) mm)
12428 term rest)
12429 (push mm tagsmatcher))
12430 (push (if (> (length tagsmatcher) 1)
12431 (cons 'and tagsmatcher)
12432 (car tagsmatcher))
12433 orlist)
12434 (setq tagsmatcher nil))
12435 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
12436 (setq tagsmatcher
12437 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
12438 ;; Make the todo matcher
12439 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
12440 (setq todomatcher t)
12441 (setq orterms (org-split-string todomatch "|") orlist nil)
12442 (while (setq term (pop orterms))
12443 (while (string-match re term)
12444 (setq minus (and (match-end 1)
12445 (equal (match-string 1 term) "-"))
12446 kwd (match-string 2 term)
12447 re-p (equal (string-to-char kwd) ?{)
12448 term (substring term (match-end 0))
12449 mm (if re-p
12450 `(string-match ,(substring kwd 1 -1) todo)
12451 (list 'equal 'todo kwd))
12452 mm (if minus (list 'not mm) mm))
12453 (push mm todomatcher))
12454 (push (if (> (length todomatcher) 1)
12455 (cons 'and todomatcher)
12456 (car todomatcher))
12457 orlist)
12458 (setq todomatcher nil))
12459 (setq todomatcher (if (> (length orlist) 1)
12460 (cons 'or orlist) (car orlist))))
12462 ;; Return the string and lisp forms of the matcher
12463 (setq matcher (if todomatcher
12464 (list 'and tagsmatcher todomatcher)
12465 tagsmatcher))
12466 (cons match0 matcher)))
12468 (defun org-op-to-function (op &optional stringp)
12469 "Turn an operator into the appropriate function."
12470 (setq op
12471 (cond
12472 ((equal op "<" ) '(< string< org-time<))
12473 ((equal op ">" ) '(> org-string> org-time>))
12474 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
12475 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
12476 ((member op '("=" "==")) '(= string= org-time=))
12477 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
12478 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
12480 (defun org<> (a b) (not (= a b)))
12481 (defun org-string<= (a b) (or (string= a b) (string< a b)))
12482 (defun org-string>= (a b) (not (string< a b)))
12483 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
12484 (defun org-string<> (a b) (not (string= a b)))
12485 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
12486 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
12487 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
12488 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
12489 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
12490 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
12491 (defun org-2ft (s)
12492 "Convert S to a floating point time.
12493 If S is already a number, just return it. If it is a string, parse
12494 it as a time string and apply `float-time' to it. If S is nil, just return 0."
12495 (cond
12496 ((numberp s) s)
12497 ((stringp s)
12498 (condition-case nil
12499 (float-time (apply 'encode-time (org-parse-time-string s)))
12500 (error 0.)))
12501 (t 0.)))
12503 (defun org-time-today ()
12504 "Time in seconds today at 0:00.
12505 Returns the float number of seconds since the beginning of the
12506 epoch to the beginning of today (00:00)."
12507 (float-time (apply 'encode-time
12508 (append '(0 0 0) (nthcdr 3 (decode-time))))))
12510 (defun org-matcher-time (s)
12511 "Interpret a time comparison value."
12512 (save-match-data
12513 (cond
12514 ((string= s "<now>") (float-time))
12515 ((string= s "<today>") (org-time-today))
12516 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
12517 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
12518 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
12519 (+ (org-time-today)
12520 (* (string-to-number (match-string 1 s))
12521 (cdr (assoc (match-string 2 s)
12522 '(("d" . 86400.0) ("w" . 604800.0)
12523 ("m" . 2678400.0) ("y" . 31557600.0)))))))
12524 (t (org-2ft s)))))
12526 (defun org-match-any-p (re list)
12527 "Does re match any element of list?"
12528 (setq list (mapcar (lambda (x) (string-match re x)) list))
12529 (delq nil list))
12531 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
12532 (defvar org-tags-overlay (make-overlay 1 1))
12533 (org-detach-overlay org-tags-overlay)
12535 (defun org-get-local-tags-at (&optional pos)
12536 "Get a list of tags defined in the current headline."
12537 (org-get-tags-at pos 'local))
12539 (defun org-get-local-tags ()
12540 "Get a list of tags defined in the current headline."
12541 (org-get-tags-at nil 'local))
12543 (defun org-get-tags-at (&optional pos local)
12544 "Get a list of all headline tags applicable at POS.
12545 POS defaults to point. If tags are inherited, the list contains
12546 the targets in the same sequence as the headlines appear, i.e.
12547 the tags of the current headline come last.
12548 When LOCAL is non-nil, only return tags from the current headline,
12549 ignore inherited ones."
12550 (interactive)
12551 (if (and org-trust-scanner-tags
12552 (or (not pos) (equal pos (point)))
12553 (not local))
12554 org-scanner-tags
12555 (let (tags ltags lastpos parent)
12556 (save-excursion
12557 (save-restriction
12558 (widen)
12559 (goto-char (or pos (point)))
12560 (save-match-data
12561 (catch 'done
12562 (condition-case nil
12563 (progn
12564 (org-back-to-heading t)
12565 (while (not (equal lastpos (point)))
12566 (setq lastpos (point))
12567 (when (looking-at
12568 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
12569 (setq ltags (org-split-string
12570 (org-match-string-no-properties 1) ":"))
12571 (when parent
12572 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
12573 (setq tags (append
12574 (if parent
12575 (org-remove-uniherited-tags ltags)
12576 ltags)
12577 tags)))
12578 (or org-use-tag-inheritance (throw 'done t))
12579 (if local (throw 'done t))
12580 (or (org-up-heading-safe) (error nil))
12581 (setq parent t)))
12582 (error nil)))))
12583 (append (org-remove-uniherited-tags org-file-tags) tags)))))
12585 (defun org-add-prop-inherited (s)
12586 (add-text-properties 0 (length s) '(inherited t) s)
12589 (defun org-toggle-tag (tag &optional onoff)
12590 "Toggle the tag TAG for the current line.
12591 If ONOFF is `on' or `off', don't toggle but set to this state."
12592 (let (res current)
12593 (save-excursion
12594 (org-back-to-heading t)
12595 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
12596 (point-at-eol) t)
12597 (progn
12598 (setq current (match-string 1))
12599 (replace-match ""))
12600 (setq current ""))
12601 (setq current (nreverse (org-split-string current ":")))
12602 (cond
12603 ((eq onoff 'on)
12604 (setq res t)
12605 (or (member tag current) (push tag current)))
12606 ((eq onoff 'off)
12607 (or (not (member tag current)) (setq current (delete tag current))))
12608 (t (if (member tag current)
12609 (setq current (delete tag current))
12610 (setq res t)
12611 (push tag current))))
12612 (end-of-line 1)
12613 (if current
12614 (progn
12615 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
12616 (org-set-tags nil t))
12617 (delete-horizontal-space))
12618 (run-hooks 'org-after-tags-change-hook))
12619 res))
12621 (defun org-align-tags-here (to-col)
12622 ;; Assumes that this is a headline
12623 (let ((pos (point)) (col (current-column)) ncol tags-l p)
12624 (beginning-of-line 1)
12625 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12626 (< pos (match-beginning 2)))
12627 (progn
12628 (setq tags-l (- (match-end 2) (match-beginning 2)))
12629 (goto-char (match-beginning 1))
12630 (insert " ")
12631 (delete-region (point) (1+ (match-beginning 2)))
12632 (setq ncol (max (1+ (current-column))
12633 (1+ col)
12634 (if (> to-col 0)
12635 to-col
12636 (- (abs to-col) tags-l))))
12637 (setq p (point))
12638 (insert (make-string (- ncol (current-column)) ?\ ))
12639 (setq ncol (current-column))
12640 (when indent-tabs-mode (tabify p (point-at-eol)))
12641 (org-move-to-column (min ncol col) t))
12642 (goto-char pos))))
12644 (defun org-set-tags-command (&optional arg just-align)
12645 "Call the set-tags command for the current entry."
12646 (interactive "P")
12647 (if (org-on-heading-p)
12648 (org-set-tags arg just-align)
12649 (save-excursion
12650 (org-back-to-heading t)
12651 (org-set-tags arg just-align))))
12653 (defun org-set-tags-to (data)
12654 "Set the tags of the current entry to DATA, replacing the current tags.
12655 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
12656 If DATA is nil or the empty string, any tags will be removed."
12657 (interactive "sTags: ")
12658 (setq data
12659 (cond
12660 ((eq data nil) "")
12661 ((equal data "") "")
12662 ((stringp data)
12663 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
12664 ":"))
12665 ((listp data)
12666 (concat ":" (mapconcat 'identity data ":") ":"))
12667 (t nil)))
12668 (when data
12669 (save-excursion
12670 (org-back-to-heading t)
12671 (when (looking-at org-complex-heading-regexp)
12672 (if (match-end 5)
12673 (progn
12674 (goto-char (match-beginning 5))
12675 (insert data)
12676 (delete-region (point) (point-at-eol))
12677 (org-set-tags nil 'align))
12678 (goto-char (point-at-eol))
12679 (insert " " data)
12680 (org-set-tags nil 'align)))
12681 (beginning-of-line 1)
12682 (if (looking-at ".*?\\([ \t]+\\)$")
12683 (delete-region (match-beginning 1) (match-end 1))))))
12685 (defun org-align-all-tags ()
12686 "Align the tags i all headings."
12687 (interactive)
12688 (save-excursion
12689 (or (ignore-errors (org-back-to-heading t))
12690 (outline-next-heading))
12691 (if (org-on-heading-p)
12692 (org-set-tags t)
12693 (message "No headings"))))
12695 (defun org-set-tags (&optional arg just-align)
12696 "Set the tags for the current headline.
12697 With prefix ARG, realign all tags in headings in the current buffer."
12698 (interactive "P")
12699 (let* ((re (concat "^" outline-regexp))
12700 (current (org-get-tags-string))
12701 (col (current-column))
12702 (org-setting-tags t)
12703 table current-tags inherited-tags ; computed below when needed
12704 tags p0 c0 c1 rpl)
12705 (if arg
12706 (save-excursion
12707 (goto-char (point-min))
12708 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12709 (while (re-search-forward re nil t)
12710 (org-set-tags nil t)
12711 (end-of-line 1)))
12712 (message "All tags realigned to column %d" org-tags-column))
12713 (if just-align
12714 (setq tags current)
12715 ;; Get a new set of tags from the user
12716 (save-excursion
12717 (setq table (append org-tag-persistent-alist
12718 (or org-tag-alist (org-get-buffer-tags))
12719 (and org-complete-tags-always-offer-all-agenda-tags
12720 (org-global-tags-completion-table (org-agenda-files))))
12721 org-last-tags-completion-table table
12722 current-tags (org-split-string current ":")
12723 inherited-tags (nreverse
12724 (nthcdr (length current-tags)
12725 (nreverse (org-get-tags-at))))
12726 tags
12727 (if (or (eq t org-use-fast-tag-selection)
12728 (and org-use-fast-tag-selection
12729 (delq nil (mapcar 'cdr table))))
12730 (org-fast-tag-selection
12731 current-tags inherited-tags table
12732 (if org-fast-tag-selection-include-todo org-todo-key-alist))
12733 (let ((org-add-colon-after-tag-completion t))
12734 (org-trim
12735 (org-without-partial-completion
12736 (org-icompleting-read "Tags: " 'org-tags-completion-function
12737 nil nil current 'org-tags-history)))))))
12738 (while (string-match "[-+&]+" tags)
12739 ;; No boolean logic, just a list
12740 (setq tags (replace-match ":" t t tags))))
12742 (if org-tags-sort-function
12743 (setq tags (mapconcat 'identity
12744 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
12745 org-tags-sort-function) ":")))
12747 (if (string-match "\\`[\t ]*\\'" tags)
12748 (setq tags "")
12749 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
12750 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
12752 ;; Insert new tags at the correct column
12753 (beginning-of-line 1)
12754 (cond
12755 ((and (equal current "") (equal tags "")))
12756 ((re-search-forward
12757 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
12758 (point-at-eol) t)
12759 (if (equal tags "")
12760 (setq rpl "")
12761 (goto-char (match-beginning 0))
12762 (setq c0 (current-column) p0 (if (equal (char-before) ?*)
12763 (1+ (point)) (point))
12764 c1 (max (1+ c0) (if (> org-tags-column 0)
12765 org-tags-column
12766 (- (- org-tags-column) (length tags))))
12767 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
12768 (replace-match rpl t t)
12769 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
12770 tags)
12771 (t (error "Tags alignment failed")))
12772 (org-move-to-column col)
12773 (unless just-align
12774 (run-hooks 'org-after-tags-change-hook)))))
12776 (defun org-change-tag-in-region (beg end tag off)
12777 "Add or remove TAG for each entry in the region.
12778 This works in the agenda, and also in an org-mode buffer."
12779 (interactive
12780 (list (region-beginning) (region-end)
12781 (let ((org-last-tags-completion-table
12782 (if (org-mode-p)
12783 (org-get-buffer-tags)
12784 (org-global-tags-completion-table))))
12785 (org-icompleting-read
12786 "Tag: " 'org-tags-completion-function nil nil nil
12787 'org-tags-history))
12788 (progn
12789 (message "[s]et or [r]emove? ")
12790 (equal (read-char-exclusive) ?r))))
12791 (if (fboundp 'deactivate-mark) (deactivate-mark))
12792 (let ((agendap (equal major-mode 'org-agenda-mode))
12793 l1 l2 m buf pos newhead (cnt 0))
12794 (goto-char end)
12795 (setq l2 (1- (org-current-line)))
12796 (goto-char beg)
12797 (setq l1 (org-current-line))
12798 (loop for l from l1 to l2 do
12799 (org-goto-line l)
12800 (setq m (get-text-property (point) 'org-hd-marker))
12801 (when (or (and (org-mode-p) (org-on-heading-p))
12802 (and agendap m))
12803 (setq buf (if agendap (marker-buffer m) (current-buffer))
12804 pos (if agendap m (point)))
12805 (with-current-buffer buf
12806 (save-excursion
12807 (save-restriction
12808 (goto-char pos)
12809 (setq cnt (1+ cnt))
12810 (org-toggle-tag tag (if off 'off 'on))
12811 (setq newhead (org-get-heading)))))
12812 (and agendap (org-agenda-change-all-lines newhead m))))
12813 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
12815 (defun org-tags-completion-function (string predicate &optional flag)
12816 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
12817 (confirm (lambda (x) (stringp (car x)))))
12818 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
12819 (setq s1 (match-string 1 string)
12820 s2 (match-string 2 string))
12821 (setq s1 "" s2 string))
12822 (cond
12823 ((eq flag nil)
12824 ;; try completion
12825 (setq rtn (try-completion s2 ctable confirm))
12826 (if (stringp rtn)
12827 (setq rtn
12828 (concat s1 s2 (substring rtn (length s2))
12829 (if (and org-add-colon-after-tag-completion
12830 (assoc rtn ctable))
12831 ":" ""))))
12832 rtn)
12833 ((eq flag t)
12834 ;; all-completions
12835 (all-completions s2 ctable confirm)
12837 ((eq flag 'lambda)
12838 ;; exact match?
12839 (assoc s2 ctable)))
12842 (defun org-fast-tag-insert (kwd tags face &optional end)
12843 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
12844 (insert (format "%-12s" (concat kwd ":"))
12845 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
12846 (or end "")))
12848 (defun org-fast-tag-show-exit (flag)
12849 (save-excursion
12850 (org-goto-line 3)
12851 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
12852 (replace-match ""))
12853 (when flag
12854 (end-of-line 1)
12855 (org-move-to-column (- (window-width) 19) t)
12856 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
12858 (defun org-set-current-tags-overlay (current prefix)
12859 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
12860 (if (featurep 'xemacs)
12861 (org-overlay-display org-tags-overlay (concat prefix s)
12862 'secondary-selection)
12863 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
12864 (org-overlay-display org-tags-overlay (concat prefix s)))))
12866 (defvar org-last-tag-selection-key nil)
12867 (defun org-fast-tag-selection (current inherited table &optional todo-table)
12868 "Fast tag selection with single keys.
12869 CURRENT is the current list of tags in the headline, INHERITED is the
12870 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
12871 possibly with grouping information. TODO-TABLE is a similar table with
12872 TODO keywords, should these have keys assigned to them.
12873 If the keys are nil, a-z are automatically assigned.
12874 Returns the new tags string, or nil to not change the current settings."
12875 (let* ((fulltable (append table todo-table))
12876 (maxlen (apply 'max (mapcar
12877 (lambda (x)
12878 (if (stringp (car x)) (string-width (car x)) 0))
12879 fulltable)))
12880 (buf (current-buffer))
12881 (expert (eq org-fast-tag-selection-single-key 'expert))
12882 (buffer-tags nil)
12883 (fwidth (+ maxlen 3 1 3))
12884 (ncol (/ (- (window-width) 4) fwidth))
12885 (i-face 'org-done)
12886 (c-face 'org-todo)
12887 tg cnt e c char c1 c2 ntable tbl rtn
12888 ov-start ov-end ov-prefix
12889 (exit-after-next org-fast-tag-selection-single-key)
12890 (done-keywords org-done-keywords)
12891 groups ingroup)
12892 (save-excursion
12893 (beginning-of-line 1)
12894 (if (looking-at
12895 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12896 (setq ov-start (match-beginning 1)
12897 ov-end (match-end 1)
12898 ov-prefix "")
12899 (setq ov-start (1- (point-at-eol))
12900 ov-end (1+ ov-start))
12901 (skip-chars-forward "^\n\r")
12902 (setq ov-prefix
12903 (concat
12904 (buffer-substring (1- (point)) (point))
12905 (if (> (current-column) org-tags-column)
12907 (make-string (- org-tags-column (current-column)) ?\ ))))))
12908 (move-overlay org-tags-overlay ov-start ov-end)
12909 (save-window-excursion
12910 (if expert
12911 (set-buffer (get-buffer-create " *Org tags*"))
12912 (delete-other-windows)
12913 (split-window-vertically)
12914 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
12915 (erase-buffer)
12916 (org-set-local 'org-done-keywords done-keywords)
12917 (org-fast-tag-insert "Inherited" inherited i-face "\n")
12918 (org-fast-tag-insert "Current" current c-face "\n\n")
12919 (org-fast-tag-show-exit exit-after-next)
12920 (org-set-current-tags-overlay current ov-prefix)
12921 (setq tbl fulltable char ?a cnt 0)
12922 (while (setq e (pop tbl))
12923 (cond
12924 ((equal (car e) :startgroup)
12925 (push '() groups) (setq ingroup t)
12926 (when (not (= cnt 0))
12927 (setq cnt 0)
12928 (insert "\n"))
12929 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
12930 ((equal (car e) :endgroup)
12931 (setq ingroup nil cnt 0)
12932 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
12933 ((equal e '(:newline))
12934 (when (not (= cnt 0))
12935 (setq cnt 0)
12936 (insert "\n")
12937 (setq e (car tbl))
12938 (while (equal (car tbl) '(:newline))
12939 (insert "\n")
12940 (setq tbl (cdr tbl)))))
12942 (setq tg (copy-sequence (car e)) c2 nil)
12943 (if (cdr e)
12944 (setq c (cdr e))
12945 ;; automatically assign a character.
12946 (setq c1 (string-to-char
12947 (downcase (substring
12948 tg (if (= (string-to-char tg) ?@) 1 0)))))
12949 (if (or (rassoc c1 ntable) (rassoc c1 table))
12950 (while (or (rassoc char ntable) (rassoc char table))
12951 (setq char (1+ char)))
12952 (setq c2 c1))
12953 (setq c (or c2 char)))
12954 (if ingroup (push tg (car groups)))
12955 (setq tg (org-add-props tg nil 'face
12956 (cond
12957 ((not (assoc tg table))
12958 (org-get-todo-face tg))
12959 ((member tg current) c-face)
12960 ((member tg inherited) i-face)
12961 (t nil))))
12962 (if (and (= cnt 0) (not ingroup)) (insert " "))
12963 (insert "[" c "] " tg (make-string
12964 (- fwidth 4 (length tg)) ?\ ))
12965 (push (cons tg c) ntable)
12966 (when (= (setq cnt (1+ cnt)) ncol)
12967 (insert "\n")
12968 (if ingroup (insert " "))
12969 (setq cnt 0)))))
12970 (setq ntable (nreverse ntable))
12971 (insert "\n")
12972 (goto-char (point-min))
12973 (if (not expert) (org-fit-window-to-buffer))
12974 (setq rtn
12975 (catch 'exit
12976 (while t
12977 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
12978 (if (not groups) "no " "")
12979 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
12980 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12981 (setq org-last-tag-selection-key c)
12982 (cond
12983 ((= c ?\r) (throw 'exit t))
12984 ((= c ?!)
12985 (setq groups (not groups))
12986 (goto-char (point-min))
12987 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12988 ((= c ?\C-c)
12989 (if (not expert)
12990 (org-fast-tag-show-exit
12991 (setq exit-after-next (not exit-after-next)))
12992 (setq expert nil)
12993 (delete-other-windows)
12994 (split-window-vertically)
12995 (org-switch-to-buffer-other-window " *Org tags*")
12996 (org-fit-window-to-buffer)))
12997 ((or (= c ?\C-g)
12998 (and (= c ?q) (not (rassoc c ntable))))
12999 (org-detach-overlay org-tags-overlay)
13000 (setq quit-flag t))
13001 ((= c ?\ )
13002 (setq current nil)
13003 (if exit-after-next (setq exit-after-next 'now)))
13004 ((= c ?\t)
13005 (condition-case nil
13006 (setq tg (org-icompleting-read
13007 "Tag: "
13008 (or buffer-tags
13009 (with-current-buffer buf
13010 (org-get-buffer-tags)))))
13011 (quit (setq tg "")))
13012 (when (string-match "\\S-" tg)
13013 (add-to-list 'buffer-tags (list tg))
13014 (if (member tg current)
13015 (setq current (delete tg current))
13016 (push tg current)))
13017 (if exit-after-next (setq exit-after-next 'now)))
13018 ((setq e (rassoc c todo-table) tg (car e))
13019 (with-current-buffer buf
13020 (save-excursion (org-todo tg)))
13021 (if exit-after-next (setq exit-after-next 'now)))
13022 ((setq e (rassoc c ntable) tg (car e))
13023 (if (member tg current)
13024 (setq current (delete tg current))
13025 (loop for g in groups do
13026 (if (member tg g)
13027 (mapc (lambda (x)
13028 (setq current (delete x current)))
13029 g)))
13030 (push tg current))
13031 (if exit-after-next (setq exit-after-next 'now))))
13033 ;; Create a sorted list
13034 (setq current
13035 (sort current
13036 (lambda (a b)
13037 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13038 (if (eq exit-after-next 'now) (throw 'exit t))
13039 (goto-char (point-min))
13040 (beginning-of-line 2)
13041 (delete-region (point) (point-at-eol))
13042 (org-fast-tag-insert "Current" current c-face)
13043 (org-set-current-tags-overlay current ov-prefix)
13044 (while (re-search-forward
13045 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
13046 (setq tg (match-string 1))
13047 (add-text-properties
13048 (match-beginning 1) (match-end 1)
13049 (list 'face
13050 (cond
13051 ((member tg current) c-face)
13052 ((member tg inherited) i-face)
13053 (t (get-text-property (match-beginning 1) 'face))))))
13054 (goto-char (point-min)))))
13055 (org-detach-overlay org-tags-overlay)
13056 (if rtn
13057 (mapconcat 'identity current ":")
13058 nil))))
13060 (defun org-get-tags-string ()
13061 "Get the TAGS string in the current headline."
13062 (unless (org-on-heading-p t)
13063 (error "Not on a heading"))
13064 (save-excursion
13065 (beginning-of-line 1)
13066 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13067 (org-match-string-no-properties 1)
13068 "")))
13070 (defun org-get-tags ()
13071 "Get the list of tags specified in the current headline."
13072 (org-split-string (org-get-tags-string) ":"))
13074 (defun org-get-buffer-tags ()
13075 "Get a table of all tags used in the buffer, for completion."
13076 (let (tags)
13077 (save-excursion
13078 (goto-char (point-min))
13079 (while (re-search-forward
13080 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
13081 (when (equal (char-after (point-at-bol 0)) ?*)
13082 (mapc (lambda (x) (add-to-list 'tags x))
13083 (org-split-string (org-match-string-no-properties 1) ":")))))
13084 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13085 (mapcar 'list tags)))
13087 ;;;; The mapping API
13089 ;;;###autoload
13090 (defun org-map-entries (func &optional match scope &rest skip)
13091 "Call FUNC at each headline selected by MATCH in SCOPE.
13093 FUNC is a function or a lisp form. The function will be called without
13094 arguments, with the cursor positioned at the beginning of the headline.
13095 The return values of all calls to the function will be collected and
13096 returned as a list.
13098 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13099 does not need to preserve point. After evaluation, the cursor will be
13100 moved to the end of the line (presumably of the headline of the
13101 processed entry) and search continues from there. Under some
13102 circumstances, this may not produce the wanted results. For example,
13103 if you have removed (e.g. archived) the current (sub)tree it could
13104 mean that the next entry will be skipped entirely. In such cases, you
13105 can specify the position from where search should continue by making
13106 FUNC set the variable `org-map-continue-from' to the desired buffer
13107 position.
13109 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13110 Only headlines that are matched by this query will be considered during
13111 the iteration. When MATCH is nil or t, all headlines will be
13112 visited by the iteration.
13114 SCOPE determines the scope of this command. It can be any of:
13116 nil The current buffer, respecting the restriction if any
13117 tree The subtree started with the entry at point
13118 file The current buffer, without restriction
13119 file-with-archives
13120 The current buffer, and any archives associated with it
13121 agenda All agenda files
13122 agenda-with-archives
13123 All agenda files with any archive files associated with them
13124 \(file1 file2 ...)
13125 If this is a list, all files in the list will be scanned
13127 The remaining args are treated as settings for the skipping facilities of
13128 the scanner. The following items can be given here:
13130 archive skip trees with the archive tag.
13131 comment skip trees with the COMMENT keyword
13132 function or Emacs Lisp form:
13133 will be used as value for `org-agenda-skip-function', so whenever
13134 the function returns t, FUNC will not be called for that
13135 entry and search will continue from the point where the
13136 function leaves it.
13138 If your function needs to retrieve the tags including inherited tags
13139 at the *current* entry, you can use the value of the variable
13140 `org-scanner-tags' which will be much faster than getting the value
13141 with `org-get-tags-at'. If your function gets properties with
13142 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13143 to t around the call to `org-entry-properties' to get the same speedup.
13144 Note that if your function moves around to retrieve tags and properties at
13145 a *different* entry, you cannot use these techniques."
13146 (let* ((org-agenda-archives-mode nil) ; just to make sure
13147 (org-agenda-skip-archived-trees (memq 'archive skip))
13148 (org-agenda-skip-comment-trees (memq 'comment skip))
13149 (org-agenda-skip-function
13150 (car (org-delete-all '(comment archive) skip)))
13151 (org-tags-match-list-sublevels t)
13152 matcher file res
13153 org-todo-keywords-for-agenda
13154 org-done-keywords-for-agenda
13155 org-todo-keyword-alist-for-agenda
13156 org-drawers-for-agenda
13157 org-tag-alist-for-agenda)
13159 (cond
13160 ((eq match t) (setq matcher t))
13161 ((eq match nil) (setq matcher t))
13162 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13164 (save-excursion
13165 (save-restriction
13166 (when (eq scope 'tree)
13167 (org-back-to-heading t)
13168 (org-narrow-to-subtree)
13169 (setq scope nil))
13171 (if (not scope)
13172 (progn
13173 (org-prepare-agenda-buffers
13174 (list (buffer-file-name (current-buffer))))
13175 (setq res (org-scan-tags func matcher)))
13176 ;; Get the right scope
13177 (cond
13178 ((and scope (listp scope) (symbolp (car scope)))
13179 (setq scope (eval scope)))
13180 ((eq scope 'agenda)
13181 (setq scope (org-agenda-files t)))
13182 ((eq scope 'agenda-with-archives)
13183 (setq scope (org-agenda-files t))
13184 (setq scope (org-add-archive-files scope)))
13185 ((eq scope 'file)
13186 (setq scope (list (buffer-file-name))))
13187 ((eq scope 'file-with-archives)
13188 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13189 (org-prepare-agenda-buffers scope)
13190 (while (setq file (pop scope))
13191 (with-current-buffer (org-find-base-buffer-visiting file)
13192 (save-excursion
13193 (save-restriction
13194 (widen)
13195 (goto-char (point-min))
13196 (setq res (append res (org-scan-tags func matcher))))))))))
13197 res))
13199 ;;;; Properties
13201 ;;; Setting and retrieving properties
13203 (defconst org-special-properties
13204 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13205 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED")
13206 "The special properties valid in Org-mode.
13208 These are properties that are not defined in the property drawer,
13209 but in some other way.")
13211 (defconst org-default-properties
13212 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13213 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13214 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13215 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13216 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13217 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13218 "Some properties that are used by Org-mode for various purposes.
13219 Being in this list makes sure that they are offered for completion.")
13221 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13222 "Regular expression matching the first line of a property drawer.")
13224 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13225 "Regular expression matching the last line of a property drawer.")
13227 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13228 "Regular expression matching the first line of a property drawer.")
13230 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13231 "Regular expression matching the first line of a property drawer.")
13233 (defconst org-property-drawer-re
13234 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13235 org-property-end-re "\\)\n?")
13236 "Matches an entire property drawer.")
13238 (defconst org-clock-drawer-re
13239 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13240 org-property-end-re "\\)\n?")
13241 "Matches an entire clock drawer.")
13243 (defun org-property-action ()
13244 "Do an action on properties."
13245 (interactive)
13246 (let (c)
13247 (org-at-property-p)
13248 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13249 (setq c (read-char-exclusive))
13250 (cond
13251 ((equal c ?s)
13252 (call-interactively 'org-set-property))
13253 ((equal c ?d)
13254 (call-interactively 'org-delete-property))
13255 ((equal c ?D)
13256 (call-interactively 'org-delete-property-globally))
13257 ((equal c ?c)
13258 (call-interactively 'org-compute-property-at-point))
13259 (t (error "No such property action %c" c)))))
13261 (defun org-set-effort (&optional value)
13262 "Set the effort property of the current entry.
13263 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13264 allowed value."
13265 (interactive "P")
13266 (if (equal value 0) (setq value 10))
13267 (let* ((completion-ignore-case t)
13268 (prop org-effort-property)
13269 (cur (org-entry-get nil prop))
13270 (allowed (org-property-get-allowed-values nil prop 'table))
13271 (existing (mapcar 'list (org-property-values prop)))
13273 (val (cond
13274 ((stringp value) value)
13275 ((and allowed (integerp value))
13276 (or (car (nth (1- value) allowed))
13277 (car (org-last allowed))))
13278 (allowed
13279 (message "Select 1-9,0, [RET%s]: %s"
13280 (if cur (concat "=" cur) "")
13281 (mapconcat 'car allowed " "))
13282 (setq rpl (read-char-exclusive))
13283 (if (equal rpl ?\r)
13285 (setq rpl (- rpl ?0))
13286 (if (equal rpl 0) (setq rpl 10))
13287 (if (and (> rpl 0) (<= rpl (length allowed)))
13288 (car (nth (1- rpl) allowed))
13289 (org-completing-read "Effort: " allowed nil))))
13291 (let (org-completion-use-ido org-completion-use-iswitchb)
13292 (org-completing-read
13293 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13294 (concat "[" cur "]") "")
13295 ": ")
13296 existing nil nil "" nil cur))))))
13297 (unless (equal (org-entry-get nil prop) val)
13298 (org-entry-put nil prop val))
13299 (message "%s is now %s" prop val)))
13301 (defun org-at-property-p ()
13302 "Is cursor inside a property drawer?"
13303 (save-excursion
13304 (beginning-of-line 1)
13305 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13306 (save-match-data ;; Used by calling procedures
13307 (let ((p (point))
13308 (range (unless (org-before-first-heading-p)
13309 (org-get-property-block))))
13310 (and range (<= (car range) p) (< p (cdr range))))))))
13312 (defun org-get-property-block (&optional beg end force)
13313 "Return the (beg . end) range of the body of the property drawer.
13314 BEG and END can be beginning and end of subtree, if not given
13315 they will be found.
13316 If the drawer does not exist and FORCE is non-nil, create the drawer."
13317 (catch 'exit
13318 (save-excursion
13319 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13320 (end (or end (progn (outline-next-heading) (point)))))
13321 (goto-char beg)
13322 (if (re-search-forward org-property-start-re end t)
13323 (setq beg (1+ (match-end 0)))
13324 (if force
13325 (save-excursion
13326 (org-insert-property-drawer)
13327 (setq end (progn (outline-next-heading) (point))))
13328 (throw 'exit nil))
13329 (goto-char beg)
13330 (if (re-search-forward org-property-start-re end t)
13331 (setq beg (1+ (match-end 0)))))
13332 (if (re-search-forward org-property-end-re end t)
13333 (setq end (match-beginning 0))
13334 (or force (throw 'exit nil))
13335 (goto-char beg)
13336 (setq end beg)
13337 (org-indent-line-function)
13338 (insert ":END:\n"))
13339 (cons beg end)))))
13341 (defun org-entry-properties (&optional pom which specific)
13342 "Get all properties of the entry at point-or-marker POM.
13343 This includes the TODO keyword, the tags, time strings for deadline,
13344 scheduled, and clocking, and any additional properties defined in the
13345 entry. The return value is an alist, keys may occur multiple times
13346 if the property key was used several times.
13347 POM may also be nil, in which case the current entry is used.
13348 If WHICH is nil or `all', get all properties. If WHICH is
13349 `special' or `standard', only get that subclass. If WHICH
13350 is a string only get exactly this property. Specific can be a string, the
13351 specific property we are interested in. Specifying it can speed
13352 things up because then unnecessary parsing is avoided."
13353 (setq which (or which 'all))
13354 (org-with-point-at pom
13355 (let ((clockstr (substring org-clock-string 0 -1))
13356 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13357 (case-fold-search nil)
13358 beg end range props sum-props key key1 value string clocksum)
13359 (save-excursion
13360 (when (condition-case nil
13361 (and (org-mode-p) (org-back-to-heading t))
13362 (error nil))
13363 (setq beg (point))
13364 (setq sum-props (get-text-property (point) 'org-summaries))
13365 (setq clocksum (get-text-property (point) :org-clock-minutes))
13366 (outline-next-heading)
13367 (setq end (point))
13368 (when (memq which '(all special))
13369 ;; Get the special properties, like TODO and tags
13370 (goto-char beg)
13371 (when (and (or (not specific) (string= specific "TODO"))
13372 (looking-at org-todo-line-regexp) (match-end 2))
13373 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13374 (when (and (or (not specific) (string= specific "PRIORITY"))
13375 (looking-at org-priority-regexp))
13376 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13377 (when (and (or (not specific) (string= specific "TAGS"))
13378 (setq value (org-get-tags-string))
13379 (string-match "\\S-" value))
13380 (push (cons "TAGS" value) props))
13381 (when (and (or (not specific) (string= specific "ALLTAGS"))
13382 (setq value (org-get-tags-at)))
13383 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
13384 ":"))
13385 props))
13386 (when (or (not specific) (string= specific "BLOCKED"))
13387 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
13388 (when (or (not specific)
13389 (member specific
13390 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
13391 "TIMESTAMP" "TIMESTAMP_IA")))
13392 (while (re-search-forward org-maybe-keyword-time-regexp end t)
13393 (setq key (if (match-end 1)
13394 (substring (org-match-string-no-properties 1)
13395 0 -1))
13396 string (if (equal key clockstr)
13397 (org-no-properties
13398 (org-trim
13399 (buffer-substring
13400 (match-beginning 3) (goto-char
13401 (point-at-eol)))))
13402 (substring (org-match-string-no-properties 3)
13403 1 -1)))
13404 ;; Get the correct property name from the key. This is
13405 ;; necessary if the user has configured time keywords.
13406 (setq key1 (concat key ":"))
13407 (cond
13408 ((not key)
13409 (setq key
13410 (if (= (char-after (match-beginning 3)) ?\[)
13411 "TIMESTAMP_IA" "TIMESTAMP")))
13412 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
13413 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
13414 ((equal key1 org-closed-string) (setq key "CLOSED"))
13415 ((equal key1 org-clock-string) (setq key "CLOCK")))
13416 (when (or (equal key "CLOCK") (not (assoc key props)))
13417 (push (cons key string) props))))
13420 (when (memq which '(all standard))
13421 ;; Get the standard properties, like :PROP: ...
13422 (setq range (org-get-property-block beg end))
13423 (when range
13424 (goto-char (car range))
13425 (while (re-search-forward
13426 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
13427 (cdr range) t)
13428 (setq key (org-match-string-no-properties 1)
13429 value (org-trim (or (org-match-string-no-properties 2) "")))
13430 (unless (member key excluded)
13431 (push (cons key (or value "")) props)))))
13432 (if clocksum
13433 (push (cons "CLOCKSUM"
13434 (org-columns-number-to-string (/ (float clocksum) 60.)
13435 'add_times))
13436 props))
13437 (unless (assoc "CATEGORY" props)
13438 (setq value (or (org-get-category)
13439 (progn (org-refresh-category-properties)
13440 (org-get-category))))
13441 (push (cons "CATEGORY" value) props))
13442 (append sum-props (nreverse props)))))))
13444 (defun org-entry-get (pom property &optional inherit literal-nil)
13445 "Get value of PROPERTY for entry at point-or-marker POM.
13446 If INHERIT is non-nil and the entry does not have the property,
13447 then also check higher levels of the hierarchy.
13448 If INHERIT is the symbol `selective', use inheritance only if the setting
13449 in `org-use-property-inheritance' selects PROPERTY for inheritance.
13450 If the property is present but empty, the return value is the empty string.
13451 If the property is not present at all, nil is returned.
13453 If LITERAL-NIL is set, return the string value \"nil\" as a string,
13454 do not interpret it as the list atom nil. This is used for inheritance
13455 when a \"nil\" value can supercede a non-nil value higher up the hierarchy."
13456 (org-with-point-at pom
13457 (if (and inherit (if (eq inherit 'selective)
13458 (org-property-inherit-p property)
13460 (org-entry-get-with-inheritance property literal-nil)
13461 (if (member property org-special-properties)
13462 ;; We need a special property. Use `org-entry-properties' to
13463 ;; retrieve it, but specify the wanted property
13464 (cdr (assoc property (org-entry-properties nil 'special property)))
13465 (let ((range (org-get-property-block)))
13466 (if (and range
13467 (goto-char (car range))
13468 (re-search-forward
13469 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
13470 (cdr range) t))
13471 ;; Found the property, return it.
13472 (if (match-end 1)
13473 (if literal-nil
13474 (org-match-string-no-properties 1)
13475 (org-not-nil (org-match-string-no-properties 1)))
13476 "")))))))
13478 (defun org-property-or-variable-value (var &optional inherit)
13479 "Check if there is a property fixing the value of VAR.
13480 If yes, return this value. If not, return the current value of the variable."
13481 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13482 (if (and prop (stringp prop) (string-match "\\S-" prop))
13483 (read prop)
13484 (symbol-value var))))
13486 (defun org-entry-delete (pom property)
13487 "Delete the property PROPERTY from entry at point-or-marker POM."
13488 (org-with-point-at pom
13489 (if (member property org-special-properties)
13490 nil ; cannot delete these properties.
13491 (let ((range (org-get-property-block)))
13492 (if (and range
13493 (goto-char (car range))
13494 (re-search-forward
13495 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
13496 (cdr range) t))
13497 (progn
13498 (delete-region (match-beginning 0) (1+ (point-at-eol)))
13500 nil)))))
13502 ;; Multi-values properties are properties that contain multiple values
13503 ;; These values are assumed to be single words, separated by whitespace.
13504 (defun org-entry-add-to-multivalued-property (pom property value)
13505 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
13506 (let* ((old (org-entry-get pom property))
13507 (values (and old (org-split-string old "[ \t]"))))
13508 (setq value (org-entry-protect-space value))
13509 (unless (member value values)
13510 (setq values (cons value values))
13511 (org-entry-put pom property
13512 (mapconcat 'identity values " ")))))
13514 (defun org-entry-remove-from-multivalued-property (pom property value)
13515 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
13516 (let* ((old (org-entry-get pom property))
13517 (values (and old (org-split-string old "[ \t]"))))
13518 (setq value (org-entry-protect-space value))
13519 (when (member value values)
13520 (setq values (delete value values))
13521 (org-entry-put pom property
13522 (mapconcat 'identity values " ")))))
13524 (defun org-entry-member-in-multivalued-property (pom property value)
13525 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
13526 (let* ((old (org-entry-get pom property))
13527 (values (and old (org-split-string old "[ \t]"))))
13528 (setq value (org-entry-protect-space value))
13529 (member value values)))
13531 (defun org-entry-get-multivalued-property (pom property)
13532 "Return a list of values in a multivalued property."
13533 (let* ((value (org-entry-get pom property))
13534 (values (and value (org-split-string value "[ \t]"))))
13535 (mapcar 'org-entry-restore-space values)))
13537 (defun org-entry-put-multivalued-property (pom property &rest values)
13538 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
13539 VALUES should be a list of strings. Spaces will be protected."
13540 (org-entry-put pom property
13541 (mapconcat 'org-entry-protect-space values " "))
13542 (let* ((value (org-entry-get pom property))
13543 (values (and value (org-split-string value "[ \t]"))))
13544 (mapcar 'org-entry-restore-space values)))
13546 (defun org-entry-protect-space (s)
13547 "Protect spaces and newline in string S."
13548 (while (string-match " " s)
13549 (setq s (replace-match "%20" t t s)))
13550 (while (string-match "\n" s)
13551 (setq s (replace-match "%0A" t t s)))
13554 (defun org-entry-restore-space (s)
13555 "Restore spaces and newline in string S."
13556 (while (string-match "%20" s)
13557 (setq s (replace-match " " t t s)))
13558 (while (string-match "%0A" s)
13559 (setq s (replace-match "\n" t t s)))
13562 (defvar org-entry-property-inherited-from (make-marker)
13563 "Marker pointing to the entry from where a property was inherited.
13564 Each call to `org-entry-get-with-inheritance' will set this marker to the
13565 location of the entry where the inheritance search matched. If there was
13566 no match, the marker will point nowhere.
13567 Note that also `org-entry-get' calls this function, if the INHERIT flag
13568 is set.")
13570 (defun org-entry-get-with-inheritance (property &optional literal-nil)
13571 "Get entry property, and search higher levels if not present.
13572 The search will stop at the first ancestor which has the property defined.
13573 If the value found is \"nil\", return nil to show that the property
13574 should be considered as undefined (this is the meaning of nil here).
13575 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
13576 (move-marker org-entry-property-inherited-from nil)
13577 (let (tmp)
13578 (save-excursion
13579 (save-restriction
13580 (widen)
13581 (catch 'ex
13582 (while t
13583 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
13584 (org-back-to-heading t)
13585 (move-marker org-entry-property-inherited-from (point))
13586 (throw 'ex tmp))
13587 (or (org-up-heading-safe) (throw 'ex nil)))))
13588 (setq tmp (or tmp
13589 (cdr (assoc property org-file-properties))
13590 (cdr (assoc property org-global-properties))
13591 (cdr (assoc property org-global-properties-fixed))))
13592 (if literal-nil tmp (org-not-nil tmp)))))
13594 (defvar org-property-changed-functions nil
13595 "Hook called when the value of a property has changed.
13596 Each hook function should accept two arguments, the name of the property
13597 and the new value.")
13599 (defun org-entry-put (pom property value)
13600 "Set PROPERTY to VALUE for entry at point-or-marker POM."
13601 (org-with-point-at pom
13602 (org-back-to-heading t)
13603 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
13604 range)
13605 (cond
13606 ((equal property "TODO")
13607 (when (and (stringp value) (string-match "\\S-" value)
13608 (not (member value org-todo-keywords-1)))
13609 (error "\"%s\" is not a valid TODO state" value))
13610 (if (or (not value)
13611 (not (string-match "\\S-" value)))
13612 (setq value 'none))
13613 (org-todo value)
13614 (org-set-tags nil 'align))
13615 ((equal property "PRIORITY")
13616 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
13617 (string-to-char value) ?\ ))
13618 (org-set-tags nil 'align))
13619 ((equal property "SCHEDULED")
13620 (if (re-search-forward org-scheduled-time-regexp end t)
13621 (cond
13622 ((eq value 'earlier) (org-timestamp-change -1 'day))
13623 ((eq value 'later) (org-timestamp-change 1 'day))
13624 (t (call-interactively 'org-schedule)))
13625 (call-interactively 'org-schedule)))
13626 ((equal property "DEADLINE")
13627 (if (re-search-forward org-deadline-time-regexp end t)
13628 (cond
13629 ((eq value 'earlier) (org-timestamp-change -1 'day))
13630 ((eq value 'later) (org-timestamp-change 1 'day))
13631 (t (call-interactively 'org-deadline)))
13632 (call-interactively 'org-deadline)))
13633 ((member property org-special-properties)
13634 (error "The %s property can not yet be set with `org-entry-put'"
13635 property))
13636 (t ; a non-special property
13637 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
13638 (setq range (org-get-property-block beg end 'force))
13639 (goto-char (car range))
13640 (if (re-search-forward
13641 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
13642 (progn
13643 (delete-region (match-beginning 1) (match-end 1))
13644 (goto-char (match-beginning 1)))
13645 (goto-char (cdr range))
13646 (insert "\n")
13647 (backward-char 1)
13648 (org-indent-line-function)
13649 (insert ":" property ":"))
13650 (and value (insert " " value))
13651 (org-indent-line-function)))))
13652 (run-hook-with-args 'org-property-changed-functions property value)))
13654 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
13655 "Get all property keys in the current buffer.
13656 With INCLUDE-SPECIALS, also list the special properties that reflect things
13657 like tags and TODO state.
13658 With INCLUDE-DEFAULTS, also include properties that has special meaning
13659 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
13660 With INCLUDE-COLUMNS, also include property names given in COLUMN
13661 formats in the current buffer."
13662 (let (rtn range cfmt s p)
13663 (save-excursion
13664 (save-restriction
13665 (widen)
13666 (goto-char (point-min))
13667 (while (re-search-forward org-property-start-re nil t)
13668 (setq range (org-get-property-block))
13669 (goto-char (car range))
13670 (while (re-search-forward
13671 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
13672 (cdr range) t)
13673 (add-to-list 'rtn (org-match-string-no-properties 1)))
13674 (outline-next-heading))))
13676 (when include-specials
13677 (setq rtn (append org-special-properties rtn)))
13679 (when include-defaults
13680 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
13681 (add-to-list 'rtn org-effort-property))
13683 (when include-columns
13684 (save-excursion
13685 (save-restriction
13686 (widen)
13687 (goto-char (point-min))
13688 (while (re-search-forward
13689 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
13690 nil t)
13691 (setq cfmt (match-string 2) s 0)
13692 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
13693 cfmt s)
13694 (setq s (match-end 0)
13695 p (match-string 1 cfmt))
13696 (unless (or (equal p "ITEM")
13697 (member p org-special-properties))
13698 (add-to-list 'rtn (match-string 1 cfmt))))))))
13700 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
13702 (defun org-property-values (key)
13703 "Return a list of all values of property KEY."
13704 (save-excursion
13705 (save-restriction
13706 (widen)
13707 (goto-char (point-min))
13708 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
13709 values)
13710 (while (re-search-forward re nil t)
13711 (add-to-list 'values (org-trim (match-string 1))))
13712 (delete "" values)))))
13714 (defun org-insert-property-drawer ()
13715 "Insert a property drawer into the current entry."
13716 (interactive)
13717 (org-back-to-heading t)
13718 (looking-at outline-regexp)
13719 (let ((indent (if org-adapt-indentation
13720 (- (match-end 0)(match-beginning 0))
13722 (beg (point))
13723 (re (concat "^[ \t]*" org-keyword-time-regexp))
13724 end hiddenp)
13725 (outline-next-heading)
13726 (setq end (point))
13727 (goto-char beg)
13728 (while (re-search-forward re end t))
13729 (setq hiddenp (org-invisible-p))
13730 (end-of-line 1)
13731 (and (equal (char-after) ?\n) (forward-char 1))
13732 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
13733 (if (member (match-string 1) '("CLOCK:" ":END:"))
13734 ;; just skip this line
13735 (beginning-of-line 2)
13736 ;; Drawer start, find the end
13737 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
13738 (beginning-of-line 1)))
13739 (org-skip-over-state-notes)
13740 (skip-chars-backward " \t\n\r")
13741 (if (eq (char-before) ?*) (forward-char 1))
13742 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
13743 (beginning-of-line 0)
13744 (org-indent-to-column indent)
13745 (beginning-of-line 2)
13746 (org-indent-to-column indent)
13747 (beginning-of-line 0)
13748 (if hiddenp
13749 (save-excursion
13750 (org-back-to-heading t)
13751 (hide-entry))
13752 (org-flag-drawer t))))
13754 (defun org-set-property (property value)
13755 "In the current entry, set PROPERTY to VALUE.
13756 When called interactively, this will prompt for a property name, offering
13757 completion on existing and default properties. And then it will prompt
13758 for a value, offering completion either on allowed values (via an inherited
13759 xxx_ALL property) or on existing values in other instances of this property
13760 in the current file."
13761 (interactive
13762 (let* ((completion-ignore-case t)
13763 (keys (org-buffer-property-keys nil t t))
13764 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
13765 (prop (if (member prop0 keys)
13766 prop0
13767 (or (cdr (assoc (downcase prop0)
13768 (mapcar (lambda (x) (cons (downcase x) x))
13769 keys)))
13770 prop0)))
13771 (cur (org-entry-get nil prop))
13772 (prompt (concat prop " value"
13773 (if (and cur (string-match "\\S-" cur))
13774 (concat " [" cur "]") "") ": "))
13775 (allowed (org-property-get-allowed-values nil prop 'table))
13776 (existing (mapcar 'list (org-property-values prop)))
13777 (val (if allowed
13778 (org-completing-read prompt allowed nil
13779 (not (get-text-property 0 'org-unrestricted
13780 (caar allowed))))
13781 (let (org-completion-use-ido org-completion-use-iswitchb)
13782 (org-completing-read prompt existing nil nil "" nil cur)))))
13783 (list prop (if (equal val "") cur val))))
13784 (unless (equal (org-entry-get nil property) value)
13785 (org-entry-put nil property value)))
13787 (defun org-delete-property (property)
13788 "In the current entry, delete PROPERTY."
13789 (interactive
13790 (let* ((completion-ignore-case t)
13791 (prop (org-icompleting-read "Property: "
13792 (org-entry-properties nil 'standard))))
13793 (list prop)))
13794 (message "Property %s %s" property
13795 (if (org-entry-delete nil property)
13796 "deleted"
13797 "was not present in the entry")))
13799 (defun org-delete-property-globally (property)
13800 "Remove PROPERTY globally, from all entries."
13801 (interactive
13802 (let* ((completion-ignore-case t)
13803 (prop (org-icompleting-read
13804 "Globally remove property: "
13805 (mapcar 'list (org-buffer-property-keys)))))
13806 (list prop)))
13807 (save-excursion
13808 (save-restriction
13809 (widen)
13810 (goto-char (point-min))
13811 (let ((cnt 0))
13812 (while (re-search-forward
13813 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
13814 nil t)
13815 (setq cnt (1+ cnt))
13816 (replace-match ""))
13817 (message "Property \"%s\" removed from %d entries" property cnt)))))
13819 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
13821 (defun org-compute-property-at-point ()
13822 "Compute the property at point.
13823 This looks for an enclosing column format, extracts the operator and
13824 then applies it to the property in the column format's scope."
13825 (interactive)
13826 (unless (org-at-property-p)
13827 (error "Not at a property"))
13828 (let ((prop (org-match-string-no-properties 2)))
13829 (org-columns-get-format-and-top-level)
13830 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
13831 (error "No operator defined for property %s" prop))
13832 (org-columns-compute prop)))
13834 (defvar org-property-allowed-value-functions nil
13835 "Hook for functions supplying allowed values for a specific property.
13836 The functions must take a single argument, the name of the property, and
13837 return a flat list of allowed values. If \":ETC\" is one of
13838 the values, this means that these values are intended as defaults for
13839 completion, but that other values should be allowed too.
13840 The functions must return nil if they are not responsible for this
13841 property.")
13843 (defun org-property-get-allowed-values (pom property &optional table)
13844 "Get allowed values for the property PROPERTY.
13845 When TABLE is non-nil, return an alist that can directly be used for
13846 completion."
13847 (let (vals)
13848 (cond
13849 ((equal property "TODO")
13850 (setq vals (org-with-point-at pom
13851 (append org-todo-keywords-1 '("")))))
13852 ((equal property "PRIORITY")
13853 (let ((n org-lowest-priority))
13854 (while (>= n org-highest-priority)
13855 (push (char-to-string n) vals)
13856 (setq n (1- n)))))
13857 ((member property org-special-properties))
13858 ((setq vals (run-hook-with-args-until-success
13859 'org-property-allowed-value-functions property)))
13861 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
13862 (when (and vals (string-match "\\S-" vals))
13863 (setq vals (car (read-from-string (concat "(" vals ")"))))
13864 (setq vals (mapcar (lambda (x)
13865 (cond ((stringp x) x)
13866 ((numberp x) (number-to-string x))
13867 ((symbolp x) (symbol-name x))
13868 (t "???")))
13869 vals)))))
13870 (when (member ":ETC" vals)
13871 (setq vals (remove ":ETC" vals))
13872 (org-add-props (car vals) '(org-unrestricted t)))
13873 (if table (mapcar 'list vals) vals)))
13875 (defun org-property-previous-allowed-value (&optional previous)
13876 "Switch to the next allowed value for this property."
13877 (interactive)
13878 (org-property-next-allowed-value t))
13880 (defun org-property-next-allowed-value (&optional previous)
13881 "Switch to the next allowed value for this property."
13882 (interactive)
13883 (unless (org-at-property-p)
13884 (error "Not at a property"))
13885 (let* ((key (match-string 2))
13886 (value (match-string 3))
13887 (allowed (or (org-property-get-allowed-values (point) key)
13888 (and (member value '("[ ]" "[-]" "[X]"))
13889 '("[ ]" "[X]"))))
13890 nval)
13891 (unless allowed
13892 (error "Allowed values for this property have not been defined"))
13893 (if previous (setq allowed (reverse allowed)))
13894 (if (member value allowed)
13895 (setq nval (car (cdr (member value allowed)))))
13896 (setq nval (or nval (car allowed)))
13897 (if (equal nval value)
13898 (error "Only one allowed value for this property"))
13899 (org-at-property-p)
13900 (replace-match (concat " :" key ": " nval) t t)
13901 (org-indent-line-function)
13902 (beginning-of-line 1)
13903 (skip-chars-forward " \t")
13904 (run-hook-with-args 'org-property-changed-functions key nval)))
13906 (defun org-find-olp (path &optional this-buffer)
13907 "Return a marker pointing to the entry at outline path OLP.
13908 If anything goes wrong, throw an error.
13909 You can wrap this call to cathc the error like this:
13911 (condition-case msg
13912 (org-mobile-locate-entry (match-string 4))
13913 (error (nth 1 msg)))
13915 The return value will then be either a string with the error message,
13916 or a marker if everyhing is OK.
13918 If THIS-BUFFER is set, the putline path does not contain a file,
13919 only headings."
13920 (let* ((file (if this-buffer buffer-file-name (pop path)))
13921 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
13922 (level 1)
13923 (lmin 1)
13924 (lmax 1)
13925 limit re end found pos heading cnt)
13926 (unless buffer (error "File not found :%s" file))
13927 (with-current-buffer buffer
13928 (save-excursion
13929 (save-restriction
13930 (widen)
13931 (setq limit (point-max))
13932 (goto-char (point-min))
13933 (while (setq heading (pop path))
13934 (setq re (format org-complex-heading-regexp-format
13935 (regexp-quote heading)))
13936 (setq cnt 0 pos (point))
13937 (while (re-search-forward re end t)
13938 (setq level (- (match-end 1) (match-beginning 1)))
13939 (if (and (>= level lmin) (<= level lmax))
13940 (setq found (match-beginning 0) cnt (1+ cnt))))
13941 (when (= cnt 0) (error "Heading not found on level %d: %s"
13942 lmax heading))
13943 (when (> cnt 1) (error "Heading not unique on level %d: %s"
13944 lmax heading))
13945 (goto-char found)
13946 (setq lmin (1+ level) lmax (+ lmin (if org-odd-levels-only 1 0)))
13947 (setq end (save-excursion (org-end-of-subtree t t))))
13948 (when (org-on-heading-p)
13949 (move-marker (make-marker) (point))))))))
13951 (defun org-find-entry-with-id (ident)
13952 "Locate the entry that contains the ID property with exact value IDENT.
13953 IDENT can be a string, a symbol or a number, this function will search for
13954 the string representation of it.
13955 Return the position where this entry starts, or nil if there is no such entry."
13956 (interactive "sID: ")
13957 (let ((id (cond
13958 ((stringp ident) ident)
13959 ((symbol-name ident) (symbol-name ident))
13960 ((numberp ident) (number-to-string ident))
13961 (t (error "IDENT %s must be a string, symbol or number" ident))))
13962 (case-fold-search nil))
13963 (save-excursion
13964 (save-restriction
13965 (widen)
13966 (goto-char (point-min))
13967 (when (re-search-forward
13968 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
13969 nil t)
13970 (org-back-to-heading t)
13971 (point))))))
13973 ;;;; Timestamps
13975 (defvar org-last-changed-timestamp nil)
13976 (defvar org-last-inserted-timestamp nil
13977 "The last time stamp inserted with `org-insert-time-stamp'.")
13978 (defvar org-time-was-given) ; dynamically scoped parameter
13979 (defvar org-end-time-was-given) ; dynamically scoped parameter
13980 (defvar org-ts-what) ; dynamically scoped parameter
13982 (defun org-time-stamp (arg &optional inactive)
13983 "Prompt for a date/time and insert a time stamp.
13984 If the user specifies a time like HH:MM, or if this command is called
13985 with a prefix argument, the time stamp will contain date and time.
13986 Otherwise, only the date will be included. All parts of a date not
13987 specified by the user will be filled in from the current date/time.
13988 So if you press just return without typing anything, the time stamp
13989 will represent the current date/time. If there is already a timestamp
13990 at the cursor, it will be modified."
13991 (interactive "P")
13992 (let* ((ts nil)
13993 (default-time
13994 ;; Default time is either today, or, when entering a range,
13995 ;; the range start.
13996 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
13997 (save-excursion
13998 (re-search-backward
13999 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14000 (- (point) 20) t)))
14001 (apply 'encode-time (org-parse-time-string (match-string 1)))
14002 (current-time)))
14003 (default-input (and ts (org-get-compact-tod ts)))
14004 org-time-was-given org-end-time-was-given time)
14005 (cond
14006 ((and (org-at-timestamp-p t)
14007 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14008 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14009 (insert "--")
14010 (setq time (let ((this-command this-command))
14011 (org-read-date arg 'totime nil nil
14012 default-time default-input)))
14013 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14014 ((org-at-timestamp-p t)
14015 (setq time (let ((this-command this-command))
14016 (org-read-date arg 'totime nil nil default-time default-input)))
14017 (when (org-at-timestamp-p t) ; just to get the match data
14018 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14019 (replace-match "")
14020 (setq org-last-changed-timestamp
14021 (org-insert-time-stamp
14022 time (or org-time-was-given arg)
14023 inactive nil nil (list org-end-time-was-given))))
14024 (message "Timestamp updated"))
14026 (setq time (let ((this-command this-command))
14027 (org-read-date arg 'totime nil nil default-time default-input)))
14028 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14029 nil nil (list org-end-time-was-given))))))
14031 ;; FIXME: can we use this for something else, like computing time differences?
14032 (defun org-get-compact-tod (s)
14033 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14034 (let* ((t1 (match-string 1 s))
14035 (h1 (string-to-number (match-string 2 s)))
14036 (m1 (string-to-number (match-string 3 s)))
14037 (t2 (and (match-end 4) (match-string 5 s)))
14038 (h2 (and t2 (string-to-number (match-string 6 s))))
14039 (m2 (and t2 (string-to-number (match-string 7 s))))
14040 dh dm)
14041 (if (not t2)
14043 (setq dh (- h2 h1) dm (- m2 m1))
14044 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14045 (concat t1 "+" (number-to-string dh)
14046 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14048 (defun org-time-stamp-inactive (&optional arg)
14049 "Insert an inactive time stamp.
14050 An inactive time stamp is enclosed in square brackets instead of angle
14051 brackets. It is inactive in the sense that it does not trigger agenda entries,
14052 does not link to the calendar and cannot be changed with the S-cursor keys.
14053 So these are more for recording a certain time/date."
14054 (interactive "P")
14055 (org-time-stamp arg 'inactive))
14057 (defvar org-date-ovl (make-overlay 1 1))
14058 (overlay-put org-date-ovl 'face 'org-warning)
14059 (org-detach-overlay org-date-ovl)
14061 (defvar org-ans1) ; dynamically scoped parameter
14062 (defvar org-ans2) ; dynamically scoped parameter
14064 (defvar org-plain-time-of-day-regexp) ; defined below
14066 (defvar org-overriding-default-time nil) ; dynamically scoped
14067 (defvar org-read-date-overlay nil)
14068 (defvar org-dcst nil) ; dynamically scoped
14069 (defvar org-read-date-history nil)
14070 (defvar org-read-date-final-answer nil)
14072 (defun org-read-date (&optional with-time to-time from-string prompt
14073 default-time default-input)
14074 "Read a date, possibly a time, and make things smooth for the user.
14075 The prompt will suggest to enter an ISO date, but you can also enter anything
14076 which will at least partially be understood by `parse-time-string'.
14077 Unrecognized parts of the date will default to the current day, month, year,
14078 hour and minute. If this command is called to replace a timestamp at point,
14079 of to enter the second timestamp of a range, the default time is taken
14080 from the existing stamp. Furthermore, the command prefers the future,
14081 so if you are giving a date where the year is not given, and the day-month
14082 combination is already past in the current year, it will assume you
14083 mean next year. For details, see the manual. A few examples:
14085 3-2-5 --> 2003-02-05
14086 feb 15 --> currentyear-02-15
14087 2/15 --> currentyear-02-15
14088 sep 12 9 --> 2009-09-12
14089 12:45 --> today 12:45
14090 22 sept 0:34 --> currentyear-09-22 0:34
14091 12 --> currentyear-currentmonth-12
14092 Fri --> nearest Friday (today or later)
14093 etc.
14095 Furthermore you can specify a relative date by giving, as the *first* thing
14096 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14097 change in days weeks, months, years.
14098 With a single plus or minus, the date is relative to today. With a double
14099 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14100 +4d --> four days from today
14101 +4 --> same as above
14102 +2w --> two weeks from today
14103 ++5 --> five days from default date
14105 The function understands only English month and weekday abbreviations,
14106 but this can be configured with the variables `parse-time-months' and
14107 `parse-time-weekdays'.
14109 While prompting, a calendar is popped up - you can also select the
14110 date with the mouse (button 1). The calendar shows a period of three
14111 months. To scroll it to other months, use the keys `>' and `<'.
14112 If you don't like the calendar, turn it off with
14113 \(setq org-read-date-popup-calendar nil)
14115 With optional argument TO-TIME, the date will immediately be converted
14116 to an internal time.
14117 With an optional argument WITH-TIME, the prompt will suggest to also
14118 insert a time. Note that when WITH-TIME is not set, you can still
14119 enter a time, and this function will inform the calling routine about
14120 this change. The calling routine may then choose to change the format
14121 used to insert the time stamp into the buffer to include the time.
14122 With optional argument FROM-STRING, read from this string instead from
14123 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14124 the time/date that is used for everything that is not specified by the
14125 user."
14126 (require 'parse-time)
14127 (let* ((org-time-stamp-rounding-minutes
14128 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14129 (org-dcst org-display-custom-times)
14130 (ct (org-current-time))
14131 (def (or org-overriding-default-time default-time ct))
14132 (defdecode (decode-time def))
14133 (dummy (progn
14134 (when (< (nth 2 defdecode) org-extend-today-until)
14135 (setcar (nthcdr 2 defdecode) -1)
14136 (setcar (nthcdr 1 defdecode) 59)
14137 (setq def (apply 'encode-time defdecode)
14138 defdecode (decode-time def)))))
14139 (calendar-frame-setup nil)
14140 (calendar-setup nil)
14141 (calendar-move-hook nil)
14142 (calendar-view-diary-initially-flag nil)
14143 (calendar-view-holidays-initially-flag nil)
14144 (timestr (format-time-string
14145 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14146 (prompt (concat (if prompt (concat prompt " ") "")
14147 (format "Date+time [%s]: " timestr)))
14148 ans (org-ans0 "") org-ans1 org-ans2 final)
14150 (cond
14151 (from-string (setq ans from-string))
14152 (org-read-date-popup-calendar
14153 (save-excursion
14154 (save-window-excursion
14155 (calendar)
14156 (calendar-forward-day (- (time-to-days def)
14157 (calendar-absolute-from-gregorian
14158 (calendar-current-date))))
14159 (org-eval-in-calendar nil t)
14160 (let* ((old-map (current-local-map))
14161 (map (copy-keymap calendar-mode-map))
14162 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14163 (org-defkey map (kbd "RET") 'org-calendar-select)
14164 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14165 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14166 (org-defkey minibuffer-local-map [(meta shift left)]
14167 (lambda () (interactive)
14168 (org-eval-in-calendar '(calendar-backward-month 1))))
14169 (org-defkey minibuffer-local-map [(meta shift right)]
14170 (lambda () (interactive)
14171 (org-eval-in-calendar '(calendar-forward-month 1))))
14172 (org-defkey minibuffer-local-map [(meta shift up)]
14173 (lambda () (interactive)
14174 (org-eval-in-calendar '(calendar-backward-year 1))))
14175 (org-defkey minibuffer-local-map [(meta shift down)]
14176 (lambda () (interactive)
14177 (org-eval-in-calendar '(calendar-forward-year 1))))
14178 (org-defkey minibuffer-local-map [?\e (shift left)]
14179 (lambda () (interactive)
14180 (org-eval-in-calendar '(calendar-backward-month 1))))
14181 (org-defkey minibuffer-local-map [?\e (shift right)]
14182 (lambda () (interactive)
14183 (org-eval-in-calendar '(calendar-forward-month 1))))
14184 (org-defkey minibuffer-local-map [?\e (shift up)]
14185 (lambda () (interactive)
14186 (org-eval-in-calendar '(calendar-backward-year 1))))
14187 (org-defkey minibuffer-local-map [?\e (shift down)]
14188 (lambda () (interactive)
14189 (org-eval-in-calendar '(calendar-forward-year 1))))
14190 (org-defkey minibuffer-local-map [(shift up)]
14191 (lambda () (interactive)
14192 (org-eval-in-calendar '(calendar-backward-week 1))))
14193 (org-defkey minibuffer-local-map [(shift down)]
14194 (lambda () (interactive)
14195 (org-eval-in-calendar '(calendar-forward-week 1))))
14196 (org-defkey minibuffer-local-map [(shift left)]
14197 (lambda () (interactive)
14198 (org-eval-in-calendar '(calendar-backward-day 1))))
14199 (org-defkey minibuffer-local-map [(shift right)]
14200 (lambda () (interactive)
14201 (org-eval-in-calendar '(calendar-forward-day 1))))
14202 (org-defkey minibuffer-local-map ">"
14203 (lambda () (interactive)
14204 (org-eval-in-calendar '(scroll-calendar-left 1))))
14205 (org-defkey minibuffer-local-map "<"
14206 (lambda () (interactive)
14207 (org-eval-in-calendar '(scroll-calendar-right 1))))
14208 (org-defkey minibuffer-local-map "\C-v"
14209 (lambda () (interactive)
14210 (org-eval-in-calendar
14211 '(calendar-scroll-left-three-months 1))))
14212 (org-defkey minibuffer-local-map "\M-v"
14213 (lambda () (interactive)
14214 (org-eval-in-calendar
14215 '(calendar-scroll-right-three-months 1))))
14216 (run-hooks 'org-read-date-minibuffer-setup-hook)
14217 (unwind-protect
14218 (progn
14219 (use-local-map map)
14220 (add-hook 'post-command-hook 'org-read-date-display)
14221 (setq org-ans0 (read-string prompt default-input
14222 'org-read-date-history nil))
14223 ;; org-ans0: from prompt
14224 ;; org-ans1: from mouse click
14225 ;; org-ans2: from calendar motion
14226 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14227 (remove-hook 'post-command-hook 'org-read-date-display)
14228 (use-local-map old-map)
14229 (when org-read-date-overlay
14230 (delete-overlay org-read-date-overlay)
14231 (setq org-read-date-overlay nil)))))))
14233 (t ; Naked prompt only
14234 (unwind-protect
14235 (setq ans (read-string prompt default-input
14236 'org-read-date-history timestr))
14237 (when org-read-date-overlay
14238 (delete-overlay org-read-date-overlay)
14239 (setq org-read-date-overlay nil)))))
14241 (setq final (org-read-date-analyze ans def defdecode))
14242 (setq org-read-date-final-answer ans)
14244 (if to-time
14245 (apply 'encode-time final)
14246 (if (and (boundp 'org-time-was-given) org-time-was-given)
14247 (format "%04d-%02d-%02d %02d:%02d"
14248 (nth 5 final) (nth 4 final) (nth 3 final)
14249 (nth 2 final) (nth 1 final))
14250 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
14252 (defvar def)
14253 (defvar defdecode)
14254 (defvar with-time)
14255 (defvar org-read-date-analyze-futurep nil)
14256 (defun org-read-date-display ()
14257 "Display the current date prompt interpretation in the minibuffer."
14258 (when org-read-date-display-live
14259 (when org-read-date-overlay
14260 (delete-overlay org-read-date-overlay))
14261 (let ((p (point)))
14262 (end-of-line 1)
14263 (while (not (equal (buffer-substring
14264 (max (point-min) (- (point) 4)) (point))
14265 " "))
14266 (insert " "))
14267 (goto-char p))
14268 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
14269 " " (or org-ans1 org-ans2)))
14270 (org-end-time-was-given nil)
14271 (f (org-read-date-analyze ans def defdecode))
14272 (fmts (if org-dcst
14273 org-time-stamp-custom-formats
14274 org-time-stamp-formats))
14275 (fmt (if (or with-time
14276 (and (boundp 'org-time-was-given) org-time-was-given))
14277 (cdr fmts)
14278 (car fmts)))
14279 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
14280 (when (and org-end-time-was-given
14281 (string-match org-plain-time-of-day-regexp txt))
14282 (setq txt (concat (substring txt 0 (match-end 0)) "-"
14283 org-end-time-was-given
14284 (substring txt (match-end 0)))))
14285 (when org-read-date-analyze-futurep
14286 (setq txt (concat txt " (=>F)")))
14287 (setq org-read-date-overlay
14288 (make-overlay (1- (point-at-eol)) (point-at-eol)))
14289 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
14291 (defun org-read-date-analyze (ans def defdecode)
14292 "Analyse the combined answer of the date prompt."
14293 ;; FIXME: cleanup and comment
14294 (let ((nowdecode (decode-time (current-time)))
14295 delta deltan deltaw deltadef year month day
14296 hour minute second wday pm h2 m2 tl wday1
14297 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
14298 (setq org-read-date-analyze-futurep nil)
14299 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
14300 (setq ans "+0"))
14302 (when (setq delta (org-read-date-get-relative ans (current-time) def))
14303 (setq ans (replace-match "" t t ans)
14304 deltan (car delta)
14305 deltaw (nth 1 delta)
14306 deltadef (nth 2 delta)))
14308 ;; Check if there is an iso week date in there
14309 ;; If yes, store the info and postpone interpreting it until the rest
14310 ;; of the parsing is done
14311 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
14312 (setq iso-year (if (match-end 1)
14313 (org-small-year-to-year
14314 (string-to-number (match-string 1 ans))))
14315 iso-weekday (if (match-end 3)
14316 (string-to-number (match-string 3 ans)))
14317 iso-week (string-to-number (match-string 2 ans)))
14318 (setq ans (replace-match "" t t ans)))
14320 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
14321 (when (string-match
14322 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
14323 (setq year (if (match-end 2)
14324 (string-to-number (match-string 2 ans))
14325 (progn (setq kill-year t)
14326 (string-to-number (format-time-string "%Y"))))
14327 month (string-to-number (match-string 3 ans))
14328 day (string-to-number (match-string 4 ans)))
14329 (if (< year 100) (setq year (+ 2000 year)))
14330 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14331 t nil ans)))
14332 ;; Help matching american dates, like 5/30 or 5/30/7
14333 (when (string-match
14334 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
14335 (setq year (if (match-end 4)
14336 (string-to-number (match-string 4 ans))
14337 (progn (setq kill-year t)
14338 (string-to-number (format-time-string "%Y"))))
14339 month (string-to-number (match-string 1 ans))
14340 day (string-to-number (match-string 2 ans)))
14341 (if (< year 100) (setq year (+ 2000 year)))
14342 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14343 t nil ans)))
14344 ;; Help matching am/pm times, because `parse-time-string' does not do that.
14345 ;; If there is a time with am/pm, and *no* time without it, we convert
14346 ;; so that matching will be successful.
14347 (loop for i from 1 to 2 do ; twice, for end time as well
14348 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
14349 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
14350 (setq hour (string-to-number (match-string 1 ans))
14351 minute (if (match-end 3)
14352 (string-to-number (match-string 3 ans))
14354 pm (equal ?p
14355 (string-to-char (downcase (match-string 4 ans)))))
14356 (if (and (= hour 12) (not pm))
14357 (setq hour 0)
14358 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
14359 (setq ans (replace-match (format "%02d:%02d" hour minute)
14360 t t ans))))
14362 ;; Check if a time range is given as a duration
14363 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
14364 (setq hour (string-to-number (match-string 1 ans))
14365 h2 (+ hour (string-to-number (match-string 3 ans)))
14366 minute (string-to-number (match-string 2 ans))
14367 m2 (+ minute (if (match-end 5) (string-to-number
14368 (match-string 5 ans))0)))
14369 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
14370 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
14371 t t ans)))
14373 ;; Check if there is a time range
14374 (when (boundp 'org-end-time-was-given)
14375 (setq org-time-was-given nil)
14376 (when (and (string-match org-plain-time-of-day-regexp ans)
14377 (match-end 8))
14378 (setq org-end-time-was-given (match-string 8 ans))
14379 (setq ans (concat (substring ans 0 (match-beginning 7))
14380 (substring ans (match-end 7))))))
14382 (setq tl (parse-time-string ans)
14383 day (or (nth 3 tl) (nth 3 defdecode))
14384 month (or (nth 4 tl)
14385 (if (and org-read-date-prefer-future
14386 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
14387 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
14388 (nth 4 defdecode)))
14389 year (or (and (not kill-year) (nth 5 tl))
14390 (if (and org-read-date-prefer-future
14391 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
14392 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
14393 (nth 5 defdecode)))
14394 hour (or (nth 2 tl) (nth 2 defdecode))
14395 minute (or (nth 1 tl) (nth 1 defdecode))
14396 second (or (nth 0 tl) 0)
14397 wday (nth 6 tl))
14399 (when (and (eq org-read-date-prefer-future 'time)
14400 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
14401 (equal day (nth 3 nowdecode))
14402 (equal month (nth 4 nowdecode))
14403 (equal year (nth 5 nowdecode))
14404 (nth 2 tl)
14405 (or (< (nth 2 tl) (nth 2 nowdecode))
14406 (and (= (nth 2 tl) (nth 2 nowdecode))
14407 (nth 1 tl)
14408 (< (nth 1 tl) (nth 1 nowdecode)))))
14409 (setq day (1+ day)
14410 futurep t))
14412 ;; Special date definitions below
14413 (cond
14414 (iso-week
14415 ;; There was an iso week
14416 (require 'cal-iso)
14417 (setq futurep nil)
14418 (setq year (or iso-year year)
14419 day (or iso-weekday wday 1)
14420 wday nil ; to make sure that the trigger below does not match
14421 iso-date (calendar-gregorian-from-absolute
14422 (calendar-absolute-from-iso
14423 (list iso-week day year))))
14424 ; FIXME: Should we also push ISO weeks into the future?
14425 ; (when (and org-read-date-prefer-future
14426 ; (not iso-year)
14427 ; (< (calendar-absolute-from-gregorian iso-date)
14428 ; (time-to-days (current-time))))
14429 ; (setq year (1+ year)
14430 ; iso-date (calendar-gregorian-from-absolute
14431 ; (calendar-absolute-from-iso
14432 ; (list iso-week day year)))))
14433 (setq month (car iso-date)
14434 year (nth 2 iso-date)
14435 day (nth 1 iso-date)))
14436 (deltan
14437 (setq futurep nil)
14438 (unless deltadef
14439 (let ((now (decode-time (current-time))))
14440 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
14441 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
14442 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
14443 ((equal deltaw "m") (setq month (+ month deltan)))
14444 ((equal deltaw "y") (setq year (+ year deltan)))))
14445 ((and wday (not (nth 3 tl)))
14446 (setq futurep nil)
14447 ;; Weekday was given, but no day, so pick that day in the week
14448 ;; on or after the derived date.
14449 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
14450 (unless (equal wday wday1)
14451 (setq day (+ day (% (- wday wday1 -7) 7))))))
14452 (if (and (boundp 'org-time-was-given)
14453 (nth 2 tl))
14454 (setq org-time-was-given t))
14455 (if (< year 100) (setq year (+ 2000 year)))
14456 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
14457 (setq org-read-date-analyze-futurep futurep)
14458 (list second minute hour day month year)))
14460 (defvar parse-time-weekdays)
14462 (defun org-read-date-get-relative (s today default)
14463 "Check string S for special relative date string.
14464 TODAY and DEFAULT are internal times, for today and for a default.
14465 Return shift list (N what def-flag)
14466 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
14467 N is the number of WHATs to shift.
14468 DEF-FLAG is t when a double ++ or -- indicates shift relative to
14469 the DEFAULT date rather than TODAY."
14470 (when (and
14471 (string-match
14472 (concat
14473 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
14474 "\\([0-9]+\\)?"
14475 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
14476 "\\([ \t]\\|$\\)") s)
14477 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
14478 (let* ((dir (if (> (match-end 1) (match-beginning 1))
14479 (string-to-char (substring (match-string 1 s) -1))
14480 ?+))
14481 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
14482 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
14483 (what (if (match-end 3) (match-string 3 s) "d"))
14484 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
14485 (date (if rel default today))
14486 (wday (nth 6 (decode-time date)))
14487 delta)
14488 (if wday1
14489 (progn
14490 (setq delta (mod (+ 7 (- wday1 wday)) 7))
14491 (if (= dir ?-) (setq delta (- delta 7)))
14492 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
14493 (list delta "d" rel))
14494 (list (* n (if (= dir ?-) -1 1)) what rel)))))
14496 (defun org-order-calendar-date-args (arg1 arg2 arg3)
14497 "Turn a user-specified date into the internal representation.
14498 The internal representation needed by the calendar is (month day year).
14499 This is a wrapper to handle the brain-dead convention in calendar that
14500 user function argument order change dependent on argument order."
14501 (if (boundp 'calendar-date-style)
14502 (cond
14503 ((eq calendar-date-style 'american)
14504 (list arg1 arg2 arg3))
14505 ((eq calendar-date-style 'european)
14506 (list arg2 arg1 arg3))
14507 ((eq calendar-date-style 'iso)
14508 (list arg2 arg3 arg1)))
14509 (if (org-bound-and-true-p european-calendar-style)
14510 (list arg2 arg1 arg3)
14511 (list arg1 arg2 arg3))))
14513 (defun org-eval-in-calendar (form &optional keepdate)
14514 "Eval FORM in the calendar window and return to current window.
14515 Also, store the cursor date in variable org-ans2."
14516 (let ((sf (selected-frame))
14517 (sw (selected-window)))
14518 (select-window (get-buffer-window "*Calendar*" t))
14519 (eval form)
14520 (when (and (not keepdate) (calendar-cursor-to-date))
14521 (let* ((date (calendar-cursor-to-date))
14522 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14523 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
14524 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
14525 (select-window sw)
14526 (org-select-frame-set-input-focus sf)))
14528 (defun org-calendar-select ()
14529 "Return to `org-read-date' with the date currently selected.
14530 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14531 (interactive)
14532 (when (calendar-cursor-to-date)
14533 (let* ((date (calendar-cursor-to-date))
14534 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14535 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14536 (if (active-minibuffer-window) (exit-minibuffer))))
14538 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
14539 "Insert a date stamp for the date given by the internal TIME.
14540 WITH-HM means use the stamp format that includes the time of the day.
14541 INACTIVE means use square brackets instead of angular ones, so that the
14542 stamp will not contribute to the agenda.
14543 PRE and POST are optional strings to be inserted before and after the
14544 stamp.
14545 The command returns the inserted time stamp."
14546 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
14547 stamp)
14548 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
14549 (insert-before-markers (or pre ""))
14550 (insert-before-markers (setq stamp (format-time-string fmt time)))
14551 (when (listp extra)
14552 (setq extra (car extra))
14553 (if (and (stringp extra)
14554 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
14555 (setq extra (format "-%02d:%02d"
14556 (string-to-number (match-string 1 extra))
14557 (string-to-number (match-string 2 extra))))
14558 (setq extra nil)))
14559 (when extra
14560 (backward-char 1)
14561 (insert-before-markers extra)
14562 (forward-char 1))
14563 (insert-before-markers (or post ""))
14564 (setq org-last-inserted-timestamp stamp)))
14566 (defun org-toggle-time-stamp-overlays ()
14567 "Toggle the use of custom time stamp formats."
14568 (interactive)
14569 (setq org-display-custom-times (not org-display-custom-times))
14570 (unless org-display-custom-times
14571 (let ((p (point-min)) (bmp (buffer-modified-p)))
14572 (while (setq p (next-single-property-change p 'display))
14573 (if (and (get-text-property p 'display)
14574 (eq (get-text-property p 'face) 'org-date))
14575 (remove-text-properties
14576 p (setq p (next-single-property-change p 'display))
14577 '(display t))))
14578 (set-buffer-modified-p bmp)))
14579 (if (featurep 'xemacs)
14580 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
14581 (org-restart-font-lock)
14582 (setq org-table-may-need-update t)
14583 (if org-display-custom-times
14584 (message "Time stamps are overlayed with custom format")
14585 (message "Time stamp overlays removed")))
14587 (defun org-display-custom-time (beg end)
14588 "Overlay modified time stamp format over timestamp between BEG and END."
14589 (let* ((ts (buffer-substring beg end))
14590 t1 w1 with-hm tf time str w2 (off 0))
14591 (save-match-data
14592 (setq t1 (org-parse-time-string ts t))
14593 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
14594 (setq off (- (match-end 0) (match-beginning 0)))))
14595 (setq end (- end off))
14596 (setq w1 (- end beg)
14597 with-hm (and (nth 1 t1) (nth 2 t1))
14598 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
14599 time (org-fix-decoded-time t1)
14600 str (org-add-props
14601 (format-time-string
14602 (substring tf 1 -1) (apply 'encode-time time))
14603 nil 'mouse-face 'highlight)
14604 w2 (length str))
14605 (if (not (= w2 w1))
14606 (add-text-properties (1+ beg) (+ 2 beg)
14607 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
14608 (if (featurep 'xemacs)
14609 (progn
14610 (put-text-property beg end 'invisible t)
14611 (put-text-property beg end 'end-glyph (make-glyph str)))
14612 (put-text-property beg end 'display str))))
14614 (defun org-translate-time (string)
14615 "Translate all timestamps in STRING to custom format.
14616 But do this only if the variable `org-display-custom-times' is set."
14617 (when org-display-custom-times
14618 (save-match-data
14619 (let* ((start 0)
14620 (re org-ts-regexp-both)
14621 t1 with-hm inactive tf time str beg end)
14622 (while (setq start (string-match re string start))
14623 (setq beg (match-beginning 0)
14624 end (match-end 0)
14625 t1 (save-match-data
14626 (org-parse-time-string (substring string beg end) t))
14627 with-hm (and (nth 1 t1) (nth 2 t1))
14628 inactive (equal (substring string beg (1+ beg)) "[")
14629 tf (funcall (if with-hm 'cdr 'car)
14630 org-time-stamp-custom-formats)
14631 time (org-fix-decoded-time t1)
14632 str (format-time-string
14633 (concat
14634 (if inactive "[" "<") (substring tf 1 -1)
14635 (if inactive "]" ">"))
14636 (apply 'encode-time time))
14637 string (replace-match str t t string)
14638 start (+ start (length str)))))))
14639 string)
14641 (defun org-fix-decoded-time (time)
14642 "Set 0 instead of nil for the first 6 elements of time.
14643 Don't touch the rest."
14644 (let ((n 0))
14645 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
14647 (defun org-days-to-time (timestamp-string)
14648 "Difference between TIMESTAMP-STRING and now in days."
14649 (- (time-to-days (org-time-string-to-time timestamp-string))
14650 (time-to-days (current-time))))
14652 (defun org-deadline-close (timestamp-string &optional ndays)
14653 "Is the time in TIMESTAMP-STRING close to the current date?"
14654 (setq ndays (or ndays (org-get-wdays timestamp-string)))
14655 (and (< (org-days-to-time timestamp-string) ndays)
14656 (not (org-entry-is-done-p))))
14658 (defun org-get-wdays (ts)
14659 "Get the deadline lead time appropriate for timestring TS."
14660 (cond
14661 ((<= org-deadline-warning-days 0)
14662 ;; 0 or negative, enforce this value no matter what
14663 (- org-deadline-warning-days))
14664 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
14665 ;; lead time is specified.
14666 (floor (* (string-to-number (match-string 1 ts))
14667 (cdr (assoc (match-string 2 ts)
14668 '(("d" . 1) ("w" . 7)
14669 ("m" . 30.4) ("y" . 365.25)))))))
14670 ;; go for the default.
14671 (t org-deadline-warning-days)))
14673 (defun org-calendar-select-mouse (ev)
14674 "Return to `org-read-date' with the date currently selected.
14675 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14676 (interactive "e")
14677 (mouse-set-point ev)
14678 (when (calendar-cursor-to-date)
14679 (let* ((date (calendar-cursor-to-date))
14680 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14681 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14682 (if (active-minibuffer-window) (exit-minibuffer))))
14684 (defun org-check-deadlines (ndays)
14685 "Check if there are any deadlines due or past due.
14686 A deadline is considered due if it happens within `org-deadline-warning-days'
14687 days from today's date. If the deadline appears in an entry marked DONE,
14688 it is not shown. The prefix arg NDAYS can be used to test that many
14689 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
14690 (interactive "P")
14691 (let* ((org-warn-days
14692 (cond
14693 ((equal ndays '(4)) 100000)
14694 (ndays (prefix-numeric-value ndays))
14695 (t (abs org-deadline-warning-days))))
14696 (case-fold-search nil)
14697 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
14698 (callback
14699 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
14701 (message "%d deadlines past-due or due within %d days"
14702 (org-occur regexp nil callback)
14703 org-warn-days)))
14705 (defun org-check-before-date (date)
14706 "Check if there are deadlines or scheduled entries before DATE."
14707 (interactive (list (org-read-date)))
14708 (let ((case-fold-search nil)
14709 (regexp (concat "\\<\\(" org-deadline-string
14710 "\\|" org-scheduled-string
14711 "\\) *<\\([^>]+\\)>"))
14712 (callback
14713 (lambda () (time-less-p
14714 (org-time-string-to-time (match-string 2))
14715 (org-time-string-to-time date)))))
14716 (message "%d entries before %s"
14717 (org-occur regexp nil callback) date)))
14719 (defun org-check-after-date (date)
14720 "Check if there are deadlines or scheduled entries after DATE."
14721 (interactive (list (org-read-date)))
14722 (let ((case-fold-search nil)
14723 (regexp (concat "\\<\\(" org-deadline-string
14724 "\\|" org-scheduled-string
14725 "\\) *<\\([^>]+\\)>"))
14726 (callback
14727 (lambda () (not
14728 (time-less-p
14729 (org-time-string-to-time (match-string 2))
14730 (org-time-string-to-time date))))))
14731 (message "%d entries after %s"
14732 (org-occur regexp nil callback) date)))
14734 (defun org-evaluate-time-range (&optional to-buffer)
14735 "Evaluate a time range by computing the difference between start and end.
14736 Normally the result is just printed in the echo area, but with prefix arg
14737 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
14738 If the time range is actually in a table, the result is inserted into the
14739 next column.
14740 For time difference computation, a year is assumed to be exactly 365
14741 days in order to avoid rounding problems."
14742 (interactive "P")
14744 (org-clock-update-time-maybe)
14745 (save-excursion
14746 (unless (org-at-date-range-p t)
14747 (goto-char (point-at-bol))
14748 (re-search-forward org-tr-regexp-both (point-at-eol) t))
14749 (if (not (org-at-date-range-p t))
14750 (error "Not at a time-stamp range, and none found in current line")))
14751 (let* ((ts1 (match-string 1))
14752 (ts2 (match-string 2))
14753 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
14754 (match-end (match-end 0))
14755 (time1 (org-time-string-to-time ts1))
14756 (time2 (org-time-string-to-time ts2))
14757 (t1 (org-float-time time1))
14758 (t2 (org-float-time time2))
14759 (diff (abs (- t2 t1)))
14760 (negative (< (- t2 t1) 0))
14761 ;; (ys (floor (* 365 24 60 60)))
14762 (ds (* 24 60 60))
14763 (hs (* 60 60))
14764 (fy "%dy %dd %02d:%02d")
14765 (fy1 "%dy %dd")
14766 (fd "%dd %02d:%02d")
14767 (fd1 "%dd")
14768 (fh "%02d:%02d")
14769 y d h m align)
14770 (if havetime
14771 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14773 d (floor (/ diff ds)) diff (mod diff ds)
14774 h (floor (/ diff hs)) diff (mod diff hs)
14775 m (floor (/ diff 60)))
14776 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14778 d (floor (+ (/ diff ds) 0.5))
14779 h 0 m 0))
14780 (if (not to-buffer)
14781 (message "%s" (org-make-tdiff-string y d h m))
14782 (if (org-at-table-p)
14783 (progn
14784 (goto-char match-end)
14785 (setq align t)
14786 (and (looking-at " *|") (goto-char (match-end 0))))
14787 (goto-char match-end))
14788 (if (looking-at
14789 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
14790 (replace-match ""))
14791 (if negative (insert " -"))
14792 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
14793 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
14794 (insert " " (format fh h m))))
14795 (if align (org-table-align))
14796 (message "Time difference inserted")))))
14798 (defun org-make-tdiff-string (y d h m)
14799 (let ((fmt "")
14800 (l nil))
14801 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
14802 l (push y l)))
14803 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
14804 l (push d l)))
14805 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
14806 l (push h l)))
14807 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
14808 l (push m l)))
14809 (apply 'format fmt (nreverse l))))
14811 (defun org-time-string-to-time (s)
14812 (apply 'encode-time (org-parse-time-string s)))
14813 (defun org-time-string-to-seconds (s)
14814 (org-float-time (org-time-string-to-time s)))
14816 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
14817 "Convert a time stamp to an absolute day number.
14818 If there is a specifyer for a cyclic time stamp, get the closest date to
14819 DAYNR.
14820 PREFER and SHOW-ALL are passed through to `org-closest-date'.
14821 the variable date is bound by the calendar when this is called."
14822 (cond
14823 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
14824 (if (org-diary-sexp-entry (match-string 1 s) "" date)
14825 daynr
14826 (+ daynr 1000)))
14827 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
14828 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
14829 (time-to-days (current-time))) (match-string 0 s)
14830 prefer show-all))
14831 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
14833 (defun org-days-to-iso-week (days)
14834 "Return the iso week number."
14835 (require 'cal-iso)
14836 (car (calendar-iso-from-absolute days)))
14838 (defun org-small-year-to-year (year)
14839 "Convert 2-digit years into 4-digit years.
14840 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
14841 The year 2000 cannot be abbreviated. Any year larger than 99
14842 is returned unchanged."
14843 (if (< year 38)
14844 (setq year (+ 2000 year))
14845 (if (< year 100)
14846 (setq year (+ 1900 year))))
14847 year)
14849 (defun org-time-from-absolute (d)
14850 "Return the time corresponding to date D.
14851 D may be an absolute day number, or a calendar-type list (month day year)."
14852 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
14853 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
14855 (defun org-calendar-holiday ()
14856 "List of holidays, for Diary display in Org-mode."
14857 (require 'holidays)
14858 (let ((hl (funcall
14859 (if (fboundp 'calendar-check-holidays)
14860 'calendar-check-holidays 'check-calendar-holidays) date)))
14861 (if hl (mapconcat 'identity hl "; "))))
14863 (defun org-diary-sexp-entry (sexp entry date)
14864 "Process a SEXP diary ENTRY for DATE."
14865 (require 'diary-lib)
14866 (let ((result (if calendar-debug-sexp
14867 (let ((stack-trace-on-error t))
14868 (eval (car (read-from-string sexp))))
14869 (condition-case nil
14870 (eval (car (read-from-string sexp)))
14871 (error
14872 (beep)
14873 (message "Bad sexp at line %d in %s: %s"
14874 (org-current-line)
14875 (buffer-file-name) sexp)
14876 (sleep-for 2))))))
14877 (cond ((stringp result) result)
14878 ((and (consp result)
14879 (stringp (cdr result))) (cdr result))
14880 (result entry)
14881 (t nil))))
14883 (defun org-diary-to-ical-string (frombuf)
14884 "Get iCalendar entries from diary entries in buffer FROMBUF.
14885 This uses the icalendar.el library."
14886 (let* ((tmpdir (if (featurep 'xemacs)
14887 (temp-directory)
14888 temporary-file-directory))
14889 (tmpfile (make-temp-name
14890 (expand-file-name "orgics" tmpdir)))
14891 buf rtn b e)
14892 (with-current-buffer frombuf
14893 (icalendar-export-region (point-min) (point-max) tmpfile)
14894 (setq buf (find-buffer-visiting tmpfile))
14895 (set-buffer buf)
14896 (goto-char (point-min))
14897 (if (re-search-forward "^BEGIN:VEVENT" nil t)
14898 (setq b (match-beginning 0)))
14899 (goto-char (point-max))
14900 (if (re-search-backward "^END:VEVENT" nil t)
14901 (setq e (match-end 0)))
14902 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
14903 (kill-buffer buf)
14904 (delete-file tmpfile)
14905 rtn))
14907 (defun org-closest-date (start current change prefer show-all)
14908 "Find the date closest to CURRENT that is consistent with START and CHANGE.
14909 When PREFER is `past' return a date that is either CURRENT or past.
14910 When PREFER is `future', return a date that is either CURRENT or future.
14911 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
14912 ;; Make the proper lists from the dates
14913 (catch 'exit
14914 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
14915 dn dw sday cday n1 n2 n0
14916 d m y y1 y2 date1 date2 nmonths nm ny m2)
14918 (setq start (org-date-to-gregorian start)
14919 current (org-date-to-gregorian
14920 (if show-all
14921 current
14922 (time-to-days (current-time))))
14923 sday (calendar-absolute-from-gregorian start)
14924 cday (calendar-absolute-from-gregorian current))
14926 (if (<= cday sday) (throw 'exit sday))
14928 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
14929 (setq dn (string-to-number (match-string 1 change))
14930 dw (cdr (assoc (match-string 2 change) a1)))
14931 (error "Invalid change specifyer: %s" change))
14932 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
14933 (cond
14934 ((eq dw 'day)
14935 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
14936 n2 (+ n1 dn)))
14937 ((eq dw 'year)
14938 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
14939 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
14940 (setq date1 (list m d y1)
14941 n1 (calendar-absolute-from-gregorian date1)
14942 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
14943 n2 (calendar-absolute-from-gregorian date2)))
14944 ((eq dw 'month)
14945 ;; approx number of month between the two dates
14946 (setq nmonths (floor (/ (- cday sday) 30.436875)))
14947 ;; How often does dn fit in there?
14948 (setq d (nth 1 start) m (car start) y (nth 2 start)
14949 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
14950 m (+ m nm)
14951 ny (floor (/ m 12))
14952 y (+ y ny)
14953 m (- m (* ny 12)))
14954 (while (> m 12) (setq m (- m 12) y (1+ y)))
14955 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
14956 (setq m2 (+ m dn) y2 y)
14957 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14958 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
14959 (while (<= n2 cday)
14960 (setq n1 n2 m m2 y y2)
14961 (setq m2 (+ m dn) y2 y)
14962 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14963 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
14964 ;; Make sure n1 is the earlier date
14965 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
14966 (if show-all
14967 (cond
14968 ((eq prefer 'past) (if (= cday n2) n2 n1))
14969 ((eq prefer 'future) (if (= cday n1) n1 n2))
14970 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
14971 (cond
14972 ((eq prefer 'past) (if (= cday n2) n2 n1))
14973 ((eq prefer 'future) (if (= cday n1) n1 n2))
14974 (t (if (= cday n1) n1 n2)))))))
14976 (defun org-date-to-gregorian (date)
14977 "Turn any specification of DATE into a gregorian date for the calendar."
14978 (cond ((integerp date) (calendar-gregorian-from-absolute date))
14979 ((and (listp date) (= (length date) 3)) date)
14980 ((stringp date)
14981 (setq date (org-parse-time-string date))
14982 (list (nth 4 date) (nth 3 date) (nth 5 date)))
14983 ((listp date)
14984 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
14986 (defun org-parse-time-string (s &optional nodefault)
14987 "Parse the standard Org-mode time string.
14988 This should be a lot faster than the normal `parse-time-string'.
14989 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
14990 hour and minute fields will be nil if not given."
14991 (if (string-match org-ts-regexp0 s)
14992 (list 0
14993 (if (or (match-beginning 8) (not nodefault))
14994 (string-to-number (or (match-string 8 s) "0")))
14995 (if (or (match-beginning 7) (not nodefault))
14996 (string-to-number (or (match-string 7 s) "0")))
14997 (string-to-number (match-string 4 s))
14998 (string-to-number (match-string 3 s))
14999 (string-to-number (match-string 2 s))
15000 nil nil nil)
15001 (error "Not a standard Org-mode time string: %s" s)))
15003 (defun org-timestamp-up (&optional arg)
15004 "Increase the date item at the cursor by one.
15005 If the cursor is on the year, change the year. If it is on the month or
15006 the day, change that.
15007 With prefix ARG, change by that many units."
15008 (interactive "p")
15009 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15011 (defun org-timestamp-down (&optional arg)
15012 "Decrease the date item at the cursor by one.
15013 If the cursor is on the year, change the year. If it is on the month or
15014 the day, change that.
15015 With prefix ARG, change by that many units."
15016 (interactive "p")
15017 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15019 (defun org-timestamp-up-day (&optional arg)
15020 "Increase the date in the time stamp by one day.
15021 With prefix ARG, change that many days."
15022 (interactive "p")
15023 (if (and (not (org-at-timestamp-p t))
15024 (org-on-heading-p))
15025 (org-todo 'up)
15026 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15028 (defun org-timestamp-down-day (&optional arg)
15029 "Decrease the date in the time stamp by one day.
15030 With prefix ARG, change that many days."
15031 (interactive "p")
15032 (if (and (not (org-at-timestamp-p t))
15033 (org-on-heading-p))
15034 (org-todo 'down)
15035 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15037 (defun org-at-timestamp-p (&optional inactive-ok)
15038 "Determine if the cursor is in or at a timestamp."
15039 (interactive)
15040 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15041 (pos (point))
15042 (ans (or (looking-at tsr)
15043 (save-excursion
15044 (skip-chars-backward "^[<\n\r\t")
15045 (if (> (point) (point-min)) (backward-char 1))
15046 (and (looking-at tsr)
15047 (> (- (match-end 0) pos) -1))))))
15048 (and ans
15049 (boundp 'org-ts-what)
15050 (setq org-ts-what
15051 (cond
15052 ((= pos (match-beginning 0)) 'bracket)
15053 ((= pos (1- (match-end 0))) 'bracket)
15054 ((org-pos-in-match-range pos 2) 'year)
15055 ((org-pos-in-match-range pos 3) 'month)
15056 ((org-pos-in-match-range pos 7) 'hour)
15057 ((org-pos-in-match-range pos 8) 'minute)
15058 ((or (org-pos-in-match-range pos 4)
15059 (org-pos-in-match-range pos 5)) 'day)
15060 ((and (> pos (or (match-end 8) (match-end 5)))
15061 (< pos (match-end 0)))
15062 (- pos (or (match-end 8) (match-end 5))))
15063 (t 'day))))
15064 ans))
15066 (defun org-toggle-timestamp-type ()
15067 "Toggle the type (<active> or [inactive]) of a time stamp."
15068 (interactive)
15069 (when (org-at-timestamp-p t)
15070 (let ((beg (match-beginning 0)) (end (match-end 0))
15071 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
15072 (save-excursion
15073 (goto-char beg)
15074 (while (re-search-forward "[][<>]" end t)
15075 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
15076 t t)))
15077 (message "Timestamp is now %sactive"
15078 (if (equal (char-after beg) ?<) "" "in")))))
15080 (defun org-timestamp-change (n &optional what updown)
15081 "Change the date in the time stamp at point.
15082 The date will be changed by N times WHAT. WHAT can be `day', `month',
15083 `year', `minute', `second'. If WHAT is not given, the cursor position
15084 in the timestamp determines what will be changed."
15085 (let ((pos (point))
15086 with-hm inactive
15087 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
15088 org-ts-what
15089 extra rem
15090 ts time time0)
15091 (if (not (org-at-timestamp-p t))
15092 (error "Not at a timestamp"))
15093 (if (and (not what) (eq org-ts-what 'bracket))
15094 (org-toggle-timestamp-type)
15095 (if (and (not what) (not (eq org-ts-what 'day))
15096 org-display-custom-times
15097 (get-text-property (point) 'display)
15098 (not (get-text-property (1- (point)) 'display)))
15099 (setq org-ts-what 'day))
15100 (setq org-ts-what (or what org-ts-what)
15101 inactive (= (char-after (match-beginning 0)) ?\[)
15102 ts (match-string 0))
15103 (replace-match "")
15104 (if (string-match
15105 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
15107 (setq extra (match-string 1 ts)))
15108 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15109 (setq with-hm t))
15110 (setq time0 (org-parse-time-string ts))
15111 (when (and updown
15112 (eq org-ts-what 'minute)
15113 (not current-prefix-arg))
15114 ;; This looks like s-up and s-down. Change by one rounding step.
15115 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
15116 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
15117 (setcar (cdr time0) (+ (nth 1 time0)
15118 (if (> n 0) (- rem) (- dm rem))))))
15119 (setq time
15120 (encode-time (or (car time0) 0)
15121 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
15122 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
15123 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
15124 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
15125 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
15126 (nthcdr 6 time0)))
15127 (when (and (member org-ts-what '(hour minute))
15128 extra
15129 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
15130 (setq extra (org-modify-ts-extra
15131 extra
15132 (if (eq org-ts-what 'hour) 2 5)
15133 n dm)))
15134 (when (integerp org-ts-what)
15135 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
15136 (if (eq what 'calendar)
15137 (let ((cal-date (org-get-date-from-calendar)))
15138 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15139 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15140 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15141 (setcar time0 (or (car time0) 0))
15142 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15143 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15144 (setq time (apply 'encode-time time0))))
15145 (setq org-last-changed-timestamp
15146 (org-insert-time-stamp time with-hm inactive nil nil extra))
15147 (org-clock-update-time-maybe)
15148 (goto-char pos)
15149 ;; Try to recenter the calendar window, if any
15150 (if (and org-calendar-follow-timestamp-change
15151 (get-buffer-window "*Calendar*" t)
15152 (memq org-ts-what '(day month year)))
15153 (org-recenter-calendar (time-to-days time))))))
15155 (defun org-modify-ts-extra (s pos n dm)
15156 "Change the different parts of the lead-time and repeat fields in timestamp."
15157 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15158 ng h m new rem)
15159 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15160 (cond
15161 ((or (org-pos-in-match-range pos 2)
15162 (org-pos-in-match-range pos 3))
15163 (setq m (string-to-number (match-string 3 s))
15164 h (string-to-number (match-string 2 s)))
15165 (if (org-pos-in-match-range pos 2)
15166 (setq h (+ h n))
15167 (setq n (* dm (org-no-warnings (signum n))))
15168 (when (not (= 0 (setq rem (% m dm))))
15169 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
15170 (setq m (+ m n)))
15171 (if (< m 0) (setq m (+ m 60) h (1- h)))
15172 (if (> m 59) (setq m (- m 60) h (1+ h)))
15173 (setq h (min 24 (max 0 h)))
15174 (setq ng 1 new (format "-%02d:%02d" h m)))
15175 ((org-pos-in-match-range pos 6)
15176 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15177 ((org-pos-in-match-range pos 5)
15178 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
15180 ((org-pos-in-match-range pos 9)
15181 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
15182 ((org-pos-in-match-range pos 8)
15183 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
15185 (when ng
15186 (setq s (concat
15187 (substring s 0 (match-beginning ng))
15189 (substring s (match-end ng))))))
15192 (defun org-recenter-calendar (date)
15193 "If the calendar is visible, recenter it to DATE."
15194 (let* ((win (selected-window))
15195 (cwin (get-buffer-window "*Calendar*" t))
15196 (calendar-move-hook nil))
15197 (when cwin
15198 (select-window cwin)
15199 (calendar-goto-date (if (listp date) date
15200 (calendar-gregorian-from-absolute date)))
15201 (select-window win))))
15203 (defun org-goto-calendar (&optional arg)
15204 "Go to the Emacs calendar at the current date.
15205 If there is a time stamp in the current line, go to that date.
15206 A prefix ARG can be used to force the current date."
15207 (interactive "P")
15208 (let ((tsr org-ts-regexp) diff
15209 (calendar-move-hook nil)
15210 (calendar-view-holidays-initially-flag nil)
15211 (calendar-view-diary-initially-flag nil))
15212 (if (or (org-at-timestamp-p)
15213 (save-excursion
15214 (beginning-of-line 1)
15215 (looking-at (concat ".*" tsr))))
15216 (let ((d1 (time-to-days (current-time)))
15217 (d2 (time-to-days
15218 (org-time-string-to-time (match-string 1)))))
15219 (setq diff (- d2 d1))))
15220 (calendar)
15221 (calendar-goto-today)
15222 (if (and diff (not arg)) (calendar-forward-day diff))))
15224 (defun org-get-date-from-calendar ()
15225 "Return a list (month day year) of date at point in calendar."
15226 (with-current-buffer "*Calendar*"
15227 (save-match-data
15228 (calendar-cursor-to-date))))
15230 (defun org-date-from-calendar ()
15231 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
15232 If there is already a time stamp at the cursor position, update it."
15233 (interactive)
15234 (if (org-at-timestamp-p t)
15235 (org-timestamp-change 0 'calendar)
15236 (let ((cal-date (org-get-date-from-calendar)))
15237 (org-insert-time-stamp
15238 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
15240 (defun org-minutes-to-hh:mm-string (m)
15241 "Compute H:MM from a number of minutes."
15242 (let ((h (/ m 60)))
15243 (setq m (- m (* 60 h)))
15244 (format org-time-clocksum-format h m)))
15246 (defun org-hh:mm-string-to-minutes (s)
15247 "Convert a string H:MM to a number of minutes.
15248 If the string is just a number, interpret it as minutes.
15249 In fact, the first hh:mm or number in the string will be taken,
15250 there can be extra stuff in the string.
15251 If no number is found, the return value is 0."
15252 (cond
15253 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
15254 (+ (* (string-to-number (match-string 1 s)) 60)
15255 (string-to-number (match-string 2 s))))
15256 ((string-match "\\([0-9]+\\)" s)
15257 (string-to-number (match-string 1 s)))
15258 (t 0)))
15260 ;;;; Files
15262 (defun org-save-all-org-buffers ()
15263 "Save all Org-mode buffers without user confirmation."
15264 (interactive)
15265 (message "Saving all Org-mode buffers...")
15266 (save-some-buffers t 'org-mode-p)
15267 (when (featurep 'org-id) (org-id-locations-save))
15268 (message "Saving all Org-mode buffers... done"))
15270 (defun org-revert-all-org-buffers ()
15271 "Revert all Org-mode buffers.
15272 Prompt for confirmation when there are unsaved changes.
15273 Be sure you know what you are doing before letting this function
15274 overwrite your changes.
15276 This function is useful in a setup where one tracks org files
15277 with a version control system, to revert on one machine after pulling
15278 changes from another. I believe the procedure must be like this:
15280 1. M-x org-save-all-org-buffers
15281 2. Pull changes from the other machine, resolve conflicts
15282 3. M-x org-revert-all-org-buffers"
15283 (interactive)
15284 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
15285 (error "Abort"))
15286 (save-excursion
15287 (save-window-excursion
15288 (mapc
15289 (lambda (b)
15290 (when (and (with-current-buffer b (org-mode-p))
15291 (with-current-buffer b buffer-file-name))
15292 (switch-to-buffer b)
15293 (revert-buffer t 'no-confirm)))
15294 (buffer-list))
15295 (when (and (featurep 'org-id) org-id-track-globally)
15296 (org-id-locations-load)))))
15298 ;;;; Agenda files
15300 ;;;###autoload
15301 (defun org-switchb (&optional arg)
15302 "Switch between Org buffers.
15303 With a prefix argument, restrict available to files.
15304 With two prefix arguments, restrict available buffers to agenda files.
15306 Defaults to `iswitchb' for buffer name completion.
15307 Set `org-completion-use-ido' to make it use ido instead."
15308 (interactive "P")
15309 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
15310 ((equal arg '(16)) (org-buffer-list 'agenda))
15311 (t (org-buffer-list))))
15312 (org-completion-use-iswitchb org-completion-use-iswitchb)
15313 (org-completion-use-ido org-completion-use-ido))
15314 (unless (or org-completion-use-ido org-completion-use-iswitchb)
15315 (setq org-completion-use-iswitchb t))
15316 (switch-to-buffer
15317 (org-icompleting-read "Org buffer: "
15318 (mapcar 'list (mapcar 'buffer-name blist))
15319 nil t))))
15321 ;;; Define some older names previously used for this functionality
15322 ;;;###autoload
15323 (defalias 'org-ido-switchb 'org-switchb)
15324 ;;;###autoload
15325 (defalias 'org-iswitchb 'org-switchb)
15327 (defun org-buffer-list (&optional predicate exclude-tmp)
15328 "Return a list of Org buffers.
15329 PREDICATE can be `export', `files' or `agenda'.
15331 export restrict the list to Export buffers.
15332 files restrict the list to buffers visiting Org files.
15333 agenda restrict the list to buffers visiting agenda files.
15335 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
15336 (let* ((bfn nil)
15337 (agenda-files (and (eq predicate 'agenda)
15338 (mapcar 'file-truename (org-agenda-files t))))
15339 (filter
15340 (cond
15341 ((eq predicate 'files)
15342 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
15343 ((eq predicate 'export)
15344 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
15345 ((eq predicate 'agenda)
15346 (lambda (b)
15347 (with-current-buffer b
15348 (and (eq major-mode 'org-mode)
15349 (setq bfn (buffer-file-name b))
15350 (member (file-truename bfn) agenda-files)))))
15351 (t (lambda (b) (with-current-buffer b
15352 (or (eq major-mode 'org-mode)
15353 (string-match "\*Org .*Export"
15354 (buffer-name b)))))))))
15355 (delq nil
15356 (mapcar
15357 (lambda(b)
15358 (if (and (funcall filter b)
15359 (or (not exclude-tmp)
15360 (not (string-match "tmp" (buffer-name b)))))
15362 nil))
15363 (buffer-list)))))
15365 (defun org-agenda-files (&optional unrestricted archives)
15366 "Get the list of agenda files.
15367 Optional UNRESTRICTED means return the full list even if a restriction
15368 is currently in place.
15369 When ARCHIVES is t, include all archive files that are really being
15370 used by the agenda files. If ARCHIVE is `ifmode', do this only if
15371 `org-agenda-archives-mode' is t."
15372 (let ((files
15373 (cond
15374 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
15375 ((stringp org-agenda-files) (org-read-agenda-file-list))
15376 ((listp org-agenda-files) org-agenda-files)
15377 (t (error "Invalid value of `org-agenda-files'")))))
15378 (setq files (apply 'append
15379 (mapcar (lambda (f)
15380 (if (file-directory-p f)
15381 (directory-files
15382 f t org-agenda-file-regexp)
15383 (list f)))
15384 files)))
15385 (when org-agenda-skip-unavailable-files
15386 (setq files (delq nil
15387 (mapcar (function
15388 (lambda (file)
15389 (and (file-readable-p file) file)))
15390 files))))
15391 (when (or (eq archives t)
15392 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
15393 (setq files (org-add-archive-files files)))
15394 files))
15396 (defun org-agenda-file-p (&optional file)
15397 "Return non-nil, if FILE is an agenda file.
15398 If FILE is omitted, use the file associated with the current
15399 buffer."
15400 (member (or file (buffer-file-name))
15401 (org-agenda-files t)))
15403 (defun org-edit-agenda-file-list ()
15404 "Edit the list of agenda files.
15405 Depending on setup, this either uses customize to edit the variable
15406 `org-agenda-files', or it visits the file that is holding the list. In the
15407 latter case, the buffer is set up in a way that saving it automatically kills
15408 the buffer and restores the previous window configuration."
15409 (interactive)
15410 (if (stringp org-agenda-files)
15411 (let ((cw (current-window-configuration)))
15412 (find-file org-agenda-files)
15413 (org-set-local 'org-window-configuration cw)
15414 (org-add-hook 'after-save-hook
15415 (lambda ()
15416 (set-window-configuration
15417 (prog1 org-window-configuration
15418 (kill-buffer (current-buffer))))
15419 (org-install-agenda-files-menu)
15420 (message "New agenda file list installed"))
15421 nil 'local)
15422 (message "%s" (substitute-command-keys
15423 "Edit list and finish with \\[save-buffer]")))
15424 (customize-variable 'org-agenda-files)))
15426 (defun org-store-new-agenda-file-list (list)
15427 "Set new value for the agenda file list and save it correctly."
15428 (if (stringp org-agenda-files)
15429 (let ((fe (org-read-agenda-file-list t)) b u)
15430 (while (setq b (find-buffer-visiting org-agenda-files))
15431 (kill-buffer b))
15432 (with-temp-file org-agenda-files
15433 (insert
15434 (mapconcat
15435 (lambda (f) ;; Keep un-expanded entries.
15436 (if (setq u (assoc f fe))
15437 (cdr u)
15439 list "\n")
15440 "\n")))
15441 (let ((org-mode-hook nil) (org-inhibit-startup t)
15442 (org-insert-mode-line-in-empty-file nil))
15443 (setq org-agenda-files list)
15444 (customize-save-variable 'org-agenda-files org-agenda-files))))
15446 (defun org-read-agenda-file-list (&optional pair-with-expansion)
15447 "Read the list of agenda files from a file.
15448 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
15449 filenames, used by `org-store-new-agenda-file-list' to write back
15450 un-expanded file names."
15451 (when (file-directory-p org-agenda-files)
15452 (error "`org-agenda-files' cannot be a single directory"))
15453 (when (stringp org-agenda-files)
15454 (with-temp-buffer
15455 (insert-file-contents org-agenda-files)
15456 (mapcar
15457 (lambda (f)
15458 (let ((e (expand-file-name (substitute-in-file-name f)
15459 org-directory)))
15460 (if pair-with-expansion
15461 (cons e f)
15462 e)))
15463 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
15465 ;;;###autoload
15466 (defun org-cycle-agenda-files ()
15467 "Cycle through the files in `org-agenda-files'.
15468 If the current buffer visits an agenda file, find the next one in the list.
15469 If the current buffer does not, find the first agenda file."
15470 (interactive)
15471 (let* ((fs (org-agenda-files t))
15472 (files (append fs (list (car fs))))
15473 (tcf (if buffer-file-name (file-truename buffer-file-name)))
15474 file)
15475 (unless files (error "No agenda files"))
15476 (catch 'exit
15477 (while (setq file (pop files))
15478 (if (equal (file-truename file) tcf)
15479 (when (car files)
15480 (find-file (car files))
15481 (throw 'exit t))))
15482 (find-file (car fs)))
15483 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
15485 (defun org-agenda-file-to-front (&optional to-end)
15486 "Move/add the current file to the top of the agenda file list.
15487 If the file is not present in the list, it is added to the front. If it is
15488 present, it is moved there. With optional argument TO-END, add/move to the
15489 end of the list."
15490 (interactive "P")
15491 (let ((org-agenda-skip-unavailable-files nil)
15492 (file-alist (mapcar (lambda (x)
15493 (cons (file-truename x) x))
15494 (org-agenda-files t)))
15495 (ctf (file-truename buffer-file-name))
15496 x had)
15497 (setq x (assoc ctf file-alist) had x)
15499 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
15500 (if to-end
15501 (setq file-alist (append (delq x file-alist) (list x)))
15502 (setq file-alist (cons x (delq x file-alist))))
15503 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
15504 (org-install-agenda-files-menu)
15505 (message "File %s to %s of agenda file list"
15506 (if had "moved" "added") (if to-end "end" "front"))))
15508 (defun org-remove-file (&optional file)
15509 "Remove current file from the list of files in variable `org-agenda-files'.
15510 These are the files which are being checked for agenda entries.
15511 Optional argument FILE means use this file instead of the current."
15512 (interactive)
15513 (let* ((org-agenda-skip-unavailable-files nil)
15514 (file (or file buffer-file-name))
15515 (true-file (file-truename file))
15516 (afile (abbreviate-file-name file))
15517 (files (delq nil (mapcar
15518 (lambda (x)
15519 (if (equal true-file
15520 (file-truename x))
15521 nil x))
15522 (org-agenda-files t)))))
15523 (if (not (= (length files) (length (org-agenda-files t))))
15524 (progn
15525 (org-store-new-agenda-file-list files)
15526 (org-install-agenda-files-menu)
15527 (message "Removed file: %s" afile))
15528 (message "File was not in list: %s (not removed)" afile))))
15530 (defun org-file-menu-entry (file)
15531 (vector file (list 'find-file file) t))
15533 (defun org-check-agenda-file (file)
15534 "Make sure FILE exists. If not, ask user what to do."
15535 (when (not (file-exists-p file))
15536 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
15537 (abbreviate-file-name file))
15538 (let ((r (downcase (read-char-exclusive))))
15539 (cond
15540 ((equal r ?r)
15541 (org-remove-file file)
15542 (throw 'nextfile t))
15543 (t (error "Abort"))))))
15545 (defun org-get-agenda-file-buffer (file)
15546 "Get a buffer visiting FILE. If the buffer needs to be created, add
15547 it to the list of buffers which might be released later."
15548 (let ((buf (org-find-base-buffer-visiting file)))
15549 (if buf
15550 buf ; just return it
15551 ;; Make a new buffer and remember it
15552 (setq buf (find-file-noselect file))
15553 (if buf (push buf org-agenda-new-buffers))
15554 buf)))
15556 (defun org-release-buffers (blist)
15557 "Release all buffers in list, asking the user for confirmation when needed.
15558 When a buffer is unmodified, it is just killed. When modified, it is saved
15559 \(if the user agrees) and then killed."
15560 (let (buf file)
15561 (while (setq buf (pop blist))
15562 (setq file (buffer-file-name buf))
15563 (when (and (buffer-modified-p buf)
15564 file
15565 (y-or-n-p (format "Save file %s? " file)))
15566 (with-current-buffer buf (save-buffer)))
15567 (kill-buffer buf))))
15569 (defun org-prepare-agenda-buffers (files)
15570 "Create buffers for all agenda files, protect archived trees and comments."
15571 (interactive)
15572 (let ((pa '(:org-archived t))
15573 (pc '(:org-comment t))
15574 (pall '(:org-archived t :org-comment t))
15575 (inhibit-read-only t)
15576 (rea (concat ":" org-archive-tag ":"))
15577 bmp file re)
15578 (save-excursion
15579 (save-restriction
15580 (while (setq file (pop files))
15581 (catch 'nextfile
15582 (if (bufferp file)
15583 (set-buffer file)
15584 (org-check-agenda-file file)
15585 (set-buffer (org-get-agenda-file-buffer file)))
15586 (widen)
15587 (setq bmp (buffer-modified-p))
15588 (org-refresh-category-properties)
15589 (setq org-todo-keywords-for-agenda
15590 (append org-todo-keywords-for-agenda org-todo-keywords-1))
15591 (setq org-done-keywords-for-agenda
15592 (append org-done-keywords-for-agenda org-done-keywords))
15593 (setq org-todo-keyword-alist-for-agenda
15594 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
15595 (setq org-drawers-for-agenda
15596 (append org-drawers-for-agenda org-drawers))
15597 (setq org-tag-alist-for-agenda
15598 (append org-tag-alist-for-agenda org-tag-alist))
15600 (save-excursion
15601 (remove-text-properties (point-min) (point-max) pall)
15602 (when org-agenda-skip-archived-trees
15603 (goto-char (point-min))
15604 (while (re-search-forward rea nil t)
15605 (if (org-on-heading-p t)
15606 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
15607 (goto-char (point-min))
15608 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
15609 (while (re-search-forward re nil t)
15610 (add-text-properties
15611 (match-beginning 0) (org-end-of-subtree t) pc)))
15612 (set-buffer-modified-p bmp)))))
15613 (setq org-todo-keywords-for-agenda
15614 (org-uniquify org-todo-keywords-for-agenda))
15615 (setq org-todo-keyword-alist-for-agenda
15616 (org-uniquify org-todo-keyword-alist-for-agenda)
15617 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
15619 ;;;; Embedded LaTeX
15621 (defvar org-cdlatex-mode-map (make-sparse-keymap)
15622 "Keymap for the minor `org-cdlatex-mode'.")
15624 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
15625 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
15626 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
15627 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
15628 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
15630 (defvar org-cdlatex-texmathp-advice-is-done nil
15631 "Flag remembering if we have applied the advice to texmathp already.")
15633 (define-minor-mode org-cdlatex-mode
15634 "Toggle the minor `org-cdlatex-mode'.
15635 This mode supports entering LaTeX environment and math in LaTeX fragments
15636 in Org-mode.
15637 \\{org-cdlatex-mode-map}"
15638 nil " OCDL" nil
15639 (when org-cdlatex-mode (require 'cdlatex))
15640 (unless org-cdlatex-texmathp-advice-is-done
15641 (setq org-cdlatex-texmathp-advice-is-done t)
15642 (defadvice texmathp (around org-math-always-on activate)
15643 "Always return t in org-mode buffers.
15644 This is because we want to insert math symbols without dollars even outside
15645 the LaTeX math segments. If Orgmode thinks that point is actually inside
15646 an embedded LaTeX fragment, let texmathp do its job.
15647 \\[org-cdlatex-mode-map]"
15648 (interactive)
15649 (let (p)
15650 (cond
15651 ((not (org-mode-p)) ad-do-it)
15652 ((eq this-command 'cdlatex-math-symbol)
15653 (setq ad-return-value t
15654 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
15656 (let ((p (org-inside-LaTeX-fragment-p)))
15657 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
15658 (setq ad-return-value t
15659 texmathp-why '("Org-mode embedded math" . 0))
15660 (if p ad-do-it)))))))))
15662 (defun turn-on-org-cdlatex ()
15663 "Unconditionally turn on `org-cdlatex-mode'."
15664 (org-cdlatex-mode 1))
15666 (defun org-inside-LaTeX-fragment-p ()
15667 "Test if point is inside a LaTeX fragment.
15668 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
15669 sequence appearing also before point.
15670 Even though the matchers for math are configurable, this function assumes
15671 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
15672 delimiters are skipped when they have been removed by customization.
15673 The return value is nil, or a cons cell with the delimiter and
15674 and the position of this delimiter.
15676 This function does a reasonably good job, but can locally be fooled by
15677 for example currency specifications. For example it will assume being in
15678 inline math after \"$22.34\". The LaTeX fragment formatter will only format
15679 fragments that are properly closed, but during editing, we have to live
15680 with the uncertainty caused by missing closing delimiters. This function
15681 looks only before point, not after."
15682 (catch 'exit
15683 (let ((pos (point))
15684 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
15685 (lim (progn
15686 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
15687 (point)))
15688 dd-on str (start 0) m re)
15689 (goto-char pos)
15690 (when dodollar
15691 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
15692 re (nth 1 (assoc "$" org-latex-regexps)))
15693 (while (string-match re str start)
15694 (cond
15695 ((= (match-end 0) (length str))
15696 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
15697 ((= (match-end 0) (- (length str) 5))
15698 (throw 'exit nil))
15699 (t (setq start (match-end 0))))))
15700 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
15701 (goto-char pos)
15702 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
15703 (and (match-beginning 2) (throw 'exit nil))
15704 ;; count $$
15705 (while (re-search-backward "\\$\\$" lim t)
15706 (setq dd-on (not dd-on)))
15707 (goto-char pos)
15708 (if dd-on (cons "$$" m))))))
15710 (defun org-inside-latex-macro-p ()
15711 "Is point inside a LaTeX macro or its arguments?"
15712 (save-match-data
15713 (org-in-regexp
15714 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
15716 (defun org-try-cdlatex-tab ()
15717 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
15718 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
15719 - inside a LaTeX fragment, or
15720 - after the first word in a line, where an abbreviation expansion could
15721 insert a LaTeX environment."
15722 (when org-cdlatex-mode
15723 (cond
15724 ((save-excursion
15725 (skip-chars-backward "a-zA-Z0-9*")
15726 (skip-chars-backward " \t")
15727 (bolp))
15728 (cdlatex-tab) t)
15729 ((org-inside-LaTeX-fragment-p)
15730 (cdlatex-tab) t)
15731 (t nil))))
15733 (defun org-cdlatex-underscore-caret (&optional arg)
15734 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
15735 Revert to the normal definition outside of these fragments."
15736 (interactive "P")
15737 (if (org-inside-LaTeX-fragment-p)
15738 (call-interactively 'cdlatex-sub-superscript)
15739 (let (org-cdlatex-mode)
15740 (call-interactively (key-binding (vector last-input-event))))))
15742 (defun org-cdlatex-math-modify (&optional arg)
15743 "Execute `cdlatex-math-modify' in LaTeX fragments.
15744 Revert to the normal definition outside of these fragments."
15745 (interactive "P")
15746 (if (org-inside-LaTeX-fragment-p)
15747 (call-interactively 'cdlatex-math-modify)
15748 (let (org-cdlatex-mode)
15749 (call-interactively (key-binding (vector last-input-event))))))
15751 (defvar org-latex-fragment-image-overlays nil
15752 "List of overlays carrying the images of latex fragments.")
15753 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
15755 (defun org-remove-latex-fragment-image-overlays ()
15756 "Remove all overlays with LaTeX fragment images in current buffer."
15757 (mapc 'delete-overlay org-latex-fragment-image-overlays)
15758 (setq org-latex-fragment-image-overlays nil))
15760 (defun org-preview-latex-fragment (&optional subtree)
15761 "Preview the LaTeX fragment at point, or all locally or globally.
15762 If the cursor is in a LaTeX fragment, create the image and overlay
15763 it over the source code. If there is no fragment at point, display
15764 all fragments in the current text, from one headline to the next. With
15765 prefix SUBTREE, display all fragments in the current subtree. With a
15766 double prefix `C-u C-u', or when the cursor is before the first headline,
15767 display all fragments in the buffer.
15768 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
15769 (interactive "P")
15770 (org-remove-latex-fragment-image-overlays)
15771 (save-excursion
15772 (save-restriction
15773 (let (beg end at msg)
15774 (cond
15775 ((or (equal subtree '(16))
15776 (not (save-excursion
15777 (re-search-backward (concat "^" outline-regexp) nil t))))
15778 (setq beg (point-min) end (point-max)
15779 msg "Creating images for buffer...%s"))
15780 ((equal subtree '(4))
15781 (org-back-to-heading)
15782 (setq beg (point) end (org-end-of-subtree t)
15783 msg "Creating images for subtree...%s"))
15785 (if (setq at (org-inside-LaTeX-fragment-p))
15786 (goto-char (max (point-min) (- (cdr at) 2)))
15787 (org-back-to-heading))
15788 (setq beg (point) end (progn (outline-next-heading) (point))
15789 msg (if at "Creating image...%s"
15790 "Creating images for entry...%s"))))
15791 (message msg "")
15792 (narrow-to-region beg end)
15793 (goto-char beg)
15794 (org-format-latex
15795 (concat "ltxpng/" (file-name-sans-extension
15796 (file-name-nondirectory
15797 buffer-file-name)))
15798 default-directory 'overlays msg at 'forbuffer)
15799 (message msg "done. Use `C-c C-c' to remove images.")))))
15801 (defvar org-latex-regexps
15802 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
15803 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
15804 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
15805 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15806 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15807 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
15808 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
15809 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
15810 "Regular expressions for matching embedded LaTeX.")
15812 (defun org-format-latex (prefix &optional dir overlays msg at
15813 forbuffer protect-only)
15814 "Replace LaTeX fragments with links to an image, and produce images.
15815 Some of the options can be changed using the variable
15816 `org-format-latex-options'."
15817 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
15818 (let* ((prefixnodir (file-name-nondirectory prefix))
15819 (absprefix (expand-file-name prefix dir))
15820 (todir (file-name-directory absprefix))
15821 (opt org-format-latex-options)
15822 (matchers (plist-get opt :matchers))
15823 (re-list org-latex-regexps)
15824 (org-format-latex-header-extra
15825 (plist-get (org-infile-export-plist) :latex-header-extra))
15826 (cnt 0) txt hash link beg end re e checkdir
15827 executables-checked
15828 m n block linkfile movefile ov)
15829 ;; Check the different regular expressions
15830 (while (setq e (pop re-list))
15831 (setq m (car e) re (nth 1 e) n (nth 2 e)
15832 block (if (nth 3 e) "\n\n" ""))
15833 (when (member m matchers)
15834 (goto-char (point-min))
15835 (while (re-search-forward re nil t)
15836 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
15837 (not (get-text-property (match-beginning n)
15838 'org-protected))
15839 (or (not overlays)
15840 (not (eq (get-char-property (match-beginning n)
15841 'org-overlay-type)
15842 'org-latex-overlay))))
15843 (if protect-only
15844 (add-text-properties (match-beginning n) (match-end n)
15845 '(org-protected t))
15846 (setq txt (match-string n)
15847 beg (match-beginning n) end (match-end n)
15848 cnt (1+ cnt))
15849 (let (print-length print-level) ; make sure full list is printed
15850 (setq hash (sha1 (prin1-to-string
15851 (list org-format-latex-header
15852 org-format-latex-header-extra
15853 org-export-latex-default-packages-alist
15854 org-export-latex-packages-alist
15855 org-format-latex-options
15856 forbuffer txt)))
15857 linkfile (format "%s_%s.png" prefix hash)
15858 movefile (format "%s_%s.png" absprefix hash)))
15859 (setq link (concat block "[[file:" linkfile "]]" block))
15860 (if msg (message msg cnt))
15861 (goto-char beg)
15862 (unless checkdir ; make sure the directory exists
15863 (setq checkdir t)
15864 (or (file-directory-p todir) (make-directory todir)))
15866 (unless executables-checked
15867 (org-check-external-command
15868 "latex" "needed to convert LaTeX fragments to images")
15869 (org-check-external-command
15870 "dvipng" "needed to convert LaTeX fragments to images")
15871 (setq executables-checked t))
15873 (unless (file-exists-p movefile)
15874 (org-create-formula-image
15875 txt movefile opt forbuffer))
15876 (if overlays
15877 (progn
15878 (mapc (lambda (o)
15879 (if (eq (overlay-get o 'org-overlay-type)
15880 'org-latex-overlay)
15881 (delete-overlay o)))
15882 (overlays-in beg end))
15883 (setq ov (make-overlay beg end))
15884 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
15885 (if (featurep 'xemacs)
15886 (progn
15887 (overlay-put ov 'invisible t)
15888 (overlay-put
15889 ov 'end-glyph
15890 (make-glyph (vector 'png :file movefile))))
15891 (overlay-put
15892 ov 'display
15893 (list 'image :type 'png :file movefile :ascent 'center)))
15894 (push ov org-latex-fragment-image-overlays)
15895 (goto-char end))
15896 (delete-region beg end)
15897 (insert (org-add-props link
15898 (list 'org-latex-src
15899 (replace-regexp-in-string "\"" "" txt))))))))))))
15901 ;; This function borrows from Ganesh Swami's latex2png.el
15902 (defun org-create-formula-image (string tofile options buffer)
15903 "This calls dvipng."
15904 (require 'org-latex)
15905 (let* ((tmpdir (if (featurep 'xemacs)
15906 (temp-directory)
15907 temporary-file-directory))
15908 (texfilebase (make-temp-name
15909 (expand-file-name "orgtex" tmpdir)))
15910 (texfile (concat texfilebase ".tex"))
15911 (dvifile (concat texfilebase ".dvi"))
15912 (pngfile (concat texfilebase ".png"))
15913 (fnh (if (featurep 'xemacs)
15914 (font-height (get-face-font 'default))
15915 (face-attribute 'default :height nil)))
15916 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
15917 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
15918 (fg (or (plist-get options (if buffer :foreground :html-foreground))
15919 "Black"))
15920 (bg (or (plist-get options (if buffer :background :html-background))
15921 "Transparent")))
15922 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
15923 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
15924 (with-temp-file texfile
15925 (insert (org-splice-latex-header
15926 org-format-latex-header
15927 org-export-latex-default-packages-alist
15928 org-export-latex-packages-alist t
15929 org-format-latex-header-extra))
15930 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
15931 (require 'org-latex)
15932 (org-export-latex-fix-inputenc))
15933 (let ((dir default-directory))
15934 (condition-case nil
15935 (progn
15936 (cd tmpdir)
15937 (call-process "latex" nil nil nil texfile))
15938 (error nil))
15939 (cd dir))
15940 (if (not (file-exists-p dvifile))
15941 (progn (message "Failed to create dvi file from %s" texfile) nil)
15942 (condition-case nil
15943 (call-process "dvipng" nil nil nil
15944 "-fg" fg "-bg" bg
15945 "-D" dpi
15946 ;;"-x" scale "-y" scale
15947 "-T" "tight"
15948 "-o" pngfile
15949 dvifile)
15950 (error nil))
15951 (if (not (file-exists-p pngfile))
15952 (if org-format-latex-signal-error
15953 (error "Failed to create png file from %s" texfile)
15954 (message "Failed to create png file from %s" texfile)
15955 nil)
15956 ;; Use the requested file name and clean up
15957 (copy-file pngfile tofile 'replace)
15958 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15959 (delete-file (concat texfilebase e)))
15960 pngfile))))
15962 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
15963 "Fill a LaTeX header template TPL.
15964 In the template, the following place holders will be recognized:
15966 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
15967 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
15968 [PACKAGES] \\usepackage statements for PKG
15969 [NO-PACKAGES] do not include PKG
15970 [EXTRA] the string EXTRA
15971 [NO-EXTRA] do not include EXTRA
15973 For backward compatibility, if both the positive and the negative place
15974 holder is missing, the positive one (without the \"NO-\") will be
15975 assumed to be present at the end of the template.
15976 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
15977 EXTRA is a string.
15978 SNIPPETS-P indicates if this is run to create snippet images for HTML."
15979 (let (rpl (end ""))
15980 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
15981 (setq rpl (if (or (match-end 1) (not def-pkg))
15982 "" (org-latex-packages-to-string def-pkg snippets-p t))
15983 tpl (replace-match rpl t t tpl))
15984 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
15986 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
15987 (setq rpl (if (or (match-end 1) (not pkg))
15988 "" (org-latex-packages-to-string pkg snippets-p t))
15989 tpl (replace-match rpl t t tpl))
15990 (if pkg (setq end
15991 (concat end "\n"
15992 (org-latex-packages-to-string pkg snippets-p)))))
15994 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
15995 (setq rpl (if (or (match-end 1) (not extra))
15996 "" (concat extra "\n"))
15997 tpl (replace-match rpl t t tpl))
15998 (if (and extra (string-match "\\S-" extra))
15999 (setq end (concat end "\n" extra))))
16001 (if (string-match "\\S-" end)
16002 (concat tpl "\n" end)
16003 tpl)))
16005 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
16006 "Turn an alist of packages into a string with the \\usepackage macros."
16007 (setq pkg (mapconcat (lambda(p)
16008 (cond
16009 ((stringp p) p)
16010 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
16011 (format "%% Package %s omitted" (cadr p)))
16012 ((equal "" (car p))
16013 (format "\\usepackage{%s}" (cadr p)))
16015 (format "\\usepackage[%s]{%s}"
16016 (car p) (cadr p)))))
16018 "\n"))
16019 (if newline (concat pkg "\n") pkg))
16021 (defun org-dvipng-color (attr)
16022 "Return an rgb color specification for dvipng."
16023 (apply 'format "rgb %s %s %s"
16024 (mapcar 'org-normalize-color
16025 (color-values (face-attribute 'default attr nil)))))
16027 (defun org-normalize-color (value)
16028 "Return string to be used as color value for an RGB component."
16029 (format "%g" (/ value 65535.0)))
16031 ;; Image display
16034 (defvar org-inline-image-overlays nil)
16035 (make-variable-buffer-local 'org-inline-image-overlays)
16037 (defun org-toggle-inline-images (&optional include-linked)
16038 "Toggle the display of inline images.
16039 INCLUDE-LINKED is passed to `org-display-inline-images'."
16040 (interactive "P")
16041 (if org-inline-image-overlays
16042 (progn
16043 (org-remove-inline-images)
16044 (message "Inline image display turned off"))
16045 (org-display-inline-images include-linked)
16046 (if org-inline-image-overlays
16047 (message "%d images displayed inline"
16048 (length org-inline-image-overlays))
16049 (message "No images to display inline"))))
16051 (defun org-display-inline-images (&optional include-linked refresh beg end)
16052 "Display inline images.
16053 Normally only links without a description part are inlined, because this
16054 is how it will work for export. When INCLUDE-LINKED is set, also links
16055 with a description part will be inlined. This can be nice for a quick
16056 look at those images, but it does not reflect whatexported files will look
16057 like.
16058 When REFRESH is set, refresh existing images between BEG and END.
16059 This will create new image displays only if necessary.
16060 BEG and END default to the buffer boundaries."
16061 (interactive "P")
16062 (unless refresh
16063 (org-remove-inline-images)
16064 (clear-image-cache))
16065 (save-excursion
16066 (save-restriction
16067 (widen)
16068 (setq beg (or beg (point-min)) end (or end (point-max)))
16069 (goto-char (point-min))
16070 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([-+~.:/\\_0-9a-zA-Z ]+"
16071 (substring (org-image-file-name-regexp) 0 -2)
16072 "\\)\\]" (if include-linked "" "\\]")))
16073 old file ov img)
16074 (while (re-search-forward re end t)
16075 (setq old (get-char-property-and-overlay (match-beginning 1)
16076 'org-image-overlay))
16077 (setq file (expand-file-name
16078 (concat (or (match-string 3) "") (match-string 4))))
16079 (when (file-exists-p file)
16080 (if (and (car-safe old) refresh)
16081 (image-refresh (overlay-get (cdr old) 'display))
16082 (setq img (create-image file))
16083 (when img
16084 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
16085 (overlay-put ov 'display img)
16086 (overlay-put ov 'face 'default)
16087 (overlay-put ov 'org-image-overlay t)
16088 (overlay-put ov 'modification-hooks
16089 (list 'org-display-inline-modification-hook))
16090 (push ov org-inline-image-overlays)))))))))
16092 (defun org-display-inline-modification-hook (ov after beg end &optional len)
16093 "Remove inline-display overlay if a corresponding region is modified."
16094 (let ((inhibit-modification-hooks t))
16095 (when (and ov after)
16096 (delete ov org-inline-image-overlays)
16097 (delete-overlay ov))))
16099 (defun org-remove-inline-images ()
16100 "Remove inline display of images."
16101 (interactive)
16102 (mapc 'delete-overlay org-inline-image-overlays)
16103 (setq org-inline-image-overlays nil))
16105 ;;;; Key bindings
16107 ;; Make `C-c C-x' a prefix key
16108 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
16110 ;; TAB key with modifiers
16111 (org-defkey org-mode-map "\C-i" 'org-cycle)
16112 (org-defkey org-mode-map [(tab)] 'org-cycle)
16113 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
16114 (org-defkey org-mode-map [(meta tab)] 'org-complete)
16115 (org-defkey org-mode-map "\M-\t" 'org-complete)
16116 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
16117 ;; The following line is necessary under Suse GNU/Linux
16118 (unless (featurep 'xemacs)
16119 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
16120 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
16121 (define-key org-mode-map [backtab] 'org-shifttab)
16123 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
16124 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
16125 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
16127 ;; Cursor keys with modifiers
16128 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
16129 (org-defkey org-mode-map [(meta right)] 'org-metaright)
16130 (org-defkey org-mode-map [(meta up)] 'org-metaup)
16131 (org-defkey org-mode-map [(meta down)] 'org-metadown)
16133 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
16134 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
16135 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
16136 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
16138 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
16139 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
16140 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
16141 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
16143 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
16144 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
16146 ;; Babel keys
16147 (define-key org-mode-map org-babel-key-prefix org-babel-map)
16148 (mapc (lambda (pair)
16149 (define-key org-babel-map (car pair) (cdr pair)))
16150 org-babel-key-bindings)
16152 ;;; Extra keys for tty access.
16153 ;; We only set them when really needed because otherwise the
16154 ;; menus don't show the simple keys
16156 (when (or org-use-extra-keys
16157 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
16158 (not window-system))
16159 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
16160 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
16161 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
16162 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
16163 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
16164 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
16165 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
16166 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
16167 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
16168 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
16169 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
16170 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
16171 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
16172 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
16173 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
16174 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
16175 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
16176 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
16177 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
16178 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
16179 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
16180 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
16181 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
16182 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
16183 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
16184 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
16185 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
16186 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
16188 ;; All the other keys
16190 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
16191 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
16192 (if (boundp 'narrow-map)
16193 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
16194 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
16195 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
16196 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
16197 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
16198 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
16199 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
16200 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
16201 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
16202 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
16203 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
16204 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
16205 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
16206 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
16207 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
16208 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
16209 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
16210 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
16211 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
16212 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
16213 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
16214 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
16215 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
16216 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
16217 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
16218 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
16219 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
16220 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
16221 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
16222 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
16223 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
16224 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
16225 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
16226 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
16227 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
16228 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
16229 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
16230 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
16231 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
16232 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
16233 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
16234 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
16235 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16236 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
16237 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
16238 (org-defkey org-mode-map "\C-c^" 'org-sort)
16239 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
16240 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
16241 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
16242 (org-defkey org-mode-map "\C-m" 'org-return)
16243 (org-defkey org-mode-map "\C-j" 'org-return-indent)
16244 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
16245 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
16246 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
16247 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
16248 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
16249 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
16250 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
16251 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
16252 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
16253 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
16254 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
16255 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
16256 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
16257 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
16258 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
16259 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
16260 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
16261 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
16262 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
16263 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
16265 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
16266 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
16267 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
16268 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
16270 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
16271 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
16272 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
16273 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
16274 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
16275 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
16276 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
16277 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
16278 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
16279 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
16280 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
16281 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
16282 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
16283 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
16284 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
16285 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
16286 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
16288 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
16289 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
16290 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
16291 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
16293 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
16295 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
16297 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
16298 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
16300 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
16303 (when (featurep 'xemacs)
16304 (org-defkey org-mode-map 'button3 'popup-mode-menu))
16307 (defconst org-speed-commands-default
16309 ("Outline Navigation")
16310 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
16311 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
16312 ("f" . (org-speed-move-safe 'org-forward-same-level))
16313 ("b" . (org-speed-move-safe 'org-backward-same-level))
16314 ("u" . (org-speed-move-safe 'outline-up-heading))
16315 ("j" . org-goto)
16316 ("g" . (org-refile t))
16317 ("Outline Visibility")
16318 ("c" . org-cycle)
16319 ("C" . org-shifttab)
16320 (" " . org-display-outline-path)
16321 ("Outline Structure Editing")
16322 ("U" . org-shiftmetaup)
16323 ("D" . org-shiftmetadown)
16324 ("r" . org-metaright)
16325 ("l" . org-metaleft)
16326 ("R" . org-shiftmetaright)
16327 ("L" . org-shiftmetaleft)
16328 ("i" . (progn (forward-char 1) (call-interactively
16329 'org-insert-heading-respect-content)))
16330 ("^" . org-sort)
16331 ("w" . org-refile)
16332 ("a" . org-archive-subtree-default-with-confirmation)
16333 ("." . outline-mark-subtree)
16334 ("Clock Commands")
16335 ("I" . org-clock-in)
16336 ("O" . org-clock-out)
16337 ("Meta Data Editing")
16338 ("t" . org-todo)
16339 ("0" . (org-priority ?\ ))
16340 ("1" . (org-priority ?A))
16341 ("2" . (org-priority ?B))
16342 ("3" . (org-priority ?C))
16343 (";" . org-set-tags-command)
16344 ("e" . org-set-effort)
16345 ("Agenda Views etc")
16346 ("v" . org-agenda)
16347 ("/" . org-sparse-tree)
16348 ("Misc")
16349 ("o" . org-open-at-point)
16350 ("?" . org-speed-command-help)
16352 "The default speed commands.")
16354 (defun org-print-speed-command (e)
16355 (if (> (length (car e)) 1)
16356 (progn
16357 (princ "\n")
16358 (princ (car e))
16359 (princ "\n")
16360 (princ (make-string (length (car e)) ?-))
16361 (princ "\n"))
16362 (princ (car e))
16363 (princ " ")
16364 (if (symbolp (cdr e))
16365 (princ (symbol-name (cdr e)))
16366 (prin1 (cdr e)))
16367 (princ "\n")))
16369 (defun org-speed-command-help ()
16370 "Show the available speed commands."
16371 (interactive)
16372 (if (not org-use-speed-commands)
16373 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
16374 (with-output-to-temp-buffer "*Help*"
16375 (princ "User-defined Speed commands\n===========================\n")
16376 (mapc 'org-print-speed-command org-speed-commands-user)
16377 (princ "\n")
16378 (princ "Built-in Speed commands\n=======================\n")
16379 (mapc 'org-print-speed-command org-speed-commands-default))
16380 (with-current-buffer "*Help*"
16381 (setq truncate-lines t))))
16383 (defun org-speed-move-safe (cmd)
16384 "Execute CMD, but make sure that the cursor always ends up in a headline.
16385 If not, return to the original position and throw an error."
16386 (interactive)
16387 (let ((pos (point)))
16388 (call-interactively cmd)
16389 (unless (and (bolp) (org-on-heading-p))
16390 (goto-char pos)
16391 (error "Boundary reached while executing %s" cmd))))
16393 (defvar org-self-insert-command-undo-counter 0)
16395 (defvar org-table-auto-blank-field) ; defined in org-table.el
16396 (defvar org-speed-command nil)
16397 (defun org-self-insert-command (N)
16398 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
16399 If the cursor is in a table looking at whitespace, the whitespace is
16400 overwritten, and the table is not marked as requiring realignment."
16401 (interactive "p")
16402 (cond
16403 ((and org-use-speed-commands
16404 (or (and (bolp) (looking-at outline-regexp))
16405 (and (functionp org-use-speed-commands)
16406 (funcall org-use-speed-commands)))
16407 (setq
16408 org-speed-command
16409 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
16410 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
16411 (cond
16412 ((commandp org-speed-command)
16413 (setq this-command org-speed-command)
16414 (call-interactively org-speed-command))
16415 ((functionp org-speed-command)
16416 (funcall org-speed-command))
16417 ((and org-speed-command (listp org-speed-command))
16418 (eval org-speed-command))
16419 (t (let (org-use-speed-commands)
16420 (call-interactively 'org-self-insert-command)))))
16421 ((and
16422 (org-table-p)
16423 (progn
16424 ;; check if we blank the field, and if that triggers align
16425 (and (featurep 'org-table) org-table-auto-blank-field
16426 (member last-command
16427 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
16428 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
16429 ;; got extra space, this field does not determine column width
16430 (let (org-table-may-need-update) (org-table-blank-field))
16431 ;; no extra space, this field may determine column width
16432 (org-table-blank-field)))
16434 (eq N 1)
16435 (looking-at "[^|\n]* |"))
16436 (let (org-table-may-need-update)
16437 (goto-char (1- (match-end 0)))
16438 (delete-backward-char 1)
16439 (goto-char (match-beginning 0))
16440 (self-insert-command N)))
16442 (setq org-table-may-need-update t)
16443 (self-insert-command N)
16444 (org-fix-tags-on-the-fly)
16445 (if org-self-insert-cluster-for-undo
16446 (if (not (eq last-command 'org-self-insert-command))
16447 (setq org-self-insert-command-undo-counter 1)
16448 (if (>= org-self-insert-command-undo-counter 20)
16449 (setq org-self-insert-command-undo-counter 1)
16450 (and (> org-self-insert-command-undo-counter 0)
16451 buffer-undo-list
16452 (not (cadr buffer-undo-list)) ; remove nil entry
16453 (setcdr buffer-undo-list (cddr buffer-undo-list)))
16454 (setq org-self-insert-command-undo-counter
16455 (1+ org-self-insert-command-undo-counter))))))))
16457 (defun org-fix-tags-on-the-fly ()
16458 (when (and (equal (char-after (point-at-bol)) ?*)
16459 (org-on-heading-p))
16460 (org-align-tags-here org-tags-column)))
16462 (defun org-delete-backward-char (N)
16463 "Like `delete-backward-char', insert whitespace at field end in tables.
16464 When deleting backwards, in tables this function will insert whitespace in
16465 front of the next \"|\" separator, to keep the table aligned. The table will
16466 still be marked for re-alignment if the field did fill the entire column,
16467 because, in this case the deletion might narrow the column."
16468 (interactive "p")
16469 (if (and (org-table-p)
16470 (eq N 1)
16471 (string-match "|" (buffer-substring (point-at-bol) (point)))
16472 (looking-at ".*?|"))
16473 (let ((pos (point))
16474 (noalign (looking-at "[^|\n\r]* |"))
16475 (c org-table-may-need-update))
16476 (backward-delete-char N)
16477 (skip-chars-forward "^|")
16478 (insert " ")
16479 (goto-char (1- pos))
16480 ;; noalign: if there were two spaces at the end, this field
16481 ;; does not determine the width of the column.
16482 (if noalign (setq org-table-may-need-update c)))
16483 (backward-delete-char N)
16484 (org-fix-tags-on-the-fly)))
16486 (defun org-delete-char (N)
16487 "Like `delete-char', but insert whitespace at field end in tables.
16488 When deleting characters, in tables this function will insert whitespace in
16489 front of the next \"|\" separator, to keep the table aligned. The table will
16490 still be marked for re-alignment if the field did fill the entire column,
16491 because, in this case the deletion might narrow the column."
16492 (interactive "p")
16493 (if (and (org-table-p)
16494 (not (bolp))
16495 (not (= (char-after) ?|))
16496 (eq N 1))
16497 (if (looking-at ".*?|")
16498 (let ((pos (point))
16499 (noalign (looking-at "[^|\n\r]* |"))
16500 (c org-table-may-need-update))
16501 (replace-match (concat
16502 (substring (match-string 0) 1 -1)
16503 " |"))
16504 (goto-char pos)
16505 ;; noalign: if there were two spaces at the end, this field
16506 ;; does not determine the width of the column.
16507 (if noalign (setq org-table-may-need-update c)))
16508 (delete-char N))
16509 (delete-char N)
16510 (org-fix-tags-on-the-fly)))
16512 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
16513 (put 'org-self-insert-command 'delete-selection t)
16514 (put 'orgtbl-self-insert-command 'delete-selection t)
16515 (put 'org-delete-char 'delete-selection 'supersede)
16516 (put 'org-delete-backward-char 'delete-selection 'supersede)
16517 (put 'org-yank 'delete-selection 'yank)
16519 ;; Make `flyspell-mode' delay after some commands
16520 (put 'org-self-insert-command 'flyspell-delayed t)
16521 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
16522 (put 'org-delete-char 'flyspell-delayed t)
16523 (put 'org-delete-backward-char 'flyspell-delayed t)
16525 ;; Make pabbrev-mode expand after org-mode commands
16526 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
16527 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
16529 ;; How to do this: Measure non-white length of current string
16530 ;; If equal to column width, we should realign.
16532 (defun org-remap (map &rest commands)
16533 "In MAP, remap the functions given in COMMANDS.
16534 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
16535 (let (new old)
16536 (while commands
16537 (setq old (pop commands) new (pop commands))
16538 (if (fboundp 'command-remapping)
16539 (org-defkey map (vector 'remap old) new)
16540 (substitute-key-definition old new map global-map)))))
16542 (when (eq org-enable-table-editor 'optimized)
16543 ;; If the user wants maximum table support, we need to hijack
16544 ;; some standard editing functions
16545 (org-remap org-mode-map
16546 'self-insert-command 'org-self-insert-command
16547 'delete-char 'org-delete-char
16548 'delete-backward-char 'org-delete-backward-char)
16549 (org-defkey org-mode-map "|" 'org-force-self-insert))
16551 (defvar org-ctrl-c-ctrl-c-hook nil
16552 "Hook for functions attaching themselves to `C-c C-c'.
16553 This can be used to add additional functionality to the C-c C-c key which
16554 executes context-dependent commands.
16555 Each function will be called with no arguments. The function must check
16556 if the context is appropriate for it to act. If yes, it should do its
16557 thing and then return a non-nil value. If the context is wrong,
16558 just do nothing and return nil.")
16560 (defvar org-tab-first-hook nil
16561 "Hook for functions to attach themselves to TAB.
16562 See `org-ctrl-c-ctrl-c-hook' for more information.
16563 This hook runs as the first action when TAB is pressed, even before
16564 `org-cycle' messes around with the `outline-regexp' to cater for
16565 inline tasks and plain list item folding.
16566 If any function in this hook returns t, any other actions that
16567 would have been caused by TAB (such as table field motion or visibility
16568 cycling) will not occur.")
16570 (defvar org-tab-after-check-for-table-hook nil
16571 "Hook for functions to attach themselves to TAB.
16572 See `org-ctrl-c-ctrl-c-hook' for more information.
16573 This hook runs after it has been established that the cursor is not in a
16574 table, but before checking if the cursor is in a headline or if global cycling
16575 should be done.
16576 If any function in this hook returns t, not other actions like visibility
16577 cycling will be done.")
16579 (defvar org-tab-after-check-for-cycling-hook nil
16580 "Hook for functions to attach themselves to TAB.
16581 See `org-ctrl-c-ctrl-c-hook' for more information.
16582 This hook runs after it has been established that not table field motion and
16583 not visibility should be done because of current context. This is probably
16584 the place where a package like yasnippets can hook in.")
16586 (defvar org-tab-before-tab-emulation-hook nil
16587 "Hook for functions to attach themselves to TAB.
16588 See `org-ctrl-c-ctrl-c-hook' for more information.
16589 This hook runs after every other options for TAB have been exhausted, but
16590 before indentation and \t insertion takes place.")
16592 (defvar org-metaleft-hook nil
16593 "Hook for functions attaching themselves to `M-left'.
16594 See `org-ctrl-c-ctrl-c-hook' for more information.")
16595 (defvar org-metaright-hook nil
16596 "Hook for functions attaching themselves to `M-right'.
16597 See `org-ctrl-c-ctrl-c-hook' for more information.")
16598 (defvar org-metaup-hook nil
16599 "Hook for functions attaching themselves to `M-up'.
16600 See `org-ctrl-c-ctrl-c-hook' for more information.")
16601 (defvar org-metadown-hook nil
16602 "Hook for functions attaching themselves to `M-down'.
16603 See `org-ctrl-c-ctrl-c-hook' for more information.")
16604 (defvar org-shiftmetaleft-hook nil
16605 "Hook for functions attaching themselves to `M-S-left'.
16606 See `org-ctrl-c-ctrl-c-hook' for more information.")
16607 (defvar org-shiftmetaright-hook nil
16608 "Hook for functions attaching themselves to `M-S-right'.
16609 See `org-ctrl-c-ctrl-c-hook' for more information.")
16610 (defvar org-shiftmetaup-hook nil
16611 "Hook for functions attaching themselves to `M-S-up'.
16612 See `org-ctrl-c-ctrl-c-hook' for more information.")
16613 (defvar org-shiftmetadown-hook nil
16614 "Hook for functions attaching themselves to `M-S-down'.
16615 See `org-ctrl-c-ctrl-c-hook' for more information.")
16616 (defvar org-metareturn-hook nil
16617 "Hook for functions attaching themselves to `M-RET'.
16618 See `org-ctrl-c-ctrl-c-hook' for more information.")
16619 (defvar org-shiftup-hook nil
16620 "Hook for functions attaching themselves to `S-up'.
16621 See `org-ctrl-c-ctrl-c-hook' for more information.")
16622 (defvar org-shiftup-final-hook nil
16623 "Hook for functions attaching themselves to `S-up'.
16624 This one runs after all other options except shift-select have been excluded.
16625 See `org-ctrl-c-ctrl-c-hook' for more information.")
16626 (defvar org-shiftdown-hook nil
16627 "Hook for functions attaching themselves to `S-down'.
16628 See `org-ctrl-c-ctrl-c-hook' for more information.")
16629 (defvar org-shiftdown-final-hook nil
16630 "Hook for functions attaching themselves to `S-down'.
16631 This one runs after all other options except shift-select have been excluded.
16632 See `org-ctrl-c-ctrl-c-hook' for more information.")
16633 (defvar org-shiftleft-hook nil
16634 "Hook for functions attaching themselves to `S-left'.
16635 See `org-ctrl-c-ctrl-c-hook' for more information.")
16636 (defvar org-shiftleft-final-hook nil
16637 "Hook for functions attaching themselves to `S-left'.
16638 This one runs after all other options except shift-select have been excluded.
16639 See `org-ctrl-c-ctrl-c-hook' for more information.")
16640 (defvar org-shiftright-hook nil
16641 "Hook for functions attaching themselves to `S-right'.
16642 See `org-ctrl-c-ctrl-c-hook' for more information.")
16643 (defvar org-shiftright-final-hook nil
16644 "Hook for functions attaching themselves to `S-right'.
16645 This one runs after all other options except shift-select have been excluded.
16646 See `org-ctrl-c-ctrl-c-hook' for more information.")
16648 (defun org-modifier-cursor-error ()
16649 "Throw an error, a modified cursor command was applied in wrong context."
16650 (error "This command is active in special context like tables, headlines or items"))
16652 (defun org-shiftselect-error ()
16653 "Throw an error because Shift-Cursor command was applied in wrong context."
16654 (if (and (boundp 'shift-select-mode) shift-select-mode)
16655 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
16656 (error "This command works only in special context like headlines or timestamps")))
16658 (defun org-call-for-shift-select (cmd)
16659 (let ((this-command-keys-shift-translated t))
16660 (call-interactively cmd)))
16662 (defun org-shifttab (&optional arg)
16663 "Global visibility cycling or move to previous table field.
16664 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
16665 on context.
16666 See the individual commands for more information."
16667 (interactive "P")
16668 (cond
16669 ((org-at-table-p) (call-interactively 'org-table-previous-field))
16670 ((integerp arg)
16671 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
16672 (message "Content view to level: %d" arg)
16673 (org-content (prefix-numeric-value arg2))
16674 (setq org-cycle-global-status 'overview)))
16675 (t (call-interactively 'org-global-cycle))))
16677 (defun org-shiftmetaleft ()
16678 "Promote subtree or delete table column.
16679 Calls `org-promote-subtree', `org-outdent-item',
16680 or `org-table-delete-column', depending on context.
16681 See the individual commands for more information."
16682 (interactive)
16683 (cond
16684 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
16685 ((org-at-table-p) (call-interactively 'org-table-delete-column))
16686 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
16687 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
16688 (t (org-modifier-cursor-error))))
16690 (defun org-shiftmetaright ()
16691 "Demote subtree or insert table column.
16692 Calls `org-demote-subtree', `org-indent-item',
16693 or `org-table-insert-column', depending on context.
16694 See the individual commands for more information."
16695 (interactive)
16696 (cond
16697 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
16698 ((org-at-table-p) (call-interactively 'org-table-insert-column))
16699 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
16700 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
16701 (t (org-modifier-cursor-error))))
16703 (defun org-shiftmetaup (&optional arg)
16704 "Move subtree up or kill table row.
16705 Calls `org-move-subtree-up' or `org-table-kill-row' or
16706 `org-move-item-up' depending on context. See the individual commands
16707 for more information."
16708 (interactive "P")
16709 (cond
16710 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
16711 ((org-at-table-p) (call-interactively 'org-table-kill-row))
16712 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
16713 ((org-at-item-p) (call-interactively 'org-move-item-up))
16714 (t (org-modifier-cursor-error))))
16716 (defun org-shiftmetadown (&optional arg)
16717 "Move subtree down or insert table row.
16718 Calls `org-move-subtree-down' or `org-table-insert-row' or
16719 `org-move-item-down', depending on context. See the individual
16720 commands for more information."
16721 (interactive "P")
16722 (cond
16723 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
16724 ((org-at-table-p) (call-interactively 'org-table-insert-row))
16725 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16726 ((org-at-item-p) (call-interactively 'org-move-item-down))
16727 (t (org-modifier-cursor-error))))
16729 (defsubst org-hidden-tree-error ()
16730 (error
16731 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
16733 (defun org-metaleft (&optional arg)
16734 "Promote heading or move table column to left.
16735 Calls `org-do-promote' or `org-table-move-column', depending on context.
16736 With no specific context, calls the Emacs default `backward-word'.
16737 See the individual commands for more information."
16738 (interactive "P")
16739 (cond
16740 ((run-hook-with-args-until-success 'org-metaleft-hook))
16741 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
16742 ((or (org-on-heading-p)
16743 (and (org-region-active-p)
16744 (save-excursion
16745 (goto-char (region-beginning))
16746 (org-on-heading-p))))
16747 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
16748 (call-interactively 'org-do-promote))
16749 ((or (org-at-item-p)
16750 (and (org-region-active-p)
16751 (save-excursion
16752 (goto-char (region-beginning))
16753 (org-at-item-p))))
16754 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
16755 (call-interactively 'org-outdent-item))
16756 (t (call-interactively 'backward-word))))
16758 (defun org-metaright (&optional arg)
16759 "Demote subtree or move table column to right.
16760 Calls `org-do-demote' or `org-table-move-column', depending on context.
16761 With no specific context, calls the Emacs default `forward-word'.
16762 See the individual commands for more information."
16763 (interactive "P")
16764 (cond
16765 ((run-hook-with-args-until-success 'org-metaright-hook))
16766 ((org-at-table-p) (call-interactively 'org-table-move-column))
16767 ((or (org-on-heading-p)
16768 (and (org-region-active-p)
16769 (save-excursion
16770 (goto-char (region-beginning))
16771 (org-on-heading-p))))
16772 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
16773 (call-interactively 'org-do-demote))
16774 ((or (org-at-item-p)
16775 (and (org-region-active-p)
16776 (save-excursion
16777 (goto-char (region-beginning))
16778 (org-at-item-p))))
16779 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
16780 (call-interactively 'org-indent-item))
16781 (t (call-interactively 'forward-word))))
16783 (defun org-check-for-hidden (what)
16784 "Check if there are hidden headlines/items in the current visual line.
16785 WHAT can be either `headlines' or `items'. If the current line is
16786 an outline or item heading and it has a folded subtree below it,
16787 this fucntion returns t, nil otherwise."
16788 (let ((re (cond
16789 ((eq what 'headlines) (concat "^" org-outline-regexp))
16790 ((eq what 'items) (concat "^" (org-item-re t)))
16791 (t (error "This should not happen"))))
16792 beg end)
16793 (save-excursion
16794 (catch 'exit
16795 (unless (org-region-active-p)
16796 (setq beg (point-at-bol))
16797 (beginning-of-line 2)
16798 (while (and (not (eobp)) ;; this is like `next-line'
16799 (get-char-property (1- (point)) 'invisible))
16800 (beginning-of-line 2))
16801 (setq end (point))
16802 (goto-char beg)
16803 (goto-char (point-at-eol))
16804 (setq end (max end (point)))
16805 (while (re-search-forward re end t)
16806 (if (get-char-property (match-beginning 0) 'invisible)
16807 (throw 'exit t))))
16808 nil))))
16810 (defun org-metaup (&optional arg)
16811 "Move subtree up or move table row up.
16812 Calls `org-move-subtree-up' or `org-table-move-row' or
16813 `org-move-item-up', depending on context. See the individual commands
16814 for more information."
16815 (interactive "P")
16816 (cond
16817 ((run-hook-with-args-until-success 'org-metaup-hook))
16818 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
16819 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
16820 ((org-at-item-p) (call-interactively 'org-move-item-up))
16821 (t (transpose-lines 1) (beginning-of-line -1))))
16823 (defun org-metadown (&optional arg)
16824 "Move subtree down or move table row down.
16825 Calls `org-move-subtree-down' or `org-table-move-row' or
16826 `org-move-item-down', depending on context. See the individual
16827 commands for more information."
16828 (interactive "P")
16829 (cond
16830 ((run-hook-with-args-until-success 'org-metadown-hook))
16831 ((org-at-table-p) (call-interactively 'org-table-move-row))
16832 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16833 ((org-at-item-p) (call-interactively 'org-move-item-down))
16834 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
16836 (defun org-shiftup (&optional arg)
16837 "Increase item in timestamp or increase priority of current headline.
16838 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
16839 depending on context. See the individual commands for more information."
16840 (interactive "P")
16841 (cond
16842 ((run-hook-with-args-until-success 'org-shiftup-hook))
16843 ((and org-support-shift-select (org-region-active-p))
16844 (org-call-for-shift-select 'previous-line))
16845 ((org-at-timestamp-p t)
16846 (call-interactively (if org-edit-timestamp-down-means-later
16847 'org-timestamp-down 'org-timestamp-up)))
16848 ((and (not (eq org-support-shift-select 'always))
16849 org-enable-priority-commands
16850 (org-on-heading-p))
16851 (call-interactively 'org-priority-up))
16852 ((and (not org-support-shift-select) (org-at-item-p))
16853 (call-interactively 'org-previous-item))
16854 ((org-clocktable-try-shift 'up arg))
16855 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
16856 (org-support-shift-select
16857 (org-call-for-shift-select 'previous-line))
16858 (t (org-shiftselect-error))))
16860 (defun org-shiftdown (&optional arg)
16861 "Decrease item in timestamp or decrease priority of current headline.
16862 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
16863 depending on context. See the individual commands for more information."
16864 (interactive "P")
16865 (cond
16866 ((run-hook-with-args-until-success 'org-shiftdown-hook))
16867 ((and org-support-shift-select (org-region-active-p))
16868 (org-call-for-shift-select 'next-line))
16869 ((org-at-timestamp-p t)
16870 (call-interactively (if org-edit-timestamp-down-means-later
16871 'org-timestamp-up 'org-timestamp-down)))
16872 ((and (not (eq org-support-shift-select 'always))
16873 org-enable-priority-commands
16874 (org-on-heading-p))
16875 (call-interactively 'org-priority-down))
16876 ((and (not org-support-shift-select) (org-at-item-p))
16877 (call-interactively 'org-next-item))
16878 ((org-clocktable-try-shift 'down arg))
16879 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
16880 (org-support-shift-select
16881 (org-call-for-shift-select 'next-line))
16882 (t (org-shiftselect-error))))
16884 (defun org-shiftright (&optional arg)
16885 "Cycle the thing at point or in the current line, depending on context.
16886 Depending on context, this does one of the following:
16888 - switch a timestamp at point one day into the future
16889 - on a headline, switch to the next TODO keyword.
16890 - on an item, switch entire list to the next bullet type
16891 - on a property line, switch to the next allowed value
16892 - on a clocktable definition line, move time block into the future"
16893 (interactive "P")
16894 (cond
16895 ((run-hook-with-args-until-success 'org-shiftright-hook))
16896 ((and org-support-shift-select (org-region-active-p))
16897 (org-call-for-shift-select 'forward-char))
16898 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
16899 ((and (not (eq org-support-shift-select 'always))
16900 (org-on-heading-p))
16901 (let ((org-inhibit-logging
16902 (not org-treat-S-cursor-todo-selection-as-state-change))
16903 (org-inhibit-blocking
16904 (not org-treat-S-cursor-todo-selection-as-state-change)))
16905 (org-call-with-arg 'org-todo 'right)))
16906 ((or (and org-support-shift-select
16907 (not (eq org-support-shift-select 'always))
16908 (org-at-item-bullet-p))
16909 (and (not org-support-shift-select) (org-at-item-p)))
16910 (org-call-with-arg 'org-cycle-list-bullet nil))
16911 ((and (not (eq org-support-shift-select 'always))
16912 (org-at-property-p))
16913 (call-interactively 'org-property-next-allowed-value))
16914 ((org-clocktable-try-shift 'right arg))
16915 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
16916 (org-support-shift-select
16917 (org-call-for-shift-select 'forward-char))
16918 (t (org-shiftselect-error))))
16920 (defun org-shiftleft (&optional arg)
16921 "Cycle the thing at point or in the current line, depending on context.
16922 Depending on context, this does one of the following:
16924 - switch a timestamp at point one day into the past
16925 - on a headline, switch to the previous TODO keyword.
16926 - on an item, switch entire list to the previous bullet type
16927 - on a property line, switch to the previous allowed value
16928 - on a clocktable definition line, move time block into the past"
16929 (interactive "P")
16930 (cond
16931 ((run-hook-with-args-until-success 'org-shiftleft-hook))
16932 ((and org-support-shift-select (org-region-active-p))
16933 (org-call-for-shift-select 'backward-char))
16934 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
16935 ((and (not (eq org-support-shift-select 'always))
16936 (org-on-heading-p))
16937 (let ((org-inhibit-logging
16938 (not org-treat-S-cursor-todo-selection-as-state-change))
16939 (org-inhibit-blocking
16940 (not org-treat-S-cursor-todo-selection-as-state-change)))
16941 (org-call-with-arg 'org-todo 'left)))
16942 ((or (and org-support-shift-select
16943 (not (eq org-support-shift-select 'always))
16944 (org-at-item-bullet-p))
16945 (and (not org-support-shift-select) (org-at-item-p)))
16946 (org-call-with-arg 'org-cycle-list-bullet 'previous))
16947 ((and (not (eq org-support-shift-select 'always))
16948 (org-at-property-p))
16949 (call-interactively 'org-property-previous-allowed-value))
16950 ((org-clocktable-try-shift 'left arg))
16951 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
16952 (org-support-shift-select
16953 (org-call-for-shift-select 'backward-char))
16954 (t (org-shiftselect-error))))
16956 (defun org-shiftcontrolright ()
16957 "Switch to next TODO set."
16958 (interactive)
16959 (cond
16960 ((and org-support-shift-select (org-region-active-p))
16961 (org-call-for-shift-select 'forward-word))
16962 ((and (not (eq org-support-shift-select 'always))
16963 (org-on-heading-p))
16964 (org-call-with-arg 'org-todo 'nextset))
16965 (org-support-shift-select
16966 (org-call-for-shift-select 'forward-word))
16967 (t (org-shiftselect-error))))
16969 (defun org-shiftcontrolleft ()
16970 "Switch to previous TODO set."
16971 (interactive)
16972 (cond
16973 ((and org-support-shift-select (org-region-active-p))
16974 (org-call-for-shift-select 'backward-word))
16975 ((and (not (eq org-support-shift-select 'always))
16976 (org-on-heading-p))
16977 (org-call-with-arg 'org-todo 'previousset))
16978 (org-support-shift-select
16979 (org-call-for-shift-select 'backward-word))
16980 (t (org-shiftselect-error))))
16982 (defun org-ctrl-c-ret ()
16983 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
16984 (interactive)
16985 (cond
16986 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
16987 (t (call-interactively 'org-insert-heading))))
16989 (defun org-copy-special ()
16990 "Copy region in table or copy current subtree.
16991 Calls `org-table-copy' or `org-copy-subtree', depending on context.
16992 See the individual commands for more information."
16993 (interactive)
16994 (call-interactively
16995 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
16997 (defun org-cut-special ()
16998 "Cut region in table or cut current subtree.
16999 Calls `org-table-copy' or `org-cut-subtree', depending on context.
17000 See the individual commands for more information."
17001 (interactive)
17002 (call-interactively
17003 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
17005 (defun org-paste-special (arg)
17006 "Paste rectangular region into table, or past subtree relative to level.
17007 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
17008 See the individual commands for more information."
17009 (interactive "P")
17010 (if (org-at-table-p)
17011 (org-table-paste-rectangle)
17012 (org-paste-subtree arg)))
17014 (defun org-edit-special (&optional arg)
17015 "Call a special editor for the stuff at point.
17016 When at a table, call the formula editor with `org-table-edit-formulas'.
17017 When at the first line of an src example, call `org-edit-src-code'.
17018 When in an #+include line, visit the include file. Otherwise call
17019 `ffap' to visit the file at point."
17020 (interactive)
17021 ;; possibly prep session before editing source
17022 (when arg
17023 (let* ((info (org-babel-get-src-block-info))
17024 (lang (nth 0 info))
17025 (params (nth 2 info))
17026 (session (cdr (assoc :session params))))
17027 (when (and info session) ;; we are in a source-code block with a session
17028 (funcall
17029 (intern (concat "org-babel-prep-session:" lang)) session params))))
17030 (cond ;; proceed with `org-edit-special'
17031 ((save-excursion
17032 (beginning-of-line 1)
17033 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
17034 (find-file (org-trim (match-string 1))))
17035 ((org-edit-src-code))
17036 ((org-edit-fixed-width-region))
17037 ((org-at-table.el-p)
17038 (org-edit-src-code))
17039 ((org-at-table-p)
17040 (call-interactively 'org-table-edit-formulas))
17041 (t (call-interactively 'ffap))))
17044 (defun org-ctrl-c-ctrl-c (&optional arg)
17045 "Set tags in headline, or update according to changed information at point.
17047 This command does many different things, depending on context:
17049 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
17050 this is what we do.
17052 - If the cursor is on a statistics cookie, update it.
17054 - If the cursor is in a headline, prompt for tags and insert them
17055 into the current line, aligned to `org-tags-column'. When called
17056 with prefix arg, realign all tags in the current buffer.
17058 - If the cursor is in one of the special #+KEYWORD lines, this
17059 triggers scanning the buffer for these lines and updating the
17060 information.
17062 - If the cursor is inside a table, realign the table. This command
17063 works even if the automatic table editor has been turned off.
17065 - If the cursor is on a #+TBLFM line, re-apply the formulas to
17066 the entire table.
17068 - If the cursor is at a footnote reference or definition, jump to
17069 the corresponding definition or references, respectively.
17071 - If the cursor is a the beginning of a dynamic block, update it.
17073 - If the current buffer is a remember buffer, close note and file
17074 it. A prefix argument of 1 files to the default location
17075 without further interaction. A prefix argument of 2 files to
17076 the currently clocking task.
17078 - If the cursor is on a <<<target>>>, update radio targets and corresponding
17079 links in this buffer.
17081 - If the cursor is on a numbered item in a plain list, renumber the
17082 ordered list.
17084 - If the cursor is on a checkbox, toggle it.
17086 - If the cursor is on a code block, evaluate it. The variable
17087 `org-confirm-babel-evaluate' can be used to control prompting
17088 before code block evaluation, by default every code block
17089 evaluation requires confirmation. Code block evaluation can be
17090 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
17091 (interactive "P")
17092 (let ((org-enable-table-editor t))
17093 (cond
17094 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
17095 org-occur-highlights
17096 org-latex-fragment-image-overlays)
17097 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
17098 (org-remove-occur-highlights)
17099 (org-remove-latex-fragment-image-overlays)
17100 (message "Temporary highlights/overlays removed from current buffer"))
17101 ((and (local-variable-p 'org-finish-function (current-buffer))
17102 (fboundp org-finish-function))
17103 (funcall org-finish-function))
17104 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
17105 ((or (looking-at org-property-start-re)
17106 (org-at-property-p))
17107 (call-interactively 'org-property-action))
17108 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
17109 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
17110 (or (org-on-heading-p) (org-at-item-p)))
17111 (call-interactively 'org-update-statistics-cookies))
17112 ((org-on-heading-p) (call-interactively 'org-set-tags))
17113 ((org-at-table.el-p)
17114 (message "Use C-c ' to edit table.el tables"))
17115 ((org-at-table-p)
17116 (org-table-maybe-eval-formula)
17117 (if arg
17118 (call-interactively 'org-table-recalculate)
17119 (org-table-maybe-recalculate-line))
17120 (call-interactively 'org-table-align))
17121 ((or (org-footnote-at-reference-p)
17122 (org-footnote-at-definition-p))
17123 (call-interactively 'org-footnote-action))
17124 ((org-at-item-checkbox-p)
17125 (call-interactively 'org-toggle-checkbox)
17126 (org-list-send-list 'maybe))
17127 ((org-at-item-p)
17128 (if arg
17129 (call-interactively 'org-toggle-checkbox)
17130 (call-interactively 'org-maybe-renumber-ordered-list))
17131 (org-list-send-list 'maybe))
17132 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
17133 ;; Dynamic block
17134 (beginning-of-line 1)
17135 (save-excursion (org-update-dblock)))
17136 ((save-excursion
17137 (beginning-of-line 1)
17138 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
17139 (cond
17140 ((equal (match-string 1) "TBLFM")
17141 ;; Recalculate the table before this line
17142 (save-excursion
17143 (beginning-of-line 1)
17144 (skip-chars-backward " \r\n\t")
17145 (if (org-at-table-p)
17146 (org-call-with-arg 'org-table-recalculate (or arg t)))))
17148 (let ((org-inhibit-startup-visibility-stuff t)
17149 (org-startup-align-all-tables nil))
17150 (org-save-outline-visibility 'use-markers (org-mode-restart)))
17151 (message "Local setup has been refreshed"))))
17152 ((org-clock-update-time-maybe))
17153 (t (error "C-c C-c can do nothing useful at this location")))))
17155 (defun org-mode-restart ()
17156 "Restart Org-mode, to scan again for special lines.
17157 Also updates the keyword regular expressions."
17158 (interactive)
17159 (org-mode)
17160 (message "Org-mode restarted"))
17162 (defun org-kill-note-or-show-branches ()
17163 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
17164 (interactive)
17165 (if (not org-finish-function)
17166 (progn
17167 (hide-subtree)
17168 (call-interactively 'show-branches))
17169 (let ((org-note-abort t))
17170 (funcall org-finish-function))))
17172 (defun org-return (&optional indent)
17173 "Goto next table row or insert a newline.
17174 Calls `org-table-next-row' or `newline', depending on context.
17175 See the individual commands for more information."
17176 (interactive)
17177 (cond
17178 ((bobp) (if indent (newline-and-indent) (newline)))
17179 ((org-at-table-p)
17180 (org-table-justify-field-maybe)
17181 (call-interactively 'org-table-next-row))
17182 ((and org-return-follows-link
17183 (eq (get-text-property (point) 'face) 'org-link))
17184 (call-interactively 'org-open-at-point))
17185 ((and (org-at-heading-p)
17186 (looking-at
17187 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
17188 (org-show-entry)
17189 (end-of-line 1)
17190 (newline))
17191 (t (if indent (newline-and-indent) (newline)))))
17193 (defun org-return-indent ()
17194 "Goto next table row or insert a newline and indent.
17195 Calls `org-table-next-row' or `newline-and-indent', depending on
17196 context. See the individual commands for more information."
17197 (interactive)
17198 (org-return t))
17200 (defun org-ctrl-c-star ()
17201 "Compute table, or change heading status of lines.
17202 Calls `org-table-recalculate' or `org-toggle-heading',
17203 depending on context."
17204 (interactive)
17205 (cond
17206 ((org-at-table-p)
17207 (call-interactively 'org-table-recalculate))
17209 ;; Convert all lines in region to list items
17210 (call-interactively 'org-toggle-heading))))
17212 (defun org-ctrl-c-minus ()
17213 "Insert separator line in table or modify bullet status of line.
17214 Also turns a plain line or a region of lines into list items.
17215 Calls `org-table-insert-hline', `org-toggle-item', or
17216 `org-cycle-list-bullet', depending on context."
17217 (interactive)
17218 (cond
17219 ((org-at-table-p)
17220 (call-interactively 'org-table-insert-hline))
17221 ((org-region-active-p)
17222 (call-interactively 'org-toggle-item))
17223 ((org-in-item-p)
17224 (call-interactively 'org-cycle-list-bullet))
17226 (call-interactively 'org-toggle-item))))
17228 (defun org-toggle-item ()
17229 "Convert headings or normal lines to items, items to normal lines.
17230 If there is no active region, only the current line is considered.
17232 If the first line in the region is a headline, convert all headlines to items.
17234 If the first line in the region is an item, convert all items to normal lines.
17236 If the first line is normal text, add an item bullet to each line."
17237 (interactive)
17238 (let (l2 l beg end)
17239 (if (org-region-active-p)
17240 (setq beg (region-beginning) end (region-end))
17241 (setq beg (point-at-bol)
17242 end (min (1+ (point-at-eol)) (point-max))))
17243 (save-excursion
17244 (goto-char end)
17245 (setq l2 (org-current-line))
17246 (goto-char beg)
17247 (beginning-of-line 1)
17248 (setq l (1- (org-current-line)))
17249 (if (org-at-item-p)
17250 ;; We already have items, de-itemize
17251 (while (< (setq l (1+ l)) l2)
17252 (when (org-at-item-p)
17253 (goto-char (match-beginning 2))
17254 (delete-region (match-beginning 2) (match-end 2))
17255 (and (looking-at "[ \t]+") (replace-match "")))
17256 (beginning-of-line 2))
17257 (if (org-on-heading-p)
17258 ;; Headings, convert to items
17259 (while (< (setq l (1+ l)) l2)
17260 (if (looking-at org-outline-regexp)
17261 (replace-match "- " t t))
17262 (beginning-of-line 2))
17263 ;; normal lines, turn them into items
17264 (while (< (setq l (1+ l)) l2)
17265 (unless (org-at-item-p)
17266 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
17267 (replace-match "\\1- \\2")))
17268 (beginning-of-line 2)))))))
17270 (defun org-toggle-heading (&optional nstars)
17271 "Convert headings to normal text, or items or text to headings.
17272 If there is no active region, only the current line is considered.
17274 If the first line is a heading, remove the stars from all headlines
17275 in the region.
17277 If the first line is a plain list item, turn all plain list items
17278 into headings.
17280 If the first line is a normal line, turn each and every line in the
17281 region into a heading.
17283 When converting a line into a heading, the number of stars is chosen
17284 such that the lines become children of the current entry. However,
17285 when a prefix argument is given, its value determines the number of
17286 stars to add."
17287 (interactive "P")
17288 (let (l2 l itemp beg end)
17289 (if (org-region-active-p)
17290 (setq beg (region-beginning) end (region-end))
17291 (setq beg (point-at-bol)
17292 end (min (1+ (point-at-eol)) (point-max))))
17293 (save-excursion
17294 (goto-char end)
17295 (setq l2 (org-current-line))
17296 (goto-char beg)
17297 (beginning-of-line 1)
17298 (setq l (1- (org-current-line)))
17299 (if (org-on-heading-p)
17300 ;; We already have headlines, de-star them
17301 (while (< (setq l (1+ l)) l2)
17302 (when (org-on-heading-p t)
17303 (and (looking-at outline-regexp) (replace-match "")))
17304 (beginning-of-line 2))
17305 (setq itemp (org-at-item-p))
17306 (let* ((stars
17307 (if nstars
17308 (make-string (prefix-numeric-value current-prefix-arg)
17310 (save-excursion
17311 (if (re-search-backward org-complex-heading-regexp nil t)
17312 (match-string 1) ""))))
17313 (add-stars (cond (nstars "")
17314 ((equal stars "") "*")
17315 (org-odd-levels-only "**")
17316 (t "*")))
17317 (rpl (concat stars add-stars " ")))
17318 (while (< (setq l (1+ l)) l2)
17319 (if itemp
17320 (and (org-at-item-p) (replace-match rpl t t))
17321 (unless (org-on-heading-p)
17322 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
17323 (replace-match (concat rpl (match-string 2))))))
17324 (beginning-of-line 2)))))))
17326 (defun org-meta-return (&optional arg)
17327 "Insert a new heading or wrap a region in a table.
17328 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
17329 See the individual commands for more information."
17330 (interactive "P")
17331 (cond
17332 ((run-hook-with-args-until-success 'org-metareturn-hook))
17333 ((org-at-table-p)
17334 (call-interactively 'org-table-wrap-region))
17335 (t (call-interactively 'org-insert-heading))))
17337 ;;; Menu entries
17339 ;; Define the Org-mode menus
17340 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
17341 '("Tbl"
17342 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
17343 ["Next Field" org-cycle (org-at-table-p)]
17344 ["Previous Field" org-shifttab (org-at-table-p)]
17345 ["Next Row" org-return (org-at-table-p)]
17346 "--"
17347 ["Blank Field" org-table-blank-field (org-at-table-p)]
17348 ["Edit Field" org-table-edit-field (org-at-table-p)]
17349 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
17350 "--"
17351 ("Column"
17352 ["Move Column Left" org-metaleft (org-at-table-p)]
17353 ["Move Column Right" org-metaright (org-at-table-p)]
17354 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
17355 ["Insert Column" org-shiftmetaright (org-at-table-p)])
17356 ("Row"
17357 ["Move Row Up" org-metaup (org-at-table-p)]
17358 ["Move Row Down" org-metadown (org-at-table-p)]
17359 ["Delete Row" org-shiftmetaup (org-at-table-p)]
17360 ["Insert Row" org-shiftmetadown (org-at-table-p)]
17361 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
17362 "--"
17363 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
17364 ("Rectangle"
17365 ["Copy Rectangle" org-copy-special (org-at-table-p)]
17366 ["Cut Rectangle" org-cut-special (org-at-table-p)]
17367 ["Paste Rectangle" org-paste-special (org-at-table-p)]
17368 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
17369 "--"
17370 ("Calculate"
17371 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
17372 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
17373 ["Edit Formulas" org-edit-special (org-at-table-p)]
17374 "--"
17375 ["Recalculate line" org-table-recalculate (org-at-table-p)]
17376 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
17377 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
17378 "--"
17379 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
17380 "--"
17381 ["Sum Column/Rectangle" org-table-sum
17382 (or (org-at-table-p) (org-region-active-p))]
17383 ["Which Column?" org-table-current-column (org-at-table-p)])
17384 ["Debug Formulas"
17385 org-table-toggle-formula-debugger
17386 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
17387 ["Show Col/Row Numbers"
17388 org-table-toggle-coordinate-overlays
17389 :style toggle
17390 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
17391 "--"
17392 ["Create" org-table-create (and (not (org-at-table-p))
17393 org-enable-table-editor)]
17394 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
17395 ["Import from File" org-table-import (not (org-at-table-p))]
17396 ["Export to File" org-table-export (org-at-table-p)]
17397 "--"
17398 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
17400 (easy-menu-define org-org-menu org-mode-map "Org menu"
17401 '("Org"
17402 ("Show/Hide"
17403 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
17404 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
17405 ["Sparse Tree..." org-sparse-tree t]
17406 ["Reveal Context" org-reveal t]
17407 ["Show All" show-all t]
17408 "--"
17409 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
17410 "--"
17411 ["New Heading" org-insert-heading t]
17412 ("Navigate Headings"
17413 ["Up" outline-up-heading t]
17414 ["Next" outline-next-visible-heading t]
17415 ["Previous" outline-previous-visible-heading t]
17416 ["Next Same Level" outline-forward-same-level t]
17417 ["Previous Same Level" outline-backward-same-level t]
17418 "--"
17419 ["Jump" org-goto t])
17420 ("Edit Structure"
17421 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
17422 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
17423 "--"
17424 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
17425 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
17426 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
17427 "--"
17428 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
17429 "--"
17430 ["Promote Heading" org-metaleft (not (org-at-table-p))]
17431 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
17432 ["Demote Heading" org-metaright (not (org-at-table-p))]
17433 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
17434 "--"
17435 ["Sort Region/Children" org-sort (not (org-at-table-p))]
17436 "--"
17437 ["Convert to odd levels" org-convert-to-odd-levels t]
17438 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
17439 ("Editing"
17440 ["Emphasis..." org-emphasize t]
17441 ["Edit Source Example" org-edit-special t]
17442 "--"
17443 ["Footnote new/jump" org-footnote-action t]
17444 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
17445 ("Archive"
17446 ["Archive (default method)" org-archive-subtree-default t]
17447 "--"
17448 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
17449 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
17450 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
17452 "--"
17453 ("Hyperlinks"
17454 ["Store Link (Global)" org-store-link t]
17455 ["Find existing link to here" org-occur-link-in-agenda-files t]
17456 ["Insert Link" org-insert-link t]
17457 ["Follow Link" org-open-at-point t]
17458 "--"
17459 ["Next link" org-next-link t]
17460 ["Previous link" org-previous-link t]
17461 "--"
17462 ["Descriptive Links"
17463 (progn (add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
17464 :style radio
17465 :selected (member '(org-link) buffer-invisibility-spec)]
17466 ["Literal Links"
17467 (progn
17468 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
17469 :style radio
17470 :selected (not (member '(org-link) buffer-invisibility-spec))])
17471 "--"
17472 ("TODO Lists"
17473 ["TODO/DONE/-" org-todo t]
17474 ("Select keyword"
17475 ["Next keyword" org-shiftright (org-on-heading-p)]
17476 ["Previous keyword" org-shiftleft (org-on-heading-p)]
17477 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
17478 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
17479 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
17480 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
17481 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
17482 "--"
17483 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
17484 :selected org-enforce-todo-dependencies :style toggle :active t]
17485 "Settings for tree at point"
17486 ["Do Children sequentially" org-toggle-ordered-property :style radio
17487 :selected (ignore-errors (org-entry-get nil "ORDERED"))
17488 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
17489 ["Do Children parallel" org-toggle-ordered-property :style radio
17490 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
17491 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
17492 "--"
17493 ["Set Priority" org-priority t]
17494 ["Priority Up" org-shiftup t]
17495 ["Priority Down" org-shiftdown t]
17496 "--"
17497 ["Get news from all feeds" org-feed-update-all t]
17498 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
17499 ["Customize feeds" (customize-variable 'org-feed-alist) t])
17500 ("TAGS and Properties"
17501 ["Set Tags" org-set-tags-command t]
17502 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
17503 "--"
17504 ["Set property" org-set-property t]
17505 ["Column view of properties" org-columns t]
17506 ["Insert Column View DBlock" org-insert-columns-dblock t])
17507 ("Dates and Scheduling"
17508 ["Timestamp" org-time-stamp t]
17509 ["Timestamp (inactive)" org-time-stamp-inactive t]
17510 ("Change Date"
17511 ["1 Day Later" org-shiftright t]
17512 ["1 Day Earlier" org-shiftleft t]
17513 ["1 ... Later" org-shiftup t]
17514 ["1 ... Earlier" org-shiftdown t])
17515 ["Compute Time Range" org-evaluate-time-range t]
17516 ["Schedule Item" org-schedule t]
17517 ["Deadline" org-deadline t]
17518 "--"
17519 ["Custom time format" org-toggle-time-stamp-overlays
17520 :style radio :selected org-display-custom-times]
17521 "--"
17522 ["Goto Calendar" org-goto-calendar t]
17523 ["Date from Calendar" org-date-from-calendar t]
17524 "--"
17525 ["Start/Restart Timer" org-timer-start t]
17526 ["Pause/Continue Timer" org-timer-pause-or-continue t]
17527 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
17528 ["Insert Timer String" org-timer t]
17529 ["Insert Timer Item" org-timer-item t])
17530 ("Logging work"
17531 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
17532 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
17533 ["Clock out" org-clock-out t]
17534 ["Clock cancel" org-clock-cancel t]
17535 "--"
17536 ["Mark as default task" org-clock-mark-default-task t]
17537 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
17538 ["Goto running clock" org-clock-goto t]
17539 "--"
17540 ["Display times" org-clock-display t]
17541 ["Create clock table" org-clock-report t]
17542 "--"
17543 ["Record DONE time"
17544 (progn (setq org-log-done (not org-log-done))
17545 (message "Switching to %s will %s record a timestamp"
17546 (car org-done-keywords)
17547 (if org-log-done "automatically" "not")))
17548 :style toggle :selected org-log-done])
17549 "--"
17550 ["Agenda Command..." org-agenda t]
17551 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
17552 ("File List for Agenda")
17553 ("Special views current file"
17554 ["TODO Tree" org-show-todo-tree t]
17555 ["Check Deadlines" org-check-deadlines t]
17556 ["Timeline" org-timeline t]
17557 ["Tags/Property tree" org-match-sparse-tree t])
17558 "--"
17559 ["Export/Publish..." org-export t]
17560 ("LaTeX"
17561 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
17562 :selected org-cdlatex-mode]
17563 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
17564 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
17565 ["Modify math symbol" org-cdlatex-math-modify
17566 (org-inside-LaTeX-fragment-p)]
17567 ["Insert citation" org-reftex-citation t]
17568 "--"
17569 ["Export LaTeX fragments as images"
17570 (if (featurep 'org-exp)
17571 (setq org-export-with-LaTeX-fragments
17572 (not org-export-with-LaTeX-fragments))
17573 (require 'org-exp))
17574 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
17575 org-export-with-LaTeX-fragments)]
17576 "--"
17577 ["Template for BEAMER" org-insert-beamer-options-template t])
17578 "--"
17579 ("MobileOrg"
17580 ["Push Files and Views" org-mobile-push t]
17581 ["Get Captured and Flagged" org-mobile-pull t]
17582 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
17583 "--"
17584 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
17585 "--"
17586 ("Documentation"
17587 ["Show Version" org-version t]
17588 ["Info Documentation" org-info t])
17589 ("Customize"
17590 ["Browse Org Group" org-customize t]
17591 "--"
17592 ["Expand This Menu" org-create-customize-menu
17593 (fboundp 'customize-menu-create)])
17594 ["Send bug report" org-submit-bug-report t]
17595 "--"
17596 ("Refresh/Reload"
17597 ["Refresh setup current buffer" org-mode-restart t]
17598 ["Reload Org (after update)" org-reload t]
17599 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
17602 (defun org-info (&optional node)
17603 "Read documentation for Org-mode in the info system.
17604 With optional NODE, go directly to that node."
17605 (interactive)
17606 (info (format "(org)%s" (or node ""))))
17608 ;;;###autoload
17609 (defun org-submit-bug-report ()
17610 "Submit a bug report on Org-mode via mail.
17612 Don't hesitate to report any problems or inaccurate documentation.
17614 If you don't have setup sending mail from (X)Emacs, please copy the
17615 output buffer into your mail program, as it gives us important
17616 information about your Org-mode version and configuration."
17617 (interactive)
17618 (require 'reporter)
17619 (org-load-modules-maybe)
17620 (org-require-autoloaded-modules)
17621 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
17622 (reporter-submit-bug-report
17623 "emacs-orgmode@gnu.org"
17624 (org-version)
17625 (let (list)
17626 (save-window-excursion
17627 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
17628 (delete-other-windows)
17629 (erase-buffer)
17630 (insert "You are about to submit a bug report to the Org-mode mailing list.
17632 We would like to add your full Org-mode and Outline configuration to the
17633 bug report. This greatly simplifies the work of the maintainer and
17634 other experts on the mailing list.
17636 HOWEVER, some variables you have customized may contain private
17637 information. The names of customers, colleagues, or friends, might
17638 appear in the form of file names, tags, todo states, or search strings.
17639 If you answer yes to the prompt, you might want to check and remove
17640 such private information before sending the email.")
17641 (add-text-properties (point-min) (point-max) '(face org-warning))
17642 (when (yes-or-no-p "Include your Org-mode configuration ")
17643 (mapatoms
17644 (lambda (v)
17645 (and (boundp v)
17646 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
17647 (or (and (symbol-value v)
17648 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
17649 (and
17650 (get v 'custom-type) (get v 'standard-value)
17651 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
17652 (push v list)))))
17653 (kill-buffer (get-buffer "*Warn about privacy*"))
17654 list))
17655 nil nil
17656 "Remember to cover the basics, that is, what you expected to happen and
17657 what in fact did happen. You don't know how to make a good report? See
17659 http://orgmode.org/manual/Feedback.html#Feedback
17661 Your bug report will be posted to the Org-mode mailing list.
17662 ------------------------------------------------------------------------")
17663 (save-excursion
17664 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
17665 (replace-match "\\1Bug: \\3 [\\2]")))))
17668 (defun org-install-agenda-files-menu ()
17669 (let ((bl (buffer-list)))
17670 (save-excursion
17671 (while bl
17672 (set-buffer (pop bl))
17673 (if (org-mode-p) (setq bl nil)))
17674 (when (org-mode-p)
17675 (easy-menu-change
17676 '("Org") "File List for Agenda"
17677 (append
17678 (list
17679 ["Edit File List" (org-edit-agenda-file-list) t]
17680 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
17681 ["Remove Current File from List" org-remove-file t]
17682 ["Cycle through agenda files" org-cycle-agenda-files t]
17683 ["Occur in all agenda files" org-occur-in-agenda-files t]
17684 "--")
17685 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
17687 ;;;; Documentation
17689 ;;;###autoload
17690 (defun org-require-autoloaded-modules ()
17691 (interactive)
17692 (mapc 'require
17693 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
17694 org-docbook org-exp org-html org-icalendar
17695 org-id org-latex
17696 org-publish org-remember org-table
17697 org-timer org-xoxo)))
17699 ;;;###autoload
17700 (defun org-reload (&optional uncompiled)
17701 "Reload all org lisp files.
17702 With prefix arg UNCOMPILED, load the uncompiled versions."
17703 (interactive "P")
17704 (require 'find-func)
17705 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
17706 (dir-org (file-name-directory (org-find-library-name "org")))
17707 (dir-org-contrib (ignore-errors
17708 (file-name-directory
17709 (org-find-library-name "org-contribdir"))))
17710 (files
17711 (append (directory-files dir-org t file-re)
17712 (and dir-org-contrib
17713 (directory-files dir-org-contrib t file-re))))
17714 (remove-re (concat (if (featurep 'xemacs)
17715 "org-colview" "org-colview-xemacs")
17716 "\\'")))
17717 (setq files (mapcar 'file-name-sans-extension files))
17718 (setq files (mapcar
17719 (lambda (x) (if (string-match remove-re x) nil x))
17720 files))
17721 (setq files (delq nil files))
17722 (mapc
17723 (lambda (f)
17724 (when (featurep (intern (file-name-nondirectory f)))
17725 (if (and (not uncompiled)
17726 (file-exists-p (concat f ".elc")))
17727 (load (concat f ".elc") nil nil t)
17728 (load (concat f ".el") nil nil t))))
17729 files))
17730 (org-version))
17732 ;;;###autoload
17733 (defun org-customize ()
17734 "Call the customize function with org as argument."
17735 (interactive)
17736 (org-load-modules-maybe)
17737 (org-require-autoloaded-modules)
17738 (customize-browse 'org))
17740 (defun org-create-customize-menu ()
17741 "Create a full customization menu for Org-mode, insert it into the menu."
17742 (interactive)
17743 (org-load-modules-maybe)
17744 (org-require-autoloaded-modules)
17745 (if (fboundp 'customize-menu-create)
17746 (progn
17747 (easy-menu-change
17748 '("Org") "Customize"
17749 `(["Browse Org group" org-customize t]
17750 "--"
17751 ,(customize-menu-create 'org)
17752 ["Set" Custom-set t]
17753 ["Save" Custom-save t]
17754 ["Reset to Current" Custom-reset-current t]
17755 ["Reset to Saved" Custom-reset-saved t]
17756 ["Reset to Standard Settings" Custom-reset-standard t]))
17757 (message "\"Org\"-menu now contains full customization menu"))
17758 (error "Cannot expand menu (outdated version of cus-edit.el)")))
17760 ;;;; Miscellaneous stuff
17762 ;;; Generally useful functions
17764 (defun org-get-at-bol (property)
17765 "Get text property PROPERTY at beginning of line."
17766 (get-text-property (point-at-bol) property))
17768 (defun org-find-text-property-in-string (prop s)
17769 "Return the first non-nil value of property PROP in string S."
17770 (or (get-text-property 0 prop s)
17771 (get-text-property (or (next-single-property-change 0 prop s) 0)
17772 prop s)))
17774 (defun org-display-warning (message) ;; Copied from Emacs-Muse
17775 "Display the given MESSAGE as a warning."
17776 (if (fboundp 'display-warning)
17777 (display-warning 'org message
17778 (if (featurep 'xemacs) 'warning :warning))
17779 (let ((buf (get-buffer-create "*Org warnings*")))
17780 (with-current-buffer buf
17781 (goto-char (point-max))
17782 (insert "Warning (Org): " message)
17783 (unless (bolp)
17784 (newline)))
17785 (display-buffer buf)
17786 (sit-for 0))))
17788 (defun org-in-commented-line ()
17789 "Is point in a line starting with `#'?"
17790 (equal (char-after (point-at-bol)) ?#))
17792 (defun org-in-indented-comment-line ()
17793 "Is point in a line starting with `#' after some white space?"
17794 (save-excursion
17795 (save-match-data
17796 (goto-char (point-at-bol))
17797 (looking-at "[ \t]*#"))))
17799 (defun org-in-verbatim-emphasis ()
17800 (save-match-data
17801 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
17803 (defun org-goto-marker-or-bmk (marker &optional bookmark)
17804 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
17805 (if (and marker (marker-buffer marker)
17806 (buffer-live-p (marker-buffer marker)))
17807 (progn
17808 (switch-to-buffer (marker-buffer marker))
17809 (if (or (> marker (point-max)) (< marker (point-min)))
17810 (widen))
17811 (goto-char marker)
17812 (org-show-context 'org-goto))
17813 (if bookmark
17814 (bookmark-jump bookmark)
17815 (error "Cannot find location"))))
17817 (defun org-quote-csv-field (s)
17818 "Quote field for inclusion in CSV material."
17819 (if (string-match "[\",]" s)
17820 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
17823 (defun org-plist-delete (plist property)
17824 "Delete PROPERTY from PLIST.
17825 This is in contrast to merely setting it to 0."
17826 (let (p)
17827 (while plist
17828 (if (not (eq property (car plist)))
17829 (setq p (plist-put p (car plist) (nth 1 plist))))
17830 (setq plist (cddr plist)))
17833 (defun org-force-self-insert (N)
17834 "Needed to enforce self-insert under remapping."
17835 (interactive "p")
17836 (self-insert-command N))
17838 (defun org-string-width (s)
17839 "Compute width of string, ignoring invisible characters.
17840 This ignores character with invisibility property `org-link', and also
17841 characters with property `org-cwidth', because these will become invisible
17842 upon the next fontification round."
17843 (let (b l)
17844 (when (or (eq t buffer-invisibility-spec)
17845 (assq 'org-link buffer-invisibility-spec))
17846 (while (setq b (text-property-any 0 (length s)
17847 'invisible 'org-link s))
17848 (setq s (concat (substring s 0 b)
17849 (substring s (or (next-single-property-change
17850 b 'invisible s) (length s)))))))
17851 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
17852 (setq s (concat (substring s 0 b)
17853 (substring s (or (next-single-property-change
17854 b 'org-cwidth s) (length s))))))
17855 (setq l (string-width s) b -1)
17856 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
17857 (setq l (- l (get-text-property b 'org-dwidth-n s))))
17860 (defun org-get-indentation (&optional line)
17861 "Get the indentation of the current line, interpreting tabs.
17862 When LINE is given, assume it represents a line and compute its indentation."
17863 (if line
17864 (if (string-match "^ *" (org-remove-tabs line))
17865 (match-end 0))
17866 (save-excursion
17867 (beginning-of-line 1)
17868 (skip-chars-forward " \t")
17869 (current-column))))
17871 (defun org-remove-tabs (s &optional width)
17872 "Replace tabulators in S with spaces.
17873 Assumes that s is a single line, starting in column 0."
17874 (setq width (or width tab-width))
17875 (while (string-match "\t" s)
17876 (setq s (replace-match
17877 (make-string
17878 (- (* width (/ (+ (match-beginning 0) width) width))
17879 (match-beginning 0)) ?\ )
17880 t t s)))
17883 (defun org-fix-indentation (line ind)
17884 "Fix indentation in LINE.
17885 IND is a cons cell with target and minimum indentation.
17886 If the current indentation in LINE is smaller than the minimum,
17887 leave it alone. If it is larger than ind, set it to the target."
17888 (let* ((l (org-remove-tabs line))
17889 (i (org-get-indentation l))
17890 (i1 (car ind)) (i2 (cdr ind)))
17891 (if (>= i i2) (setq l (substring line i2)))
17892 (if (> i1 0)
17893 (concat (make-string i1 ?\ ) l)
17894 l)))
17896 (defun org-remove-indentation (code &optional n)
17897 "Remove the maximum common indentation from the lines in CODE.
17898 N may optionally be the number of spaces to remove."
17899 (with-temp-buffer
17900 (insert code)
17901 (org-do-remove-indentation n)
17902 (buffer-string)))
17904 (defun org-do-remove-indentation (&optional n)
17905 "Remove the maximum common indentation from the buffer."
17906 (untabify (point-min) (point-max))
17907 (let ((min 10000) re)
17908 (if n
17909 (setq min n)
17910 (goto-char (point-min))
17911 (while (re-search-forward "^ *[^ \n]" nil t)
17912 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
17913 (unless (or (= min 0) (= min 10000))
17914 (setq re (format "^ \\{%d\\}" min))
17915 (goto-char (point-min))
17916 (while (re-search-forward re nil t)
17917 (replace-match "")
17918 (end-of-line 1))
17919 min)))
17921 (defun org-fill-template (template alist)
17922 "Find each %key of ALIST in TEMPLATE and replace it."
17923 (let ((case-fold-search nil)
17924 entry key value)
17925 (setq alist (sort (copy-sequence alist)
17926 (lambda (a b) (< (length (car a)) (length (car b))))))
17927 (while (setq entry (pop alist))
17928 (setq template
17929 (replace-regexp-in-string
17930 (concat "%" (regexp-quote (car entry)))
17931 (cdr entry) template t t)))
17932 template))
17934 (defun org-base-buffer (buffer)
17935 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
17936 (if (not buffer)
17937 buffer
17938 (or (buffer-base-buffer buffer)
17939 buffer)))
17941 (defun org-trim (s)
17942 "Remove whitespace at beginning and end of string."
17943 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
17944 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
17947 (defun org-wrap (string &optional width lines)
17948 "Wrap string to either a number of lines, or a width in characters.
17949 If WIDTH is non-nil, the string is wrapped to that width, however many lines
17950 that costs. If there is a word longer than WIDTH, the text is actually
17951 wrapped to the length of that word.
17952 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
17953 many lines, whatever width that takes.
17954 The return value is a list of lines, without newlines at the end."
17955 (let* ((words (org-split-string string "[ \t\n]+"))
17956 (maxword (apply 'max (mapcar 'org-string-width words)))
17957 w ll)
17958 (cond (width
17959 (org-do-wrap words (max maxword width)))
17960 (lines
17961 (setq w maxword)
17962 (setq ll (org-do-wrap words maxword))
17963 (if (<= (length ll) lines)
17965 (setq ll words)
17966 (while (> (length ll) lines)
17967 (setq w (1+ w))
17968 (setq ll (org-do-wrap words w)))
17969 ll))
17970 (t (error "Cannot wrap this")))))
17972 (defun org-do-wrap (words width)
17973 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
17974 (let (lines line)
17975 (while words
17976 (setq line (pop words))
17977 (while (and words (< (+ (length line) (length (car words))) width))
17978 (setq line (concat line " " (pop words))))
17979 (setq lines (push line lines)))
17980 (nreverse lines)))
17982 (defun org-split-string (string &optional separators)
17983 "Splits STRING into substrings at SEPARATORS.
17984 No empty strings are returned if there are matches at the beginning
17985 and end of string."
17986 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
17987 (start 0)
17988 notfirst
17989 (list nil))
17990 (while (and (string-match rexp string
17991 (if (and notfirst
17992 (= start (match-beginning 0))
17993 (< start (length string)))
17994 (1+ start) start))
17995 (< (match-beginning 0) (length string)))
17996 (setq notfirst t)
17997 (or (eq (match-beginning 0) 0)
17998 (and (eq (match-beginning 0) (match-end 0))
17999 (eq (match-beginning 0) start))
18000 (setq list
18001 (cons (substring string start (match-beginning 0))
18002 list)))
18003 (setq start (match-end 0)))
18004 (or (eq start (length string))
18005 (setq list
18006 (cons (substring string start)
18007 list)))
18008 (nreverse list)))
18010 (defun org-quote-vert (s)
18011 "Replace \"|\" with \"\\vert\"."
18012 (while (string-match "|" s)
18013 (setq s (replace-match "\\vert" t t s)))
18016 (defun org-uuidgen-p (s)
18017 "Is S an ID created by UUIDGEN?"
18018 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
18020 (defun org-context ()
18021 "Return a list of contexts of the current cursor position.
18022 If several contexts apply, all are returned.
18023 Each context entry is a list with a symbol naming the context, and
18024 two positions indicating start and end of the context. Possible
18025 contexts are:
18027 :headline anywhere in a headline
18028 :headline-stars on the leading stars in a headline
18029 :todo-keyword on a TODO keyword (including DONE) in a headline
18030 :tags on the TAGS in a headline
18031 :priority on the priority cookie in a headline
18032 :item on the first line of a plain list item
18033 :item-bullet on the bullet/number of a plain list item
18034 :checkbox on the checkbox in a plain list item
18035 :table in an org-mode table
18036 :table-special on a special filed in a table
18037 :table-table in a table.el table
18038 :link on a hyperlink
18039 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
18040 :target on a <<target>>
18041 :radio-target on a <<<radio-target>>>
18042 :latex-fragment on a LaTeX fragment
18043 :latex-preview on a LaTeX fragment with overlayed preview image
18045 This function expects the position to be visible because it uses font-lock
18046 faces as a help to recognize the following contexts: :table-special, :link,
18047 and :keyword."
18048 (let* ((f (get-text-property (point) 'face))
18049 (faces (if (listp f) f (list f)))
18050 (p (point)) clist o)
18051 ;; First the large context
18052 (cond
18053 ((org-on-heading-p t)
18054 (push (list :headline (point-at-bol) (point-at-eol)) clist)
18055 (when (progn
18056 (beginning-of-line 1)
18057 (looking-at org-todo-line-tags-regexp))
18058 (push (org-point-in-group p 1 :headline-stars) clist)
18059 (push (org-point-in-group p 2 :todo-keyword) clist)
18060 (push (org-point-in-group p 4 :tags) clist))
18061 (goto-char p)
18062 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
18063 (if (looking-at "\\[#[A-Z0-9]\\]")
18064 (push (org-point-in-group p 0 :priority) clist)))
18066 ((org-at-item-p)
18067 (push (org-point-in-group p 2 :item-bullet) clist)
18068 (push (list :item (point-at-bol)
18069 (save-excursion (org-end-of-item) (point)))
18070 clist)
18071 (and (org-at-item-checkbox-p)
18072 (push (org-point-in-group p 0 :checkbox) clist)))
18074 ((org-at-table-p)
18075 (push (list :table (org-table-begin) (org-table-end)) clist)
18076 (if (memq 'org-formula faces)
18077 (push (list :table-special
18078 (previous-single-property-change p 'face)
18079 (next-single-property-change p 'face)) clist)))
18080 ((org-at-table-p 'any)
18081 (push (list :table-table) clist)))
18082 (goto-char p)
18084 ;; Now the small context
18085 (cond
18086 ((org-at-timestamp-p)
18087 (push (org-point-in-group p 0 :timestamp) clist))
18088 ((memq 'org-link faces)
18089 (push (list :link
18090 (previous-single-property-change p 'face)
18091 (next-single-property-change p 'face)) clist))
18092 ((memq 'org-special-keyword faces)
18093 (push (list :keyword
18094 (previous-single-property-change p 'face)
18095 (next-single-property-change p 'face)) clist))
18096 ((org-on-target-p)
18097 (push (org-point-in-group p 0 :target) clist)
18098 (goto-char (1- (match-beginning 0)))
18099 (if (looking-at org-radio-target-regexp)
18100 (push (org-point-in-group p 0 :radio-target) clist))
18101 (goto-char p))
18102 ((setq o (car (delq nil
18103 (mapcar
18104 (lambda (x)
18105 (if (memq x org-latex-fragment-image-overlays) x))
18106 (overlays-at (point))))))
18107 (push (list :latex-fragment
18108 (overlay-start o) (overlay-end o)) clist)
18109 (push (list :latex-preview
18110 (overlay-start o) (overlay-end o)) clist))
18111 ((org-inside-LaTeX-fragment-p)
18112 ;; FIXME: positions wrong.
18113 (push (list :latex-fragment (point) (point)) clist)))
18115 (setq clist (nreverse (delq nil clist)))
18116 clist))
18118 ;; FIXME: Compare with at-regexp-p Do we need both?
18119 (defun org-in-regexp (re &optional nlines visually)
18120 "Check if point is inside a match of regexp.
18121 Normally only the current line is checked, but you can include NLINES extra
18122 lines both before and after point into the search.
18123 If VISUALLY is set, require that the cursor is not after the match but
18124 really on, so that the block visually is on the match."
18125 (catch 'exit
18126 (let ((pos (point))
18127 (eol (point-at-eol (+ 1 (or nlines 0))))
18128 (inc (if visually 1 0)))
18129 (save-excursion
18130 (beginning-of-line (- 1 (or nlines 0)))
18131 (while (re-search-forward re eol t)
18132 (if (and (<= (match-beginning 0) pos)
18133 (>= (+ inc (match-end 0)) pos))
18134 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
18136 (defun org-at-regexp-p (regexp)
18137 "Is point inside a match of REGEXP in the current line?"
18138 (catch 'exit
18139 (save-excursion
18140 (let ((pos (point)) (end (point-at-eol)))
18141 (beginning-of-line 1)
18142 (while (re-search-forward regexp end t)
18143 (if (and (<= (match-beginning 0) pos)
18144 (>= (match-end 0) pos))
18145 (throw 'exit t)))
18146 nil))))
18148 (defun org-in-regexps-block-p (start-re end-re)
18149 "Returns t if the current point is between matches of START-RE and END-RE.
18150 This will also return to if point is on one of the two matches."
18151 (interactive)
18152 (let ((p (point)))
18153 (save-excursion
18154 (and (or (org-at-regexp-p start-re)
18155 (re-search-backward start-re nil t))
18156 (re-search-forward end-re nil t)
18157 (>= (point) p)))))
18159 (defun org-occur-in-agenda-files (regexp &optional nlines)
18160 "Call `multi-occur' with buffers for all agenda files."
18161 (interactive "sOrg-files matching: \np")
18162 (let* ((files (org-agenda-files))
18163 (tnames (mapcar 'file-truename files))
18164 (extra org-agenda-text-search-extra-files)
18166 (when (eq (car extra) 'agenda-archives)
18167 (setq extra (cdr extra))
18168 (setq files (org-add-archive-files files)))
18169 (while (setq f (pop extra))
18170 (unless (member (file-truename f) tnames)
18171 (add-to-list 'files f 'append)
18172 (add-to-list 'tnames (file-truename f) 'append)))
18173 (multi-occur
18174 (mapcar (lambda (x)
18175 (with-current-buffer
18176 (or (get-file-buffer x) (find-file-noselect x))
18177 (widen)
18178 (current-buffer)))
18179 files)
18180 regexp)))
18182 (if (boundp 'occur-mode-find-occurrence-hook)
18183 ;; Emacs 23
18184 (add-hook 'occur-mode-find-occurrence-hook
18185 (lambda ()
18186 (when (org-mode-p)
18187 (org-reveal))))
18188 ;; Emacs 22
18189 (defadvice occur-mode-goto-occurrence
18190 (after org-occur-reveal activate)
18191 (and (org-mode-p) (org-reveal)))
18192 (defadvice occur-mode-goto-occurrence-other-window
18193 (after org-occur-reveal activate)
18194 (and (org-mode-p) (org-reveal)))
18195 (defadvice occur-mode-display-occurrence
18196 (after org-occur-reveal activate)
18197 (when (org-mode-p)
18198 (let ((pos (occur-mode-find-occurrence)))
18199 (with-current-buffer (marker-buffer pos)
18200 (save-excursion
18201 (goto-char pos)
18202 (org-reveal)))))))
18204 (defun org-occur-link-in-agenda-files ()
18205 "Create a link and search for it in the agendas.
18206 The link is not stored in `org-stored-links', it is just created
18207 for the search purpose."
18208 (interactive)
18209 (let ((link (condition-case nil
18210 (org-store-link nil)
18211 (error "Unable to create a link to here"))))
18212 (org-occur-in-agenda-files (regexp-quote link))))
18214 (defun org-uniquify (list)
18215 "Remove duplicate elements from LIST."
18216 (let (res)
18217 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
18218 res))
18220 (defun org-delete-all (elts list)
18221 "Remove all elements in ELTS from LIST."
18222 (while elts
18223 (setq list (delete (pop elts) list)))
18224 list)
18226 (defun org-remove-if (predicate seq)
18227 "Remove everything from SEQ that fulfills PREDICATE."
18228 (let (res e)
18229 (while seq
18230 (setq e (pop seq))
18231 (if (not (funcall predicate e)) (push e res)))
18232 (nreverse res)))
18234 (defun org-remove-if-not (predicate seq)
18235 "Remove everything from SEQ that does not fulfill PREDICATE."
18236 (let (res e)
18237 (while seq
18238 (setq e (pop seq))
18239 (if (funcall predicate e) (push e res)))
18240 (nreverse res)))
18242 (defun org-back-over-empty-lines ()
18243 "Move backwards over whitespace, to the beginning of the first empty line.
18244 Returns the number of empty lines passed."
18245 (let ((pos (point)))
18246 (skip-chars-backward " \t\n\r")
18247 (beginning-of-line 2)
18248 (goto-char (min (point) pos))
18249 (count-lines (point) pos)))
18251 (defun org-skip-whitespace ()
18252 (skip-chars-forward " \t\n\r"))
18254 (defun org-point-in-group (point group &optional context)
18255 "Check if POINT is in match-group GROUP.
18256 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
18257 match. If the match group does ot exist or point is not inside it,
18258 return nil."
18259 (and (match-beginning group)
18260 (>= point (match-beginning group))
18261 (<= point (match-end group))
18262 (if context
18263 (list context (match-beginning group) (match-end group))
18264 t)))
18266 (defun org-switch-to-buffer-other-window (&rest args)
18267 "Switch to buffer in a second window on the current frame.
18268 In particular, do not allow pop-up frames.
18269 Returns the newly created buffer."
18270 (let (pop-up-frames special-display-buffer-names special-display-regexps
18271 special-display-function)
18272 (apply 'switch-to-buffer-other-window args)))
18274 (defun org-combine-plists (&rest plists)
18275 "Create a single property list from all plists in PLISTS.
18276 The process starts by copying the first list, and then setting properties
18277 from the other lists. Settings in the last list are the most significant
18278 ones and overrule settings in the other lists."
18279 (let ((rtn (copy-sequence (pop plists)))
18280 p v ls)
18281 (while plists
18282 (setq ls (pop plists))
18283 (while ls
18284 (setq p (pop ls) v (pop ls))
18285 (setq rtn (plist-put rtn p v))))
18286 rtn))
18288 (defun org-move-line-down (arg)
18289 "Move the current line down. With prefix argument, move it past ARG lines."
18290 (interactive "p")
18291 (let ((col (current-column))
18292 beg end pos)
18293 (beginning-of-line 1) (setq beg (point))
18294 (beginning-of-line 2) (setq end (point))
18295 (beginning-of-line (+ 1 arg))
18296 (setq pos (move-marker (make-marker) (point)))
18297 (insert (delete-and-extract-region beg end))
18298 (goto-char pos)
18299 (org-move-to-column col)))
18301 (defun org-move-line-up (arg)
18302 "Move the current line up. With prefix argument, move it past ARG lines."
18303 (interactive "p")
18304 (let ((col (current-column))
18305 beg end pos)
18306 (beginning-of-line 1) (setq beg (point))
18307 (beginning-of-line 2) (setq end (point))
18308 (beginning-of-line (- arg))
18309 (setq pos (move-marker (make-marker) (point)))
18310 (insert (delete-and-extract-region beg end))
18311 (goto-char pos)
18312 (org-move-to-column col)))
18314 (defun org-replace-escapes (string table)
18315 "Replace %-escapes in STRING with values in TABLE.
18316 TABLE is an association list with keys like \"%a\" and string values.
18317 The sequences in STRING may contain normal field width and padding information,
18318 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
18319 so values can contain further %-escapes if they are define later in TABLE."
18320 (let ((tbl (copy-alist table))
18321 (case-fold-search nil)
18322 (pchg 0)
18323 e re rpl)
18324 (while (setq e (pop tbl))
18325 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
18326 (when (and (cdr e) (string-match re (cdr e)))
18327 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
18328 (safe "SREF"))
18329 (add-text-properties 0 3 (list 'sref sref) safe)
18330 (setcdr e (replace-match safe t t (cdr e)))))
18331 (while (string-match re string)
18332 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
18333 (cdr e)))
18334 (setq string (replace-match rpl t t string))))
18335 (while (setq pchg (next-property-change pchg string))
18336 (let ((sref (get-text-property pchg 'sref string)))
18337 (when (and sref (string-match "SREF" string pchg))
18338 (setq string (replace-match sref t t string)))))
18339 string))
18341 (defun org-sublist (list start end)
18342 "Return a section of LIST, from START to END.
18343 Counting starts at 1."
18344 (let (rtn (c start))
18345 (setq list (nthcdr (1- start) list))
18346 (while (and list (<= c end))
18347 (push (pop list) rtn)
18348 (setq c (1+ c)))
18349 (nreverse rtn)))
18351 (defun org-find-base-buffer-visiting (file)
18352 "Like `find-buffer-visiting' but always return the base buffer and
18353 not an indirect buffer."
18354 (let ((buf (or (get-file-buffer file)
18355 (find-buffer-visiting file))))
18356 (if buf
18357 (or (buffer-base-buffer buf) buf)
18358 nil)))
18360 (defun org-image-file-name-regexp (&optional extensions)
18361 "Return regexp matching the file names of images.
18362 If EXTENSIONS is given, only match these."
18363 (if (and (not extensions) (fboundp 'image-file-name-regexp))
18364 (image-file-name-regexp)
18365 (let ((image-file-name-extensions
18366 (or extensions
18367 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
18368 "xbm" "xpm" "pbm" "pgm" "ppm"))))
18369 (concat "\\."
18370 (regexp-opt (nconc (mapcar 'upcase
18371 image-file-name-extensions)
18372 image-file-name-extensions)
18374 "\\'"))))
18376 (defun org-file-image-p (file &optional extensions)
18377 "Return non-nil if FILE is an image."
18378 (save-match-data
18379 (string-match (org-image-file-name-regexp extensions) file)))
18381 (defun org-get-cursor-date ()
18382 "Return the date at cursor in as a time.
18383 This works in the calendar and in the agenda, anywhere else it just
18384 returns the current time."
18385 (let (date day defd)
18386 (cond
18387 ((eq major-mode 'calendar-mode)
18388 (setq date (calendar-cursor-to-date)
18389 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18390 ((eq major-mode 'org-agenda-mode)
18391 (setq day (get-text-property (point) 'day))
18392 (if day
18393 (setq date (calendar-gregorian-from-absolute day)
18394 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
18395 (nth 2 date))))))
18396 (or defd (current-time))))
18398 (defvar org-agenda-action-marker (make-marker)
18399 "Marker pointing to the entry for the next agenda action.")
18401 (defun org-mark-entry-for-agenda-action ()
18402 "Mark the current entry as target of an agenda action.
18403 Agenda actions are actions executed from the agenda with the key `k',
18404 which make use of the date at the cursor."
18405 (interactive)
18406 (move-marker org-agenda-action-marker
18407 (save-excursion (org-back-to-heading t) (point))
18408 (current-buffer))
18409 (message
18410 "Entry marked for action; press `k' at desired date in agenda or calendar"))
18412 ;;; Paragraph filling stuff.
18413 ;; We want this to be just right, so use the full arsenal.
18415 (defun org-indent-line-function ()
18416 "Indent line like previous, but further if previous was headline or item."
18417 (interactive)
18418 (let* ((pos (point))
18419 (itemp (org-at-item-p))
18420 (case-fold-search t)
18421 (org-drawer-regexp (or org-drawer-regexp "\000"))
18422 column bpos bcol tpos tcol bullet btype bullet-type)
18423 ;; Find the previous relevant line
18424 (beginning-of-line 1)
18425 (cond
18426 ((looking-at "#") (setq column 0))
18427 ((looking-at "\\*+ ") (setq column 0))
18428 ((and (looking-at "[ \t]*:END:")
18429 (save-excursion (re-search-backward org-drawer-regexp nil t)))
18430 (save-excursion
18431 (goto-char (1- (match-beginning 1)))
18432 (setq column (current-column))))
18433 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
18434 (save-excursion
18435 (re-search-backward
18436 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
18437 (setq column (org-get-indentation (match-string 0))))
18439 (beginning-of-line 0)
18440 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
18441 (not (looking-at "[ \t]*:END:"))
18442 (not (looking-at org-drawer-regexp)))
18443 (beginning-of-line 0))
18444 (cond
18445 ((looking-at "\\*+[ \t]+")
18446 (if (not org-adapt-indentation)
18447 (setq column 0)
18448 (goto-char (match-end 0))
18449 (setq column (current-column))))
18450 ((looking-at org-drawer-regexp)
18451 (goto-char (1- (match-beginning 1)))
18452 (setq column (current-column)))
18453 ((looking-at "\\([ \t]*\\):END:")
18454 (goto-char (match-end 1))
18455 (setq column (current-column)))
18456 ((org-in-item-p)
18457 (org-beginning-of-item)
18458 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
18459 (setq bpos (match-beginning 1) tpos (match-end 0)
18460 bcol (progn (goto-char bpos) (current-column))
18461 tcol (progn (goto-char tpos) (current-column))
18462 bullet (match-string 1)
18463 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
18464 (if (> tcol (+ bcol org-description-max-indent))
18465 (setq tcol (+ bcol 5)))
18466 (if (not itemp)
18467 (setq column tcol)
18468 (goto-char pos)
18469 (beginning-of-line 1)
18470 (if (looking-at "\\S-")
18471 (progn
18472 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
18473 (setq bullet (match-string 1)
18474 btype (if (string-match "[0-9]" bullet) "n" bullet))
18475 (setq column (if (equal btype bullet-type) bcol tcol)))
18476 (setq column (org-get-indentation)))))
18477 (t (setq column (org-get-indentation))))))
18478 (goto-char pos)
18479 (if (<= (current-column) (current-indentation))
18480 (org-indent-line-to column)
18481 (save-excursion (org-indent-line-to column)))
18482 (setq column (current-column))
18483 (beginning-of-line 1)
18484 (if (looking-at
18485 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
18486 (replace-match (concat (match-string 1)
18487 (format org-property-format
18488 (match-string 2) (match-string 3)))
18489 t t))
18490 (org-move-to-column column)))
18492 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
18493 "Variable to store copy of `adaptive-fill-regexp'.
18494 Since `adaptive-fill-regexp' is set to never match, we need to
18495 store a backup of its value before entering `org-mode' so that
18496 the functionality can be provided as a fall-back.")
18498 (defun org-set-autofill-regexps ()
18499 (interactive)
18500 ;; In the paragraph separator we include headlines, because filling
18501 ;; text in a line directly attached to a headline would otherwise
18502 ;; fill the headline as well.
18503 (org-set-local 'comment-start-skip "^#+[ \t]*")
18504 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
18505 ;; The paragraph starter includes hand-formatted lists.
18506 (org-set-local
18507 'paragraph-start
18508 (concat
18509 "\f" "\\|"
18510 "[ ]*$" "\\|"
18511 "\\*+ " "\\|"
18512 "[ \t]*#" "\\|"
18513 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
18514 "[ \t]*[:|]" "\\|"
18515 "\\$\\$" "\\|"
18516 "\\\\\\(begin\\|end\\|[][]\\)"))
18517 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
18518 ;; But only if the user has not turned off tables or fixed-width regions
18519 (org-set-local
18520 'auto-fill-inhibit-regexp
18521 (concat "\\*+ \\|#\\+"
18522 "\\|[ \t]*" org-keyword-time-regexp
18523 (if (or org-enable-table-editor org-enable-fixed-width-editor)
18524 (concat
18525 "\\|[ \t]*["
18526 (if org-enable-table-editor "|" "")
18527 (if org-enable-fixed-width-editor ":" "")
18528 "]"))))
18529 ;; We use our own fill-paragraph function, to make sure that tables
18530 ;; and fixed-width regions are not wrapped. That function will pass
18531 ;; through to `fill-paragraph' when appropriate.
18532 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
18533 ;; Adaptive filling: To get full control, first make sure that
18534 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
18535 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
18536 (org-set-local 'org-adaptive-fill-regexp-backup
18537 adaptive-fill-regexp))
18538 (org-set-local 'adaptive-fill-regexp "\000")
18539 (org-set-local 'adaptive-fill-function
18540 'org-adaptive-fill-function)
18541 (org-set-local
18542 'align-mode-rules-list
18543 '((org-in-buffer-settings
18544 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
18545 (modes . '(org-mode))))))
18547 (defun org-fill-paragraph (&optional justify)
18548 "Re-align a table, pass through to fill-paragraph if no table."
18549 (let ((table-p (org-at-table-p))
18550 (table.el-p (org-at-table.el-p)))
18551 (cond ((and (equal (char-after (point-at-bol)) ?*)
18552 (save-excursion (goto-char (point-at-bol))
18553 (looking-at outline-regexp)))
18554 t) ; skip headlines
18555 (table.el-p t) ; skip table.el tables
18556 (table-p (org-table-align) t) ; align org-mode tables
18557 (t nil)))) ; call paragraph-fill
18559 ;; For reference, this is the default value of adaptive-fill-regexp
18560 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
18562 (defun org-adaptive-fill-function ()
18563 "Return a fill prefix for org-mode files.
18564 In particular, this makes sure hanging paragraphs for hand-formatted lists
18565 work correctly."
18566 (cond
18567 ;; Comment line
18568 ((looking-at "#[ \t]+")
18569 (match-string-no-properties 0))
18570 ;; Description list
18571 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
18572 (save-excursion
18573 (if (> (match-end 1) (+ (match-beginning 1)
18574 org-description-max-indent))
18575 (goto-char (+ (match-beginning 1) 5))
18576 (goto-char (match-end 0)))
18577 (make-string (current-column) ?\ )))
18578 ;; Ordered or unordered list
18579 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)")
18580 (save-excursion
18581 (goto-char (match-end 0))
18582 (make-string (current-column) ?\ )))
18583 ;; Other text
18584 ((looking-at org-adaptive-fill-regexp-backup)
18585 (match-string-no-properties 0))))
18587 ;;; Other stuff.
18589 (defun org-toggle-fixed-width-section (arg)
18590 "Toggle the fixed-width export.
18591 If there is no active region, the QUOTE keyword at the current headline is
18592 inserted or removed. When present, it causes the text between this headline
18593 and the next to be exported as fixed-width text, and unmodified.
18594 If there is an active region, this command adds or removes a colon as the
18595 first character of this line. If the first character of a line is a colon,
18596 this line is also exported in fixed-width font."
18597 (interactive "P")
18598 (let* ((cc 0)
18599 (regionp (org-region-active-p))
18600 (beg (if regionp (region-beginning) (point)))
18601 (end (if regionp (region-end)))
18602 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
18603 (case-fold-search nil)
18604 (re "[ \t]*\\(: \\)")
18605 off)
18606 (if regionp
18607 (save-excursion
18608 (goto-char beg)
18609 (setq cc (current-column))
18610 (beginning-of-line 1)
18611 (setq off (looking-at re))
18612 (while (> nlines 0)
18613 (setq nlines (1- nlines))
18614 (beginning-of-line 1)
18615 (cond
18616 (arg
18617 (org-move-to-column cc t)
18618 (insert ": \n")
18619 (forward-line -1))
18620 ((and off (looking-at re))
18621 (replace-match "" t t nil 1))
18622 ((not off) (org-move-to-column cc t) (insert ": ")))
18623 (forward-line 1)))
18624 (save-excursion
18625 (org-back-to-heading)
18626 (if (looking-at (concat outline-regexp
18627 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
18628 (replace-match "" t t nil 1)
18629 (if (looking-at outline-regexp)
18630 (progn
18631 (goto-char (match-end 0))
18632 (insert org-quote-string " "))))))))
18634 (defun org-reftex-citation ()
18635 "Use reftex-citation to insert a citation into the buffer.
18636 This looks for a line like
18638 #+BIBLIOGRAPHY: foo plain option:-d
18640 and derives from it that foo.bib is the bibliography file relevant
18641 for this document. It then installs the necessary environment for RefTeX
18642 to work in this buffer and calls `reftex-citation' to insert a citation
18643 into the buffer.
18645 Export of such citations to both LaTeX and HTML is handled by the contributed
18646 package org-exp-bibtex by Taru Karttunen."
18647 (interactive)
18648 (let ((reftex-docstruct-symbol 'rds)
18649 (reftex-cite-format "\\cite{%l}")
18650 rds bib)
18651 (save-excursion
18652 (save-restriction
18653 (widen)
18654 (let ((case-fold-search t)
18655 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
18656 (if (not (save-excursion
18657 (or (re-search-forward re nil t)
18658 (re-search-backward re nil t))))
18659 (error "No bibliography defined in file")
18660 (setq bib (concat (match-string 1) ".bib")
18661 rds (list (list 'bib bib)))))))
18662 (call-interactively 'reftex-citation)))
18664 ;;;; Functions extending outline functionality
18666 (defun org-beginning-of-line (&optional arg)
18667 "Go to the beginning of the current line. If that is invisible, continue
18668 to a visible line beginning. This makes the function of C-a more intuitive.
18669 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
18670 first attempt, and only move to after the tags when the cursor is already
18671 beyond the end of the headline."
18672 (interactive "P")
18673 (let ((pos (point))
18674 (special (if (consp org-special-ctrl-a/e)
18675 (car org-special-ctrl-a/e)
18676 org-special-ctrl-a/e))
18677 refpos)
18678 (if (org-bound-and-true-p line-move-visual)
18679 (beginning-of-visual-line 1)
18680 (beginning-of-line 1))
18681 (if (and arg (fboundp 'move-beginning-of-line))
18682 (call-interactively 'move-beginning-of-line)
18683 (if (bobp)
18685 (backward-char 1)
18686 (if (org-truely-invisible-p)
18687 (while (and (not (bobp)) (org-truely-invisible-p))
18688 (backward-char 1)
18689 (beginning-of-line 1))
18690 (forward-char 1))))
18691 (when special
18692 (cond
18693 ((and (looking-at org-complex-heading-regexp)
18694 (= (char-after (match-end 1)) ?\ ))
18695 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
18696 (point-at-eol)))
18697 (goto-char
18698 (if (eq special t)
18699 (cond ((> pos refpos) refpos)
18700 ((= pos (point)) refpos)
18701 (t (point)))
18702 (cond ((> pos (point)) (point))
18703 ((not (eq last-command this-command)) (point))
18704 (t refpos)))))
18705 ((org-at-item-p)
18706 (goto-char
18707 (if (eq special t)
18708 (cond ((> pos (match-end 4)) (match-end 4))
18709 ((= pos (point)) (match-end 4))
18710 (t (point)))
18711 (cond ((> pos (point)) (point))
18712 ((not (eq last-command this-command)) (point))
18713 (t (match-end 4))))))))
18714 (org-no-warnings
18715 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
18717 (defun org-end-of-line (&optional arg)
18718 "Go to the end of the line.
18719 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
18720 first attempt, and only move to after the tags when the cursor is already
18721 beyond the end of the headline."
18722 (interactive "P")
18723 (let ((special (if (consp org-special-ctrl-a/e)
18724 (cdr org-special-ctrl-a/e)
18725 org-special-ctrl-a/e)))
18726 (if (or (not special)
18727 (not (org-on-heading-p))
18728 arg)
18729 (call-interactively
18730 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
18731 ((fboundp 'move-end-of-line) 'move-end-of-line)
18732 (t 'end-of-line)))
18733 (let ((pos (point)))
18734 (beginning-of-line 1)
18735 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
18736 (if (eq special t)
18737 (if (or (< pos (match-beginning 1))
18738 (= pos (match-end 0)))
18739 (goto-char (match-beginning 1))
18740 (goto-char (match-end 0)))
18741 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
18742 (goto-char (match-end 0))
18743 (goto-char (match-beginning 1))))
18744 (call-interactively (if (fboundp 'move-end-of-line)
18745 'move-end-of-line
18746 'end-of-line)))))
18747 (org-no-warnings
18748 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
18750 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
18751 (define-key org-mode-map "\C-e" 'org-end-of-line)
18752 (define-key org-mode-map [home] 'org-beginning-of-line)
18753 (define-key org-mode-map [end] 'org-end-of-line)
18755 (defun org-backward-sentence (&optional arg)
18756 "Go to beginning of sentence, or beginning of table field.
18757 This will call `backward-sentence' or `org-table-beginning-of-field',
18758 depending on context."
18759 (interactive "P")
18760 (cond
18761 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
18762 (t (call-interactively 'backward-sentence))))
18764 (defun org-forward-sentence (&optional arg)
18765 "Go to end of sentence, or end of table field.
18766 This will call `forward-sentence' or `org-table-end-of-field',
18767 depending on context."
18768 (interactive "P")
18769 (cond
18770 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
18771 (t (call-interactively 'forward-sentence))))
18773 (define-key org-mode-map "\M-a" 'org-backward-sentence)
18774 (define-key org-mode-map "\M-e" 'org-forward-sentence)
18776 (defun org-kill-line (&optional arg)
18777 "Kill line, to tags or end of line."
18778 (interactive "P")
18779 (cond
18780 ((or (not org-special-ctrl-k)
18781 (bolp)
18782 (not (org-on-heading-p)))
18783 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
18784 org-ctrl-k-protect-subtree)
18785 (if (or (eq org-ctrl-k-protect-subtree 'error)
18786 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
18787 (error "C-k aborted - would kill hidden subtree")))
18788 (call-interactively 'kill-line))
18789 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
18790 (kill-region (point) (match-beginning 1))
18791 (org-set-tags nil t))
18792 (t (kill-region (point) (point-at-eol)))))
18794 (define-key org-mode-map "\C-k" 'org-kill-line)
18796 (defun org-yank (&optional arg)
18797 "Yank. If the kill is a subtree, treat it specially.
18798 This command will look at the current kill and check if is a single
18799 subtree, or a series of subtrees[1]. If it passes the test, and if the
18800 cursor is at the beginning of a line or after the stars of a currently
18801 empty headline, then the yank is handled specially. How exactly depends
18802 on the value of the following variables, both set by default.
18804 org-yank-folded-subtrees
18805 When set, the subtree(s) will be folded after insertion, but only
18806 if doing so would now swallow text after the yanked text.
18808 org-yank-adjusted-subtrees
18809 When set, the subtree will be promoted or demoted in order to
18810 fit into the local outline tree structure, which means that the level
18811 will be adjusted so that it becomes the smaller one of the two
18812 *visible* surrounding headings.
18814 Any prefix to this command will cause `yank' to be called directly with
18815 no special treatment. In particular, a simple `C-u' prefix will just
18816 plainly yank the text as it is.
18818 \[1] The test checks if the first non-white line is a heading
18819 and if there are no other headings with fewer stars."
18820 (interactive "P")
18821 (org-yank-generic 'yank arg))
18823 (defun org-yank-generic (command arg)
18824 "Perform some yank-like command.
18826 This function implements the behavior described in the `org-yank'
18827 documentation. However, it has been generalized to work for any
18828 interactive command with similar behavior."
18830 ;; pretend to be command COMMAND
18831 (setq this-command command)
18833 (if arg
18834 (call-interactively command)
18836 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
18837 (and (org-kill-is-subtree-p)
18838 (or (bolp)
18839 (and (looking-at "[ \t]*$")
18840 (string-match
18841 "\\`\\*+\\'"
18842 (buffer-substring (point-at-bol) (point)))))))
18843 swallowp)
18844 (cond
18845 ((and subtreep org-yank-folded-subtrees)
18846 (let ((beg (point))
18847 end)
18848 (if (and subtreep org-yank-adjusted-subtrees)
18849 (org-paste-subtree nil nil 'for-yank)
18850 (call-interactively command))
18852 (setq end (point))
18853 (goto-char beg)
18854 (when (and (bolp) subtreep
18855 (not (setq swallowp
18856 (org-yank-folding-would-swallow-text beg end))))
18857 (or (looking-at outline-regexp)
18858 (re-search-forward (concat "^" outline-regexp) end t))
18859 (while (and (< (point) end) (looking-at outline-regexp))
18860 (hide-subtree)
18861 (org-cycle-show-empty-lines 'folded)
18862 (condition-case nil
18863 (outline-forward-same-level 1)
18864 (error (goto-char end)))))
18865 (when swallowp
18866 (message
18867 "Inserted text not folded because that would swallow text"))
18869 (goto-char end)
18870 (skip-chars-forward " \t\n\r")
18871 (beginning-of-line 1)
18872 (push-mark beg 'nomsg)))
18873 ((and subtreep org-yank-adjusted-subtrees)
18874 (let ((beg (point-at-bol)))
18875 (org-paste-subtree nil nil 'for-yank)
18876 (push-mark beg 'nomsg)))
18878 (call-interactively command))))))
18880 (defun org-yank-folding-would-swallow-text (beg end)
18881 "Would hide-subtree at BEG swallow any text after END?"
18882 (let (level)
18883 (save-excursion
18884 (goto-char beg)
18885 (when (or (looking-at outline-regexp)
18886 (re-search-forward (concat "^" outline-regexp) end t))
18887 (setq level (org-outline-level)))
18888 (goto-char end)
18889 (skip-chars-forward " \t\r\n\v\f")
18890 (if (or (eobp)
18891 (and (bolp) (looking-at org-outline-regexp)
18892 (<= (org-outline-level) level)))
18893 nil ; Nothing would be swallowed
18894 t)))) ; something would swallow
18896 (define-key org-mode-map "\C-y" 'org-yank)
18898 (defun org-invisible-p ()
18899 "Check if point is at a character currently not visible."
18900 ;; Early versions of noutline don't have `outline-invisible-p'.
18901 (if (fboundp 'outline-invisible-p)
18902 (outline-invisible-p)
18903 (get-char-property (point) 'invisible)))
18905 (defun org-truely-invisible-p ()
18906 "Check if point is at a character currently not visible.
18907 This version does not only check the character property, but also
18908 `visible-mode'."
18909 ;; Early versions of noutline don't have `outline-invisible-p'.
18910 (if (org-bound-and-true-p visible-mode)
18912 (if (fboundp 'outline-invisible-p)
18913 (outline-invisible-p)
18914 (get-char-property (point) 'invisible))))
18916 (defun org-invisible-p2 ()
18917 "Check if point is at a character currently not visible."
18918 (save-excursion
18919 (if (and (eolp) (not (bobp))) (backward-char 1))
18920 ;; Early versions of noutline don't have `outline-invisible-p'.
18921 (if (fboundp 'outline-invisible-p)
18922 (outline-invisible-p)
18923 (get-char-property (point) 'invisible))))
18925 (defun org-back-to-heading (&optional invisible-ok)
18926 "Call `outline-back-to-heading', but provide a better error message."
18927 (condition-case nil
18928 (outline-back-to-heading invisible-ok)
18929 (error (error "Before first headline at position %d in buffer %s"
18930 (point) (current-buffer)))))
18932 (defun org-beginning-of-defun ()
18933 "Go to the beginning of the subtree, i.e. back to the heading."
18934 (org-back-to-heading))
18935 (defun org-end-of-defun ()
18936 "Go to the end of the subtree."
18937 (org-end-of-subtree nil t))
18939 (defun org-before-first-heading-p ()
18940 "Before first heading?"
18941 (save-excursion
18942 (null (re-search-backward "^\\*+ " nil t))))
18944 (defun org-on-heading-p (&optional ignored)
18945 (outline-on-heading-p t))
18946 (defun org-at-heading-p (&optional ignored)
18947 (outline-on-heading-p t))
18949 (defun org-point-at-end-of-empty-headline ()
18950 "If point is at the end of an empty headline, return t, else nil.
18951 If the heading only contains a TODO keyword, it is still still considered
18952 empty."
18953 (and (looking-at "[ \t]*$")
18954 (save-excursion
18955 (beginning-of-line 1)
18956 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
18957 "\\)?[ \t]*$")))))
18958 (defun org-at-heading-or-item-p ()
18959 (or (org-on-heading-p) (org-at-item-p)))
18961 (defun org-on-target-p ()
18962 (or (org-in-regexp org-radio-target-regexp)
18963 (org-in-regexp org-target-regexp)))
18965 (defun org-up-heading-all (arg)
18966 "Move to the heading line of which the present line is a subheading.
18967 This function considers both visible and invisible heading lines.
18968 With argument, move up ARG levels."
18969 (if (fboundp 'outline-up-heading-all)
18970 (outline-up-heading-all arg) ; emacs 21 version of outline.el
18971 (outline-up-heading arg t))) ; emacs 22 version of outline.el
18973 (defun org-up-heading-safe ()
18974 "Move to the heading line of which the present line is a subheading.
18975 This version will not throw an error. It will return the level of the
18976 headline found, or nil if no higher level is found.
18978 Also, this function will be a lot faster than `outline-up-heading',
18979 because it relies on stars being the outline starters. This can really
18980 make a significant difference in outlines with very many siblings."
18981 (let (start-level re)
18982 (org-back-to-heading t)
18983 (setq start-level (funcall outline-level))
18984 (if (equal start-level 1)
18986 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
18987 (if (re-search-backward re nil t)
18988 (funcall outline-level)))))
18990 (defun org-first-sibling-p ()
18991 "Is this heading the first child of its parents?"
18992 (interactive)
18993 (let ((re (concat "^" outline-regexp))
18994 level l)
18995 (unless (org-at-heading-p t)
18996 (error "Not at a heading"))
18997 (setq level (funcall outline-level))
18998 (save-excursion
18999 (if (not (re-search-backward re nil t))
19001 (setq l (funcall outline-level))
19002 (< l level)))))
19004 (defun org-goto-sibling (&optional previous)
19005 "Goto the next sibling, even if it is invisible.
19006 When PREVIOUS is set, go to the previous sibling instead. Returns t
19007 when a sibling was found. When none is found, return nil and don't
19008 move point."
19009 (let ((fun (if previous 're-search-backward 're-search-forward))
19010 (pos (point))
19011 (re (concat "^" outline-regexp))
19012 level l)
19013 (when (condition-case nil (org-back-to-heading t) (error nil))
19014 (setq level (funcall outline-level))
19015 (catch 'exit
19016 (or previous (forward-char 1))
19017 (while (funcall fun re nil t)
19018 (setq l (funcall outline-level))
19019 (when (< l level) (goto-char pos) (throw 'exit nil))
19020 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
19021 (goto-char pos)
19022 nil))))
19024 (defun org-show-siblings ()
19025 "Show all siblings of the current headline."
19026 (save-excursion
19027 (while (org-goto-sibling) (org-flag-heading nil)))
19028 (save-excursion
19029 (while (org-goto-sibling 'previous)
19030 (org-flag-heading nil))))
19032 (defun org-show-hidden-entry ()
19033 "Show an entry where even the heading is hidden."
19034 (save-excursion
19035 (org-show-entry)))
19037 (defun org-flag-heading (flag &optional entry)
19038 "Flag the current heading. FLAG non-nil means make invisible.
19039 When ENTRY is non-nil, show the entire entry."
19040 (save-excursion
19041 (org-back-to-heading t)
19042 ;; Check if we should show the entire entry
19043 (if entry
19044 (progn
19045 (org-show-entry)
19046 (save-excursion
19047 (and (outline-next-heading)
19048 (org-flag-heading nil))))
19049 (outline-flag-region (max (point-min) (1- (point)))
19050 (save-excursion (outline-end-of-heading) (point))
19051 flag))))
19053 (defun org-get-next-sibling ()
19054 "Move to next heading of the same level, and return point.
19055 If there is no such heading, return nil.
19056 This is like outline-next-sibling, but invisible headings are ok."
19057 (let ((level (funcall outline-level)))
19058 (outline-next-heading)
19059 (while (and (not (eobp)) (> (funcall outline-level) level))
19060 (outline-next-heading))
19061 (if (or (eobp) (< (funcall outline-level) level))
19063 (point))))
19065 (defun org-get-last-sibling ()
19066 "Move to previous heading of the same level, and return point.
19067 If there is no such heading, return nil."
19068 (let ((opoint (point))
19069 (level (funcall outline-level)))
19070 (outline-previous-heading)
19071 (when (and (/= (point) opoint) (outline-on-heading-p t))
19072 (while (and (> (funcall outline-level) level)
19073 (not (bobp)))
19074 (outline-previous-heading))
19075 (if (< (funcall outline-level) level)
19077 (point)))))
19079 (defun org-end-of-subtree (&optional invisible-OK to-heading)
19080 ;; This contains an exact copy of the original function, but it uses
19081 ;; `org-back-to-heading', to make it work also in invisible
19082 ;; trees. And is uses an invisible-OK argument.
19083 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
19084 ;; Furthermore, when used inside Org, finding the end of a large subtree
19085 ;; with many children and grandchildren etc, this can be much faster
19086 ;; than the outline version.
19087 (org-back-to-heading invisible-OK)
19088 (let ((first t)
19089 (level (funcall outline-level)))
19090 (if (and (org-mode-p) (< level 1000))
19091 ;; A true heading (not a plain list item), in Org-mode
19092 ;; This means we can easily find the end by looking
19093 ;; only for the right number of stars. Using a regexp to do
19094 ;; this is so much faster than using a Lisp loop.
19095 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
19096 (forward-char 1)
19097 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
19098 ;; something else, do it the slow way
19099 (while (and (not (eobp))
19100 (or first (> (funcall outline-level) level)))
19101 (setq first nil)
19102 (outline-next-heading)))
19103 (unless to-heading
19104 (if (memq (preceding-char) '(?\n ?\^M))
19105 (progn
19106 ;; Go to end of line before heading
19107 (forward-char -1)
19108 (if (memq (preceding-char) '(?\n ?\^M))
19109 ;; leave blank line before heading
19110 (forward-char -1))))))
19111 (point))
19113 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
19114 "Use Org version in org-mode, for dramatic speed-up."
19115 (if (eq major-mode 'org-mode)
19116 (progn
19117 (org-end-of-subtree nil t)
19118 (unless (eobp) (backward-char 1)))
19119 ad-do-it))
19121 (defun org-forward-same-level (arg &optional invisible-ok)
19122 "Move forward to the arg'th subheading at same level as this one.
19123 Stop at the first and last subheadings of a superior heading."
19124 (interactive "p")
19125 (org-back-to-heading invisible-ok)
19126 (org-on-heading-p)
19127 (let* ((level (- (match-end 0) (match-beginning 0) 1))
19128 (re (format "^\\*\\{1,%d\\} " level))
19130 (forward-char 1)
19131 (while (> arg 0)
19132 (while (and (re-search-forward re nil 'move)
19133 (setq l (- (match-end 0) (match-beginning 0) 1))
19134 (= l level)
19135 (not invisible-ok)
19136 (progn (backward-char 1) (org-invisible-p)))
19137 (if (< l level) (setq arg 1)))
19138 (setq arg (1- arg)))
19139 (beginning-of-line 1)))
19141 (defun org-backward-same-level (arg &optional invisible-ok)
19142 "Move backward to the arg'th subheading at same level as this one.
19143 Stop at the first and last subheadings of a superior heading."
19144 (interactive "p")
19145 (org-back-to-heading)
19146 (org-on-heading-p)
19147 (let* ((level (- (match-end 0) (match-beginning 0) 1))
19148 (re (format "^\\*\\{1,%d\\} " level))
19150 (while (> arg 0)
19151 (while (and (re-search-backward re nil 'move)
19152 (setq l (- (match-end 0) (match-beginning 0) 1))
19153 (= l level)
19154 (not invisible-ok)
19155 (org-invisible-p))
19156 (if (< l level) (setq arg 1)))
19157 (setq arg (1- arg)))))
19159 (defun org-show-subtree ()
19160 "Show everything after this heading at deeper levels."
19161 (outline-flag-region
19162 (point)
19163 (save-excursion
19164 (org-end-of-subtree t t))
19165 nil))
19167 (defun org-show-entry ()
19168 "Show the body directly following this heading.
19169 Show the heading too, if it is currently invisible."
19170 (interactive)
19171 (save-excursion
19172 (condition-case nil
19173 (progn
19174 (org-back-to-heading t)
19175 (outline-flag-region
19176 (max (point-min) (1- (point)))
19177 (save-excursion
19178 (if (re-search-forward
19179 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
19180 (match-beginning 1)
19181 (point-max)))
19182 nil)
19183 (org-cycle-hide-drawers 'children))
19184 (error nil))))
19186 (defun org-make-options-regexp (kwds &optional extra)
19187 "Make a regular expression for keyword lines."
19188 (concat
19190 "#?[ \t]*\\+\\("
19191 (mapconcat 'regexp-quote kwds "\\|")
19192 (if extra (concat "\\|" extra))
19193 "\\):[ \t]*"
19194 "\\(.*\\)"))
19196 ;; Make isearch reveal the necessary context
19197 (defun org-isearch-end ()
19198 "Reveal context after isearch exits."
19199 (when isearch-success ; only if search was successful
19200 (if (featurep 'xemacs)
19201 ;; Under XEmacs, the hook is run in the correct place,
19202 ;; we directly show the context.
19203 (org-show-context 'isearch)
19204 ;; In Emacs the hook runs *before* restoring the overlays.
19205 ;; So we have to use a one-time post-command-hook to do this.
19206 ;; (Emacs 22 has a special variable, see function `org-mode')
19207 (unless (and (boundp 'isearch-mode-end-hook-quit)
19208 isearch-mode-end-hook-quit)
19209 ;; Only when the isearch was not quitted.
19210 (org-add-hook 'post-command-hook 'org-isearch-post-command
19211 'append 'local)))))
19213 (defun org-isearch-post-command ()
19214 "Remove self from hook, and show context."
19215 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
19216 (org-show-context 'isearch))
19219 ;;;; Integration with and fixes for other packages
19221 ;;; Imenu support
19223 (defvar org-imenu-markers nil
19224 "All markers currently used by Imenu.")
19225 (make-variable-buffer-local 'org-imenu-markers)
19227 (defun org-imenu-new-marker (&optional pos)
19228 "Return a new marker for use by Imenu, and remember the marker."
19229 (let ((m (make-marker)))
19230 (move-marker m (or pos (point)))
19231 (push m org-imenu-markers)
19234 (defun org-imenu-get-tree ()
19235 "Produce the index for Imenu."
19236 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
19237 (setq org-imenu-markers nil)
19238 (let* ((n org-imenu-depth)
19239 (re (concat "^" outline-regexp))
19240 (subs (make-vector (1+ n) nil))
19241 (last-level 0)
19242 m level head)
19243 (save-excursion
19244 (save-restriction
19245 (widen)
19246 (goto-char (point-max))
19247 (while (re-search-backward re nil t)
19248 (setq level (org-reduced-level (funcall outline-level)))
19249 (when (<= level n)
19250 (looking-at org-complex-heading-regexp)
19251 (setq head (org-link-display-format
19252 (org-match-string-no-properties 4))
19253 m (org-imenu-new-marker))
19254 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
19255 (if (>= level last-level)
19256 (push (cons head m) (aref subs level))
19257 (push (cons head (aref subs (1+ level))) (aref subs level))
19258 (loop for i from (1+ level) to n do (aset subs i nil)))
19259 (setq last-level level)))))
19260 (aref subs 1)))
19262 (eval-after-load "imenu"
19263 '(progn
19264 (add-hook 'imenu-after-jump-hook
19265 (lambda ()
19266 (if (eq major-mode 'org-mode)
19267 (org-show-context 'org-goto))))))
19269 (defun org-link-display-format (link)
19270 "Replace a link with either the description, or the link target
19271 if no description is present"
19272 (save-match-data
19273 (if (string-match org-bracket-link-analytic-regexp link)
19274 (replace-match (if (match-end 5)
19275 (match-string 5 link)
19276 (concat (match-string 1 link)
19277 (match-string 3 link)))
19278 nil t link)
19279 link)))
19281 ;; Speedbar support
19283 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
19284 "Overlay marking the agenda restriction line in speedbar.")
19285 (overlay-put org-speedbar-restriction-lock-overlay
19286 'face 'org-agenda-restriction-lock)
19287 (overlay-put org-speedbar-restriction-lock-overlay
19288 'help-echo "Agendas are currently limited to this item.")
19289 (org-detach-overlay org-speedbar-restriction-lock-overlay)
19291 (defun org-speedbar-set-agenda-restriction ()
19292 "Restrict future agenda commands to the location at point in speedbar.
19293 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
19294 (interactive)
19295 (require 'org-agenda)
19296 (let (p m tp np dir txt)
19297 (cond
19298 ((setq p (text-property-any (point-at-bol) (point-at-eol)
19299 'org-imenu t))
19300 (setq m (get-text-property p 'org-imenu-marker))
19301 (with-current-buffer (marker-buffer m)
19302 (goto-char m)
19303 (org-agenda-set-restriction-lock 'subtree)))
19304 ((setq p (text-property-any (point-at-bol) (point-at-eol)
19305 'speedbar-function 'speedbar-find-file))
19306 (setq tp (previous-single-property-change
19307 (1+ p) 'speedbar-function)
19308 np (next-single-property-change
19309 tp 'speedbar-function)
19310 dir (speedbar-line-directory)
19311 txt (buffer-substring-no-properties (or tp (point-min))
19312 (or np (point-max))))
19313 (with-current-buffer (find-file-noselect
19314 (let ((default-directory dir))
19315 (expand-file-name txt)))
19316 (unless (org-mode-p)
19317 (error "Cannot restrict to non-Org-mode file"))
19318 (org-agenda-set-restriction-lock 'file)))
19319 (t (error "Don't know how to restrict Org-mode's agenda")))
19320 (move-overlay org-speedbar-restriction-lock-overlay
19321 (point-at-bol) (point-at-eol))
19322 (setq current-prefix-arg nil)
19323 (org-agenda-maybe-redo)))
19325 (eval-after-load "speedbar"
19326 '(progn
19327 (speedbar-add-supported-extension ".org")
19328 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
19329 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
19330 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
19331 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19332 (add-hook 'speedbar-visiting-tag-hook
19333 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
19335 ;;; Fixes and Hacks for problems with other packages
19337 ;; Make flyspell not check words in links, to not mess up our keymap
19338 (defun org-mode-flyspell-verify ()
19339 "Don't let flyspell put overlays at active buttons."
19340 (and (not (get-text-property (point) 'keymap))
19341 (not (get-text-property (point) 'org-no-flyspell))))
19343 (defun org-remove-flyspell-overlays-in (beg end)
19344 "Remove flyspell overlays in region."
19345 (and (org-bound-and-true-p flyspell-mode)
19346 (fboundp 'flyspell-delete-region-overlays)
19347 (flyspell-delete-region-overlays beg end))
19348 (add-text-properties beg end '(org-no-flyspell t)))
19350 ;; Make `bookmark-jump' shows the jump location if it was hidden.
19351 (eval-after-load "bookmark"
19352 '(if (boundp 'bookmark-after-jump-hook)
19353 ;; We can use the hook
19354 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
19355 ;; Hook not available, use advice
19356 (defadvice bookmark-jump (after org-make-visible activate)
19357 "Make the position visible."
19358 (org-bookmark-jump-unhide))))
19360 ;; Make sure saveplace shows the location if it was hidden
19361 (eval-after-load "saveplace"
19362 '(defadvice save-place-find-file-hook (after org-make-visible activate)
19363 "Make the position visible."
19364 (org-bookmark-jump-unhide)))
19366 ;; Make sure ecb shows the location if it was hidden
19367 (eval-after-load "ecb"
19368 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
19369 "Make hierarchy visible when jumping into location from ECB tree buffer."
19370 (if (eq major-mode 'org-mode)
19371 (org-show-context))))
19373 (defun org-bookmark-jump-unhide ()
19374 "Unhide the current position, to show the bookmark location."
19375 (and (org-mode-p)
19376 (or (org-invisible-p)
19377 (save-excursion (goto-char (max (point-min) (1- (point))))
19378 (org-invisible-p)))
19379 (org-show-context 'bookmark-jump)))
19381 ;; Make session.el ignore our circular variable
19382 (eval-after-load "session"
19383 '(add-to-list 'session-globals-exclude 'org-mark-ring))
19385 ;;;; Experimental code
19387 (defun org-closed-in-range ()
19388 "Sparse tree of items closed in a certain time range.
19389 Still experimental, may disappear in the future."
19390 (interactive)
19391 ;; Get the time interval from the user.
19392 (let* ((time1 (org-float-time
19393 (org-read-date nil 'to-time nil "Starting date: ")))
19394 (time2 (org-float-time
19395 (org-read-date nil 'to-time nil "End date:")))
19396 ;; callback function
19397 (callback (lambda ()
19398 (let ((time
19399 (org-float-time
19400 (apply 'encode-time
19401 (org-parse-time-string
19402 (match-string 1))))))
19403 ;; check if time in interval
19404 (and (>= time time1) (<= time time2))))))
19405 ;; make tree, check each match with the callback
19406 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
19408 ;;;; Finish up
19410 (provide 'org)
19412 (run-hooks 'org-load-hook)
19414 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
19416 ;;; org.el ends here