Use Slashdot.org as feed example in the documentation
[org-mode/org-jambu.git] / lisp / org.el
blobdf511e7c06ed253e1600f403dc42e2583777144f
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 (file-name-as-directory
8708 default-directory)))
8709 (expand-file-name path))
8710 ;; We are linking a file with relative path name.
8711 (setq path (substring (expand-file-name path)
8712 (match-end 0)))
8713 (setq path (abbreviate-file-name (expand-file-name path)))))))
8714 (setq link (concat type path))
8715 (if (equal desc origpath)
8716 (setq desc path))))
8718 (if org-make-link-description-function
8719 (setq desc (funcall org-make-link-description-function link desc)))
8721 (setq desc (read-string "Description: " desc))
8722 (unless (string-match "\\S-" desc) (setq desc nil))
8723 (if remove (apply 'delete-region remove))
8724 (insert (org-make-link-string link desc))))
8726 (defun org-link-try-special-completion (type)
8727 "If there is completion support for link type TYPE, offer it."
8728 (let ((fun (intern (concat "org-" type "-complete-link"))))
8729 (if (functionp fun)
8730 (funcall fun)
8731 (read-string "Link (no completion support): " (concat type ":")))))
8733 (defun org-file-complete-link (&optional arg)
8734 "Create a file link using completion."
8735 (let (file link)
8736 (setq file (read-file-name "File: "))
8737 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8738 (pwd1 (file-name-as-directory (abbreviate-file-name
8739 (expand-file-name ".")))))
8740 (cond
8741 ((equal arg '(16))
8742 (setq link (org-make-link
8743 "file:"
8744 (abbreviate-file-name (expand-file-name file)))))
8745 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8746 (setq link (org-make-link "file:" (match-string 1 file))))
8747 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8748 (expand-file-name file))
8749 (setq link (org-make-link
8750 "file:" (match-string 1 (expand-file-name file)))))
8751 (t (setq link (org-make-link "file:" file)))))
8752 link))
8754 (defun org-completing-read (&rest args)
8755 "Completing-read with SPACE being a normal character."
8756 (let ((minibuffer-local-completion-map
8757 (copy-keymap minibuffer-local-completion-map)))
8758 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8759 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8760 (apply 'org-icompleting-read args)))
8762 (defun org-completing-read-no-i (&rest args)
8763 (let (org-completion-use-ido org-completion-use-iswitchb)
8764 (apply 'org-completing-read args)))
8766 (defun org-iswitchb-completing-read (prompt choices &rest args)
8767 "Use iswitch as a completing-read replacement to choose from choices.
8768 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8769 from."
8770 (let* ((iswitchb-use-virtual-buffers nil)
8771 (iswitchb-make-buflist-hook
8772 (lambda ()
8773 (setq iswitchb-temp-buflist choices))))
8774 (iswitchb-read-buffer prompt)))
8776 (defun org-icompleting-read (&rest args)
8777 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8778 (org-without-partial-completion
8779 (if (and org-completion-use-ido
8780 (fboundp 'ido-completing-read)
8781 (boundp 'ido-mode) ido-mode
8782 (listp (second args)))
8783 (let ((ido-enter-matching-directory nil))
8784 (apply 'ido-completing-read (concat (car args))
8785 (if (consp (car (nth 1 args)))
8786 (mapcar (lambda (x) (car x)) (nth 1 args))
8787 (nth 1 args))
8788 (cddr args)))
8789 (if (and org-completion-use-iswitchb
8790 (boundp 'iswitchb-mode) iswitchb-mode
8791 (listp (second args)))
8792 (apply 'org-iswitchb-completing-read (concat (car args))
8793 (if (consp (car (nth 1 args)))
8794 (mapcar (lambda (x) (car x)) (nth 1 args))
8795 (nth 1 args))
8796 (cddr args))
8797 (apply 'completing-read args)))))
8799 (defun org-extract-attributes (s)
8800 "Extract the attributes cookie from a string and set as text property."
8801 (let (a attr (start 0) key value)
8802 (save-match-data
8803 (when (string-match "{{\\([^}]+\\)}}$" s)
8804 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8805 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8806 (setq key (match-string 1 a) value (match-string 2 a)
8807 start (match-end 0)
8808 attr (plist-put attr (intern key) value))))
8809 (org-add-props s nil 'org-attr attr))
8812 (defun org-extract-attributes-from-string (tag)
8813 (let (key value attr)
8814 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8815 (setq key (match-string 1 tag) value (match-string 2 tag)
8816 tag (replace-match "" t t tag)
8817 attr (plist-put attr (intern key) value)))
8818 (cons tag attr)))
8820 (defun org-attributes-to-string (plist)
8821 "Format a property list into an HTML attribute list."
8822 (let ((s "") key value)
8823 (while plist
8824 (setq key (pop plist) value (pop plist))
8825 (and value
8826 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8829 ;;; Opening/following a link
8831 (defvar org-link-search-failed nil)
8833 (defvar org-open-link-functions nil
8834 "Hook for functions finding a plain text link.
8835 These functions must take a single argument, the link content.
8836 They will be called for links that look like [[link text][description]]
8837 when LINK TEXT does not have a protocol like \"http:\" and does not look
8838 like a filename (e.g. \"./blue.png\").
8840 These functions will be called *before* Org attempts to resolve the
8841 link by doing text searches in the current buffer - so if you want a
8842 link \"[[target]]\" to still find \"<<target>>\", your function should
8843 handle this as a special case.
8845 When the function does handle the link, it must return a non-nil value.
8846 If it decides that it is not responsible for this link, it must return
8847 nil to indicate that that Org-mode can continue with other options
8848 like exact and fuzzy text search.")
8850 (defun org-next-link ()
8851 "Move forward to the next link.
8852 If the link is in hidden text, expose it."
8853 (interactive)
8854 (when (and org-link-search-failed (eq this-command last-command))
8855 (goto-char (point-min))
8856 (message "Link search wrapped back to beginning of buffer"))
8857 (setq org-link-search-failed nil)
8858 (let* ((pos (point))
8859 (ct (org-context))
8860 (a (assoc :link ct)))
8861 (if a (goto-char (nth 2 a)))
8862 (if (re-search-forward org-any-link-re nil t)
8863 (progn
8864 (goto-char (match-beginning 0))
8865 (if (org-invisible-p) (org-show-context)))
8866 (goto-char pos)
8867 (setq org-link-search-failed t)
8868 (error "No further link found"))))
8870 (defun org-previous-link ()
8871 "Move backward to the previous link.
8872 If the link is in hidden text, expose it."
8873 (interactive)
8874 (when (and org-link-search-failed (eq this-command last-command))
8875 (goto-char (point-max))
8876 (message "Link search wrapped back to end of buffer"))
8877 (setq org-link-search-failed nil)
8878 (let* ((pos (point))
8879 (ct (org-context))
8880 (a (assoc :link ct)))
8881 (if a (goto-char (nth 1 a)))
8882 (if (re-search-backward org-any-link-re nil t)
8883 (progn
8884 (goto-char (match-beginning 0))
8885 (if (org-invisible-p) (org-show-context)))
8886 (goto-char pos)
8887 (setq org-link-search-failed t)
8888 (error "No further link found"))))
8890 (defun org-translate-link (s)
8891 "Translate a link string if a translation function has been defined."
8892 (if (and org-link-translation-function
8893 (fboundp org-link-translation-function)
8894 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8895 (progn
8896 (setq s (funcall org-link-translation-function
8897 (match-string 1) (match-string 2)))
8898 (concat (car s) ":" (cdr s)))
8901 (defun org-translate-link-from-planner (type path)
8902 "Translate a link from Emacs Planner syntax so that Org can follow it.
8903 This is still an experimental function, your mileage may vary."
8904 (cond
8905 ((member type '("http" "https" "news" "ftp"))
8906 ;; standard Internet links are the same.
8907 nil)
8908 ((and (equal type "irc") (string-match "^//" path))
8909 ;; Planner has two / at the beginning of an irc link, we have 1.
8910 ;; We should have zero, actually....
8911 (setq path (substring path 1)))
8912 ((and (equal type "lisp") (string-match "^/" path))
8913 ;; Planner has a slash, we do not.
8914 (setq type "elisp" path (substring path 1)))
8915 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8916 ;; A typical message link. Planner has the id after the final slash,
8917 ;; we separate it with a hash mark
8918 (setq path (concat (match-string 1 path) "#"
8919 (org-remove-angle-brackets (match-string 2 path)))))
8921 (cons type path))
8923 (defun org-find-file-at-mouse (ev)
8924 "Open file link or URL at mouse."
8925 (interactive "e")
8926 (mouse-set-point ev)
8927 (org-open-at-point 'in-emacs))
8929 (defun org-open-at-mouse (ev)
8930 "Open file link or URL at mouse."
8931 (interactive "e")
8932 (mouse-set-point ev)
8933 (if (eq major-mode 'org-agenda-mode)
8934 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8935 (org-open-at-point))
8937 (defvar org-window-config-before-follow-link nil
8938 "The window configuration before following a link.
8939 This is saved in case the need arises to restore it.")
8941 (defvar org-open-link-marker (make-marker)
8942 "Marker pointing to the location where `org-open-at-point; was called.")
8944 ;;;###autoload
8945 (defun org-open-at-point-global ()
8946 "Follow a link like Org-mode does.
8947 This command can be called in any mode to follow a link that has
8948 Org-mode syntax."
8949 (interactive)
8950 (org-run-like-in-org-mode 'org-open-at-point))
8952 ;;;###autoload
8953 (defun org-open-link-from-string (s &optional arg reference-buffer)
8954 "Open a link in the string S, as if it was in Org-mode."
8955 (interactive "sLink: \nP")
8956 (let ((reference-buffer (or reference-buffer (current-buffer))))
8957 (with-temp-buffer
8958 (let ((org-inhibit-startup t))
8959 (org-mode)
8960 (insert s)
8961 (goto-char (point-min))
8962 (when reference-buffer
8963 (setq org-link-abbrev-alist-local
8964 (with-current-buffer reference-buffer
8965 org-link-abbrev-alist-local)))
8966 (org-open-at-point arg reference-buffer)))))
8968 (defun org-open-at-point (&optional in-emacs reference-buffer)
8969 "Open link at or after point.
8970 If there is no link at point, this function will search forward up to
8971 the end of the current line.
8972 Normally, files will be opened by an appropriate application. If the
8973 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8974 With a double prefix argument, try to open outside of Emacs, in the
8975 application the system uses for this file type."
8976 (interactive "P")
8977 ;; if in a code block, then open the block's results
8978 (unless (call-interactively #'org-babel-open-src-block-result)
8979 (org-load-modules-maybe)
8980 (move-marker org-open-link-marker (point))
8981 (setq org-window-config-before-follow-link (current-window-configuration))
8982 (org-remove-occur-highlights nil nil t)
8983 (cond
8984 ((and (org-on-heading-p)
8985 (not (org-in-regexp
8986 (concat org-plain-link-re "\\|"
8987 org-bracket-link-regexp "\\|"
8988 org-angle-link-re "\\|"
8989 "[ \t]:[^ \t\n]+:[ \t]*$")))
8990 (not (get-text-property (point) 'org-linked-text)))
8991 (or (org-offer-links-in-entry in-emacs)
8992 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8993 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8994 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8995 (org-footnote-action))
8997 (let (type path link line search (pos (point)))
8998 (catch 'match
8999 (save-excursion
9000 (skip-chars-forward "^]\n\r")
9001 (when (org-in-regexp org-bracket-link-regexp 1)
9002 (setq link (org-extract-attributes
9003 (org-link-unescape (org-match-string-no-properties 1))))
9004 (while (string-match " *\n *" link)
9005 (setq link (replace-match " " t t link)))
9006 (setq link (org-link-expand-abbrev link))
9007 (cond
9008 ((or (file-name-absolute-p link)
9009 (string-match "^\\.\\.?/" link))
9010 (setq type "file" path link))
9011 ((string-match org-link-re-with-space3 link)
9012 (setq type (match-string 1 link) path (match-string 2 link)))
9013 (t (setq type "thisfile" path link)))
9014 (throw 'match t)))
9016 (when (get-text-property (point) 'org-linked-text)
9017 (setq type "thisfile"
9018 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9019 (1+ (point)) (point))
9020 path (buffer-substring
9021 (previous-single-property-change pos 'org-linked-text)
9022 (next-single-property-change pos 'org-linked-text)))
9023 (throw 'match t))
9025 (save-excursion
9026 (when (or (org-in-regexp org-angle-link-re)
9027 (org-in-regexp org-plain-link-re))
9028 (setq type (match-string 1) path (match-string 2))
9029 (throw 'match t)))
9030 (save-excursion
9031 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
9032 (setq type "tags"
9033 path (match-string 1))
9034 (while (string-match ":" path)
9035 (setq path (replace-match "+" t t path)))
9036 (throw 'match t)))
9037 (when (org-in-regexp "<\\([^><\n]+\\)>")
9038 (setq type "tree-match"
9039 path (match-string 1))
9040 (throw 'match t)))
9041 (unless path
9042 (error "No link found"))
9044 ;; switch back to reference buffer
9045 ;; needed when if called in a temporary buffer through
9046 ;; org-open-link-from-string
9047 (with-current-buffer (or reference-buffer (current-buffer))
9049 ;; Remove any trailing spaces in path
9050 (if (string-match " +\\'" path)
9051 (setq path (replace-match "" t t path)))
9052 (if (and org-link-translation-function
9053 (fboundp org-link-translation-function))
9054 ;; Check if we need to translate the link
9055 (let ((tmp (funcall org-link-translation-function type path)))
9056 (setq type (car tmp) path (cdr tmp))))
9058 (cond
9060 ((assoc type org-link-protocols)
9061 (funcall (nth 1 (assoc type org-link-protocols)) path))
9063 ((equal type "mailto")
9064 (let ((cmd (car org-link-mailto-program))
9065 (args (cdr org-link-mailto-program)) args1
9066 (address path) (subject "") a)
9067 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9068 (setq address (match-string 1 path)
9069 subject (org-link-escape (match-string 2 path))))
9070 (while args
9071 (cond
9072 ((not (stringp (car args))) (push (pop args) args1))
9073 (t (setq a (pop args))
9074 (if (string-match "%a" a)
9075 (setq a (replace-match address t t a)))
9076 (if (string-match "%s" a)
9077 (setq a (replace-match subject t t a)))
9078 (push a args1))))
9079 (apply cmd (nreverse args1))))
9081 ((member type '("http" "https" "ftp" "news"))
9082 (browse-url (concat type ":" (org-link-escape
9083 path org-link-escape-chars-browser))))
9085 ((string= type "doi")
9086 (browse-url (concat "http://dx.doi.org/"
9087 (org-link-escape
9088 path org-link-escape-chars-browser))))
9090 ((member type '("message"))
9091 (browse-url (concat type ":" path)))
9093 ((string= type "tags")
9094 (org-tags-view in-emacs path))
9096 ((string= type "tree-match")
9097 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9099 ((string= type "file")
9100 (if (string-match "::\\([0-9]+\\)\\'" path)
9101 (setq line (string-to-number (match-string 1 path))
9102 path (substring path 0 (match-beginning 0)))
9103 (if (string-match "::\\(.+\\)\\'" path)
9104 (setq search (match-string 1 path)
9105 path (substring path 0 (match-beginning 0)))))
9106 (if (string-match "[*?{]" (file-name-nondirectory path))
9107 (dired path)
9108 (org-open-file path in-emacs line search)))
9110 ((string= type "news")
9111 (require 'org-gnus)
9112 (org-gnus-follow-link path))
9114 ((string= type "shell")
9115 (let ((cmd path))
9116 (if (or (not org-confirm-shell-link-function)
9117 (funcall org-confirm-shell-link-function
9118 (format "Execute \"%s\" in shell? "
9119 (org-add-props cmd nil
9120 'face 'org-warning))))
9121 (progn
9122 (message "Executing %s" cmd)
9123 (shell-command cmd))
9124 (error "Abort"))))
9126 ((string= type "elisp")
9127 (let ((cmd path))
9128 (if (or (not org-confirm-elisp-link-function)
9129 (funcall org-confirm-elisp-link-function
9130 (format "Execute \"%s\" as elisp? "
9131 (org-add-props cmd nil
9132 'face 'org-warning))))
9133 (message "%s => %s" cmd
9134 (if (equal (string-to-char cmd) ?\()
9135 (eval (read cmd))
9136 (call-interactively (read cmd))))
9137 (error "Abort"))))
9139 ((and (string= type "thisfile")
9140 (run-hook-with-args-until-success
9141 'org-open-link-functions path)))
9143 ((string= type "thisfile")
9144 (if in-emacs
9145 (switch-to-buffer-other-window
9146 (org-get-buffer-for-internal-link (current-buffer)))
9147 (org-mark-ring-push))
9148 (let ((cmd `(org-link-search
9149 ,path
9150 ,(cond ((equal in-emacs '(4)) 'occur)
9151 ((equal in-emacs '(16)) 'org-occur)
9152 (t nil))
9153 ,pos)))
9154 (condition-case nil (eval cmd)
9155 (error (progn (widen) (eval cmd))))))
9158 (browse-url-at-point)))))))
9159 (move-marker org-open-link-marker nil)
9160 (run-hook-with-args 'org-follow-link-hook)))
9162 (defun org-offer-links-in-entry (&optional nth zero)
9163 "Offer links in the current entry and follow the selected link.
9164 If there is only one link, follow it immediately as well.
9165 If NTH is an integer, immediately pick the NTH link found.
9166 If ZERO is a string, check also this string for a link, and if
9167 there is one, offer it as link number zero."
9168 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9169 "\\(" org-angle-link-re "\\)\\|"
9170 "\\(" org-plain-link-re "\\)"))
9171 (cnt ?0)
9172 (in-emacs (if (integerp nth) nil nth))
9173 have-zero end links link c)
9174 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9175 (push (match-string 0 zero) links)
9176 (setq cnt (1- cnt) have-zero t))
9177 (save-excursion
9178 (org-back-to-heading t)
9179 (setq end (save-excursion (outline-next-heading) (point)))
9180 (while (re-search-forward re end t)
9181 (push (match-string 0) links))
9182 (setq links (org-uniquify (reverse links))))
9184 (cond
9185 ((null links)
9186 (message "No links"))
9187 ((equal (length links) 1)
9188 (setq link (list (car links))))
9189 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9190 (setq link (nth (if have-zero nth (1- nth)) links)))
9191 (t ; we have to select a link
9192 (save-excursion
9193 (save-window-excursion
9194 (delete-other-windows)
9195 (with-output-to-temp-buffer "*Select Link*"
9196 (mapc (lambda (l)
9197 (if (not (string-match org-bracket-link-regexp l))
9198 (princ (format "[%c] %s\n" (incf cnt)
9199 (org-remove-angle-brackets l)))
9200 (if (match-end 3)
9201 (princ (format "[%c] %s (%s)\n" (incf cnt)
9202 (match-string 3 l) (match-string 1 l)))
9203 (princ (format "[%c] %s\n" (incf cnt)
9204 (match-string 1 l))))))
9205 links))
9206 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9207 (message "Select link to open, RET to open all:")
9208 (setq c (read-char-exclusive))
9209 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9210 (when (equal c ?q) (error "Abort"))
9211 (if (equal c ?\C-m)
9212 (setq link links)
9213 (setq nth (- c ?0))
9214 (if have-zero (setq nth (1+ nth)))
9215 (unless (and (integerp nth) (>= (length links) nth))
9216 (error "Invalid link selection"))
9217 (setq link (list (nth (1- nth) links))))))
9218 (if link
9219 (let ((buf (current-buffer)))
9220 (dolist (l link)
9221 (org-open-link-from-string l in-emacs buf))
9223 nil)))
9225 ;; Add special file links that specify the way of opening
9227 (org-add-link-type "file+sys" 'org-open-file-with-system)
9228 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9229 (defun org-open-file-with-system (path)
9230 "Open file at PATH using the system way of opeing it."
9231 (org-open-file path 'system))
9232 (defun org-open-file-with-emacs (path)
9233 "Open file at PATH in emacs."
9234 (org-open-file path 'emacs))
9235 (defun org-remove-file-link-modifiers ()
9236 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9237 (goto-char (point-min))
9238 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9239 (org-if-unprotected
9240 (replace-match "file:" t t))))
9241 (eval-after-load "org-exp"
9242 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9243 'org-remove-file-link-modifiers))
9245 ;;;; Time estimates
9247 (defun org-get-effort (&optional pom)
9248 "Get the effort estimate for the current entry."
9249 (org-entry-get pom org-effort-property))
9251 ;;; File search
9253 (defvar org-create-file-search-functions nil
9254 "List of functions to construct the right search string for a file link.
9255 These functions are called in turn with point at the location to
9256 which the link should point.
9258 A function in the hook should first test if it would like to
9259 handle this file type, for example by checking the major-mode or
9260 the file extension. If it decides not to handle this file, it
9261 should just return nil to give other functions a chance. If it
9262 does handle the file, it must return the search string to be used
9263 when following the link. The search string will be part of the
9264 file link, given after a double colon, and `org-open-at-point'
9265 will automatically search for it. If special measures must be
9266 taken to make the search successful, another function should be
9267 added to the companion hook `org-execute-file-search-functions',
9268 which see.
9270 A function in this hook may also use `setq' to set the variable
9271 `description' to provide a suggestion for the descriptive text to
9272 be used for this link when it gets inserted into an Org-mode
9273 buffer with \\[org-insert-link].")
9275 (defvar org-execute-file-search-functions nil
9276 "List of functions to execute a file search triggered by a link.
9278 Functions added to this hook must accept a single argument, the
9279 search string that was part of the file link, the part after the
9280 double colon. The function must first check if it would like to
9281 handle this search, for example by checking the major-mode or the
9282 file extension. If it decides not to handle this search, it
9283 should just return nil to give other functions a chance. If it
9284 does handle the search, it must return a non-nil value to keep
9285 other functions from trying.
9287 Each function can access the current prefix argument through the
9288 variable `current-prefix-argument'. Note that a single prefix is
9289 used to force opening a link in Emacs, so it may be good to only
9290 use a numeric or double prefix to guide the search function.
9292 In case this is needed, a function in this hook can also restore
9293 the window configuration before `org-open-at-point' was called using:
9295 (set-window-configuration org-window-config-before-follow-link)")
9297 (defun org-link-search (s &optional type avoid-pos)
9298 "Search for a link search option.
9299 If S is surrounded by forward slashes, it is interpreted as a
9300 regular expression. In org-mode files, this will create an `org-occur'
9301 sparse tree. In ordinary files, `occur' will be used to list matches.
9302 If the current buffer is in `dired-mode', grep will be used to search
9303 in all files. If AVOID-POS is given, ignore matches near that position."
9304 (let ((case-fold-search t)
9305 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9306 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9307 (append '(("") (" ") ("\t") ("\n"))
9308 org-emphasis-alist)
9309 "\\|") "\\)"))
9310 (pos (point))
9311 (pre nil) (post nil)
9312 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9313 (cond
9314 ;; First check if there are any special
9315 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9316 ;; Now try the builtin stuff
9317 ((and (equal (string-to-char s0) ?#)
9318 (> (length s0) 1)
9319 (save-excursion
9320 (goto-char (point-min))
9321 (and
9322 (re-search-forward
9323 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9324 (setq type 'dedicated
9325 pos (match-beginning 0))))
9326 ;; There is an exact target for this
9327 (goto-char pos)
9328 (org-back-to-heading t)))
9329 ((save-excursion
9330 (goto-char (point-min))
9331 (and
9332 (re-search-forward
9333 (concat "<<" (regexp-quote s0) ">>") nil t)
9334 (setq type 'dedicated
9335 pos (match-beginning 0))))
9336 ;; There is an exact target for this
9337 (goto-char pos))
9338 ((and (string-match "^(\\(.*\\))$" s0)
9339 (save-excursion
9340 (goto-char (point-min))
9341 (and
9342 (re-search-forward
9343 (concat "[^[]" (regexp-quote
9344 (format org-coderef-label-format
9345 (match-string 1 s0))))
9346 nil t)
9347 (setq type 'dedicated
9348 pos (1+ (match-beginning 0))))))
9349 ;; There is a coderef target for this
9350 (goto-char pos))
9351 ((string-match "^/\\(.*\\)/$" s)
9352 ;; A regular expression
9353 (cond
9354 ((org-mode-p)
9355 (org-occur (match-string 1 s)))
9356 ;;((eq major-mode 'dired-mode)
9357 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9358 (t (org-do-occur (match-string 1 s)))))
9360 ;; A normal search strings
9361 (when (equal (string-to-char s) ?*)
9362 ;; Anchor on headlines, post may include tags.
9363 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9364 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
9365 s (substring s 1)))
9366 (remove-text-properties
9367 0 (length s)
9368 '(face nil mouse-face nil keymap nil fontified nil) s)
9369 ;; Make a series of regular expressions to find a match
9370 (setq words (org-split-string s "[ \n\r\t]+")
9372 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9373 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9374 "\\)" markers)
9375 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9376 re2a (concat "[ \t\r\n]" re2a_)
9377 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9378 re4 (concat "[^a-zA-Z_]" re4_)
9380 re1 (concat pre re2 post)
9381 re3 (concat pre (if pre re4_ re4) post)
9382 re5 (concat pre ".*" re4)
9383 re2 (concat pre re2)
9384 re2a (concat pre (if pre re2a_ re2a))
9385 re4 (concat pre (if pre re4_ re4))
9386 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9387 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9388 re5 "\\)"
9390 (cond
9391 ((eq type 'org-occur) (org-occur reall))
9392 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9393 (t (goto-char (point-min))
9394 (setq type 'fuzzy)
9395 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9396 (org-search-not-self 1 re1 nil t)
9397 (org-search-not-self 1 re2 nil t)
9398 (org-search-not-self 1 re2a nil t)
9399 (org-search-not-self 1 re3 nil t)
9400 (org-search-not-self 1 re4 nil t)
9401 (org-search-not-self 1 re5 nil t)
9403 (goto-char (match-beginning 1))
9404 (goto-char pos)
9405 (error "No match")))))
9407 ;; Normal string-search
9408 (goto-char (point-min))
9409 (if (search-forward s nil t)
9410 (goto-char (match-beginning 0))
9411 (error "No match"))))
9412 (and (org-mode-p) (org-show-context 'link-search))
9413 type))
9415 (defun org-search-not-self (group &rest args)
9416 "Execute `re-search-forward', but only accept matches that do not
9417 enclose the position of `org-open-link-marker'."
9418 (let ((m org-open-link-marker))
9419 (catch 'exit
9420 (while (apply 're-search-forward args)
9421 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9422 (goto-char (match-end group))
9423 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9424 (> (match-beginning 0) (marker-position m))
9425 (< (match-end 0) (marker-position m)))
9426 (save-match-data
9427 (or (not (org-in-regexp
9428 org-bracket-link-analytic-regexp 1))
9429 (not (match-end 4)) ; no description
9430 (and (<= (match-beginning 4) (point))
9431 (>= (match-end 4) (point))))))
9432 (throw 'exit (point))))))))
9434 (defun org-get-buffer-for-internal-link (buffer)
9435 "Return a buffer to be used for displaying the link target of internal links."
9436 (cond
9437 ((not org-display-internal-link-with-indirect-buffer)
9438 buffer)
9439 ((string-match "(Clone)$" (buffer-name buffer))
9440 (message "Buffer is already a clone, not making another one")
9441 ;; we also do not modify visibility in this case
9442 buffer)
9443 (t ; make a new indirect buffer for displaying the link
9444 (let* ((bn (buffer-name buffer))
9445 (ibn (concat bn "(Clone)"))
9446 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9447 (with-current-buffer ib (org-overview))
9448 ib))))
9450 (defun org-do-occur (regexp &optional cleanup)
9451 "Call the Emacs command `occur'.
9452 If CLEANUP is non-nil, remove the printout of the regular expression
9453 in the *Occur* buffer. This is useful if the regex is long and not useful
9454 to read."
9455 (occur regexp)
9456 (when cleanup
9457 (let ((cwin (selected-window)) win beg end)
9458 (when (setq win (get-buffer-window "*Occur*"))
9459 (select-window win))
9460 (goto-char (point-min))
9461 (when (re-search-forward "match[a-z]+" nil t)
9462 (setq beg (match-end 0))
9463 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9464 (setq end (1- (match-beginning 0)))))
9465 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9466 (goto-char (point-min))
9467 (select-window cwin))))
9469 ;;; The mark ring for links jumps
9471 (defvar org-mark-ring nil
9472 "Mark ring for positions before jumps in Org-mode.")
9473 (defvar org-mark-ring-last-goto nil
9474 "Last position in the mark ring used to go back.")
9475 ;; Fill and close the ring
9476 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9477 (loop for i from 1 to org-mark-ring-length do
9478 (push (make-marker) org-mark-ring))
9479 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9480 org-mark-ring)
9482 (defun org-mark-ring-push (&optional pos buffer)
9483 "Put the current position or POS into the mark ring and rotate it."
9484 (interactive)
9485 (setq pos (or pos (point)))
9486 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9487 (move-marker (car org-mark-ring)
9488 (or pos (point))
9489 (or buffer (current-buffer)))
9490 (message "%s"
9491 (substitute-command-keys
9492 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9494 (defun org-mark-ring-goto (&optional n)
9495 "Jump to the previous position in the mark ring.
9496 With prefix arg N, jump back that many stored positions. When
9497 called several times in succession, walk through the entire ring.
9498 Org-mode commands jumping to a different position in the current file,
9499 or to another Org-mode file, automatically push the old position
9500 onto the ring."
9501 (interactive "p")
9502 (let (p m)
9503 (if (eq last-command this-command)
9504 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9505 (setq p org-mark-ring))
9506 (setq org-mark-ring-last-goto p)
9507 (setq m (car p))
9508 (switch-to-buffer (marker-buffer m))
9509 (goto-char m)
9510 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9512 (defun org-remove-angle-brackets (s)
9513 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9514 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9516 (defun org-add-angle-brackets (s)
9517 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9518 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9520 (defun org-remove-double-quotes (s)
9521 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9522 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
9525 ;;; Following specific links
9527 (defun org-follow-timestamp-link ()
9528 (cond
9529 ((org-at-date-range-p t)
9530 (let ((org-agenda-start-on-weekday)
9531 (t1 (match-string 1))
9532 (t2 (match-string 2)))
9533 (setq t1 (time-to-days (org-time-string-to-time t1))
9534 t2 (time-to-days (org-time-string-to-time t2)))
9535 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9536 ((org-at-timestamp-p t)
9537 (org-agenda-list nil (time-to-days (org-time-string-to-time
9538 (substring (match-string 1) 0 10)))
9540 (t (error "This should not happen"))))
9543 ;;; Following file links
9544 (defvar org-wait nil)
9545 (defun org-open-file (path &optional in-emacs line search)
9546 "Open the file at PATH.
9547 First, this expands any special file name abbreviations. Then the
9548 configuration variable `org-file-apps' is checked if it contains an
9549 entry for this file type, and if yes, the corresponding command is launched.
9551 If no application is found, Emacs simply visits the file.
9553 With optional prefix argument IN-EMACS, Emacs will visit the file.
9554 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
9555 and to use an external application to visit the file.
9557 Optional LINE specifies a line to go to, optional SEARCH a string
9558 to search for. If LINE or SEARCH is given, the file will be
9559 opened in Emacs, unless an entry from org-file-apps that makes
9560 use of groups in a regexp matches.
9561 If the file does not exist, an error is thrown."
9562 (let* ((file (if (equal path "")
9563 buffer-file-name
9564 (substitute-in-file-name (expand-file-name path))))
9565 (file-apps (append org-file-apps (org-default-apps)))
9566 (apps (org-remove-if
9567 'org-file-apps-entry-match-against-dlink-p file-apps))
9568 (apps-dlink (org-remove-if-not
9569 'org-file-apps-entry-match-against-dlink-p file-apps))
9570 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9571 (dirp (if remp nil (file-directory-p file)))
9572 (file (if (and dirp org-open-directory-means-index-dot-org)
9573 (concat (file-name-as-directory file) "index.org")
9574 file))
9575 (a-m-a-p (assq 'auto-mode apps))
9576 (dfile (downcase file))
9577 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
9578 (link (cond ((and (eq line nil)
9579 (eq search nil))
9580 file)
9581 (line
9582 (concat file "::" (number-to-string line)))
9583 (search
9584 (concat file "::" search))))
9585 (dlink (downcase link))
9586 (old-buffer (current-buffer))
9587 (old-pos (point))
9588 (old-mode major-mode)
9589 ext cmd link-match-data)
9590 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9591 (setq ext (match-string 1 dfile))
9592 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9593 (setq ext (match-string 1 dfile))))
9594 (cond
9595 ((member in-emacs '((16) system))
9596 (setq cmd (cdr (assoc 'system apps))))
9597 (in-emacs (setq cmd 'emacs))
9599 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9600 (and dirp (cdr (assoc 'directory apps)))
9601 ; first, try matching against apps-dlink
9602 ; if we get a match here, store the match data for later
9603 (let ((match (assoc-default dlink apps-dlink
9604 'string-match)))
9605 (if match
9606 (progn (setq link-match-data (match-data))
9607 match)
9608 (progn (setq in-emacs (or in-emacs line search))
9609 nil))) ; if we have no match in apps-dlink,
9610 ; always open the file in emacs if line or search
9611 ; is given (for backwards compatibility)
9612 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
9613 'string-match)
9614 (cdr (assoc ext apps))
9615 (cdr (assoc t apps))))))
9616 (when (eq cmd 'system)
9617 (setq cmd (cdr (assoc 'system apps))))
9618 (when (eq cmd 'default)
9619 (setq cmd (cdr (assoc t apps))))
9620 (when (eq cmd 'mailcap)
9621 (require 'mailcap)
9622 (mailcap-parse-mailcaps)
9623 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9624 (command (mailcap-mime-info mime-type)))
9625 (if (stringp command)
9626 (setq cmd command)
9627 (setq cmd 'emacs))))
9628 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
9629 (not (file-exists-p file))
9630 (not org-open-non-existing-files))
9631 (error "No such file: %s" file))
9632 (cond
9633 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9634 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9635 (while (string-match "['\"]%s['\"]" cmd)
9636 (setq cmd (replace-match "%s" t t cmd)))
9637 (while (string-match "%s" cmd)
9638 (setq cmd (replace-match
9639 (save-match-data
9640 (shell-quote-argument
9641 (convert-standard-filename file)))
9642 t t cmd)))
9644 ;; Replace "%1", "%2" etc. in command with group matches from regex
9645 (save-match-data
9646 (let ((match-index 1)
9647 (number-of-groups (- (/ (length link-match-data) 2) 1)))
9648 (set-match-data link-match-data)
9649 (while (<= match-index number-of-groups)
9650 (let ((regex (concat "%" (number-to-string match-index)))
9651 (replace-with (match-string match-index dlink)))
9652 (while (string-match regex cmd)
9653 (setq cmd (replace-match replace-with t t cmd))))
9654 (setq match-index (+ match-index 1)))))
9656 (save-window-excursion
9657 (start-process-shell-command cmd nil cmd)
9658 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9660 ((or (stringp cmd)
9661 (eq cmd 'emacs))
9662 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9663 (widen)
9664 (if line (org-goto-line line)
9665 (if search (org-link-search search))))
9666 ((consp cmd)
9667 (let ((file (convert-standard-filename file)))
9668 (save-match-data
9669 (set-match-data link-match-data)
9670 (eval cmd))))
9671 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9672 (and (org-mode-p) (eq old-mode 'org-mode)
9673 (or (not (equal old-buffer (current-buffer)))
9674 (not (equal old-pos (point))))
9675 (org-mark-ring-push old-pos old-buffer))))
9677 (defun org-file-apps-entry-match-against-dlink-p (entry)
9678 "This function returns non-nil if `entry' uses a regular
9679 expression which should be matched against the whole link by
9680 org-open-file.
9682 It assumes that is the case when the entry uses a regular
9683 expression which has at least one grouping construct and the
9684 action is either a lisp form or a command string containing
9685 '%1', i.e. using at least one subexpression match as a
9686 parameter."
9687 (let ((selector (car entry))
9688 (action (cdr entry)))
9689 (if (stringp selector)
9690 (and (> (regexp-opt-depth selector) 0)
9691 (or (and (stringp action)
9692 (string-match "%[0-9]" action))
9693 (consp action)))
9694 nil)))
9696 (defun org-default-apps ()
9697 "Return the default applications for this operating system."
9698 (cond
9699 ((eq system-type 'darwin)
9700 org-file-apps-defaults-macosx)
9701 ((eq system-type 'windows-nt)
9702 org-file-apps-defaults-windowsnt)
9703 (t org-file-apps-defaults-gnu)))
9705 (defun org-apps-regexp-alist (list &optional add-auto-mode)
9706 "Convert extensions to regular expressions in the cars of LIST.
9707 Also, weed out any non-string entries, because the return value is used
9708 only for regexp matching.
9709 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
9710 point to the symbol `emacs', indicating that the file should
9711 be opened in Emacs."
9712 (append
9713 (delq nil
9714 (mapcar (lambda (x)
9715 (if (not (stringp (car x)))
9717 (if (string-match "\\W" (car x))
9719 (cons (concat "\\." (car x) "\\'") (cdr x)))))
9720 list))
9721 (if add-auto-mode
9722 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
9724 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
9725 (defun org-file-remote-p (file)
9726 "Test whether FILE specifies a location on a remote system.
9727 Return non-nil if the location is indeed remote.
9729 For example, the filename \"/user@host:/foo\" specifies a location
9730 on the system \"/user@host:\"."
9731 (cond ((fboundp 'file-remote-p)
9732 (file-remote-p file))
9733 ((fboundp 'tramp-handle-file-remote-p)
9734 (tramp-handle-file-remote-p file))
9735 ((and (boundp 'ange-ftp-name-format)
9736 (string-match (car ange-ftp-name-format) file))
9738 (t nil)))
9741 ;;;; Refiling
9743 (defun org-get-org-file ()
9744 "Read a filename, with default directory `org-directory'."
9745 (let ((default (or org-default-notes-file remember-data-file)))
9746 (read-file-name (format "File name [%s]: " default)
9747 (file-name-as-directory org-directory)
9748 default)))
9750 (defun org-notes-order-reversed-p ()
9751 "Check if the current file should receive notes in reversed order."
9752 (cond
9753 ((not org-reverse-note-order) nil)
9754 ((eq t org-reverse-note-order) t)
9755 ((not (listp org-reverse-note-order)) nil)
9756 (t (catch 'exit
9757 (let ((all org-reverse-note-order)
9758 entry)
9759 (while (setq entry (pop all))
9760 (if (string-match (car entry) buffer-file-name)
9761 (throw 'exit (cdr entry))))
9762 nil)))))
9764 (defvar org-refile-target-table nil
9765 "The list of refile targets, created by `org-refile'.")
9767 (defvar org-agenda-new-buffers nil
9768 "Buffers created to visit agenda files.")
9770 (defvar org-refile-cache nil
9771 "Cache for refile targets.")
9774 (defvar org-refile-markers nil
9775 "All the markers used for caching refile locations.")
9777 (defun org-refile-marker (pos)
9778 "Get a new refile marker, but only if caching is in use."
9779 (if (not org-refile-use-cache)
9781 (let ((m (make-marker)))
9782 (move-marker m pos)
9783 (push m org-refile-markers)
9784 m)))
9786 (defun org-refile-cache-clear ()
9787 "Clear the refile cache and disable all the markers."
9788 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
9789 (setq org-refile-markers nil)
9790 (setq org-refile-cache nil)
9791 (message "Refile cache has been cleared"))
9793 (defun org-refile-cache-check-set (set)
9794 "Check if all the markers in the cache still have live buffers."
9795 (let (marker)
9796 (catch 'exit
9797 (while (and set (setq marker (nth 3 (pop set))))
9798 ;; if org-refile-use-outline-path is 'file, marker may be nil
9799 (when (and marker (null (marker-buffer marker)))
9800 (message "not found") (sit-for 3)
9801 (throw 'exit nil)))
9802 t)))
9804 (defun org-refile-cache-put (set &rest identifiers)
9805 "Push the refile targets SET into the cache, under IDENTIFIERS."
9806 (let* ((key (sha1 (prin1-to-string identifiers)))
9807 (entry (assoc key org-refile-cache)))
9808 (if entry
9809 (setcdr entry set)
9810 (push (cons key set) org-refile-cache))))
9812 (defun org-refile-cache-get (&rest identifiers)
9813 "Retrieve the cached value for refile targets given by IDENTIFIERS."
9814 (cond
9815 ((not org-refile-cache) nil)
9816 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
9818 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
9819 org-refile-cache))))
9820 (and set (org-refile-cache-check-set set) set)))))
9822 (defun org-get-refile-targets (&optional default-buffer)
9823 "Produce a table with refile targets."
9824 (let ((case-fold-search nil)
9825 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
9826 (entries (or org-refile-targets '((nil . (:level . 1)))))
9827 targets tgs txt re files f desc descre fast-path-p level pos0)
9828 (message "Getting targets...")
9829 (with-current-buffer (or default-buffer (current-buffer))
9830 (while (setq entry (pop entries))
9831 (setq files (car entry) desc (cdr entry))
9832 (setq fast-path-p nil)
9833 (cond
9834 ((null files) (setq files (list (current-buffer))))
9835 ((eq files 'org-agenda-files)
9836 (setq files (org-agenda-files 'unrestricted)))
9837 ((and (symbolp files) (fboundp files))
9838 (setq files (funcall files)))
9839 ((and (symbolp files) (boundp files))
9840 (setq files (symbol-value files))))
9841 (if (stringp files) (setq files (list files)))
9842 (cond
9843 ((eq (car desc) :tag)
9844 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
9845 ((eq (car desc) :todo)
9846 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
9847 ((eq (car desc) :regexp)
9848 (setq descre (cdr desc)))
9849 ((eq (car desc) :level)
9850 (setq descre (concat "^\\*\\{" (number-to-string
9851 (if org-odd-levels-only
9852 (1- (* 2 (cdr desc)))
9853 (cdr desc)))
9854 "\\}[ \t]")))
9855 ((eq (car desc) :maxlevel)
9856 (setq fast-path-p t)
9857 (setq descre (concat "^\\*\\{1," (number-to-string
9858 (if org-odd-levels-only
9859 (1- (* 2 (cdr desc)))
9860 (cdr desc)))
9861 "\\}[ \t]")))
9862 (t (error "Bad refiling target description %s" desc)))
9863 (while (setq f (pop files))
9864 (with-current-buffer
9865 (if (bufferp f) f (org-get-agenda-file-buffer f))
9867 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
9868 (progn
9869 (if (bufferp f) (setq f (buffer-file-name
9870 (buffer-base-buffer f))))
9871 (setq f (and f (expand-file-name f)))
9872 (if (eq org-refile-use-outline-path 'file)
9873 (push (list (file-name-nondirectory f) f nil nil) tgs))
9874 (save-excursion
9875 (save-restriction
9876 (widen)
9877 (goto-char (point-min))
9878 (while (re-search-forward descre nil t)
9879 (goto-char (setq pos0 (point-at-bol)))
9880 (catch 'next
9881 (when org-refile-target-verify-function
9882 (save-match-data
9883 (or (funcall org-refile-target-verify-function)
9884 (throw 'next t))))
9885 (when (looking-at org-complex-heading-regexp)
9886 (setq level (org-reduced-level
9887 (- (match-end 1) (match-beginning 1)))
9888 txt (org-link-display-format (match-string 4))
9889 re (concat "^" (regexp-quote
9890 (buffer-substring
9891 (match-beginning 1)
9892 (match-end 4)))))
9893 (if (match-end 5) (setq re (concat
9894 re "[ \t]+"
9895 (regexp-quote
9896 (match-string 5)))))
9897 (setq re (concat re "[ \t]*$"))
9898 (when org-refile-use-outline-path
9899 (setq txt (mapconcat
9900 'org-protect-slash
9901 (append
9902 (if (eq org-refile-use-outline-path
9903 'file)
9904 (list (file-name-nondirectory
9905 (buffer-file-name
9906 (buffer-base-buffer))))
9907 (if (eq org-refile-use-outline-path
9908 'full-file-path)
9909 (list (buffer-file-name
9910 (buffer-base-buffer)))))
9911 (org-get-outline-path fast-path-p
9912 level txt)
9913 (list txt))
9914 "/")))
9915 (push (list txt f re (org-refile-marker (point)))
9916 tgs)))
9917 (when (= (point) pos0)
9918 ;; verification function has not moved point
9919 (goto-char (point-at-eol))))))))
9920 (when org-refile-use-cache
9921 (org-refile-cache-put tgs (buffer-file-name) descre))
9922 (setq targets (append tgs targets))
9923 ))))
9924 (message "Getting targets...done")
9925 (nreverse targets)))
9927 (defun org-protect-slash (s)
9928 (while (string-match "/" s)
9929 (setq s (replace-match "\\" t t s)))
9932 (defvar org-olpa (make-vector 20 nil))
9934 (defun org-get-outline-path (&optional fastp level heading)
9935 "Return the outline path to the current entry, as a list.
9937 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
9938 routine which makes outline path derivations for an entire file,
9939 avoiding backtracing. Refile target collection makes use of that."
9940 (if fastp
9941 (progn
9942 (if (> level 19)
9943 (error "Outline path failure, more than 19 levels."))
9944 (loop for i from level upto 19 do
9945 (aset org-olpa i nil))
9946 (prog1
9947 (delq nil (append org-olpa nil))
9948 (aset org-olpa level heading)))
9949 (let (rtn case-fold-search)
9950 (save-excursion
9951 (save-restriction
9952 (widen)
9953 (while (org-up-heading-safe)
9954 (when (looking-at org-complex-heading-regexp)
9955 (push (org-match-string-no-properties 4) rtn)))
9956 rtn)))))
9958 (defun org-format-outline-path (path &optional width prefix)
9959 "Format the outlie path PATH for display.
9960 Width is the maximum number of characters that is available.
9961 Prefix is a prefix to be included in the returned string,
9962 such as the file name."
9963 (setq width (or width 79))
9964 (if prefix (setq width (- width (length prefix))))
9965 (if (not path)
9966 (or prefix "")
9967 (let* ((nsteps (length path))
9968 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9969 (maxwidth (if (<= total-width width)
9970 10000 ;; everything fits
9971 ;; we need to shorten the level headings
9972 (/ (- width nsteps) nsteps)))
9973 (org-odd-levels-only nil)
9974 (n 0)
9975 (total (1+ (length prefix))))
9976 (setq maxwidth (max maxwidth 10))
9977 (concat prefix
9978 (mapconcat
9979 (lambda (h)
9980 (setq n (1+ n))
9981 (if (and (= n nsteps) (< maxwidth 10000))
9982 (setq maxwidth (- total-width total)))
9983 (if (< (length h) maxwidth)
9984 (progn (setq total (+ total (length h) 1)) h)
9985 (setq h (substring h 0 (- maxwidth 2))
9986 total (+ total maxwidth 1))
9987 (if (string-match "[ \t]+\\'" h)
9988 (setq h (substring h 0 (match-beginning 0))))
9989 (setq h (concat h "..")))
9990 (org-add-props h nil 'face
9991 (nth (% (1- n) org-n-level-faces)
9992 org-level-faces))
9994 path "/")))))
9996 (defun org-display-outline-path (&optional file current)
9997 "Display the current outline path in the echo area."
9998 (interactive "P")
9999 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10000 (case-fold-search nil)
10001 (path (and (org-mode-p) (org-get-outline-path))))
10002 (if current (setq path (append path
10003 (save-excursion
10004 (org-back-to-heading t)
10005 (if (looking-at org-complex-heading-regexp)
10006 (list (match-string 4)))))))
10007 (message "%s"
10008 (org-format-outline-path
10009 path
10010 (1- (frame-width))
10011 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10013 (defvar org-refile-history nil
10014 "History for refiling operations.")
10016 (defvar org-after-refile-insert-hook nil
10017 "Hook run after `org-refile' has inserted its stuff at the new location.
10018 Note that this is still *before* the stuff will be removed from
10019 the *old* location.")
10021 (defvar org-capture-last-stored-marker)
10022 (defun org-refile (&optional goto default-buffer rfloc)
10023 "Move the entry at point to another heading.
10024 The list of target headings is compiled using the information in
10025 `org-refile-targets', which see. This list is created before each use
10026 and will therefore always be up-to-date.
10028 At the target location, the entry is filed as a subitem of the target heading.
10029 Depending on `org-reverse-note-order', the new subitem will either be the
10030 first or the last subitem.
10032 If there is an active region, all entries in that region will be moved.
10033 However, the region must fulfil the requirement that the first heading
10034 is the first one sets the top-level of the moved text - at most siblings
10035 below it are allowed.
10037 With prefix arg GOTO, the command will only visit the target location,
10038 not actually move anything.
10039 With a double prefix `C-u C-u', go to the location where the last refiling
10040 operation has put the subtree.
10041 With a prefix argument of `2', refile to the running clock.
10043 RFLOC can be a refile location obtained in a different way.
10045 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10047 If you are using target caching (see `org-refile-use-cache'),
10048 You have to clear the target cache in order to find new targets.
10049 This can be done with a 0 prefix: `C-0 C-c C-w'"
10050 (interactive "P")
10051 (if (member goto '(0 (64)))
10052 (org-refile-cache-clear)
10053 (let* ((cbuf (current-buffer))
10054 (regionp (org-region-active-p))
10055 (region-start (and regionp (region-beginning)))
10056 (region-end (and regionp (region-end)))
10057 (region-length (and regionp (- region-end region-start)))
10058 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10059 pos it nbuf file re level reversed)
10060 (setq last-command nil)
10061 (when regionp
10062 (goto-char region-start)
10063 (or (bolp) (goto-char (point-at-bol)))
10064 (setq region-start (point))
10065 (unless (org-kill-is-subtree-p
10066 (buffer-substring region-start region-end))
10067 (error "The region is not a (sequence of) subtree(s)")))
10068 (if (equal goto '(16))
10069 (org-refile-goto-last-stored)
10070 (when (or
10071 (and (equal goto 2)
10072 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10073 (prog1
10074 (setq it (list (or org-clock-heading "running clock")
10075 (buffer-file-name
10076 (marker-buffer org-clock-hd-marker))
10078 (marker-position org-clock-hd-marker)))
10079 (setq goto nil)))
10080 (setq it (or rfloc
10081 (save-excursion
10082 (org-refile-get-location
10083 (if goto "Goto: " "Refile to: ") default-buffer
10084 org-refile-allow-creating-parent-nodes)))))
10085 (setq file (nth 1 it)
10086 re (nth 2 it)
10087 pos (nth 3 it))
10088 (if (and (not goto)
10090 (equal (buffer-file-name) file)
10091 (if regionp
10092 (and (>= pos region-start)
10093 (<= pos region-end))
10094 (and (>= pos (point))
10095 (< pos (save-excursion
10096 (org-end-of-subtree t t))))))
10097 (error "Cannot refile to position inside the tree or region"))
10099 (setq nbuf (or (find-buffer-visiting file)
10100 (find-file-noselect file)))
10101 (if goto
10102 (progn
10103 (switch-to-buffer nbuf)
10104 (goto-char pos)
10105 (org-show-context 'org-goto))
10106 (if regionp
10107 (progn
10108 (org-kill-new (buffer-substring region-start region-end))
10109 (org-save-markers-in-region region-start region-end))
10110 (org-copy-subtree 1 nil t))
10111 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10112 (find-file-noselect file)))
10113 (setq reversed (org-notes-order-reversed-p))
10114 (save-excursion
10115 (save-restriction
10116 (widen)
10117 (if pos
10118 (progn
10119 (goto-char pos)
10120 (looking-at outline-regexp)
10121 (setq level (org-get-valid-level (funcall outline-level) 1))
10122 (goto-char
10123 (if reversed
10124 (or (outline-next-heading) (point-max))
10125 (or (save-excursion (org-get-next-sibling))
10126 (org-end-of-subtree t t)
10127 (point-max)))))
10128 (setq level 1)
10129 (if (not reversed)
10130 (goto-char (point-max))
10131 (goto-char (point-min))
10132 (or (outline-next-heading) (goto-char (point-max)))))
10133 (if (not (bolp)) (newline))
10134 (org-paste-subtree level)
10135 (when org-log-refile
10136 (org-add-log-setup 'refile nil nil 'findpos
10137 org-log-refile)
10138 (unless (eq org-log-refile 'note)
10139 (save-excursion (org-add-log-note))))
10140 (and org-auto-align-tags (org-set-tags nil t))
10141 (bookmark-set "org-refile-last-stored")
10142 ;; If we are refiling for capture, make sure that the
10143 ;; last-capture pointers point here
10144 (when (org-bound-and-true-p org-refile-for-capture)
10145 (bookmark-set "org-refile-last-stored")
10146 (move-marker org-capture-last-stored-marker (point)))
10147 (if (fboundp 'deactivate-mark) (deactivate-mark))
10148 (run-hooks 'org-after-refile-insert-hook))))
10149 (if regionp
10150 (delete-region (point) (+ (point) region-length))
10151 (org-cut-subtree))
10152 (when (featurep 'org-inlinetask)
10153 (org-inlinetask-remove-END-maybe))
10154 (setq org-markers-to-move nil)
10155 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10157 (defun org-refile-goto-last-stored ()
10158 "Go to the location where the last refile was stored."
10159 (interactive)
10160 (bookmark-jump "org-refile-last-stored")
10161 (message "This is the location of the last refile"))
10163 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
10164 "Prompt the user for a refile location, using PROMPT."
10165 (let ((org-refile-targets org-refile-targets)
10166 (org-refile-use-outline-path org-refile-use-outline-path))
10167 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
10168 (unless org-refile-target-table
10169 (error "No refile targets"))
10170 (let* ((cbuf (current-buffer))
10171 (partial-completion-mode nil)
10172 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10173 (cfunc (if (and org-refile-use-outline-path
10174 org-outline-path-complete-in-steps)
10175 'org-olpath-completing-read
10176 'org-icompleting-read))
10177 (extra (if org-refile-use-outline-path "/" ""))
10178 (filename (and cfn (expand-file-name cfn)))
10179 (tbl (mapcar
10180 (lambda (x)
10181 (if (and (not (member org-refile-use-outline-path
10182 '(file full-file-path)))
10183 (not (equal filename (nth 1 x))))
10184 (cons (concat (car x) extra " ("
10185 (file-name-nondirectory (nth 1 x)) ")")
10186 (cdr x))
10187 (cons (concat (car x) extra) (cdr x))))
10188 org-refile-target-table))
10189 (completion-ignore-case t)
10190 pa answ parent-target child parent old-hist)
10191 (setq old-hist org-refile-history)
10192 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10193 nil 'org-refile-history))
10194 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10195 (if pa
10196 (progn
10197 (when (or (not org-refile-history)
10198 (not (eq old-hist org-refile-history))
10199 (not (equal (car pa) (car org-refile-history))))
10200 (setq org-refile-history
10201 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10202 org-refile-history
10203 (cdr org-refile-history))))
10204 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10205 (pop org-refile-history)))
10207 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10208 (progn
10209 (setq parent (match-string 1 answ)
10210 child (match-string 2 answ))
10211 (setq parent-target (or (assoc parent tbl)
10212 (assoc (concat parent "/") tbl)))
10213 (when (and parent-target
10214 (or (eq new-nodes t)
10215 (and (eq new-nodes 'confirm)
10216 (y-or-n-p (format "Create new node \"%s\"? "
10217 child)))))
10218 (org-refile-new-child parent-target child)))
10219 (error "Invalid target location")))))
10221 (defun org-refile-new-child (parent-target child)
10222 "Use refile target PARENT-TARGET to add new CHILD below it."
10223 (unless parent-target
10224 (error "Cannot find parent for new node"))
10225 (let ((file (nth 1 parent-target))
10226 (pos (nth 3 parent-target))
10227 level)
10228 (with-current-buffer (or (find-buffer-visiting file)
10229 (find-file-noselect file))
10230 (save-excursion
10231 (save-restriction
10232 (widen)
10233 (if pos
10234 (goto-char pos)
10235 (goto-char (point-max))
10236 (if (not (bolp)) (newline)))
10237 (when (looking-at outline-regexp)
10238 (setq level (funcall outline-level))
10239 (org-end-of-subtree t t))
10240 (org-back-over-empty-lines)
10241 (insert "\n" (make-string
10242 (if pos (org-get-valid-level level 1) 1) ?*)
10243 " " child "\n")
10244 (beginning-of-line 0)
10245 (list (concat (car parent-target) "/" child) file "" (point)))))))
10247 (defun org-olpath-completing-read (prompt collection &rest args)
10248 "Read an outline path like a file name."
10249 (let ((thetable collection)
10250 (org-completion-use-ido nil) ; does not work with ido.
10251 (org-completion-use-iswitchb nil)) ; or iswitchb
10252 (apply
10253 'org-icompleting-read prompt
10254 (lambda (string predicate &optional flag)
10255 (let (rtn r f (l (length string)))
10256 (cond
10257 ((eq flag nil)
10258 ;; try completion
10259 (try-completion string thetable))
10260 ((eq flag t)
10261 ;; all-completions
10262 (setq rtn (all-completions string thetable predicate))
10263 (mapcar
10264 (lambda (x)
10265 (setq r (substring x l))
10266 (if (string-match " ([^)]*)$" x)
10267 (setq f (match-string 0 x))
10268 (setq f ""))
10269 (if (string-match "/" r)
10270 (concat string (substring r 0 (match-end 0)) f)
10272 rtn))
10273 ((eq flag 'lambda)
10274 ;; exact match?
10275 (assoc string thetable)))
10277 args)))
10279 ;;;; Dynamic blocks
10281 (defun org-find-dblock (name)
10282 "Find the first dynamic block with name NAME in the buffer.
10283 If not found, stay at current position and return nil."
10284 (let (pos)
10285 (save-excursion
10286 (goto-char (point-min))
10287 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
10288 nil t)
10289 (match-beginning 0))))
10290 (if pos (goto-char pos))
10291 pos))
10293 (defconst org-dblock-start-re
10294 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10295 "Matches the start line of a dynamic block, with parameters.")
10297 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10298 "Matches the end of a dynamic block.")
10300 (defun org-create-dblock (plist)
10301 "Create a dynamic block section, with parameters taken from PLIST.
10302 PLIST must contain a :name entry which is used as name of the block."
10303 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10304 (end-of-line 1)
10305 (newline))
10306 (let ((col (current-column))
10307 (name (plist-get plist :name)))
10308 (insert "#+BEGIN: " name)
10309 (while plist
10310 (if (eq (car plist) :name)
10311 (setq plist (cddr plist))
10312 (insert " " (prin1-to-string (pop plist)))))
10313 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10314 (beginning-of-line -2)))
10316 (defun org-prepare-dblock ()
10317 "Prepare dynamic block for refresh.
10318 This empties the block, puts the cursor at the insert position and returns
10319 the property list including an extra property :name with the block name."
10320 (unless (looking-at org-dblock-start-re)
10321 (error "Not at a dynamic block"))
10322 (let* ((begdel (1+ (match-end 0)))
10323 (name (org-no-properties (match-string 1)))
10324 (params (append (list :name name)
10325 (read (concat "(" (match-string 3) ")")))))
10326 (save-excursion
10327 (beginning-of-line 1)
10328 (skip-chars-forward " \t")
10329 (setq params (plist-put params :indentation-column (current-column))))
10330 (unless (re-search-forward org-dblock-end-re nil t)
10331 (error "Dynamic block not terminated"))
10332 (setq params
10333 (append params
10334 (list :content (buffer-substring
10335 begdel (match-beginning 0)))))
10336 (delete-region begdel (match-beginning 0))
10337 (goto-char begdel)
10338 (open-line 1)
10339 params))
10341 (defun org-map-dblocks (&optional command)
10342 "Apply COMMAND to all dynamic blocks in the current buffer.
10343 If COMMAND is not given, use `org-update-dblock'."
10344 (let ((cmd (or command 'org-update-dblock)))
10345 (save-excursion
10346 (goto-char (point-min))
10347 (while (re-search-forward org-dblock-start-re nil t)
10348 (goto-char (match-beginning 0))
10349 (save-excursion
10350 (condition-case nil
10351 (funcall cmd)
10352 (error (message "Error during update of dynamic block"))))
10353 (unless (re-search-forward org-dblock-end-re nil t)
10354 (error "Dynamic block not terminated"))))))
10356 (defun org-dblock-update (&optional arg)
10357 "User command for updating dynamic blocks.
10358 Update the dynamic block at point. With prefix ARG, update all dynamic
10359 blocks in the buffer."
10360 (interactive "P")
10361 (if arg
10362 (org-update-all-dblocks)
10363 (or (looking-at org-dblock-start-re)
10364 (org-beginning-of-dblock))
10365 (org-update-dblock)))
10367 (defun org-update-dblock ()
10368 "Update the dynamic block at point
10369 This means to empty the block, parse for parameters and then call
10370 the correct writing function."
10371 (save-window-excursion
10372 (let* ((pos (point))
10373 (line (org-current-line))
10374 (params (org-prepare-dblock))
10375 (name (plist-get params :name))
10376 (indent (plist-get params :indentation-column))
10377 (cmd (intern (concat "org-dblock-write:" name))))
10378 (message "Updating dynamic block `%s' at line %d..." name line)
10379 (funcall cmd params)
10380 (message "Updating dynamic block `%s' at line %d...done" name line)
10381 (goto-char pos)
10382 (when (and indent (> indent 0))
10383 (setq indent (make-string indent ?\ ))
10384 (save-excursion
10385 (org-beginning-of-dblock)
10386 (forward-line 1)
10387 (while (not (looking-at org-dblock-end-re))
10388 (insert indent)
10389 (beginning-of-line 2))
10390 (when (looking-at org-dblock-end-re)
10391 (and (looking-at "[ \t]+")
10392 (replace-match ""))
10393 (insert indent)))))))
10395 (defun org-beginning-of-dblock ()
10396 "Find the beginning of the dynamic block at point.
10397 Error if there is no such block at point."
10398 (let ((pos (point))
10399 beg)
10400 (end-of-line 1)
10401 (if (and (re-search-backward org-dblock-start-re nil t)
10402 (setq beg (match-beginning 0))
10403 (re-search-forward org-dblock-end-re nil t)
10404 (> (match-end 0) pos))
10405 (goto-char beg)
10406 (goto-char pos)
10407 (error "Not in a dynamic block"))))
10409 (defun org-update-all-dblocks ()
10410 "Update all dynamic blocks in the buffer.
10411 This function can be used in a hook."
10412 (when (org-mode-p)
10413 (org-map-dblocks 'org-update-dblock)))
10416 ;;;; Completion
10418 (defconst org-additional-option-like-keywords
10419 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
10420 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
10421 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
10422 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX"
10423 "BEGIN:" "END:"
10424 "ORGTBL" "TBLFM:" "TBLNAME:"
10425 "BEGIN_EXAMPLE" "END_EXAMPLE"
10426 "BEGIN_QUOTE" "END_QUOTE"
10427 "BEGIN_VERSE" "END_VERSE"
10428 "BEGIN_CENTER" "END_CENTER"
10429 "BEGIN_SRC" "END_SRC"
10430 "CATEGORY" "COLUMNS"
10431 "CAPTION" "LABEL"
10432 "SETUPFILE"
10433 "BIND"
10434 "MACRO"))
10436 (defcustom org-structure-template-alist
10438 ("s" "#+begin_src ?\n\n#+end_src"
10439 "<src lang=\"?\">\n\n</src>")
10440 ("e" "#+begin_example\n?\n#+end_example"
10441 "<example>\n?\n</example>")
10442 ("q" "#+begin_quote\n?\n#+end_quote"
10443 "<quote>\n?\n</quote>")
10444 ("v" "#+begin_verse\n?\n#+end_verse"
10445 "<verse>\n?\n/verse>")
10446 ("c" "#+begin_center\n?\n#+end_center"
10447 "<center>\n?\n/center>")
10448 ("l" "#+begin_latex\n?\n#+end_latex"
10449 "<literal style=\"latex\">\n?\n</literal>")
10450 ("L" "#+latex: "
10451 "<literal style=\"latex\">?</literal>")
10452 ("h" "#+begin_html\n?\n#+end_html"
10453 "<literal style=\"html\">\n?\n</literal>")
10454 ("H" "#+html: "
10455 "<literal style=\"html\">?</literal>")
10456 ("a" "#+begin_ascii\n?\n#+end_ascii")
10457 ("A" "#+ascii: ")
10458 ("i" "#+include %file ?"
10459 "<include file=%file markup=\"?\">")
10461 "Structure completion elements.
10462 This is a list of abbreviation keys and values. The value gets inserted
10463 if you type `<' followed by the key and then press the completion key,
10464 usually `M-TAB'. %file will be replaced by a file name after prompting
10465 for the file using completion.
10466 There are two templates for each key, the first uses the original Org syntax,
10467 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
10468 the default when the /org-mtags.el/ module has been loaded. See also the
10469 variable `org-mtags-prefer-muse-templates'.
10470 This is an experimental feature, it is undecided if it is going to stay in."
10471 :group 'org-completion
10472 :type '(repeat
10473 (string :tag "Key")
10474 (string :tag "Template")
10475 (string :tag "Muse Template")))
10477 (defun org-try-structure-completion ()
10478 "Try to complete a structure template before point.
10479 This looks for strings like \"<e\" on an otherwise empty line and
10480 expands them."
10481 (let ((l (buffer-substring (point-at-bol) (point)))
10483 (when (and (looking-at "[ \t]*$")
10484 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
10485 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
10486 (org-complete-expand-structure-template (+ -1 (point-at-bol)
10487 (match-beginning 1)) a)
10488 t)))
10490 (defun org-complete-expand-structure-template (start cell)
10491 "Expand a structure template."
10492 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
10493 (rpl (nth (if musep 2 1) cell))
10494 (ind ""))
10495 (delete-region start (point))
10496 (when (string-match "\\`#\\+" rpl)
10497 (cond
10498 ((bolp))
10499 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
10500 (setq ind (buffer-substring (point-at-bol) (point))))
10501 (t (newline))))
10502 (setq start (point))
10503 (if (string-match "%file" rpl)
10504 (setq rpl (replace-match
10505 (concat
10506 "\""
10507 (save-match-data
10508 (abbreviate-file-name (read-file-name "Include file: ")))
10509 "\"")
10510 t t rpl)))
10511 (setq rpl (mapconcat 'identity (split-string rpl "\n")
10512 (concat "\n" ind)))
10513 (insert rpl)
10514 (if (re-search-backward "\\?" start t) (delete-char 1))))
10517 (defun org-complete (&optional arg)
10518 "Perform completion on word at point.
10519 At the beginning of a headline, this completes TODO keywords as given in
10520 `org-todo-keywords'.
10521 If the current word is preceded by a backslash, completes the TeX symbols
10522 that are supported for HTML support.
10523 If the current word is preceded by \"#+\", completes special words for
10524 setting file options.
10525 In the line after \"#+STARTUP:, complete valid keywords.\"
10526 At all other locations, this simply calls the value of
10527 `org-completion-fallback-command'."
10528 (interactive "P")
10529 (org-without-partial-completion
10530 (catch 'exit
10531 (let* ((a nil)
10532 (end (point))
10533 (beg1 (save-excursion
10534 (skip-chars-backward (org-re "[:alnum:]_@"))
10535 (point)))
10536 (beg (save-excursion
10537 (skip-chars-backward "a-zA-Z0-9_:$")
10538 (point)))
10539 (confirm (lambda (x) (stringp (car x))))
10540 (searchhead (equal (char-before beg) ?*))
10541 (struct
10542 (when (and (member (char-before beg1) '(?. ?<))
10543 (setq a (assoc (buffer-substring beg1 (point))
10544 org-structure-template-alist)))
10545 (org-complete-expand-structure-template (1- beg1) a)
10546 (throw 'exit t)))
10547 (tag (and (equal (char-before beg1) ?:)
10548 (equal (char-after (point-at-bol)) ?*)))
10549 (prop (and (equal (char-before beg1) ?:)
10550 (not (equal (char-after (point-at-bol)) ?*))))
10551 (texp (equal (char-before beg) ?\\))
10552 (link (equal (char-before beg) ?\[))
10553 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
10554 beg)
10555 "#+"))
10556 (startup (string-match "^#\\+STARTUP:.*"
10557 (buffer-substring (point-at-bol) (point))))
10558 (completion-ignore-case opt)
10559 (type nil)
10560 (tbl nil)
10561 (table (cond
10562 (opt
10563 (setq type :opt)
10564 (require 'org-exp)
10565 (append
10566 (delq nil
10567 (mapcar
10568 (lambda (x)
10569 (if (string-match
10570 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
10571 (cons (match-string 2 x)
10572 (match-string 1 x))))
10573 (org-split-string (org-get-current-options) "\n")))
10574 (mapcar 'list org-additional-option-like-keywords)))
10575 (startup
10576 (setq type :startup)
10577 org-startup-options)
10578 (link (append org-link-abbrev-alist-local
10579 org-link-abbrev-alist))
10580 (texp
10581 (setq type :tex)
10582 (append org-entities-user org-entities))
10583 ((string-match "\\`\\*+[ \t]+\\'"
10584 (buffer-substring (point-at-bol) beg))
10585 (setq type :todo)
10586 (mapcar 'list org-todo-keywords-1))
10587 (searchhead
10588 (setq type :searchhead)
10589 (save-excursion
10590 (goto-char (point-min))
10591 (while (re-search-forward org-todo-line-regexp nil t)
10592 (push (list
10593 (org-make-org-heading-search-string
10594 (match-string 3) t))
10595 tbl)))
10596 tbl)
10597 (tag (setq type :tag beg beg1)
10598 (or org-tag-alist (org-get-buffer-tags)))
10599 (prop (setq type :prop beg beg1)
10600 (mapcar 'list (org-buffer-property-keys nil t t)))
10601 (t (progn
10602 (call-interactively org-completion-fallback-command)
10603 (throw 'exit nil)))))
10604 (pattern (buffer-substring-no-properties beg end))
10605 (completion (try-completion pattern table confirm)))
10606 (cond ((eq completion t)
10607 (if (not (assoc (upcase pattern) table))
10608 (message "Already complete")
10609 (if (and (equal type :opt)
10610 (not (member (car (assoc (upcase pattern) table))
10611 org-additional-option-like-keywords)))
10612 (insert (substring (cdr (assoc (upcase pattern) table))
10613 (length pattern)))
10614 (if (memq type '(:tag :prop)) (insert ":")))))
10615 ((null completion)
10616 (message "Can't find completion for \"%s\"" pattern)
10617 (ding))
10618 ((not (string= pattern completion))
10619 (delete-region beg end)
10620 (if (string-match " +$" completion)
10621 (setq completion (replace-match "" t t completion)))
10622 (insert completion)
10623 (if (get-buffer-window "*Completions*")
10624 (delete-window (get-buffer-window "*Completions*")))
10625 (if (assoc completion table)
10626 (if (eq type :todo) (insert " ")
10627 (if (memq type '(:tag :prop)) (insert ":"))))
10628 (if (and (equal type :opt) (assoc completion table))
10629 (message "%s" (substitute-command-keys
10630 "Press \\[org-complete] again to insert example settings"))))
10632 (message "Making completion list...")
10633 (let ((list (sort (all-completions pattern table confirm)
10634 'string<)))
10635 (with-output-to-temp-buffer "*Completions*"
10636 (condition-case nil
10637 ;; Protection needed for XEmacs and emacs 21
10638 (display-completion-list list pattern)
10639 (error (display-completion-list list)))))
10640 (message "Making completion list...%s" "done")))))))
10642 ;;;; TODO, DEADLINE, Comments
10644 (defun org-toggle-comment ()
10645 "Change the COMMENT state of an entry."
10646 (interactive)
10647 (save-excursion
10648 (org-back-to-heading)
10649 (let (case-fold-search)
10650 (if (looking-at (concat outline-regexp
10651 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10652 (replace-match "" t t nil 1)
10653 (if (looking-at outline-regexp)
10654 (progn
10655 (goto-char (match-end 0))
10656 (insert org-comment-string " ")))))))
10658 (defvar org-last-todo-state-is-todo nil
10659 "This is non-nil when the last TODO state change led to a TODO state.
10660 If the last change removed the TODO tag or switched to DONE, then
10661 this is nil.")
10663 (defvar org-setting-tags nil) ; dynamically skipped
10665 (defun org-parse-local-options (string var)
10666 "Parse STRING for startup setting relevant for variable VAR."
10667 (let ((rtn (symbol-value var))
10668 e opts)
10669 (save-match-data
10670 (if (or (not string) (not (string-match "\\S-" string)))
10672 (setq opts (delq nil (mapcar (lambda (x)
10673 (setq e (assoc x org-startup-options))
10674 (if (eq (nth 1 e) var) e nil))
10675 (org-split-string string "[ \t]+"))))
10676 (if (not opts)
10678 (setq rtn nil)
10679 (while (setq e (pop opts))
10680 (if (not (nth 3 e))
10681 (setq rtn (nth 2 e))
10682 (if (not (listp rtn)) (setq rtn nil))
10683 (push (nth 2 e) rtn)))
10684 rtn)))))
10686 (defvar org-todo-setup-filter-hook nil
10687 "Hook for functions that pre-filter todo specs.
10689 Each function takes a todo spec and returns either `nil' or the spec
10690 transformed into canonical form." )
10692 (defvar org-todo-get-default-hook nil
10693 "Hook for functions that get a default item for todo.
10695 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
10696 `nil' or a string to be used for the todo mark." )
10698 (defvar org-agenda-headline-snapshot-before-repeat)
10700 (defun org-todo (&optional arg)
10701 "Change the TODO state of an item.
10702 The state of an item is given by a keyword at the start of the heading,
10703 like
10704 *** TODO Write paper
10705 *** DONE Call mom
10707 The different keywords are specified in the variable `org-todo-keywords'.
10708 By default the available states are \"TODO\" and \"DONE\".
10709 So for this example: when the item starts with TODO, it is changed to DONE.
10710 When it starts with DONE, the DONE is removed. And when neither TODO nor
10711 DONE are present, add TODO at the beginning of the heading.
10713 With C-u prefix arg, use completion to determine the new state.
10714 With numeric prefix arg, switch to that state.
10715 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
10716 With a triple C-u prefix, circumvent any state blocking.
10718 For calling through lisp, arg is also interpreted in the following way:
10719 'none -> empty state
10720 \"\"(empty string) -> switch to empty state
10721 'done -> switch to DONE
10722 'nextset -> switch to the next set of keywords
10723 'previousset -> switch to the previous set of keywords
10724 \"WAITING\" -> switch to the specified keyword, but only if it
10725 really is a member of `org-todo-keywords'."
10726 (interactive "P")
10727 (if (equal arg '(16)) (setq arg 'nextset))
10728 (let ((org-blocker-hook org-blocker-hook)
10729 (case-fold-search nil))
10730 (when (equal arg '(64))
10731 (setq arg nil org-blocker-hook nil))
10732 (when (and org-blocker-hook
10733 (or org-inhibit-blocking
10734 (org-entry-get nil "NOBLOCKING")))
10735 (setq org-blocker-hook nil))
10736 (save-excursion
10737 (catch 'exit
10738 (org-back-to-heading t)
10739 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
10740 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
10741 (looking-at " *"))
10742 (let* ((match-data (match-data))
10743 (startpos (point-at-bol))
10744 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
10745 (org-log-done org-log-done)
10746 (org-log-repeat org-log-repeat)
10747 (org-todo-log-states org-todo-log-states)
10748 (this (match-string 1))
10749 (hl-pos (match-beginning 0))
10750 (head (org-get-todo-sequence-head this))
10751 (ass (assoc head org-todo-kwd-alist))
10752 (interpret (nth 1 ass))
10753 (done-word (nth 3 ass))
10754 (final-done-word (nth 4 ass))
10755 (last-state (or this ""))
10756 (completion-ignore-case t)
10757 (member (member this org-todo-keywords-1))
10758 (tail (cdr member))
10759 (state (cond
10760 ((and org-todo-key-trigger
10761 (or (and (equal arg '(4))
10762 (eq org-use-fast-todo-selection 'prefix))
10763 (and (not arg) org-use-fast-todo-selection
10764 (not (eq org-use-fast-todo-selection
10765 'prefix)))))
10766 ;; Use fast selection
10767 (org-fast-todo-selection))
10768 ((and (equal arg '(4))
10769 (or (not org-use-fast-todo-selection)
10770 (not org-todo-key-trigger)))
10771 ;; Read a state with completion
10772 (org-icompleting-read
10773 "State: " (mapcar (lambda(x) (list x))
10774 org-todo-keywords-1)
10775 nil t))
10776 ((eq arg 'right)
10777 (if this
10778 (if tail (car tail) nil)
10779 (car org-todo-keywords-1)))
10780 ((eq arg 'left)
10781 (if (equal member org-todo-keywords-1)
10783 (if this
10784 (nth (- (length org-todo-keywords-1)
10785 (length tail) 2)
10786 org-todo-keywords-1)
10787 (org-last org-todo-keywords-1))))
10788 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10789 (setq arg nil))) ; hack to fall back to cycling
10790 (arg
10791 ;; user or caller requests a specific state
10792 (cond
10793 ((equal arg "") nil)
10794 ((eq arg 'none) nil)
10795 ((eq arg 'done) (or done-word (car org-done-keywords)))
10796 ((eq arg 'nextset)
10797 (or (car (cdr (member head org-todo-heads)))
10798 (car org-todo-heads)))
10799 ((eq arg 'previousset)
10800 (let ((org-todo-heads (reverse org-todo-heads)))
10801 (or (car (cdr (member head org-todo-heads)))
10802 (car org-todo-heads))))
10803 ((car (member arg org-todo-keywords-1)))
10804 ((stringp arg)
10805 (error "State `%s' not valid in this file" arg))
10806 ((nth (1- (prefix-numeric-value arg))
10807 org-todo-keywords-1))))
10808 ((null member) (or head (car org-todo-keywords-1)))
10809 ((equal this final-done-word) nil) ;; -> make empty
10810 ((null tail) nil) ;; -> first entry
10811 ((memq interpret '(type priority))
10812 (if (eq this-command last-command)
10813 (car tail)
10814 (if (> (length tail) 0)
10815 (or done-word (car org-done-keywords))
10816 nil)))
10818 (car tail))))
10819 (state (or
10820 (run-hook-with-args-until-success
10821 'org-todo-get-default-hook state last-state)
10822 state))
10823 (next (if state (concat " " state " ") " "))
10824 (change-plist (list :type 'todo-state-change :from this :to state
10825 :position startpos))
10826 dolog now-done-p)
10827 (when org-blocker-hook
10828 (setq org-last-todo-state-is-todo
10829 (not (member this org-done-keywords)))
10830 (unless (save-excursion
10831 (save-match-data
10832 (run-hook-with-args-until-failure
10833 'org-blocker-hook change-plist)))
10834 (if (interactive-p)
10835 (error "TODO state change from %s to %s blocked" this state)
10836 ;; fail silently
10837 (message "TODO state change from %s to %s blocked" this state)
10838 (throw 'exit nil))))
10839 (store-match-data match-data)
10840 (replace-match next t t)
10841 (unless (pos-visible-in-window-p hl-pos)
10842 (message "TODO state changed to %s" (org-trim next)))
10843 (unless head
10844 (setq head (org-get-todo-sequence-head state)
10845 ass (assoc head org-todo-kwd-alist)
10846 interpret (nth 1 ass)
10847 done-word (nth 3 ass)
10848 final-done-word (nth 4 ass)))
10849 (when (memq arg '(nextset previousset))
10850 (message "Keyword-Set %d/%d: %s"
10851 (- (length org-todo-sets) -1
10852 (length (memq (assoc state org-todo-sets) org-todo-sets)))
10853 (length org-todo-sets)
10854 (mapconcat 'identity (assoc state org-todo-sets) " ")))
10855 (setq org-last-todo-state-is-todo
10856 (not (member state org-done-keywords)))
10857 (setq now-done-p (and (member state org-done-keywords)
10858 (not (member this org-done-keywords))))
10859 (and logging (org-local-logging logging))
10860 (when (and (or org-todo-log-states org-log-done)
10861 (not (eq org-inhibit-logging t))
10862 (not (memq arg '(nextset previousset))))
10863 ;; we need to look at recording a time and note
10864 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
10865 (nth 2 (assoc this org-todo-log-states))))
10866 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
10867 (setq dolog 'time))
10868 (when (and state
10869 (member state org-not-done-keywords)
10870 (not (member this org-not-done-keywords)))
10871 ;; This is now a todo state and was not one before
10872 ;; If there was a CLOSED time stamp, get rid of it.
10873 (org-add-planning-info nil nil 'closed))
10874 (when (and now-done-p org-log-done)
10875 ;; It is now done, and it was not done before
10876 (org-add-planning-info 'closed (org-current-time))
10877 (if (and (not dolog) (eq 'note org-log-done))
10878 (org-add-log-setup 'done state this 'findpos 'note)))
10879 (when (and state dolog)
10880 ;; This is a non-nil state, and we need to log it
10881 (org-add-log-setup 'state state this 'findpos dolog)))
10882 ;; Fixup tag positioning
10883 (org-todo-trigger-tag-changes state)
10884 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
10885 (when org-provide-todo-statistics
10886 (org-update-parent-todo-statistics))
10887 (run-hooks 'org-after-todo-state-change-hook)
10888 (if (and arg (not (member state org-done-keywords)))
10889 (setq head (org-get-todo-sequence-head state)))
10890 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
10891 ;; Do we need to trigger a repeat?
10892 (when now-done-p
10893 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
10894 ;; This is for the agenda, take a snapshot of the headline.
10895 (save-match-data
10896 (setq org-agenda-headline-snapshot-before-repeat
10897 (org-get-heading))))
10898 (org-auto-repeat-maybe state))
10899 ;; Fixup cursor location if close to the keyword
10900 (if (and (outline-on-heading-p)
10901 (not (bolp))
10902 (save-excursion (beginning-of-line 1)
10903 (looking-at org-todo-line-regexp))
10904 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
10905 (progn
10906 (goto-char (or (match-end 2) (match-end 1)))
10907 (and (looking-at " ") (just-one-space))))
10908 (when org-trigger-hook
10909 (save-excursion
10910 (run-hook-with-args 'org-trigger-hook change-plist))))))))
10912 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
10913 "Block turning an entry into a TODO, using the hierarchy.
10914 This checks whether the current task should be blocked from state
10915 changes. Such blocking occurs when:
10917 1. The task has children which are not all in a completed state.
10919 2. A task has a parent with the property :ORDERED:, and there
10920 are siblings prior to the current task with incomplete
10921 status.
10923 3. The parent of the task is blocked because it has siblings that should
10924 be done first, or is child of a block grandparent TODO entry."
10926 (if (not org-enforce-todo-dependencies)
10927 t ; if locally turned off don't block
10928 (catch 'dont-block
10929 ;; If this is not a todo state change, or if this entry is already DONE,
10930 ;; do not block
10931 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10932 (member (plist-get change-plist :from)
10933 (cons 'done org-done-keywords))
10934 (member (plist-get change-plist :to)
10935 (cons 'todo org-not-done-keywords))
10936 (not (plist-get change-plist :to)))
10937 (throw 'dont-block t))
10938 ;; If this task has children, and any are undone, it's blocked
10939 (save-excursion
10940 (org-back-to-heading t)
10941 (let ((this-level (funcall outline-level)))
10942 (outline-next-heading)
10943 (let ((child-level (funcall outline-level)))
10944 (while (and (not (eobp))
10945 (> child-level this-level))
10946 ;; this todo has children, check whether they are all
10947 ;; completed
10948 (if (and (not (org-entry-is-done-p))
10949 (org-entry-is-todo-p))
10950 (throw 'dont-block nil))
10951 (outline-next-heading)
10952 (setq child-level (funcall outline-level))))))
10953 ;; Otherwise, if the task's parent has the :ORDERED: property, and
10954 ;; any previous siblings are undone, it's blocked
10955 (save-excursion
10956 (org-back-to-heading t)
10957 (let* ((pos (point))
10958 (parent-pos (and (org-up-heading-safe) (point))))
10959 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10960 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
10961 (forward-line 1)
10962 (re-search-forward org-not-done-heading-regexp pos t))
10963 (throw 'dont-block nil)) ; block, there is an older sibling not done.
10964 ;; Search further up the hierarchy, to see if an anchestor is blocked
10965 (while t
10966 (goto-char parent-pos)
10967 (if (not (looking-at org-not-done-heading-regexp))
10968 (throw 'dont-block t)) ; do not block, parent is not a TODO
10969 (setq pos (point))
10970 (setq parent-pos (and (org-up-heading-safe) (point)))
10971 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10972 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
10973 (forward-line 1)
10974 (re-search-forward org-not-done-heading-regexp pos t))
10975 (throw 'dont-block nil)))))))) ; block, older sibling not done.
10977 (defcustom org-track-ordered-property-with-tag nil
10978 "Should the ORDERED property also be shown as a tag?
10979 The ORDERED property decides if an entry should require subtasks to be
10980 completed in sequence. Since a property is not very visible, setting
10981 this option means that toggling the ORDERED property with the command
10982 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10983 not relevant for the behavior, but it makes things more visible.
10985 Note that toggling the tag with tags commands will not change the property
10986 and therefore not influence behavior!
10988 This can be t, meaning the tag ORDERED should be used, It can also be a
10989 string to select a different tag for this task."
10990 :group 'org-todo
10991 :type '(choice
10992 (const :tag "No tracking" nil)
10993 (const :tag "Track with ORDERED tag" t)
10994 (string :tag "Use other tag")))
10996 (defun org-toggle-ordered-property ()
10997 "Toggle the ORDERED property of the current entry.
10998 For better visibility, you can track the value of this property with a tag.
10999 See variable `org-track-ordered-property-with-tag'."
11000 (interactive)
11001 (let* ((t1 org-track-ordered-property-with-tag)
11002 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11003 (save-excursion
11004 (org-back-to-heading)
11005 (if (org-entry-get nil "ORDERED")
11006 (progn
11007 (org-delete-property "ORDERED")
11008 (and tag (org-toggle-tag tag 'off))
11009 (message "Subtasks can be completed in arbitrary order"))
11010 (org-entry-put nil "ORDERED" "t")
11011 (and tag (org-toggle-tag tag 'on))
11012 (message "Subtasks must be completed in sequence")))))
11014 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11015 (defun org-block-todo-from-checkboxes (change-plist)
11016 "Block turning an entry into a TODO, using checkboxes.
11017 This checks whether the current task should be blocked from state
11018 changes because there are unchecked boxes in this entry."
11019 (if (not org-enforce-todo-checkbox-dependencies)
11020 t ; if locally turned off don't block
11021 (catch 'dont-block
11022 ;; If this is not a todo state change, or if this entry is already DONE,
11023 ;; do not block
11024 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11025 (member (plist-get change-plist :from)
11026 (cons 'done org-done-keywords))
11027 (member (plist-get change-plist :to)
11028 (cons 'todo org-not-done-keywords))
11029 (not (plist-get change-plist :to)))
11030 (throw 'dont-block t))
11031 ;; If this task has checkboxes that are not checked, it's blocked
11032 (save-excursion
11033 (org-back-to-heading t)
11034 (let ((beg (point)) end)
11035 (outline-next-heading)
11036 (setq end (point))
11037 (goto-char beg)
11038 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
11039 end t)
11040 (progn
11041 (if (boundp 'org-blocked-by-checkboxes)
11042 (setq org-blocked-by-checkboxes t))
11043 (throw 'dont-block nil)))))
11044 t))) ; do not block
11046 (defun org-entry-blocked-p ()
11047 "Is the current entry blocked?"
11048 (if (org-entry-get nil "NOBLOCKING")
11049 nil ;; Never block this entry
11050 (not
11051 (run-hook-with-args-until-failure
11052 'org-blocker-hook
11053 (list :type 'todo-state-change
11054 :position (point)
11055 :from 'todo
11056 :to 'done)))))
11058 (defun org-update-statistics-cookies (all)
11059 "Update the statistics cookie, either from TODO or from checkboxes.
11060 This should be called with the cursor in a line with a statistics cookie."
11061 (interactive "P")
11062 (if all
11063 (progn
11064 (org-update-checkbox-count 'all)
11065 (org-map-entries 'org-update-parent-todo-statistics))
11066 (if (not (org-on-heading-p))
11067 (org-update-checkbox-count)
11068 (let ((pos (move-marker (make-marker) (point)))
11069 end l1 l2)
11070 (ignore-errors (org-back-to-heading t))
11071 (if (not (org-on-heading-p))
11072 (org-update-checkbox-count)
11073 (setq l1 (org-outline-level))
11074 (setq end (save-excursion
11075 (outline-next-heading)
11076 (if (org-on-heading-p) (setq l2 (org-outline-level)))
11077 (point)))
11078 (if (and (save-excursion
11079 (re-search-forward
11080 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11081 (not (save-excursion (re-search-forward
11082 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11083 (org-update-checkbox-count)
11084 (if (and l2 (> l2 l1))
11085 (progn
11086 (goto-char end)
11087 (org-update-parent-todo-statistics))
11088 (goto-char pos)
11089 (beginning-of-line 1)
11090 (while (re-search-forward
11091 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11092 (point-at-eol) t)
11093 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11094 (goto-char pos)
11095 (move-marker pos nil)))))
11097 (defvar org-entry-property-inherited-from) ;; defined below
11098 (defun org-update-parent-todo-statistics ()
11099 "Update any statistics cookie in the parent of the current headline.
11100 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11101 the entire subtree and this will travel up the hierarchy and update
11102 statistics everywhere."
11103 (interactive)
11104 (let* ((lim 0) prop
11105 (recursive (or (not org-hierarchical-todo-statistics)
11106 (string-match
11107 "\\<recursive\\>"
11108 (or (setq prop (org-entry-get
11109 nil "COOKIE_DATA" 'inherit)) ""))))
11110 (lim (or (and prop (marker-position
11111 org-entry-property-inherited-from))
11112 lim))
11113 (first t)
11114 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11115 level ltoggle l1 new ndel
11116 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
11117 (catch 'exit
11118 (save-excursion
11119 (beginning-of-line 1)
11120 (if (org-at-heading-p)
11121 (setq ltoggle (funcall outline-level))
11122 (error "This should not happen"))
11123 (while (and (setq level (org-up-heading-safe))
11124 (or recursive first)
11125 (>= (point) lim))
11126 (setq first nil cookie-present nil)
11127 (unless (and level
11128 (not (string-match
11129 "\\<checkbox\\>"
11130 (downcase
11131 (or (org-entry-get
11132 nil "COOKIE_DATA")
11133 "")))))
11134 (throw 'exit nil))
11135 (while (re-search-forward box-re (point-at-eol) t)
11136 (setq cnt-all 0 cnt-done 0 cookie-present t)
11137 (setq is-percent (match-end 2))
11138 (save-match-data
11139 (unless (outline-next-heading) (throw 'exit nil))
11140 (while (and (looking-at org-complex-heading-regexp)
11141 (> (setq l1 (length (match-string 1))) level))
11142 (setq kwd (and (or recursive (= l1 ltoggle))
11143 (match-string 2)))
11144 (if (or (eq org-provide-todo-statistics 'all-headlines)
11145 (and (listp org-provide-todo-statistics)
11146 (or (member kwd org-provide-todo-statistics)
11147 (member kwd org-done-keywords))))
11148 (setq cnt-all (1+ cnt-all))
11149 (if (eq org-provide-todo-statistics t)
11150 (and kwd (setq cnt-all (1+ cnt-all)))))
11151 (and (member kwd org-done-keywords)
11152 (setq cnt-done (1+ cnt-done)))
11153 (outline-next-heading)))
11154 (setq new
11155 (if is-percent
11156 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11157 (format "[%d/%d]" cnt-done cnt-all))
11158 ndel (- (match-end 0) (match-beginning 0)))
11159 (goto-char (match-beginning 0))
11160 (insert new)
11161 (delete-region (point) (+ (point) ndel)))
11162 (when cookie-present
11163 (run-hook-with-args 'org-after-todo-statistics-hook
11164 cnt-done (- cnt-all cnt-done))))))
11165 (run-hooks 'org-todo-statistics-hook)))
11167 (defvar org-after-todo-statistics-hook nil
11168 "Hook that is called after a TODO statistics cookie has been updated.
11169 Each function is called with two arguments: the number of not-done entries
11170 and the number of done entries.
11172 For example, the following function, when added to this hook, will switch
11173 an entry to DONE when all children are done, and back to TODO when new
11174 entries are set to a TODO status. Note that this hook is only called
11175 when there is a statistics cookie in the headline!
11177 (defun org-summary-todo (n-done n-not-done)
11178 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11179 (let (org-log-done org-log-states) ; turn off logging
11180 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11183 (defvar org-todo-statistics-hook nil
11184 "Hook that is run whenever Org thinks TODO statistics should be updated.
11185 This hook runs even if there is no statistics cookie present, in which case
11186 `org-after-todo-statistics-hook' would not run.")
11188 (defun org-todo-trigger-tag-changes (state)
11189 "Apply the changes defined in `org-todo-state-tags-triggers'."
11190 (let ((l org-todo-state-tags-triggers)
11191 changes)
11192 (when (or (not state) (equal state ""))
11193 (setq changes (append changes (cdr (assoc "" l)))))
11194 (when (and (stringp state) (> (length state) 0))
11195 (setq changes (append changes (cdr (assoc state l)))))
11196 (when (member state org-not-done-keywords)
11197 (setq changes (append changes (cdr (assoc 'todo l)))))
11198 (when (member state org-done-keywords)
11199 (setq changes (append changes (cdr (assoc 'done l)))))
11200 (dolist (c changes)
11201 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11203 (defun org-local-logging (value)
11204 "Get logging settings from a property VALUE."
11205 (let* (words w a)
11206 ;; directly set the variables, they are already local.
11207 (setq org-log-done nil
11208 org-log-repeat nil
11209 org-todo-log-states nil)
11210 (setq words (org-split-string value))
11211 (while (setq w (pop words))
11212 (cond
11213 ((setq a (assoc w org-startup-options))
11214 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11215 (set (nth 1 a) (nth 2 a))))
11216 ((setq a (org-extract-log-state-settings w))
11217 (and (member (car a) org-todo-keywords-1)
11218 (push a org-todo-log-states)))))))
11220 (defun org-get-todo-sequence-head (kwd)
11221 "Return the head of the TODO sequence to which KWD belongs.
11222 If KWD is not set, check if there is a text property remembering the
11223 right sequence."
11224 (let (p)
11225 (cond
11226 ((not kwd)
11227 (or (get-text-property (point-at-bol) 'org-todo-head)
11228 (progn
11229 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11230 nil (point-at-eol)))
11231 (get-text-property p 'org-todo-head))))
11232 ((not (member kwd org-todo-keywords-1))
11233 (car org-todo-keywords-1))
11234 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11236 (defun org-fast-todo-selection ()
11237 "Fast TODO keyword selection with single keys.
11238 Returns the new TODO keyword, or nil if no state change should occur."
11239 (let* ((fulltable org-todo-key-alist)
11240 (done-keywords org-done-keywords) ;; needed for the faces.
11241 (maxlen (apply 'max (mapcar
11242 (lambda (x)
11243 (if (stringp (car x)) (string-width (car x)) 0))
11244 fulltable)))
11245 (expert nil)
11246 (fwidth (+ maxlen 3 1 3))
11247 (ncol (/ (- (window-width) 4) fwidth))
11248 tg cnt e c tbl
11249 groups ingroup)
11250 (save-excursion
11251 (save-window-excursion
11252 (if expert
11253 (set-buffer (get-buffer-create " *Org todo*"))
11254 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11255 (erase-buffer)
11256 (org-set-local 'org-done-keywords done-keywords)
11257 (setq tbl fulltable cnt 0)
11258 (while (setq e (pop tbl))
11259 (cond
11260 ((equal e '(:startgroup))
11261 (push '() groups) (setq ingroup t)
11262 (when (not (= cnt 0))
11263 (setq cnt 0)
11264 (insert "\n"))
11265 (insert "{ "))
11266 ((equal e '(:endgroup))
11267 (setq ingroup nil cnt 0)
11268 (insert "}\n"))
11269 ((equal e '(:newline))
11270 (when (not (= cnt 0))
11271 (setq cnt 0)
11272 (insert "\n")
11273 (setq e (car tbl))
11274 (while (equal (car tbl) '(:newline))
11275 (insert "\n")
11276 (setq tbl (cdr tbl)))))
11278 (setq tg (car e) c (cdr e))
11279 (if ingroup (push tg (car groups)))
11280 (setq tg (org-add-props tg nil 'face
11281 (org-get-todo-face tg)))
11282 (if (and (= cnt 0) (not ingroup)) (insert " "))
11283 (insert "[" c "] " tg (make-string
11284 (- fwidth 4 (length tg)) ?\ ))
11285 (when (= (setq cnt (1+ cnt)) ncol)
11286 (insert "\n")
11287 (if ingroup (insert " "))
11288 (setq cnt 0)))))
11289 (insert "\n")
11290 (goto-char (point-min))
11291 (if (not expert) (org-fit-window-to-buffer))
11292 (message "[a-z..]:Set [SPC]:clear")
11293 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11294 (cond
11295 ((or (= c ?\C-g)
11296 (and (= c ?q) (not (rassoc c fulltable))))
11297 (setq quit-flag t))
11298 ((= c ?\ ) nil)
11299 ((setq e (rassoc c fulltable) tg (car e))
11301 (t (setq quit-flag t)))))))
11303 (defun org-entry-is-todo-p ()
11304 (member (org-get-todo-state) org-not-done-keywords))
11306 (defun org-entry-is-done-p ()
11307 (member (org-get-todo-state) org-done-keywords))
11309 (defun org-get-todo-state ()
11310 (save-excursion
11311 (org-back-to-heading t)
11312 (and (looking-at org-todo-line-regexp)
11313 (match-end 2)
11314 (match-string 2))))
11316 (defun org-at-date-range-p (&optional inactive-ok)
11317 "Is the cursor inside a date range?"
11318 (interactive)
11319 (save-excursion
11320 (catch 'exit
11321 (let ((pos (point)))
11322 (skip-chars-backward "^[<\r\n")
11323 (skip-chars-backward "<[")
11324 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11325 (>= (match-end 0) pos)
11326 (throw 'exit t))
11327 (skip-chars-backward "^<[\r\n")
11328 (skip-chars-backward "<[")
11329 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11330 (>= (match-end 0) pos)
11331 (throw 'exit t)))
11332 nil)))
11334 (defun org-get-repeat (&optional tagline)
11335 "Check if there is a deadline/schedule with repeater in this entry."
11336 (save-match-data
11337 (save-excursion
11338 (org-back-to-heading t)
11339 (and (re-search-forward (if tagline
11340 (concat tagline "\\s-*" org-repeat-re)
11341 org-repeat-re)
11342 (org-entry-end-position) t)
11343 (match-string-no-properties 1)))))
11345 (defvar org-last-changed-timestamp)
11346 (defvar org-last-inserted-timestamp)
11347 (defvar org-log-post-message)
11348 (defvar org-log-note-purpose)
11349 (defvar org-log-note-how)
11350 (defvar org-log-note-extra)
11351 (defun org-auto-repeat-maybe (done-word)
11352 "Check if the current headline contains a repeated deadline/schedule.
11353 If yes, set TODO state back to what it was and change the base date
11354 of repeating deadline/scheduled time stamps to new date.
11355 This function is run automatically after each state change to a DONE state."
11356 ;; last-state is dynamically scoped into this function
11357 (let* ((repeat (org-get-repeat))
11358 (aa (assoc last-state org-todo-kwd-alist))
11359 (interpret (nth 1 aa))
11360 (head (nth 2 aa))
11361 (whata '(("d" . day) ("m" . month) ("y" . year)))
11362 (msg "Entry repeats: ")
11363 (org-log-done nil)
11364 (org-todo-log-states nil)
11365 (nshiftmax 10) (nshift 0)
11366 re type n what ts time to-state)
11367 (when repeat
11368 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11369 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11370 org-todo-repeat-to-state))
11371 (unless (and to-state (member to-state org-todo-keywords-1))
11372 (setq to-state (if (eq interpret 'type) last-state head)))
11373 (org-todo to-state)
11374 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11375 (org-entry-put nil "LAST_REPEAT" (format-time-string
11376 (org-time-stamp-format t t))))
11377 (when org-log-repeat
11378 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11379 (memq 'org-add-log-note post-command-hook))
11380 ;; OK, we are already setup for some record
11381 (if (eq org-log-repeat 'note)
11382 ;; make sure we take a note, not only a time stamp
11383 (setq org-log-note-how 'note))
11384 ;; Set up for taking a record
11385 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11386 last-state
11387 'findpos org-log-repeat)))
11388 (org-back-to-heading t)
11389 (org-add-planning-info nil nil 'closed)
11390 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11391 org-deadline-time-regexp "\\)\\|\\("
11392 org-ts-regexp "\\)"))
11393 (while (re-search-forward
11394 re (save-excursion (outline-next-heading) (point)) t)
11395 (setq type (if (match-end 1) org-scheduled-string
11396 (if (match-end 3) org-deadline-string "Plain:"))
11397 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11398 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11399 (setq n (string-to-number (match-string 2 ts))
11400 what (match-string 3 ts))
11401 (if (equal what "w") (setq n (* n 7) what "d"))
11402 ;; Preparation, see if we need to modify the start date for the change
11403 (when (match-end 1)
11404 (setq time (save-match-data (org-time-string-to-time ts)))
11405 (cond
11406 ((equal (match-string 1 ts) ".")
11407 ;; Shift starting date to today
11408 (org-timestamp-change
11409 (- (time-to-days (current-time)) (time-to-days time))
11410 'day))
11411 ((equal (match-string 1 ts) "+")
11412 (while (or (= nshift 0)
11413 (<= (time-to-days time) (time-to-days (current-time))))
11414 (when (= (incf nshift) nshiftmax)
11415 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11416 (error "Abort")))
11417 (org-timestamp-change n (cdr (assoc what whata)))
11418 (org-at-timestamp-p t)
11419 (setq ts (match-string 1))
11420 (setq time (save-match-data (org-time-string-to-time ts))))
11421 (org-timestamp-change (- n) (cdr (assoc what whata)))
11422 ;; rematch, so that we have everything in place for the real shift
11423 (org-at-timestamp-p t)
11424 (setq ts (match-string 1))
11425 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11426 (org-timestamp-change n (cdr (assoc what whata)))
11427 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11428 (setq org-log-post-message msg)
11429 (message "%s" msg))))
11431 (defun org-show-todo-tree (arg)
11432 "Make a compact tree which shows all headlines marked with TODO.
11433 The tree will show the lines where the regexp matches, and all higher
11434 headlines above the match.
11435 With a \\[universal-argument] prefix, prompt for a regexp to match.
11436 With a numeric prefix N, construct a sparse tree for the Nth element
11437 of `org-todo-keywords-1'."
11438 (interactive "P")
11439 (let ((case-fold-search nil)
11440 (kwd-re
11441 (cond ((null arg) org-not-done-regexp)
11442 ((equal arg '(4))
11443 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11444 (mapcar 'list org-todo-keywords-1))))
11445 (concat "\\("
11446 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11447 "\\)\\>")))
11448 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11449 (regexp-quote (nth (1- (prefix-numeric-value arg))
11450 org-todo-keywords-1)))
11451 (t (error "Invalid prefix argument: %s" arg)))))
11452 (message "%d TODO entries found"
11453 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
11455 (defun org-deadline (&optional remove time)
11456 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11457 With argument REMOVE, remove any deadline from the item.
11458 When TIME is set, it should be an internal time specification, and the
11459 scheduling will use the corresponding date."
11460 (interactive "P")
11461 (let* ((old-date (org-entry-get nil "DEADLINE"))
11462 (repeater (and old-date
11463 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
11464 (match-string 1 old-date))))
11465 (if remove
11466 (progn
11467 (when (and old-date org-log-redeadline)
11468 (org-add-log-setup 'deldeadline nil old-date 'findpos
11469 org-log-redeadline))
11470 (org-remove-timestamp-with-keyword org-deadline-string)
11471 (message "Item no longer has a deadline."))
11472 (org-add-planning-info 'deadline time 'closed)
11473 (when (and old-date org-log-redeadline
11474 (not (equal old-date
11475 (substring org-last-inserted-timestamp 1 -1))))
11476 (org-add-log-setup 'redeadline nil old-date 'findpos
11477 org-log-redeadline))
11478 (when repeater
11479 (save-excursion
11480 (org-back-to-heading t)
11481 (when (re-search-forward (concat org-deadline-string " "
11482 org-last-inserted-timestamp)
11483 (save-excursion
11484 (outline-next-heading) (point)) t)
11485 (goto-char (1- (match-end 0)))
11486 (insert " " repeater)
11487 (setq org-last-inserted-timestamp
11488 (concat (substring org-last-inserted-timestamp 0 -1)
11489 " " repeater
11490 (substring org-last-inserted-timestamp -1))))))
11491 (message "Deadline on %s" org-last-inserted-timestamp))))
11493 (defun org-schedule (&optional remove time)
11494 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11495 With argument REMOVE, remove any scheduling date from the item.
11496 When TIME is set, it should be an internal time specification, and the
11497 scheduling will use the corresponding date."
11498 (interactive "P")
11499 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11500 (repeater (and old-date
11501 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
11502 (match-string 1 old-date))))
11503 (if remove
11504 (progn
11505 (when (and old-date org-log-reschedule)
11506 (org-add-log-setup 'delschedule nil old-date 'findpos
11507 org-log-reschedule))
11508 (org-remove-timestamp-with-keyword org-scheduled-string)
11509 (message "Item is no longer scheduled."))
11510 (org-add-planning-info 'scheduled time 'closed)
11511 (when (and old-date org-log-reschedule
11512 (not (equal old-date
11513 (substring org-last-inserted-timestamp 1 -1))))
11514 (org-add-log-setup 'reschedule nil old-date 'findpos
11515 org-log-reschedule))
11516 (when repeater
11517 (save-excursion
11518 (org-back-to-heading t)
11519 (when (re-search-forward (concat org-scheduled-string " "
11520 org-last-inserted-timestamp)
11521 (save-excursion
11522 (outline-next-heading) (point)) t)
11523 (goto-char (1- (match-end 0)))
11524 (insert " " repeater)
11525 (setq org-last-inserted-timestamp
11526 (concat (substring org-last-inserted-timestamp 0 -1)
11527 " " repeater
11528 (substring org-last-inserted-timestamp -1))))))
11529 (message "Scheduled to %s" org-last-inserted-timestamp))))
11531 (defun org-get-scheduled-time (pom &optional inherit)
11532 "Get the scheduled time as a time tuple, of a format suitable
11533 for calling org-schedule with, or if there is no scheduling,
11534 returns nil."
11535 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
11536 (when time
11537 (apply 'encode-time (org-parse-time-string time)))))
11539 (defun org-get-deadline-time (pom &optional inherit)
11540 "Get the deadine as a time tuple, of a format suitable for
11541 calling org-deadline with, or if there is no scheduling, returns
11542 nil."
11543 (let ((time (org-entry-get pom "DEADLINE" inherit)))
11544 (when time
11545 (apply 'encode-time (org-parse-time-string time)))))
11547 (defun org-remove-timestamp-with-keyword (keyword)
11548 "Remove all time stamps with KEYWORD in the current entry."
11549 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
11550 beg)
11551 (save-excursion
11552 (org-back-to-heading t)
11553 (setq beg (point))
11554 (outline-next-heading)
11555 (while (re-search-backward re beg t)
11556 (replace-match "")
11557 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
11558 (equal (char-before) ?\ ))
11559 (backward-delete-char 1)
11560 (if (string-match "^[ \t]*$" (buffer-substring
11561 (point-at-bol) (point-at-eol)))
11562 (delete-region (point-at-bol)
11563 (min (point-max) (1+ (point-at-eol))))))))))
11565 (defun org-add-planning-info (what &optional time &rest remove)
11566 "Insert new timestamp with keyword in the line directly after the headline.
11567 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11568 If non is given, the user is prompted for a date.
11569 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11570 be removed."
11571 (interactive)
11572 (let (org-time-was-given org-end-time-was-given ts
11573 end default-time default-input)
11575 (catch 'exit
11576 (when (and (not time) (memq what '(scheduled deadline)))
11577 ;; Try to get a default date/time from existing timestamp
11578 (save-excursion
11579 (org-back-to-heading t)
11580 (setq end (save-excursion (outline-next-heading) (point)))
11581 (when (re-search-forward (if (eq what 'scheduled)
11582 org-scheduled-time-regexp
11583 org-deadline-time-regexp)
11584 end t)
11585 (setq ts (match-string 1)
11586 default-time
11587 (apply 'encode-time (org-parse-time-string ts))
11588 default-input (and ts (org-get-compact-tod ts))))))
11589 (when what
11590 ;; If necessary, get the time from the user
11591 (setq time (or time (org-read-date nil 'to-time nil nil
11592 default-time default-input))))
11594 (when (and org-insert-labeled-timestamps-at-point
11595 (member what '(scheduled deadline)))
11596 (insert
11597 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11598 (org-insert-time-stamp time org-time-was-given
11599 nil nil nil (list org-end-time-was-given))
11600 (setq what nil))
11601 (save-excursion
11602 (save-restriction
11603 (let (col list elt ts buffer-invisibility-spec)
11604 (org-back-to-heading t)
11605 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11606 (goto-char (match-end 1))
11607 (setq col (current-column))
11608 (goto-char (match-end 0))
11609 (if (eobp) (insert "\n") (forward-char 1))
11610 (when (and (not what)
11611 (not (looking-at
11612 (concat "[ \t]*"
11613 org-keyword-time-not-clock-regexp))))
11614 ;; Nothing to add, nothing to remove...... :-)
11615 (throw 'exit nil))
11616 (if (and (not (looking-at outline-regexp))
11617 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11618 "[^\r\n]*"))
11619 (not (equal (match-string 1) org-clock-string)))
11620 (narrow-to-region (match-beginning 0) (match-end 0))
11621 (insert-before-markers "\n")
11622 (backward-char 1)
11623 (narrow-to-region (point) (point))
11624 (and org-adapt-indentation (org-indent-to-column col)))
11625 ;; Check if we have to remove something.
11626 (setq list (cons what remove))
11627 (while list
11628 (setq elt (pop list))
11629 (goto-char (point-min))
11630 (when (or (and (eq elt 'scheduled)
11631 (re-search-forward org-scheduled-time-regexp nil t))
11632 (and (eq elt 'deadline)
11633 (re-search-forward org-deadline-time-regexp nil t))
11634 (and (eq elt 'closed)
11635 (re-search-forward org-closed-time-regexp nil t)))
11636 (replace-match "")
11637 (if (looking-at "--+<[^>]+>") (replace-match ""))
11638 (skip-chars-backward " ")
11639 (if (looking-at " +") (replace-match ""))))
11640 (goto-char (point-max))
11641 (and org-adapt-indentation (bolp) (org-indent-to-column col))
11642 (when what
11643 (insert
11644 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
11645 (cond ((eq what 'scheduled) org-scheduled-string)
11646 ((eq what 'deadline) org-deadline-string)
11647 ((eq what 'closed) org-closed-string))
11648 " ")
11649 (setq ts (org-insert-time-stamp
11650 time
11651 (or org-time-was-given
11652 (and (eq what 'closed) org-log-done-with-time))
11653 (eq what 'closed)
11654 nil nil (list org-end-time-was-given)))
11655 (end-of-line 1))
11656 (goto-char (point-min))
11657 (widen)
11658 (if (and (looking-at "[ \t]*\n")
11659 (equal (char-before) ?\n))
11660 (delete-region (1- (point)) (point-at-eol)))
11661 ts))))))
11663 (defvar org-log-note-marker (make-marker))
11664 (defvar org-log-note-purpose nil)
11665 (defvar org-log-note-state nil)
11666 (defvar org-log-note-previous-state nil)
11667 (defvar org-log-note-how nil)
11668 (defvar org-log-note-extra nil)
11669 (defvar org-log-note-window-configuration nil)
11670 (defvar org-log-note-return-to (make-marker))
11671 (defvar org-log-post-message nil
11672 "Message to be displayed after a log note has been stored.
11673 The auto-repeater uses this.")
11675 (defun org-add-note ()
11676 "Add a note to the current entry.
11677 This is done in the same way as adding a state change note."
11678 (interactive)
11679 (org-add-log-setup 'note nil nil 'findpos nil))
11681 (defvar org-property-end-re)
11682 (defun org-add-log-setup (&optional purpose state prev-state
11683 findpos how &optional extra)
11684 "Set up the post command hook to take a note.
11685 If this is about to TODO state change, the new state is expected in STATE.
11686 When FINDPOS is non-nil, find the correct position for the note in
11687 the current entry. If not, assume that it can be inserted at point.
11688 HOW is an indicator what kind of note should be created.
11689 EXTRA is additional text that will be inserted into the notes buffer."
11690 (let* ((org-log-into-drawer (org-log-into-drawer))
11691 (drawer (cond ((stringp org-log-into-drawer)
11692 org-log-into-drawer)
11693 (org-log-into-drawer "LOGBOOK")
11694 (t nil))))
11695 (save-restriction
11696 (save-excursion
11697 (when findpos
11698 (org-back-to-heading t)
11699 (narrow-to-region (point) (save-excursion
11700 (outline-next-heading) (point)))
11701 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11702 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11703 "[^\r\n]*\\)?"))
11704 (goto-char (match-end 0))
11705 (cond
11706 (drawer
11707 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
11708 nil t)
11709 (progn
11710 (goto-char (match-end 0))
11711 (or org-log-states-order-reversed
11712 (and (re-search-forward org-property-end-re nil t)
11713 (goto-char (1- (match-beginning 0))))))
11714 (insert "\n:" drawer ":\n:END:")
11715 (beginning-of-line 0)
11716 (org-indent-line-function)
11717 (beginning-of-line 2)
11718 (org-indent-line-function)
11719 (end-of-line 0)))
11720 ((and org-log-state-notes-insert-after-drawers
11721 (save-excursion
11722 (forward-line) (looking-at org-drawer-regexp)))
11723 (forward-line)
11724 (while (looking-at org-drawer-regexp)
11725 (goto-char (match-end 0))
11726 (re-search-forward org-property-end-re (point-max) t)
11727 (forward-line))
11728 (forward-line -1)))
11729 (unless org-log-states-order-reversed
11730 (and (= (char-after) ?\n) (forward-char 1))
11731 (org-skip-over-state-notes)
11732 (skip-chars-backward " \t\n\r")))
11733 (move-marker org-log-note-marker (point))
11734 (setq org-log-note-purpose purpose
11735 org-log-note-state state
11736 org-log-note-previous-state prev-state
11737 org-log-note-how how
11738 org-log-note-extra extra)
11739 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
11741 (defun org-skip-over-state-notes ()
11742 "Skip past the list of State notes in an entry."
11743 (if (looking-at "\n[ \t]*- State") (forward-char 1))
11744 (while (looking-at "[ \t]*- State")
11745 (condition-case nil
11746 (org-next-item)
11747 (error (org-end-of-item)))))
11749 (defun org-add-log-note (&optional purpose)
11750 "Pop up a window for taking a note, and add this note later at point."
11751 (remove-hook 'post-command-hook 'org-add-log-note)
11752 (setq org-log-note-window-configuration (current-window-configuration))
11753 (delete-other-windows)
11754 (move-marker org-log-note-return-to (point))
11755 (switch-to-buffer (marker-buffer org-log-note-marker))
11756 (goto-char org-log-note-marker)
11757 (org-switch-to-buffer-other-window "*Org Note*")
11758 (erase-buffer)
11759 (if (memq org-log-note-how '(time state))
11760 (let (current-prefix-arg) (org-store-log-note))
11761 (let ((org-inhibit-startup t)) (org-mode))
11762 (insert (format "# Insert note for %s.
11763 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
11764 (cond
11765 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11766 ((eq org-log-note-purpose 'done) "closed todo item")
11767 ((eq org-log-note-purpose 'state)
11768 (format "state change from \"%s\" to \"%s\""
11769 (or org-log-note-previous-state "")
11770 (or org-log-note-state "")))
11771 ((eq org-log-note-purpose 'reschedule)
11772 "rescheduling")
11773 ((eq org-log-note-purpose 'delschedule)
11774 "no longer scheduled")
11775 ((eq org-log-note-purpose 'redeadline)
11776 "changing deadline")
11777 ((eq org-log-note-purpose 'deldeadline)
11778 "removing deadline")
11779 ((eq org-log-note-purpose 'refile)
11780 "refiling")
11781 ((eq org-log-note-purpose 'note)
11782 "this entry")
11783 (t (error "This should not happen")))))
11784 (if org-log-note-extra (insert org-log-note-extra))
11785 (org-set-local 'org-finish-function 'org-store-log-note)))
11787 (defvar org-note-abort nil) ; dynamically scoped
11788 (defun org-store-log-note ()
11789 "Finish taking a log note, and insert it to where it belongs."
11790 (let ((txt (buffer-string))
11791 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11792 lines ind)
11793 (kill-buffer (current-buffer))
11794 (while (string-match "\\`#.*\n[ \t\n]*" txt)
11795 (setq txt (replace-match "" t t txt)))
11796 (if (string-match "\\s-+\\'" txt)
11797 (setq txt (replace-match "" t t txt)))
11798 (setq lines (org-split-string txt "\n"))
11799 (when (and note (string-match "\\S-" note))
11800 (setq note
11801 (org-replace-escapes
11802 note
11803 (list (cons "%u" (user-login-name))
11804 (cons "%U" user-full-name)
11805 (cons "%t" (format-time-string
11806 (org-time-stamp-format 'long 'inactive)
11807 (current-time)))
11808 (cons "%T" (format-time-string
11809 (org-time-stamp-format 'long nil)
11810 (current-time)))
11811 (cons "%s" (if org-log-note-state
11812 (concat "\"" org-log-note-state "\"")
11813 ""))
11814 (cons "%S" (if org-log-note-previous-state
11815 (concat "\"" org-log-note-previous-state "\"")
11816 "\"\"")))))
11817 (if lines (setq note (concat note " \\\\")))
11818 (push note lines))
11819 (when (or current-prefix-arg org-note-abort)
11820 (when org-log-into-drawer
11821 (org-remove-empty-drawer-at
11822 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
11823 org-log-note-marker))
11824 (setq lines nil))
11825 (when lines
11826 (with-current-buffer (marker-buffer org-log-note-marker)
11827 (save-excursion
11828 (goto-char org-log-note-marker)
11829 (move-marker org-log-note-marker nil)
11830 (end-of-line 1)
11831 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
11832 (insert "- " (pop lines))
11833 (org-indent-line-function)
11834 (beginning-of-line 1)
11835 (looking-at "[ \t]*")
11836 (setq ind (concat (match-string 0) " "))
11837 (end-of-line 1)
11838 (while lines (insert "\n" ind (pop lines)))
11839 (message "Note stored")
11840 (org-back-to-heading t)
11841 (org-cycle-hide-drawers 'children)))))
11842 (set-window-configuration org-log-note-window-configuration)
11843 (with-current-buffer (marker-buffer org-log-note-return-to)
11844 (goto-char org-log-note-return-to))
11845 (move-marker org-log-note-return-to nil)
11846 (and org-log-post-message (message "%s" org-log-post-message)))
11848 (defun org-remove-empty-drawer-at (drawer pos)
11849 "Remove an empty drawer DRAWER at position POS.
11850 POS may also be a marker."
11851 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
11852 (save-excursion
11853 (save-restriction
11854 (widen)
11855 (goto-char pos)
11856 (if (org-in-regexp
11857 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
11858 (replace-match ""))))))
11860 (defun org-sparse-tree (&optional arg)
11861 "Create a sparse tree, prompt for the details.
11862 This command can create sparse trees. You first need to select the type
11863 of match used to create the tree:
11865 t Show all TODO entries.
11866 T Show entries with a specific TODO keyword.
11867 m Show entries selected by a tags/property match.
11868 p Enter a property name and its value (both with completion on existing
11869 names/values) and show entries with that property.
11870 / Show entries matching a regular expression (`r' can be used as well)
11871 d Show deadlines due within `org-deadline-warning-days'.
11872 b Show deadlines and scheduled items before a date.
11873 a Show deadlines and scheduled items after a date."
11874 (interactive "P")
11875 (let (ans kwd value)
11876 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty [d]eadlines\n [b]efore-date [a]fter-date")
11877 (setq ans (read-char-exclusive))
11878 (cond
11879 ((equal ans ?d)
11880 (call-interactively 'org-check-deadlines))
11881 ((equal ans ?b)
11882 (call-interactively 'org-check-before-date))
11883 ((equal ans ?a)
11884 (call-interactively 'org-check-after-date))
11885 ((equal ans ?t)
11886 (org-show-todo-tree nil))
11887 ((equal ans ?T)
11888 (org-show-todo-tree '(4)))
11889 ((member ans '(?T ?m))
11890 (call-interactively 'org-match-sparse-tree))
11891 ((member ans '(?p ?P))
11892 (setq kwd (org-icompleting-read "Property: "
11893 (mapcar 'list (org-buffer-property-keys))))
11894 (setq value (org-icompleting-read "Value: "
11895 (mapcar 'list (org-property-values kwd))))
11896 (unless (string-match "\\`{.*}\\'" value)
11897 (setq value (concat "\"" value "\"")))
11898 (org-match-sparse-tree arg (concat kwd "=" value)))
11899 ((member ans '(?r ?R ?/))
11900 (call-interactively 'org-occur))
11901 (t (error "No such sparse tree command \"%c\"" ans)))))
11903 (defvar org-occur-highlights nil
11904 "List of overlays used for occur matches.")
11905 (make-variable-buffer-local 'org-occur-highlights)
11906 (defvar org-occur-parameters nil
11907 "Parameters of the active org-occur calls.
11908 This is a list, each call to org-occur pushes as cons cell,
11909 containing the regular expression and the callback, onto the list.
11910 The list can contain several entries if `org-occur' has been called
11911 several time with the KEEP-PREVIOUS argument. Otherwise, this list
11912 will only contain one set of parameters. When the highlights are
11913 removed (for example with `C-c C-c', or with the next edit (depending
11914 on `org-remove-highlights-with-change'), this variable is emptied
11915 as well.")
11916 (make-variable-buffer-local 'org-occur-parameters)
11918 (defun org-occur (regexp &optional keep-previous callback)
11919 "Make a compact tree which shows all matches of REGEXP.
11920 The tree will show the lines where the regexp matches, and all higher
11921 headlines above the match. It will also show the heading after the match,
11922 to make sure editing the matching entry is easy.
11923 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11924 call to `org-occur' will be kept, to allow stacking of calls to this
11925 command.
11926 If CALLBACK is non-nil, it is a function which is called to confirm
11927 that the match should indeed be shown."
11928 (interactive "sRegexp: \nP")
11929 (when (equal regexp "")
11930 (error "Regexp cannot be empty"))
11931 (unless keep-previous
11932 (org-remove-occur-highlights nil nil t))
11933 (push (cons regexp callback) org-occur-parameters)
11934 (let ((cnt 0))
11935 (save-excursion
11936 (goto-char (point-min))
11937 (if (or (not keep-previous) ; do not want to keep
11938 (not org-occur-highlights)) ; no previous matches
11939 ;; hide everything
11940 (org-overview))
11941 (while (re-search-forward regexp nil t)
11942 (when (or (not callback)
11943 (save-match-data (funcall callback)))
11944 (setq cnt (1+ cnt))
11945 (when org-highlight-sparse-tree-matches
11946 (org-highlight-new-match (match-beginning 0) (match-end 0)))
11947 (org-show-context 'occur-tree))))
11948 (when org-remove-highlights-with-change
11949 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11950 nil 'local))
11951 (unless org-sparse-tree-open-archived-trees
11952 (org-hide-archived-subtrees (point-min) (point-max)))
11953 (run-hooks 'org-occur-hook)
11954 (if (interactive-p)
11955 (message "%d match(es) for regexp %s" cnt regexp))
11956 cnt))
11958 (defun org-show-context (&optional key)
11959 "Make sure point and context are visible.
11960 How much context is shown depends upon the variables
11961 `org-show-hierarchy-above', `org-show-following-heading'. and
11962 `org-show-siblings'."
11963 (let ((heading-p (org-on-heading-p t))
11964 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11965 (following-p (org-get-alist-option org-show-following-heading key))
11966 (entry-p (org-get-alist-option org-show-entry-below key))
11967 (siblings-p (org-get-alist-option org-show-siblings key)))
11968 (catch 'exit
11969 ;; Show heading or entry text
11970 (if (and heading-p (not entry-p))
11971 (org-flag-heading nil) ; only show the heading
11972 (and (or entry-p (org-invisible-p) (org-invisible-p2))
11973 (org-show-hidden-entry))) ; show entire entry
11974 (when following-p
11975 ;; Show next sibling, or heading below text
11976 (save-excursion
11977 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11978 (org-flag-heading nil))))
11979 (when siblings-p (org-show-siblings))
11980 (when hierarchy-p
11981 ;; show all higher headings, possibly with siblings
11982 (save-excursion
11983 (while (and (condition-case nil
11984 (progn (org-up-heading-all 1) t)
11985 (error nil))
11986 (not (bobp)))
11987 (org-flag-heading nil)
11988 (when siblings-p (org-show-siblings))))))))
11990 (defvar org-reveal-start-hook nil
11991 "Hook run before revealing a location.")
11993 (defun org-reveal (&optional siblings)
11994 "Show current entry, hierarchy above it, and the following headline.
11995 This can be used to show a consistent set of context around locations
11996 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
11997 not t for the search context.
11999 With optional argument SIBLINGS, on each level of the hierarchy all
12000 siblings are shown. This repairs the tree structure to what it would
12001 look like when opened with hierarchical calls to `org-cycle'.
12002 With double optional argument `C-u C-u', go to the parent and show the
12003 entire tree."
12004 (interactive "P")
12005 (run-hooks 'org-reveal-start-hook)
12006 (let ((org-show-hierarchy-above t)
12007 (org-show-following-heading t)
12008 (org-show-siblings (if siblings t org-show-siblings)))
12009 (org-show-context nil))
12010 (when (equal siblings '(16))
12011 (save-excursion
12012 (when (org-up-heading-safe)
12013 (org-show-subtree)
12014 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12016 (defun org-highlight-new-match (beg end)
12017 "Highlight from BEG to END and mark the highlight is an occur headline."
12018 (let ((ov (make-overlay beg end)))
12019 (overlay-put ov 'face 'secondary-selection)
12020 (push ov org-occur-highlights)))
12022 (defun org-remove-occur-highlights (&optional beg end noremove)
12023 "Remove the occur highlights from the buffer.
12024 BEG and END are ignored. If NOREMOVE is nil, remove this function
12025 from the `before-change-functions' in the current buffer."
12026 (interactive)
12027 (unless org-inhibit-highlight-removal
12028 (mapc 'delete-overlay org-occur-highlights)
12029 (setq org-occur-highlights nil)
12030 (setq org-occur-parameters nil)
12031 (unless noremove
12032 (remove-hook 'before-change-functions
12033 'org-remove-occur-highlights 'local))))
12035 ;;;; Priorities
12037 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12038 "Regular expression matching the priority indicator.")
12040 (defvar org-remove-priority-next-time nil)
12042 (defun org-priority-up ()
12043 "Increase the priority of the current item."
12044 (interactive)
12045 (org-priority 'up))
12047 (defun org-priority-down ()
12048 "Decrease the priority of the current item."
12049 (interactive)
12050 (org-priority 'down))
12052 (defun org-priority (&optional action)
12053 "Change the priority of an item by ARG.
12054 ACTION can be `set', `up', `down', or a character."
12055 (interactive)
12056 (unless org-enable-priority-commands
12057 (error "Priority commands are disabled"))
12058 (setq action (or action 'set))
12059 (let (current new news have remove)
12060 (save-excursion
12061 (org-back-to-heading t)
12062 (if (looking-at org-priority-regexp)
12063 (setq current (string-to-char (match-string 2))
12064 have t)
12065 (setq current org-default-priority))
12066 (cond
12067 ((eq action 'remove)
12068 (setq remove t new ?\ ))
12069 ((or (eq action 'set)
12070 (if (featurep 'xemacs) (characterp action) (integerp action)))
12071 (if (not (eq action 'set))
12072 (setq new action)
12073 (message "Priority %c-%c, SPC to remove: "
12074 org-highest-priority org-lowest-priority)
12075 (setq new (read-char-exclusive)))
12076 (if (and (= (upcase org-highest-priority) org-highest-priority)
12077 (= (upcase org-lowest-priority) org-lowest-priority))
12078 (setq new (upcase new)))
12079 (cond ((equal new ?\ ) (setq remove t))
12080 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12081 (error "Priority must be between `%c' and `%c'"
12082 org-highest-priority org-lowest-priority))))
12083 ((eq action 'up)
12084 (if (and (not have) (eq last-command this-command))
12085 (setq new org-lowest-priority)
12086 (setq new (if (and org-priority-start-cycle-with-default (not have))
12087 org-default-priority (1- current)))))
12088 ((eq action 'down)
12089 (if (and (not have) (eq last-command this-command))
12090 (setq new org-highest-priority)
12091 (setq new (if (and org-priority-start-cycle-with-default (not have))
12092 org-default-priority (1+ current)))))
12093 (t (error "Invalid action")))
12094 (if (or (< (upcase new) org-highest-priority)
12095 (> (upcase new) org-lowest-priority))
12096 (setq remove t))
12097 (setq news (format "%c" new))
12098 (if have
12099 (if remove
12100 (replace-match "" t t nil 1)
12101 (replace-match news t t nil 2))
12102 (if remove
12103 (error "No priority cookie found in line")
12104 (let ((case-fold-search nil))
12105 (looking-at org-todo-line-regexp))
12106 (if (match-end 2)
12107 (progn
12108 (goto-char (match-end 2))
12109 (insert " [#" news "]"))
12110 (goto-char (match-beginning 3))
12111 (insert "[#" news "] "))))
12112 (org-preserve-lc (org-set-tags nil 'align)))
12113 (if remove
12114 (message "Priority removed")
12115 (message "Priority of current item set to %s" news))))
12117 (defun org-get-priority (s)
12118 "Find priority cookie and return priority."
12119 (save-match-data
12120 (if (not (string-match org-priority-regexp s))
12121 (* 1000 (- org-lowest-priority org-default-priority))
12122 (* 1000 (- org-lowest-priority
12123 (string-to-char (match-string 2 s)))))))
12125 ;;;; Tags
12127 (defvar org-agenda-archives-mode)
12128 (defvar org-map-continue-from nil
12129 "Position from where mapping should continue.
12130 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
12132 (defvar org-scanner-tags nil
12133 "The current tag list while the tags scanner is running.")
12134 (defvar org-trust-scanner-tags nil
12135 "Should `org-get-tags-at' use the tags fro the scanner.
12136 This is for internal dynamical scoping only.
12137 When this is non-nil, the function `org-get-tags-at' will return the value
12138 of `org-scanner-tags' instead of building the list by itself. This
12139 can lead to large speed-ups when the tags scanner is used in a file with
12140 many entries, and when the list of tags is retrieved, for example to
12141 obtain a list of properties. Building the tags list for each entry in such
12142 a file becomes an N^2 operation - but with this variable set, it scales
12143 as N.")
12145 (defun org-scan-tags (action matcher &optional todo-only)
12146 "Scan headline tags with inheritance and produce output ACTION.
12148 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12149 or `agenda' to produce an entry list for an agenda view. It can also be
12150 a Lisp form or a function that should be called at each matched headline, in
12151 this case the return value is a list of all return values from these calls.
12153 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12154 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12155 only lines with a TODO keyword are included in the output."
12156 (require 'org-agenda)
12157 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
12158 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12159 (org-re
12160 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
12161 (props (list 'face 'default
12162 'done-face 'org-agenda-done
12163 'undone-face 'default
12164 'mouse-face 'highlight
12165 'org-not-done-regexp org-not-done-regexp
12166 'org-todo-regexp org-todo-regexp
12167 'help-echo
12168 (format "mouse-2 or RET jump to org file %s"
12169 (abbreviate-file-name
12170 (or (buffer-file-name (buffer-base-buffer))
12171 (buffer-name (buffer-base-buffer)))))))
12172 (case-fold-search nil)
12173 (org-map-continue-from nil)
12174 lspos tags tags-list
12175 (tags-alist (list (cons 0 org-file-tags)))
12176 (llast 0) rtn rtn1 level category i txt
12177 todo marker entry priority)
12178 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12179 (setq action (list 'lambda nil action)))
12180 (save-excursion
12181 (goto-char (point-min))
12182 (when (eq action 'sparse-tree)
12183 (org-overview)
12184 (org-remove-occur-highlights))
12185 (while (re-search-forward re nil t)
12186 (catch :skip
12187 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12188 tags (if (match-end 4) (org-match-string-no-properties 4)))
12189 (goto-char (setq lspos (match-beginning 0)))
12190 (setq level (org-reduced-level (funcall outline-level))
12191 category (org-get-category))
12192 (setq i llast llast level)
12193 ;; remove tag lists from same and sublevels
12194 (while (>= i level)
12195 (when (setq entry (assoc i tags-alist))
12196 (setq tags-alist (delete entry tags-alist)))
12197 (setq i (1- i)))
12198 ;; add the next tags
12199 (when tags
12200 (setq tags (org-split-string tags ":")
12201 tags-alist
12202 (cons (cons level tags) tags-alist)))
12203 ;; compile tags for current headline
12204 (setq tags-list
12205 (if org-use-tag-inheritance
12206 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12207 tags)
12208 org-scanner-tags tags-list)
12209 (when org-use-tag-inheritance
12210 (setcdr (car tags-alist)
12211 (mapcar (lambda (x)
12212 (setq x (copy-sequence x))
12213 (org-add-prop-inherited x))
12214 (cdar tags-alist))))
12215 (when (and tags org-use-tag-inheritance
12216 (or (not (eq t org-use-tag-inheritance))
12217 org-tags-exclude-from-inheritance))
12218 ;; selective inheritance, remove uninherited ones
12219 (setcdr (car tags-alist)
12220 (org-remove-uniherited-tags (cdar tags-alist))))
12221 (when (and (or (not todo-only)
12222 (and (member todo org-not-done-keywords)
12223 (or (not org-agenda-tags-todo-honor-ignore-options)
12224 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12225 (let ((case-fold-search t)) (eval matcher))
12227 (not (member org-archive-tag tags-list))
12228 ;; we have an archive tag, should we use this anyway?
12229 (or (not org-agenda-skip-archived-trees)
12230 (and (eq action 'agenda) org-agenda-archives-mode))))
12231 (unless (eq action 'sparse-tree) (org-agenda-skip))
12233 ;; select this headline
12235 (cond
12236 ((eq action 'sparse-tree)
12237 (and org-highlight-sparse-tree-matches
12238 (org-get-heading) (match-end 0)
12239 (org-highlight-new-match
12240 (match-beginning 0) (match-beginning 1)))
12241 (org-show-context 'tags-tree))
12242 ((eq action 'agenda)
12243 (setq txt (org-format-agenda-item
12245 (concat
12246 (if (eq org-tags-match-list-sublevels 'indented)
12247 (make-string (1- level) ?.) "")
12248 (org-get-heading))
12249 category
12250 tags-list
12252 priority (org-get-priority txt))
12253 (goto-char lspos)
12254 (setq marker (org-agenda-new-marker))
12255 (org-add-props txt props
12256 'org-marker marker 'org-hd-marker marker 'org-category category
12257 'todo-state todo
12258 'priority priority 'type "tagsmatch")
12259 (push txt rtn))
12260 ((functionp action)
12261 (setq org-map-continue-from nil)
12262 (save-excursion
12263 (setq rtn1 (funcall action))
12264 (push rtn1 rtn)))
12265 (t (error "Invalid action")))
12267 ;; if we are to skip sublevels, jump to end of subtree
12268 (unless org-tags-match-list-sublevels
12269 (org-end-of-subtree t)
12270 (backward-char 1))))
12271 ;; Get the correct position from where to continue
12272 (if org-map-continue-from
12273 (goto-char org-map-continue-from)
12274 (and (= (point) lspos) (end-of-line 1)))))
12275 (when (and (eq action 'sparse-tree)
12276 (not org-sparse-tree-open-archived-trees))
12277 (org-hide-archived-subtrees (point-min) (point-max)))
12278 (nreverse rtn)))
12280 (defun org-remove-uniherited-tags (tags)
12281 "Remove all tags that are not inherited from the list TAGS."
12282 (cond
12283 ((eq org-use-tag-inheritance t)
12284 (if org-tags-exclude-from-inheritance
12285 (org-delete-all org-tags-exclude-from-inheritance tags)
12286 tags))
12287 ((not org-use-tag-inheritance) nil)
12288 ((stringp org-use-tag-inheritance)
12289 (delq nil (mapcar
12290 (lambda (x)
12291 (if (and (string-match org-use-tag-inheritance x)
12292 (not (member x org-tags-exclude-from-inheritance)))
12293 x nil))
12294 tags)))
12295 ((listp org-use-tag-inheritance)
12296 (delq nil (mapcar
12297 (lambda (x)
12298 (if (member x org-use-tag-inheritance) x nil))
12299 tags)))))
12301 (defvar todo-only) ;; dynamically scoped
12303 (defun org-match-sparse-tree (&optional todo-only match)
12304 "Create a sparse tree according to tags string MATCH.
12305 MATCH can contain positive and negative selection of tags, like
12306 \"+WORK+URGENT-WITHBOSS\".
12307 If optional argument TODO-ONLY is non-nil, only select lines that are
12308 also TODO lines."
12309 (interactive "P")
12310 (org-prepare-agenda-buffers (list (current-buffer)))
12311 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12313 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12315 (defvar org-cached-props nil)
12316 (defun org-cached-entry-get (pom property)
12317 (if (or (eq t org-use-property-inheritance)
12318 (and (stringp org-use-property-inheritance)
12319 (string-match org-use-property-inheritance property))
12320 (and (listp org-use-property-inheritance)
12321 (member property org-use-property-inheritance)))
12322 ;; Caching is not possible, check it directly
12323 (org-entry-get pom property 'inherit)
12324 ;; Get all properties, so that we can do complicated checks easily
12325 (cdr (assoc property (or org-cached-props
12326 (setq org-cached-props
12327 (org-entry-properties pom)))))))
12329 (defun org-global-tags-completion-table (&optional files)
12330 "Return the list of all tags in all agenda buffer/files."
12331 (save-excursion
12332 (org-uniquify
12333 (delq nil
12334 (apply 'append
12335 (mapcar
12336 (lambda (file)
12337 (set-buffer (find-file-noselect file))
12338 (append (org-get-buffer-tags)
12339 (mapcar (lambda (x) (if (stringp (car-safe x))
12340 (list (car-safe x)) nil))
12341 org-tag-alist)))
12342 (if (and files (car files))
12343 files
12344 (org-agenda-files))))))))
12346 (defun org-make-tags-matcher (match)
12347 "Create the TAGS//TODO matcher form for the selection string MATCH."
12348 ;; todo-only is scoped dynamically into this function, and the function
12349 ;; may change it if the matcher asks for it.
12350 (unless match
12351 ;; Get a new match request, with completion
12352 (let ((org-last-tags-completion-table
12353 (org-global-tags-completion-table)))
12354 (setq match (org-completing-read-no-i
12355 "Match: " 'org-tags-completion-function nil nil nil
12356 'org-tags-history))))
12358 ;; Parse the string and create a lisp form
12359 (let ((match0 match)
12360 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
12361 minus tag mm
12362 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12363 orterms term orlist re-p str-p level-p level-op time-p
12364 prop-p pn pv po cat-p gv rest)
12365 (if (string-match "/+" match)
12366 ;; match contains also a todo-matching request
12367 (progn
12368 (setq tagsmatch (substring match 0 (match-beginning 0))
12369 todomatch (substring match (match-end 0)))
12370 (if (string-match "^!" todomatch)
12371 (setq todo-only t todomatch (substring todomatch 1)))
12372 (if (string-match "^\\s-*$" todomatch)
12373 (setq todomatch nil)))
12374 ;; only matching tags
12375 (setq tagsmatch match todomatch nil))
12377 ;; Make the tags matcher
12378 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12379 (setq tagsmatcher t)
12380 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12381 (while (setq term (pop orterms))
12382 (while (and (equal (substring term -1) "\\") orterms)
12383 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12384 (while (string-match re term)
12385 (setq rest (substring term (match-end 0))
12386 minus (and (match-end 1)
12387 (equal (match-string 1 term) "-"))
12388 tag (match-string 2 term)
12389 re-p (equal (string-to-char tag) ?{)
12390 level-p (match-end 4)
12391 prop-p (match-end 5)
12392 mm (cond
12393 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12394 (level-p
12395 (setq level-op (org-op-to-function (match-string 3 term)))
12396 `(,level-op level ,(string-to-number
12397 (match-string 4 term))))
12398 (prop-p
12399 (setq pn (match-string 5 term)
12400 po (match-string 6 term)
12401 pv (match-string 7 term)
12402 cat-p (equal pn "CATEGORY")
12403 re-p (equal (string-to-char pv) ?{)
12404 str-p (equal (string-to-char pv) ?\")
12405 time-p (save-match-data
12406 (string-match "^\"[[<].*[]>]\"$" pv))
12407 pv (if (or re-p str-p) (substring pv 1 -1) pv))
12408 (if time-p (setq pv (org-matcher-time pv)))
12409 (setq po (org-op-to-function po (if time-p 'time str-p)))
12410 (cond
12411 ((equal pn "CATEGORY")
12412 (setq gv '(get-text-property (point) 'org-category)))
12413 ((equal pn "TODO")
12414 (setq gv 'todo))
12416 (setq gv `(org-cached-entry-get nil ,pn))))
12417 (if re-p
12418 (if (eq po 'org<>)
12419 `(not (string-match ,pv (or ,gv "")))
12420 `(string-match ,pv (or ,gv "")))
12421 (if str-p
12422 `(,po (or ,gv "") ,pv)
12423 `(,po (string-to-number (or ,gv ""))
12424 ,(string-to-number pv) ))))
12425 (t `(member ,tag tags-list)))
12426 mm (if minus (list 'not mm) mm)
12427 term rest)
12428 (push mm tagsmatcher))
12429 (push (if (> (length tagsmatcher) 1)
12430 (cons 'and tagsmatcher)
12431 (car tagsmatcher))
12432 orlist)
12433 (setq tagsmatcher nil))
12434 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
12435 (setq tagsmatcher
12436 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
12437 ;; Make the todo matcher
12438 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
12439 (setq todomatcher t)
12440 (setq orterms (org-split-string todomatch "|") orlist nil)
12441 (while (setq term (pop orterms))
12442 (while (string-match re term)
12443 (setq minus (and (match-end 1)
12444 (equal (match-string 1 term) "-"))
12445 kwd (match-string 2 term)
12446 re-p (equal (string-to-char kwd) ?{)
12447 term (substring term (match-end 0))
12448 mm (if re-p
12449 `(string-match ,(substring kwd 1 -1) todo)
12450 (list 'equal 'todo kwd))
12451 mm (if minus (list 'not mm) mm))
12452 (push mm todomatcher))
12453 (push (if (> (length todomatcher) 1)
12454 (cons 'and todomatcher)
12455 (car todomatcher))
12456 orlist)
12457 (setq todomatcher nil))
12458 (setq todomatcher (if (> (length orlist) 1)
12459 (cons 'or orlist) (car orlist))))
12461 ;; Return the string and lisp forms of the matcher
12462 (setq matcher (if todomatcher
12463 (list 'and tagsmatcher todomatcher)
12464 tagsmatcher))
12465 (cons match0 matcher)))
12467 (defun org-op-to-function (op &optional stringp)
12468 "Turn an operator into the appropriate function."
12469 (setq op
12470 (cond
12471 ((equal op "<" ) '(< string< org-time<))
12472 ((equal op ">" ) '(> org-string> org-time>))
12473 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
12474 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
12475 ((member op '("=" "==")) '(= string= org-time=))
12476 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
12477 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
12479 (defun org<> (a b) (not (= a b)))
12480 (defun org-string<= (a b) (or (string= a b) (string< a b)))
12481 (defun org-string>= (a b) (not (string< a b)))
12482 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
12483 (defun org-string<> (a b) (not (string= a b)))
12484 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= 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) (org<> a b)))
12490 (defun org-2ft (s)
12491 "Convert S to a floating point time.
12492 If S is already a number, just return it. If it is a string, parse
12493 it as a time string and apply `float-time' to it. If S is nil, just return 0."
12494 (cond
12495 ((numberp s) s)
12496 ((stringp s)
12497 (condition-case nil
12498 (float-time (apply 'encode-time (org-parse-time-string s)))
12499 (error 0.)))
12500 (t 0.)))
12502 (defun org-time-today ()
12503 "Time in seconds today at 0:00.
12504 Returns the float number of seconds since the beginning of the
12505 epoch to the beginning of today (00:00)."
12506 (float-time (apply 'encode-time
12507 (append '(0 0 0) (nthcdr 3 (decode-time))))))
12509 (defun org-matcher-time (s)
12510 "Interpret a time comparison value."
12511 (save-match-data
12512 (cond
12513 ((string= s "<now>") (float-time))
12514 ((string= s "<today>") (org-time-today))
12515 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
12516 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
12517 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
12518 (+ (org-time-today)
12519 (* (string-to-number (match-string 1 s))
12520 (cdr (assoc (match-string 2 s)
12521 '(("d" . 86400.0) ("w" . 604800.0)
12522 ("m" . 2678400.0) ("y" . 31557600.0)))))))
12523 (t (org-2ft s)))))
12525 (defun org-match-any-p (re list)
12526 "Does re match any element of list?"
12527 (setq list (mapcar (lambda (x) (string-match re x)) list))
12528 (delq nil list))
12530 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
12531 (defvar org-tags-overlay (make-overlay 1 1))
12532 (org-detach-overlay org-tags-overlay)
12534 (defun org-get-local-tags-at (&optional pos)
12535 "Get a list of tags defined in the current headline."
12536 (org-get-tags-at pos 'local))
12538 (defun org-get-local-tags ()
12539 "Get a list of tags defined in the current headline."
12540 (org-get-tags-at nil 'local))
12542 (defun org-get-tags-at (&optional pos local)
12543 "Get a list of all headline tags applicable at POS.
12544 POS defaults to point. If tags are inherited, the list contains
12545 the targets in the same sequence as the headlines appear, i.e.
12546 the tags of the current headline come last.
12547 When LOCAL is non-nil, only return tags from the current headline,
12548 ignore inherited ones."
12549 (interactive)
12550 (if (and org-trust-scanner-tags
12551 (or (not pos) (equal pos (point)))
12552 (not local))
12553 org-scanner-tags
12554 (let (tags ltags lastpos parent)
12555 (save-excursion
12556 (save-restriction
12557 (widen)
12558 (goto-char (or pos (point)))
12559 (save-match-data
12560 (catch 'done
12561 (condition-case nil
12562 (progn
12563 (org-back-to-heading t)
12564 (while (not (equal lastpos (point)))
12565 (setq lastpos (point))
12566 (when (looking-at
12567 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
12568 (setq ltags (org-split-string
12569 (org-match-string-no-properties 1) ":"))
12570 (when parent
12571 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
12572 (setq tags (append
12573 (if parent
12574 (org-remove-uniherited-tags ltags)
12575 ltags)
12576 tags)))
12577 (or org-use-tag-inheritance (throw 'done t))
12578 (if local (throw 'done t))
12579 (or (org-up-heading-safe) (error nil))
12580 (setq parent t)))
12581 (error nil)))))
12582 (append (org-remove-uniherited-tags org-file-tags) tags)))))
12584 (defun org-add-prop-inherited (s)
12585 (add-text-properties 0 (length s) '(inherited t) s)
12588 (defun org-toggle-tag (tag &optional onoff)
12589 "Toggle the tag TAG for the current line.
12590 If ONOFF is `on' or `off', don't toggle but set to this state."
12591 (let (res current)
12592 (save-excursion
12593 (org-back-to-heading t)
12594 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
12595 (point-at-eol) t)
12596 (progn
12597 (setq current (match-string 1))
12598 (replace-match ""))
12599 (setq current ""))
12600 (setq current (nreverse (org-split-string current ":")))
12601 (cond
12602 ((eq onoff 'on)
12603 (setq res t)
12604 (or (member tag current) (push tag current)))
12605 ((eq onoff 'off)
12606 (or (not (member tag current)) (setq current (delete tag current))))
12607 (t (if (member tag current)
12608 (setq current (delete tag current))
12609 (setq res t)
12610 (push tag current))))
12611 (end-of-line 1)
12612 (if current
12613 (progn
12614 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
12615 (org-set-tags nil t))
12616 (delete-horizontal-space))
12617 (run-hooks 'org-after-tags-change-hook))
12618 res))
12620 (defun org-align-tags-here (to-col)
12621 ;; Assumes that this is a headline
12622 (let ((pos (point)) (col (current-column)) ncol tags-l p)
12623 (beginning-of-line 1)
12624 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12625 (< pos (match-beginning 2)))
12626 (progn
12627 (setq tags-l (- (match-end 2) (match-beginning 2)))
12628 (goto-char (match-beginning 1))
12629 (insert " ")
12630 (delete-region (point) (1+ (match-beginning 2)))
12631 (setq ncol (max (1+ (current-column))
12632 (1+ col)
12633 (if (> to-col 0)
12634 to-col
12635 (- (abs to-col) tags-l))))
12636 (setq p (point))
12637 (insert (make-string (- ncol (current-column)) ?\ ))
12638 (setq ncol (current-column))
12639 (when indent-tabs-mode (tabify p (point-at-eol)))
12640 (org-move-to-column (min ncol col) t))
12641 (goto-char pos))))
12643 (defun org-set-tags-command (&optional arg just-align)
12644 "Call the set-tags command for the current entry."
12645 (interactive "P")
12646 (if (org-on-heading-p)
12647 (org-set-tags arg just-align)
12648 (save-excursion
12649 (org-back-to-heading t)
12650 (org-set-tags arg just-align))))
12652 (defun org-set-tags-to (data)
12653 "Set the tags of the current entry to DATA, replacing the current tags.
12654 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
12655 If DATA is nil or the empty string, any tags will be removed."
12656 (interactive "sTags: ")
12657 (setq data
12658 (cond
12659 ((eq data nil) "")
12660 ((equal data "") "")
12661 ((stringp data)
12662 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
12663 ":"))
12664 ((listp data)
12665 (concat ":" (mapconcat 'identity data ":") ":"))
12666 (t nil)))
12667 (when data
12668 (save-excursion
12669 (org-back-to-heading t)
12670 (when (looking-at org-complex-heading-regexp)
12671 (if (match-end 5)
12672 (progn
12673 (goto-char (match-beginning 5))
12674 (insert data)
12675 (delete-region (point) (point-at-eol))
12676 (org-set-tags nil 'align))
12677 (goto-char (point-at-eol))
12678 (insert " " data)
12679 (org-set-tags nil 'align)))
12680 (beginning-of-line 1)
12681 (if (looking-at ".*?\\([ \t]+\\)$")
12682 (delete-region (match-beginning 1) (match-end 1))))))
12684 (defun org-align-all-tags ()
12685 "Align the tags i all headings."
12686 (interactive)
12687 (save-excursion
12688 (or (ignore-errors (org-back-to-heading t))
12689 (outline-next-heading))
12690 (if (org-on-heading-p)
12691 (org-set-tags t)
12692 (message "No headings"))))
12694 (defun org-set-tags (&optional arg just-align)
12695 "Set the tags for the current headline.
12696 With prefix ARG, realign all tags in headings in the current buffer."
12697 (interactive "P")
12698 (let* ((re (concat "^" outline-regexp))
12699 (current (org-get-tags-string))
12700 (col (current-column))
12701 (org-setting-tags t)
12702 table current-tags inherited-tags ; computed below when needed
12703 tags p0 c0 c1 rpl)
12704 (if arg
12705 (save-excursion
12706 (goto-char (point-min))
12707 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12708 (while (re-search-forward re nil t)
12709 (org-set-tags nil t)
12710 (end-of-line 1)))
12711 (message "All tags realigned to column %d" org-tags-column))
12712 (if just-align
12713 (setq tags current)
12714 ;; Get a new set of tags from the user
12715 (save-excursion
12716 (setq table (append org-tag-persistent-alist
12717 (or org-tag-alist (org-get-buffer-tags))
12718 (and org-complete-tags-always-offer-all-agenda-tags
12719 (org-global-tags-completion-table (org-agenda-files))))
12720 org-last-tags-completion-table table
12721 current-tags (org-split-string current ":")
12722 inherited-tags (nreverse
12723 (nthcdr (length current-tags)
12724 (nreverse (org-get-tags-at))))
12725 tags
12726 (if (or (eq t org-use-fast-tag-selection)
12727 (and org-use-fast-tag-selection
12728 (delq nil (mapcar 'cdr table))))
12729 (org-fast-tag-selection
12730 current-tags inherited-tags table
12731 (if org-fast-tag-selection-include-todo org-todo-key-alist))
12732 (let ((org-add-colon-after-tag-completion t))
12733 (org-trim
12734 (org-without-partial-completion
12735 (org-icompleting-read "Tags: " 'org-tags-completion-function
12736 nil nil current 'org-tags-history)))))))
12737 (while (string-match "[-+&]+" tags)
12738 ;; No boolean logic, just a list
12739 (setq tags (replace-match ":" t t tags))))
12741 (if org-tags-sort-function
12742 (setq tags (mapconcat 'identity
12743 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
12744 org-tags-sort-function) ":")))
12746 (if (string-match "\\`[\t ]*\\'" tags)
12747 (setq tags "")
12748 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
12749 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
12751 ;; Insert new tags at the correct column
12752 (beginning-of-line 1)
12753 (cond
12754 ((and (equal current "") (equal tags "")))
12755 ((re-search-forward
12756 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
12757 (point-at-eol) t)
12758 (if (equal tags "")
12759 (setq rpl "")
12760 (goto-char (match-beginning 0))
12761 (setq c0 (current-column) p0 (if (equal (char-before) ?*)
12762 (1+ (point)) (point))
12763 c1 (max (1+ c0) (if (> org-tags-column 0)
12764 org-tags-column
12765 (- (- org-tags-column) (length tags))))
12766 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
12767 (replace-match rpl t t)
12768 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
12769 tags)
12770 (t (error "Tags alignment failed")))
12771 (org-move-to-column col)
12772 (unless just-align
12773 (run-hooks 'org-after-tags-change-hook)))))
12775 (defun org-change-tag-in-region (beg end tag off)
12776 "Add or remove TAG for each entry in the region.
12777 This works in the agenda, and also in an org-mode buffer."
12778 (interactive
12779 (list (region-beginning) (region-end)
12780 (let ((org-last-tags-completion-table
12781 (if (org-mode-p)
12782 (org-get-buffer-tags)
12783 (org-global-tags-completion-table))))
12784 (org-icompleting-read
12785 "Tag: " 'org-tags-completion-function nil nil nil
12786 'org-tags-history))
12787 (progn
12788 (message "[s]et or [r]emove? ")
12789 (equal (read-char-exclusive) ?r))))
12790 (if (fboundp 'deactivate-mark) (deactivate-mark))
12791 (let ((agendap (equal major-mode 'org-agenda-mode))
12792 l1 l2 m buf pos newhead (cnt 0))
12793 (goto-char end)
12794 (setq l2 (1- (org-current-line)))
12795 (goto-char beg)
12796 (setq l1 (org-current-line))
12797 (loop for l from l1 to l2 do
12798 (org-goto-line l)
12799 (setq m (get-text-property (point) 'org-hd-marker))
12800 (when (or (and (org-mode-p) (org-on-heading-p))
12801 (and agendap m))
12802 (setq buf (if agendap (marker-buffer m) (current-buffer))
12803 pos (if agendap m (point)))
12804 (with-current-buffer buf
12805 (save-excursion
12806 (save-restriction
12807 (goto-char pos)
12808 (setq cnt (1+ cnt))
12809 (org-toggle-tag tag (if off 'off 'on))
12810 (setq newhead (org-get-heading)))))
12811 (and agendap (org-agenda-change-all-lines newhead m))))
12812 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
12814 (defun org-tags-completion-function (string predicate &optional flag)
12815 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
12816 (confirm (lambda (x) (stringp (car x)))))
12817 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
12818 (setq s1 (match-string 1 string)
12819 s2 (match-string 2 string))
12820 (setq s1 "" s2 string))
12821 (cond
12822 ((eq flag nil)
12823 ;; try completion
12824 (setq rtn (try-completion s2 ctable confirm))
12825 (if (stringp rtn)
12826 (setq rtn
12827 (concat s1 s2 (substring rtn (length s2))
12828 (if (and org-add-colon-after-tag-completion
12829 (assoc rtn ctable))
12830 ":" ""))))
12831 rtn)
12832 ((eq flag t)
12833 ;; all-completions
12834 (all-completions s2 ctable confirm)
12836 ((eq flag 'lambda)
12837 ;; exact match?
12838 (assoc s2 ctable)))
12841 (defun org-fast-tag-insert (kwd tags face &optional end)
12842 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
12843 (insert (format "%-12s" (concat kwd ":"))
12844 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
12845 (or end "")))
12847 (defun org-fast-tag-show-exit (flag)
12848 (save-excursion
12849 (org-goto-line 3)
12850 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
12851 (replace-match ""))
12852 (when flag
12853 (end-of-line 1)
12854 (org-move-to-column (- (window-width) 19) t)
12855 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
12857 (defun org-set-current-tags-overlay (current prefix)
12858 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
12859 (if (featurep 'xemacs)
12860 (org-overlay-display org-tags-overlay (concat prefix s)
12861 'secondary-selection)
12862 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
12863 (org-overlay-display org-tags-overlay (concat prefix s)))))
12865 (defvar org-last-tag-selection-key nil)
12866 (defun org-fast-tag-selection (current inherited table &optional todo-table)
12867 "Fast tag selection with single keys.
12868 CURRENT is the current list of tags in the headline, INHERITED is the
12869 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
12870 possibly with grouping information. TODO-TABLE is a similar table with
12871 TODO keywords, should these have keys assigned to them.
12872 If the keys are nil, a-z are automatically assigned.
12873 Returns the new tags string, or nil to not change the current settings."
12874 (let* ((fulltable (append table todo-table))
12875 (maxlen (apply 'max (mapcar
12876 (lambda (x)
12877 (if (stringp (car x)) (string-width (car x)) 0))
12878 fulltable)))
12879 (buf (current-buffer))
12880 (expert (eq org-fast-tag-selection-single-key 'expert))
12881 (buffer-tags nil)
12882 (fwidth (+ maxlen 3 1 3))
12883 (ncol (/ (- (window-width) 4) fwidth))
12884 (i-face 'org-done)
12885 (c-face 'org-todo)
12886 tg cnt e c char c1 c2 ntable tbl rtn
12887 ov-start ov-end ov-prefix
12888 (exit-after-next org-fast-tag-selection-single-key)
12889 (done-keywords org-done-keywords)
12890 groups ingroup)
12891 (save-excursion
12892 (beginning-of-line 1)
12893 (if (looking-at
12894 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12895 (setq ov-start (match-beginning 1)
12896 ov-end (match-end 1)
12897 ov-prefix "")
12898 (setq ov-start (1- (point-at-eol))
12899 ov-end (1+ ov-start))
12900 (skip-chars-forward "^\n\r")
12901 (setq ov-prefix
12902 (concat
12903 (buffer-substring (1- (point)) (point))
12904 (if (> (current-column) org-tags-column)
12906 (make-string (- org-tags-column (current-column)) ?\ ))))))
12907 (move-overlay org-tags-overlay ov-start ov-end)
12908 (save-window-excursion
12909 (if expert
12910 (set-buffer (get-buffer-create " *Org tags*"))
12911 (delete-other-windows)
12912 (split-window-vertically)
12913 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
12914 (erase-buffer)
12915 (org-set-local 'org-done-keywords done-keywords)
12916 (org-fast-tag-insert "Inherited" inherited i-face "\n")
12917 (org-fast-tag-insert "Current" current c-face "\n\n")
12918 (org-fast-tag-show-exit exit-after-next)
12919 (org-set-current-tags-overlay current ov-prefix)
12920 (setq tbl fulltable char ?a cnt 0)
12921 (while (setq e (pop tbl))
12922 (cond
12923 ((equal (car e) :startgroup)
12924 (push '() groups) (setq ingroup t)
12925 (when (not (= cnt 0))
12926 (setq cnt 0)
12927 (insert "\n"))
12928 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
12929 ((equal (car e) :endgroup)
12930 (setq ingroup nil cnt 0)
12931 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
12932 ((equal e '(:newline))
12933 (when (not (= cnt 0))
12934 (setq cnt 0)
12935 (insert "\n")
12936 (setq e (car tbl))
12937 (while (equal (car tbl) '(:newline))
12938 (insert "\n")
12939 (setq tbl (cdr tbl)))))
12941 (setq tg (copy-sequence (car e)) c2 nil)
12942 (if (cdr e)
12943 (setq c (cdr e))
12944 ;; automatically assign a character.
12945 (setq c1 (string-to-char
12946 (downcase (substring
12947 tg (if (= (string-to-char tg) ?@) 1 0)))))
12948 (if (or (rassoc c1 ntable) (rassoc c1 table))
12949 (while (or (rassoc char ntable) (rassoc char table))
12950 (setq char (1+ char)))
12951 (setq c2 c1))
12952 (setq c (or c2 char)))
12953 (if ingroup (push tg (car groups)))
12954 (setq tg (org-add-props tg nil 'face
12955 (cond
12956 ((not (assoc tg table))
12957 (org-get-todo-face tg))
12958 ((member tg current) c-face)
12959 ((member tg inherited) i-face)
12960 (t nil))))
12961 (if (and (= cnt 0) (not ingroup)) (insert " "))
12962 (insert "[" c "] " tg (make-string
12963 (- fwidth 4 (length tg)) ?\ ))
12964 (push (cons tg c) ntable)
12965 (when (= (setq cnt (1+ cnt)) ncol)
12966 (insert "\n")
12967 (if ingroup (insert " "))
12968 (setq cnt 0)))))
12969 (setq ntable (nreverse ntable))
12970 (insert "\n")
12971 (goto-char (point-min))
12972 (if (not expert) (org-fit-window-to-buffer))
12973 (setq rtn
12974 (catch 'exit
12975 (while t
12976 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
12977 (if (not groups) "no " "")
12978 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
12979 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12980 (setq org-last-tag-selection-key c)
12981 (cond
12982 ((= c ?\r) (throw 'exit t))
12983 ((= c ?!)
12984 (setq groups (not groups))
12985 (goto-char (point-min))
12986 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12987 ((= c ?\C-c)
12988 (if (not expert)
12989 (org-fast-tag-show-exit
12990 (setq exit-after-next (not exit-after-next)))
12991 (setq expert nil)
12992 (delete-other-windows)
12993 (split-window-vertically)
12994 (org-switch-to-buffer-other-window " *Org tags*")
12995 (org-fit-window-to-buffer)))
12996 ((or (= c ?\C-g)
12997 (and (= c ?q) (not (rassoc c ntable))))
12998 (org-detach-overlay org-tags-overlay)
12999 (setq quit-flag t))
13000 ((= c ?\ )
13001 (setq current nil)
13002 (if exit-after-next (setq exit-after-next 'now)))
13003 ((= c ?\t)
13004 (condition-case nil
13005 (setq tg (org-icompleting-read
13006 "Tag: "
13007 (or buffer-tags
13008 (with-current-buffer buf
13009 (org-get-buffer-tags)))))
13010 (quit (setq tg "")))
13011 (when (string-match "\\S-" tg)
13012 (add-to-list 'buffer-tags (list tg))
13013 (if (member tg current)
13014 (setq current (delete tg current))
13015 (push tg current)))
13016 (if exit-after-next (setq exit-after-next 'now)))
13017 ((setq e (rassoc c todo-table) tg (car e))
13018 (with-current-buffer buf
13019 (save-excursion (org-todo tg)))
13020 (if exit-after-next (setq exit-after-next 'now)))
13021 ((setq e (rassoc c ntable) tg (car e))
13022 (if (member tg current)
13023 (setq current (delete tg current))
13024 (loop for g in groups do
13025 (if (member tg g)
13026 (mapc (lambda (x)
13027 (setq current (delete x current)))
13028 g)))
13029 (push tg current))
13030 (if exit-after-next (setq exit-after-next 'now))))
13032 ;; Create a sorted list
13033 (setq current
13034 (sort current
13035 (lambda (a b)
13036 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13037 (if (eq exit-after-next 'now) (throw 'exit t))
13038 (goto-char (point-min))
13039 (beginning-of-line 2)
13040 (delete-region (point) (point-at-eol))
13041 (org-fast-tag-insert "Current" current c-face)
13042 (org-set-current-tags-overlay current ov-prefix)
13043 (while (re-search-forward
13044 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
13045 (setq tg (match-string 1))
13046 (add-text-properties
13047 (match-beginning 1) (match-end 1)
13048 (list 'face
13049 (cond
13050 ((member tg current) c-face)
13051 ((member tg inherited) i-face)
13052 (t (get-text-property (match-beginning 1) 'face))))))
13053 (goto-char (point-min)))))
13054 (org-detach-overlay org-tags-overlay)
13055 (if rtn
13056 (mapconcat 'identity current ":")
13057 nil))))
13059 (defun org-get-tags-string ()
13060 "Get the TAGS string in the current headline."
13061 (unless (org-on-heading-p t)
13062 (error "Not on a heading"))
13063 (save-excursion
13064 (beginning-of-line 1)
13065 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13066 (org-match-string-no-properties 1)
13067 "")))
13069 (defun org-get-tags ()
13070 "Get the list of tags specified in the current headline."
13071 (org-split-string (org-get-tags-string) ":"))
13073 (defun org-get-buffer-tags ()
13074 "Get a table of all tags used in the buffer, for completion."
13075 (let (tags)
13076 (save-excursion
13077 (goto-char (point-min))
13078 (while (re-search-forward
13079 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
13080 (when (equal (char-after (point-at-bol 0)) ?*)
13081 (mapc (lambda (x) (add-to-list 'tags x))
13082 (org-split-string (org-match-string-no-properties 1) ":")))))
13083 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13084 (mapcar 'list tags)))
13086 ;;;; The mapping API
13088 ;;;###autoload
13089 (defun org-map-entries (func &optional match scope &rest skip)
13090 "Call FUNC at each headline selected by MATCH in SCOPE.
13092 FUNC is a function or a lisp form. The function will be called without
13093 arguments, with the cursor positioned at the beginning of the headline.
13094 The return values of all calls to the function will be collected and
13095 returned as a list.
13097 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13098 does not need to preserve point. After evaluation, the cursor will be
13099 moved to the end of the line (presumably of the headline of the
13100 processed entry) and search continues from there. Under some
13101 circumstances, this may not produce the wanted results. For example,
13102 if you have removed (e.g. archived) the current (sub)tree it could
13103 mean that the next entry will be skipped entirely. In such cases, you
13104 can specify the position from where search should continue by making
13105 FUNC set the variable `org-map-continue-from' to the desired buffer
13106 position.
13108 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13109 Only headlines that are matched by this query will be considered during
13110 the iteration. When MATCH is nil or t, all headlines will be
13111 visited by the iteration.
13113 SCOPE determines the scope of this command. It can be any of:
13115 nil The current buffer, respecting the restriction if any
13116 tree The subtree started with the entry at point
13117 file The current buffer, without restriction
13118 file-with-archives
13119 The current buffer, and any archives associated with it
13120 agenda All agenda files
13121 agenda-with-archives
13122 All agenda files with any archive files associated with them
13123 \(file1 file2 ...)
13124 If this is a list, all files in the list will be scanned
13126 The remaining args are treated as settings for the skipping facilities of
13127 the scanner. The following items can be given here:
13129 archive skip trees with the archive tag.
13130 comment skip trees with the COMMENT keyword
13131 function or Emacs Lisp form:
13132 will be used as value for `org-agenda-skip-function', so whenever
13133 the function returns t, FUNC will not be called for that
13134 entry and search will continue from the point where the
13135 function leaves it.
13137 If your function needs to retrieve the tags including inherited tags
13138 at the *current* entry, you can use the value of the variable
13139 `org-scanner-tags' which will be much faster than getting the value
13140 with `org-get-tags-at'. If your function gets properties with
13141 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13142 to t around the call to `org-entry-properties' to get the same speedup.
13143 Note that if your function moves around to retrieve tags and properties at
13144 a *different* entry, you cannot use these techniques."
13145 (let* ((org-agenda-archives-mode nil) ; just to make sure
13146 (org-agenda-skip-archived-trees (memq 'archive skip))
13147 (org-agenda-skip-comment-trees (memq 'comment skip))
13148 (org-agenda-skip-function
13149 (car (org-delete-all '(comment archive) skip)))
13150 (org-tags-match-list-sublevels t)
13151 matcher file res
13152 org-todo-keywords-for-agenda
13153 org-done-keywords-for-agenda
13154 org-todo-keyword-alist-for-agenda
13155 org-drawers-for-agenda
13156 org-tag-alist-for-agenda)
13158 (cond
13159 ((eq match t) (setq matcher t))
13160 ((eq match nil) (setq matcher t))
13161 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13163 (save-excursion
13164 (save-restriction
13165 (when (eq scope 'tree)
13166 (org-back-to-heading t)
13167 (org-narrow-to-subtree)
13168 (setq scope nil))
13170 (if (not scope)
13171 (progn
13172 (org-prepare-agenda-buffers
13173 (list (buffer-file-name (current-buffer))))
13174 (setq res (org-scan-tags func matcher)))
13175 ;; Get the right scope
13176 (cond
13177 ((and scope (listp scope) (symbolp (car scope)))
13178 (setq scope (eval scope)))
13179 ((eq scope 'agenda)
13180 (setq scope (org-agenda-files t)))
13181 ((eq scope 'agenda-with-archives)
13182 (setq scope (org-agenda-files t))
13183 (setq scope (org-add-archive-files scope)))
13184 ((eq scope 'file)
13185 (setq scope (list (buffer-file-name))))
13186 ((eq scope 'file-with-archives)
13187 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13188 (org-prepare-agenda-buffers scope)
13189 (while (setq file (pop scope))
13190 (with-current-buffer (org-find-base-buffer-visiting file)
13191 (save-excursion
13192 (save-restriction
13193 (widen)
13194 (goto-char (point-min))
13195 (setq res (append res (org-scan-tags func matcher))))))))))
13196 res))
13198 ;;;; Properties
13200 ;;; Setting and retrieving properties
13202 (defconst org-special-properties
13203 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13204 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED")
13205 "The special properties valid in Org-mode.
13207 These are properties that are not defined in the property drawer,
13208 but in some other way.")
13210 (defconst org-default-properties
13211 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13212 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13213 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13214 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13215 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13216 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13217 "Some properties that are used by Org-mode for various purposes.
13218 Being in this list makes sure that they are offered for completion.")
13220 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13221 "Regular expression matching the first line of a property drawer.")
13223 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13224 "Regular expression matching the last line of a property drawer.")
13226 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13227 "Regular expression matching the first line of a property drawer.")
13229 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13230 "Regular expression matching the first line of a property drawer.")
13232 (defconst org-property-drawer-re
13233 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13234 org-property-end-re "\\)\n?")
13235 "Matches an entire property drawer.")
13237 (defconst org-clock-drawer-re
13238 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13239 org-property-end-re "\\)\n?")
13240 "Matches an entire clock drawer.")
13242 (defun org-property-action ()
13243 "Do an action on properties."
13244 (interactive)
13245 (let (c)
13246 (org-at-property-p)
13247 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13248 (setq c (read-char-exclusive))
13249 (cond
13250 ((equal c ?s)
13251 (call-interactively 'org-set-property))
13252 ((equal c ?d)
13253 (call-interactively 'org-delete-property))
13254 ((equal c ?D)
13255 (call-interactively 'org-delete-property-globally))
13256 ((equal c ?c)
13257 (call-interactively 'org-compute-property-at-point))
13258 (t (error "No such property action %c" c)))))
13260 (defun org-set-effort (&optional value)
13261 "Set the effort property of the current entry.
13262 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13263 allowed value."
13264 (interactive "P")
13265 (if (equal value 0) (setq value 10))
13266 (let* ((completion-ignore-case t)
13267 (prop org-effort-property)
13268 (cur (org-entry-get nil prop))
13269 (allowed (org-property-get-allowed-values nil prop 'table))
13270 (existing (mapcar 'list (org-property-values prop)))
13272 (val (cond
13273 ((stringp value) value)
13274 ((and allowed (integerp value))
13275 (or (car (nth (1- value) allowed))
13276 (car (org-last allowed))))
13277 (allowed
13278 (message "Select 1-9,0, [RET%s]: %s"
13279 (if cur (concat "=" cur) "")
13280 (mapconcat 'car allowed " "))
13281 (setq rpl (read-char-exclusive))
13282 (if (equal rpl ?\r)
13284 (setq rpl (- rpl ?0))
13285 (if (equal rpl 0) (setq rpl 10))
13286 (if (and (> rpl 0) (<= rpl (length allowed)))
13287 (car (nth (1- rpl) allowed))
13288 (org-completing-read "Effort: " allowed nil))))
13290 (let (org-completion-use-ido org-completion-use-iswitchb)
13291 (org-completing-read
13292 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13293 (concat "[" cur "]") "")
13294 ": ")
13295 existing nil nil "" nil cur))))))
13296 (unless (equal (org-entry-get nil prop) val)
13297 (org-entry-put nil prop val))
13298 (message "%s is now %s" prop val)))
13300 (defun org-at-property-p ()
13301 "Is cursor inside a property drawer?"
13302 (save-excursion
13303 (beginning-of-line 1)
13304 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13305 (save-match-data ;; Used by calling procedures
13306 (let ((p (point))
13307 (range (unless (org-before-first-heading-p)
13308 (org-get-property-block))))
13309 (and range (<= (car range) p) (< p (cdr range))))))))
13311 (defun org-get-property-block (&optional beg end force)
13312 "Return the (beg . end) range of the body of the property drawer.
13313 BEG and END can be beginning and end of subtree, if not given
13314 they will be found.
13315 If the drawer does not exist and FORCE is non-nil, create the drawer."
13316 (catch 'exit
13317 (save-excursion
13318 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13319 (end (or end (progn (outline-next-heading) (point)))))
13320 (goto-char beg)
13321 (if (re-search-forward org-property-start-re end t)
13322 (setq beg (1+ (match-end 0)))
13323 (if force
13324 (save-excursion
13325 (org-insert-property-drawer)
13326 (setq end (progn (outline-next-heading) (point))))
13327 (throw 'exit nil))
13328 (goto-char beg)
13329 (if (re-search-forward org-property-start-re end t)
13330 (setq beg (1+ (match-end 0)))))
13331 (if (re-search-forward org-property-end-re end t)
13332 (setq end (match-beginning 0))
13333 (or force (throw 'exit nil))
13334 (goto-char beg)
13335 (setq end beg)
13336 (org-indent-line-function)
13337 (insert ":END:\n"))
13338 (cons beg end)))))
13340 (defun org-entry-properties (&optional pom which specific)
13341 "Get all properties of the entry at point-or-marker POM.
13342 This includes the TODO keyword, the tags, time strings for deadline,
13343 scheduled, and clocking, and any additional properties defined in the
13344 entry. The return value is an alist, keys may occur multiple times
13345 if the property key was used several times.
13346 POM may also be nil, in which case the current entry is used.
13347 If WHICH is nil or `all', get all properties. If WHICH is
13348 `special' or `standard', only get that subclass. If WHICH
13349 is a string only get exactly this property. Specific can be a string, the
13350 specific property we are interested in. Specifying it can speed
13351 things up because then unnecessary parsing is avoided."
13352 (setq which (or which 'all))
13353 (org-with-point-at pom
13354 (let ((clockstr (substring org-clock-string 0 -1))
13355 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13356 (case-fold-search nil)
13357 beg end range props sum-props key key1 value string clocksum)
13358 (save-excursion
13359 (when (condition-case nil
13360 (and (org-mode-p) (org-back-to-heading t))
13361 (error nil))
13362 (setq beg (point))
13363 (setq sum-props (get-text-property (point) 'org-summaries))
13364 (setq clocksum (get-text-property (point) :org-clock-minutes))
13365 (outline-next-heading)
13366 (setq end (point))
13367 (when (memq which '(all special))
13368 ;; Get the special properties, like TODO and tags
13369 (goto-char beg)
13370 (when (and (or (not specific) (string= specific "TODO"))
13371 (looking-at org-todo-line-regexp) (match-end 2))
13372 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13373 (when (and (or (not specific) (string= specific "PRIORITY"))
13374 (looking-at org-priority-regexp))
13375 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13376 (when (and (or (not specific) (string= specific "TAGS"))
13377 (setq value (org-get-tags-string))
13378 (string-match "\\S-" value))
13379 (push (cons "TAGS" value) props))
13380 (when (and (or (not specific) (string= specific "ALLTAGS"))
13381 (setq value (org-get-tags-at)))
13382 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
13383 ":"))
13384 props))
13385 (when (or (not specific) (string= specific "BLOCKED"))
13386 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
13387 (when (or (not specific)
13388 (member specific
13389 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
13390 "TIMESTAMP" "TIMESTAMP_IA")))
13391 (while (re-search-forward org-maybe-keyword-time-regexp end t)
13392 (setq key (if (match-end 1)
13393 (substring (org-match-string-no-properties 1)
13394 0 -1))
13395 string (if (equal key clockstr)
13396 (org-no-properties
13397 (org-trim
13398 (buffer-substring
13399 (match-beginning 3) (goto-char
13400 (point-at-eol)))))
13401 (substring (org-match-string-no-properties 3)
13402 1 -1)))
13403 ;; Get the correct property name from the key. This is
13404 ;; necessary if the user has configured time keywords.
13405 (setq key1 (concat key ":"))
13406 (cond
13407 ((not key)
13408 (setq key
13409 (if (= (char-after (match-beginning 3)) ?\[)
13410 "TIMESTAMP_IA" "TIMESTAMP")))
13411 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
13412 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
13413 ((equal key1 org-closed-string) (setq key "CLOSED"))
13414 ((equal key1 org-clock-string) (setq key "CLOCK")))
13415 (when (or (equal key "CLOCK") (not (assoc key props)))
13416 (push (cons key string) props))))
13419 (when (memq which '(all standard))
13420 ;; Get the standard properties, like :PROP: ...
13421 (setq range (org-get-property-block beg end))
13422 (when range
13423 (goto-char (car range))
13424 (while (re-search-forward
13425 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
13426 (cdr range) t)
13427 (setq key (org-match-string-no-properties 1)
13428 value (org-trim (or (org-match-string-no-properties 2) "")))
13429 (unless (member key excluded)
13430 (push (cons key (or value "")) props)))))
13431 (if clocksum
13432 (push (cons "CLOCKSUM"
13433 (org-columns-number-to-string (/ (float clocksum) 60.)
13434 'add_times))
13435 props))
13436 (unless (assoc "CATEGORY" props)
13437 (setq value (or (org-get-category)
13438 (progn (org-refresh-category-properties)
13439 (org-get-category))))
13440 (push (cons "CATEGORY" value) props))
13441 (append sum-props (nreverse props)))))))
13443 (defun org-entry-get (pom property &optional inherit literal-nil)
13444 "Get value of PROPERTY for entry at point-or-marker POM.
13445 If INHERIT is non-nil and the entry does not have the property,
13446 then also check higher levels of the hierarchy.
13447 If INHERIT is the symbol `selective', use inheritance only if the setting
13448 in `org-use-property-inheritance' selects PROPERTY for inheritance.
13449 If the property is present but empty, the return value is the empty string.
13450 If the property is not present at all, nil is returned.
13452 If LITERAL-NIL is set, return the string value \"nil\" as a string,
13453 do not interpret it as the list atom nil. This is used for inheritance
13454 when a \"nil\" value can supercede a non-nil value higher up the hierarchy."
13455 (org-with-point-at pom
13456 (if (and inherit (if (eq inherit 'selective)
13457 (org-property-inherit-p property)
13459 (org-entry-get-with-inheritance property literal-nil)
13460 (if (member property org-special-properties)
13461 ;; We need a special property. Use `org-entry-properties' to
13462 ;; retrieve it, but specify the wanted property
13463 (cdr (assoc property (org-entry-properties nil 'special property)))
13464 (let ((range (org-get-property-block)))
13465 (if (and range
13466 (goto-char (car range))
13467 (re-search-forward
13468 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
13469 (cdr range) t))
13470 ;; Found the property, return it.
13471 (if (match-end 1)
13472 (if literal-nil
13473 (org-match-string-no-properties 1)
13474 (org-not-nil (org-match-string-no-properties 1)))
13475 "")))))))
13477 (defun org-property-or-variable-value (var &optional inherit)
13478 "Check if there is a property fixing the value of VAR.
13479 If yes, return this value. If not, return the current value of the variable."
13480 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13481 (if (and prop (stringp prop) (string-match "\\S-" prop))
13482 (read prop)
13483 (symbol-value var))))
13485 (defun org-entry-delete (pom property)
13486 "Delete the property PROPERTY from entry at point-or-marker POM."
13487 (org-with-point-at pom
13488 (if (member property org-special-properties)
13489 nil ; cannot delete these properties.
13490 (let ((range (org-get-property-block)))
13491 (if (and range
13492 (goto-char (car range))
13493 (re-search-forward
13494 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
13495 (cdr range) t))
13496 (progn
13497 (delete-region (match-beginning 0) (1+ (point-at-eol)))
13499 nil)))))
13501 ;; Multi-values properties are properties that contain multiple values
13502 ;; These values are assumed to be single words, separated by whitespace.
13503 (defun org-entry-add-to-multivalued-property (pom property value)
13504 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
13505 (let* ((old (org-entry-get pom property))
13506 (values (and old (org-split-string old "[ \t]"))))
13507 (setq value (org-entry-protect-space value))
13508 (unless (member value values)
13509 (setq values (cons value values))
13510 (org-entry-put pom property
13511 (mapconcat 'identity values " ")))))
13513 (defun org-entry-remove-from-multivalued-property (pom property value)
13514 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
13515 (let* ((old (org-entry-get pom property))
13516 (values (and old (org-split-string old "[ \t]"))))
13517 (setq value (org-entry-protect-space value))
13518 (when (member value values)
13519 (setq values (delete value values))
13520 (org-entry-put pom property
13521 (mapconcat 'identity values " ")))))
13523 (defun org-entry-member-in-multivalued-property (pom property value)
13524 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
13525 (let* ((old (org-entry-get pom property))
13526 (values (and old (org-split-string old "[ \t]"))))
13527 (setq value (org-entry-protect-space value))
13528 (member value values)))
13530 (defun org-entry-get-multivalued-property (pom property)
13531 "Return a list of values in a multivalued property."
13532 (let* ((value (org-entry-get pom property))
13533 (values (and value (org-split-string value "[ \t]"))))
13534 (mapcar 'org-entry-restore-space values)))
13536 (defun org-entry-put-multivalued-property (pom property &rest values)
13537 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
13538 VALUES should be a list of strings. Spaces will be protected."
13539 (org-entry-put pom property
13540 (mapconcat 'org-entry-protect-space values " "))
13541 (let* ((value (org-entry-get pom property))
13542 (values (and value (org-split-string value "[ \t]"))))
13543 (mapcar 'org-entry-restore-space values)))
13545 (defun org-entry-protect-space (s)
13546 "Protect spaces and newline in string S."
13547 (while (string-match " " s)
13548 (setq s (replace-match "%20" t t s)))
13549 (while (string-match "\n" s)
13550 (setq s (replace-match "%0A" t t s)))
13553 (defun org-entry-restore-space (s)
13554 "Restore spaces and newline in string S."
13555 (while (string-match "%20" s)
13556 (setq s (replace-match " " t t s)))
13557 (while (string-match "%0A" s)
13558 (setq s (replace-match "\n" t t s)))
13561 (defvar org-entry-property-inherited-from (make-marker)
13562 "Marker pointing to the entry from where a property was inherited.
13563 Each call to `org-entry-get-with-inheritance' will set this marker to the
13564 location of the entry where the inheritance search matched. If there was
13565 no match, the marker will point nowhere.
13566 Note that also `org-entry-get' calls this function, if the INHERIT flag
13567 is set.")
13569 (defun org-entry-get-with-inheritance (property &optional literal-nil)
13570 "Get entry property, and search higher levels if not present.
13571 The search will stop at the first ancestor which has the property defined.
13572 If the value found is \"nil\", return nil to show that the property
13573 should be considered as undefined (this is the meaning of nil here).
13574 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
13575 (move-marker org-entry-property-inherited-from nil)
13576 (let (tmp)
13577 (save-excursion
13578 (save-restriction
13579 (widen)
13580 (catch 'ex
13581 (while t
13582 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
13583 (org-back-to-heading t)
13584 (move-marker org-entry-property-inherited-from (point))
13585 (throw 'ex tmp))
13586 (or (org-up-heading-safe) (throw 'ex nil)))))
13587 (setq tmp (or tmp
13588 (cdr (assoc property org-file-properties))
13589 (cdr (assoc property org-global-properties))
13590 (cdr (assoc property org-global-properties-fixed))))
13591 (if literal-nil tmp (org-not-nil tmp)))))
13593 (defvar org-property-changed-functions nil
13594 "Hook called when the value of a property has changed.
13595 Each hook function should accept two arguments, the name of the property
13596 and the new value.")
13598 (defun org-entry-put (pom property value)
13599 "Set PROPERTY to VALUE for entry at point-or-marker POM."
13600 (org-with-point-at pom
13601 (org-back-to-heading t)
13602 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
13603 range)
13604 (cond
13605 ((equal property "TODO")
13606 (when (and (stringp value) (string-match "\\S-" value)
13607 (not (member value org-todo-keywords-1)))
13608 (error "\"%s\" is not a valid TODO state" value))
13609 (if (or (not value)
13610 (not (string-match "\\S-" value)))
13611 (setq value 'none))
13612 (org-todo value)
13613 (org-set-tags nil 'align))
13614 ((equal property "PRIORITY")
13615 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
13616 (string-to-char value) ?\ ))
13617 (org-set-tags nil 'align))
13618 ((equal property "SCHEDULED")
13619 (if (re-search-forward org-scheduled-time-regexp end t)
13620 (cond
13621 ((eq value 'earlier) (org-timestamp-change -1 'day))
13622 ((eq value 'later) (org-timestamp-change 1 'day))
13623 (t (call-interactively 'org-schedule)))
13624 (call-interactively 'org-schedule)))
13625 ((equal property "DEADLINE")
13626 (if (re-search-forward org-deadline-time-regexp end t)
13627 (cond
13628 ((eq value 'earlier) (org-timestamp-change -1 'day))
13629 ((eq value 'later) (org-timestamp-change 1 'day))
13630 (t (call-interactively 'org-deadline)))
13631 (call-interactively 'org-deadline)))
13632 ((member property org-special-properties)
13633 (error "The %s property can not yet be set with `org-entry-put'"
13634 property))
13635 (t ; a non-special property
13636 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
13637 (setq range (org-get-property-block beg end 'force))
13638 (goto-char (car range))
13639 (if (re-search-forward
13640 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
13641 (progn
13642 (delete-region (match-beginning 1) (match-end 1))
13643 (goto-char (match-beginning 1)))
13644 (goto-char (cdr range))
13645 (insert "\n")
13646 (backward-char 1)
13647 (org-indent-line-function)
13648 (insert ":" property ":"))
13649 (and value (insert " " value))
13650 (org-indent-line-function)))))
13651 (run-hook-with-args 'org-property-changed-functions property value)))
13653 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
13654 "Get all property keys in the current buffer.
13655 With INCLUDE-SPECIALS, also list the special properties that reflect things
13656 like tags and TODO state.
13657 With INCLUDE-DEFAULTS, also include properties that has special meaning
13658 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
13659 With INCLUDE-COLUMNS, also include property names given in COLUMN
13660 formats in the current buffer."
13661 (let (rtn range cfmt s p)
13662 (save-excursion
13663 (save-restriction
13664 (widen)
13665 (goto-char (point-min))
13666 (while (re-search-forward org-property-start-re nil t)
13667 (setq range (org-get-property-block))
13668 (goto-char (car range))
13669 (while (re-search-forward
13670 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
13671 (cdr range) t)
13672 (add-to-list 'rtn (org-match-string-no-properties 1)))
13673 (outline-next-heading))))
13675 (when include-specials
13676 (setq rtn (append org-special-properties rtn)))
13678 (when include-defaults
13679 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
13680 (add-to-list 'rtn org-effort-property))
13682 (when include-columns
13683 (save-excursion
13684 (save-restriction
13685 (widen)
13686 (goto-char (point-min))
13687 (while (re-search-forward
13688 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
13689 nil t)
13690 (setq cfmt (match-string 2) s 0)
13691 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
13692 cfmt s)
13693 (setq s (match-end 0)
13694 p (match-string 1 cfmt))
13695 (unless (or (equal p "ITEM")
13696 (member p org-special-properties))
13697 (add-to-list 'rtn (match-string 1 cfmt))))))))
13699 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
13701 (defun org-property-values (key)
13702 "Return a list of all values of property KEY."
13703 (save-excursion
13704 (save-restriction
13705 (widen)
13706 (goto-char (point-min))
13707 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
13708 values)
13709 (while (re-search-forward re nil t)
13710 (add-to-list 'values (org-trim (match-string 1))))
13711 (delete "" values)))))
13713 (defun org-insert-property-drawer ()
13714 "Insert a property drawer into the current entry."
13715 (interactive)
13716 (org-back-to-heading t)
13717 (looking-at outline-regexp)
13718 (let ((indent (if org-adapt-indentation
13719 (- (match-end 0)(match-beginning 0))
13721 (beg (point))
13722 (re (concat "^[ \t]*" org-keyword-time-regexp))
13723 end hiddenp)
13724 (outline-next-heading)
13725 (setq end (point))
13726 (goto-char beg)
13727 (while (re-search-forward re end t))
13728 (setq hiddenp (org-invisible-p))
13729 (end-of-line 1)
13730 (and (equal (char-after) ?\n) (forward-char 1))
13731 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
13732 (if (member (match-string 1) '("CLOCK:" ":END:"))
13733 ;; just skip this line
13734 (beginning-of-line 2)
13735 ;; Drawer start, find the end
13736 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
13737 (beginning-of-line 1)))
13738 (org-skip-over-state-notes)
13739 (skip-chars-backward " \t\n\r")
13740 (if (eq (char-before) ?*) (forward-char 1))
13741 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
13742 (beginning-of-line 0)
13743 (org-indent-to-column indent)
13744 (beginning-of-line 2)
13745 (org-indent-to-column indent)
13746 (beginning-of-line 0)
13747 (if hiddenp
13748 (save-excursion
13749 (org-back-to-heading t)
13750 (hide-entry))
13751 (org-flag-drawer t))))
13753 (defun org-set-property (property value)
13754 "In the current entry, set PROPERTY to VALUE.
13755 When called interactively, this will prompt for a property name, offering
13756 completion on existing and default properties. And then it will prompt
13757 for a value, offering completion either on allowed values (via an inherited
13758 xxx_ALL property) or on existing values in other instances of this property
13759 in the current file."
13760 (interactive
13761 (let* ((completion-ignore-case t)
13762 (keys (org-buffer-property-keys nil t t))
13763 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
13764 (prop (if (member prop0 keys)
13765 prop0
13766 (or (cdr (assoc (downcase prop0)
13767 (mapcar (lambda (x) (cons (downcase x) x))
13768 keys)))
13769 prop0)))
13770 (cur (org-entry-get nil prop))
13771 (prompt (concat prop " value"
13772 (if (and cur (string-match "\\S-" cur))
13773 (concat " [" cur "]") "") ": "))
13774 (allowed (org-property-get-allowed-values nil prop 'table))
13775 (existing (mapcar 'list (org-property-values prop)))
13776 (val (if allowed
13777 (org-completing-read prompt allowed nil
13778 (not (get-text-property 0 'org-unrestricted
13779 (caar allowed))))
13780 (let (org-completion-use-ido org-completion-use-iswitchb)
13781 (org-completing-read prompt existing nil nil "" nil cur)))))
13782 (list prop (if (equal val "") cur val))))
13783 (unless (equal (org-entry-get nil property) value)
13784 (org-entry-put nil property value)))
13786 (defun org-delete-property (property)
13787 "In the current entry, delete PROPERTY."
13788 (interactive
13789 (let* ((completion-ignore-case t)
13790 (prop (org-icompleting-read "Property: "
13791 (org-entry-properties nil 'standard))))
13792 (list prop)))
13793 (message "Property %s %s" property
13794 (if (org-entry-delete nil property)
13795 "deleted"
13796 "was not present in the entry")))
13798 (defun org-delete-property-globally (property)
13799 "Remove PROPERTY globally, from all entries."
13800 (interactive
13801 (let* ((completion-ignore-case t)
13802 (prop (org-icompleting-read
13803 "Globally remove property: "
13804 (mapcar 'list (org-buffer-property-keys)))))
13805 (list prop)))
13806 (save-excursion
13807 (save-restriction
13808 (widen)
13809 (goto-char (point-min))
13810 (let ((cnt 0))
13811 (while (re-search-forward
13812 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
13813 nil t)
13814 (setq cnt (1+ cnt))
13815 (replace-match ""))
13816 (message "Property \"%s\" removed from %d entries" property cnt)))))
13818 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
13820 (defun org-compute-property-at-point ()
13821 "Compute the property at point.
13822 This looks for an enclosing column format, extracts the operator and
13823 then applies it to the property in the column format's scope."
13824 (interactive)
13825 (unless (org-at-property-p)
13826 (error "Not at a property"))
13827 (let ((prop (org-match-string-no-properties 2)))
13828 (org-columns-get-format-and-top-level)
13829 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
13830 (error "No operator defined for property %s" prop))
13831 (org-columns-compute prop)))
13833 (defvar org-property-allowed-value-functions nil
13834 "Hook for functions supplying allowed values for a specific property.
13835 The functions must take a single argument, the name of the property, and
13836 return a flat list of allowed values. If \":ETC\" is one of
13837 the values, this means that these values are intended as defaults for
13838 completion, but that other values should be allowed too.
13839 The functions must return nil if they are not responsible for this
13840 property.")
13842 (defun org-property-get-allowed-values (pom property &optional table)
13843 "Get allowed values for the property PROPERTY.
13844 When TABLE is non-nil, return an alist that can directly be used for
13845 completion."
13846 (let (vals)
13847 (cond
13848 ((equal property "TODO")
13849 (setq vals (org-with-point-at pom
13850 (append org-todo-keywords-1 '("")))))
13851 ((equal property "PRIORITY")
13852 (let ((n org-lowest-priority))
13853 (while (>= n org-highest-priority)
13854 (push (char-to-string n) vals)
13855 (setq n (1- n)))))
13856 ((member property org-special-properties))
13857 ((setq vals (run-hook-with-args-until-success
13858 'org-property-allowed-value-functions property)))
13860 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
13861 (when (and vals (string-match "\\S-" vals))
13862 (setq vals (car (read-from-string (concat "(" vals ")"))))
13863 (setq vals (mapcar (lambda (x)
13864 (cond ((stringp x) x)
13865 ((numberp x) (number-to-string x))
13866 ((symbolp x) (symbol-name x))
13867 (t "???")))
13868 vals)))))
13869 (when (member ":ETC" vals)
13870 (setq vals (remove ":ETC" vals))
13871 (org-add-props (car vals) '(org-unrestricted t)))
13872 (if table (mapcar 'list vals) vals)))
13874 (defun org-property-previous-allowed-value (&optional previous)
13875 "Switch to the next allowed value for this property."
13876 (interactive)
13877 (org-property-next-allowed-value t))
13879 (defun org-property-next-allowed-value (&optional previous)
13880 "Switch to the next allowed value for this property."
13881 (interactive)
13882 (unless (org-at-property-p)
13883 (error "Not at a property"))
13884 (let* ((key (match-string 2))
13885 (value (match-string 3))
13886 (allowed (or (org-property-get-allowed-values (point) key)
13887 (and (member value '("[ ]" "[-]" "[X]"))
13888 '("[ ]" "[X]"))))
13889 nval)
13890 (unless allowed
13891 (error "Allowed values for this property have not been defined"))
13892 (if previous (setq allowed (reverse allowed)))
13893 (if (member value allowed)
13894 (setq nval (car (cdr (member value allowed)))))
13895 (setq nval (or nval (car allowed)))
13896 (if (equal nval value)
13897 (error "Only one allowed value for this property"))
13898 (org-at-property-p)
13899 (replace-match (concat " :" key ": " nval) t t)
13900 (org-indent-line-function)
13901 (beginning-of-line 1)
13902 (skip-chars-forward " \t")
13903 (run-hook-with-args 'org-property-changed-functions key nval)))
13905 (defun org-find-olp (path &optional this-buffer)
13906 "Return a marker pointing to the entry at outline path OLP.
13907 If anything goes wrong, throw an error.
13908 You can wrap this call to cathc the error like this:
13910 (condition-case msg
13911 (org-mobile-locate-entry (match-string 4))
13912 (error (nth 1 msg)))
13914 The return value will then be either a string with the error message,
13915 or a marker if everyhing is OK.
13917 If THIS-BUFFER is set, the putline path does not contain a file,
13918 only headings."
13919 (let* ((file (if this-buffer buffer-file-name (pop path)))
13920 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
13921 (level 1)
13922 (lmin 1)
13923 (lmax 1)
13924 limit re end found pos heading cnt)
13925 (unless buffer (error "File not found :%s" file))
13926 (with-current-buffer buffer
13927 (save-excursion
13928 (save-restriction
13929 (widen)
13930 (setq limit (point-max))
13931 (goto-char (point-min))
13932 (while (setq heading (pop path))
13933 (setq re (format org-complex-heading-regexp-format
13934 (regexp-quote heading)))
13935 (setq cnt 0 pos (point))
13936 (while (re-search-forward re end t)
13937 (setq level (- (match-end 1) (match-beginning 1)))
13938 (if (and (>= level lmin) (<= level lmax))
13939 (setq found (match-beginning 0) cnt (1+ cnt))))
13940 (when (= cnt 0) (error "Heading not found on level %d: %s"
13941 lmax heading))
13942 (when (> cnt 1) (error "Heading not unique on level %d: %s"
13943 lmax heading))
13944 (goto-char found)
13945 (setq lmin (1+ level) lmax (+ lmin (if org-odd-levels-only 1 0)))
13946 (setq end (save-excursion (org-end-of-subtree t t))))
13947 (when (org-on-heading-p)
13948 (move-marker (make-marker) (point))))))))
13950 (defun org-find-entry-with-id (ident)
13951 "Locate the entry that contains the ID property with exact value IDENT.
13952 IDENT can be a string, a symbol or a number, this function will search for
13953 the string representation of it.
13954 Return the position where this entry starts, or nil if there is no such entry."
13955 (interactive "sID: ")
13956 (let ((id (cond
13957 ((stringp ident) ident)
13958 ((symbol-name ident) (symbol-name ident))
13959 ((numberp ident) (number-to-string ident))
13960 (t (error "IDENT %s must be a string, symbol or number" ident))))
13961 (case-fold-search nil))
13962 (save-excursion
13963 (save-restriction
13964 (widen)
13965 (goto-char (point-min))
13966 (when (re-search-forward
13967 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
13968 nil t)
13969 (org-back-to-heading t)
13970 (point))))))
13972 ;;;; Timestamps
13974 (defvar org-last-changed-timestamp nil)
13975 (defvar org-last-inserted-timestamp nil
13976 "The last time stamp inserted with `org-insert-time-stamp'.")
13977 (defvar org-time-was-given) ; dynamically scoped parameter
13978 (defvar org-end-time-was-given) ; dynamically scoped parameter
13979 (defvar org-ts-what) ; dynamically scoped parameter
13981 (defun org-time-stamp (arg &optional inactive)
13982 "Prompt for a date/time and insert a time stamp.
13983 If the user specifies a time like HH:MM, or if this command is called
13984 with a prefix argument, the time stamp will contain date and time.
13985 Otherwise, only the date will be included. All parts of a date not
13986 specified by the user will be filled in from the current date/time.
13987 So if you press just return without typing anything, the time stamp
13988 will represent the current date/time. If there is already a timestamp
13989 at the cursor, it will be modified."
13990 (interactive "P")
13991 (let* ((ts nil)
13992 (default-time
13993 ;; Default time is either today, or, when entering a range,
13994 ;; the range start.
13995 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
13996 (save-excursion
13997 (re-search-backward
13998 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
13999 (- (point) 20) t)))
14000 (apply 'encode-time (org-parse-time-string (match-string 1)))
14001 (current-time)))
14002 (default-input (and ts (org-get-compact-tod ts)))
14003 org-time-was-given org-end-time-was-given time)
14004 (cond
14005 ((and (org-at-timestamp-p t)
14006 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14007 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14008 (insert "--")
14009 (setq time (let ((this-command this-command))
14010 (org-read-date arg 'totime nil nil
14011 default-time default-input)))
14012 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14013 ((org-at-timestamp-p t)
14014 (setq time (let ((this-command this-command))
14015 (org-read-date arg 'totime nil nil default-time default-input)))
14016 (when (org-at-timestamp-p t) ; just to get the match data
14017 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14018 (replace-match "")
14019 (setq org-last-changed-timestamp
14020 (org-insert-time-stamp
14021 time (or org-time-was-given arg)
14022 inactive nil nil (list org-end-time-was-given))))
14023 (message "Timestamp updated"))
14025 (setq time (let ((this-command this-command))
14026 (org-read-date arg 'totime nil nil default-time default-input)))
14027 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14028 nil nil (list org-end-time-was-given))))))
14030 ;; FIXME: can we use this for something else, like computing time differences?
14031 (defun org-get-compact-tod (s)
14032 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14033 (let* ((t1 (match-string 1 s))
14034 (h1 (string-to-number (match-string 2 s)))
14035 (m1 (string-to-number (match-string 3 s)))
14036 (t2 (and (match-end 4) (match-string 5 s)))
14037 (h2 (and t2 (string-to-number (match-string 6 s))))
14038 (m2 (and t2 (string-to-number (match-string 7 s))))
14039 dh dm)
14040 (if (not t2)
14042 (setq dh (- h2 h1) dm (- m2 m1))
14043 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14044 (concat t1 "+" (number-to-string dh)
14045 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14047 (defun org-time-stamp-inactive (&optional arg)
14048 "Insert an inactive time stamp.
14049 An inactive time stamp is enclosed in square brackets instead of angle
14050 brackets. It is inactive in the sense that it does not trigger agenda entries,
14051 does not link to the calendar and cannot be changed with the S-cursor keys.
14052 So these are more for recording a certain time/date."
14053 (interactive "P")
14054 (org-time-stamp arg 'inactive))
14056 (defvar org-date-ovl (make-overlay 1 1))
14057 (overlay-put org-date-ovl 'face 'org-warning)
14058 (org-detach-overlay org-date-ovl)
14060 (defvar org-ans1) ; dynamically scoped parameter
14061 (defvar org-ans2) ; dynamically scoped parameter
14063 (defvar org-plain-time-of-day-regexp) ; defined below
14065 (defvar org-overriding-default-time nil) ; dynamically scoped
14066 (defvar org-read-date-overlay nil)
14067 (defvar org-dcst nil) ; dynamically scoped
14068 (defvar org-read-date-history nil)
14069 (defvar org-read-date-final-answer nil)
14071 (defun org-read-date (&optional with-time to-time from-string prompt
14072 default-time default-input)
14073 "Read a date, possibly a time, and make things smooth for the user.
14074 The prompt will suggest to enter an ISO date, but you can also enter anything
14075 which will at least partially be understood by `parse-time-string'.
14076 Unrecognized parts of the date will default to the current day, month, year,
14077 hour and minute. If this command is called to replace a timestamp at point,
14078 of to enter the second timestamp of a range, the default time is taken
14079 from the existing stamp. Furthermore, the command prefers the future,
14080 so if you are giving a date where the year is not given, and the day-month
14081 combination is already past in the current year, it will assume you
14082 mean next year. For details, see the manual. A few examples:
14084 3-2-5 --> 2003-02-05
14085 feb 15 --> currentyear-02-15
14086 2/15 --> currentyear-02-15
14087 sep 12 9 --> 2009-09-12
14088 12:45 --> today 12:45
14089 22 sept 0:34 --> currentyear-09-22 0:34
14090 12 --> currentyear-currentmonth-12
14091 Fri --> nearest Friday (today or later)
14092 etc.
14094 Furthermore you can specify a relative date by giving, as the *first* thing
14095 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14096 change in days weeks, months, years.
14097 With a single plus or minus, the date is relative to today. With a double
14098 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14099 +4d --> four days from today
14100 +4 --> same as above
14101 +2w --> two weeks from today
14102 ++5 --> five days from default date
14104 The function understands only English month and weekday abbreviations,
14105 but this can be configured with the variables `parse-time-months' and
14106 `parse-time-weekdays'.
14108 While prompting, a calendar is popped up - you can also select the
14109 date with the mouse (button 1). The calendar shows a period of three
14110 months. To scroll it to other months, use the keys `>' and `<'.
14111 If you don't like the calendar, turn it off with
14112 \(setq org-read-date-popup-calendar nil)
14114 With optional argument TO-TIME, the date will immediately be converted
14115 to an internal time.
14116 With an optional argument WITH-TIME, the prompt will suggest to also
14117 insert a time. Note that when WITH-TIME is not set, you can still
14118 enter a time, and this function will inform the calling routine about
14119 this change. The calling routine may then choose to change the format
14120 used to insert the time stamp into the buffer to include the time.
14121 With optional argument FROM-STRING, read from this string instead from
14122 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14123 the time/date that is used for everything that is not specified by the
14124 user."
14125 (require 'parse-time)
14126 (let* ((org-time-stamp-rounding-minutes
14127 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14128 (org-dcst org-display-custom-times)
14129 (ct (org-current-time))
14130 (def (or org-overriding-default-time default-time ct))
14131 (defdecode (decode-time def))
14132 (dummy (progn
14133 (when (< (nth 2 defdecode) org-extend-today-until)
14134 (setcar (nthcdr 2 defdecode) -1)
14135 (setcar (nthcdr 1 defdecode) 59)
14136 (setq def (apply 'encode-time defdecode)
14137 defdecode (decode-time def)))))
14138 (calendar-frame-setup nil)
14139 (calendar-setup nil)
14140 (calendar-move-hook nil)
14141 (calendar-view-diary-initially-flag nil)
14142 (calendar-view-holidays-initially-flag nil)
14143 (timestr (format-time-string
14144 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14145 (prompt (concat (if prompt (concat prompt " ") "")
14146 (format "Date+time [%s]: " timestr)))
14147 ans (org-ans0 "") org-ans1 org-ans2 final)
14149 (cond
14150 (from-string (setq ans from-string))
14151 (org-read-date-popup-calendar
14152 (save-excursion
14153 (save-window-excursion
14154 (calendar)
14155 (calendar-forward-day (- (time-to-days def)
14156 (calendar-absolute-from-gregorian
14157 (calendar-current-date))))
14158 (org-eval-in-calendar nil t)
14159 (let* ((old-map (current-local-map))
14160 (map (copy-keymap calendar-mode-map))
14161 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14162 (org-defkey map (kbd "RET") 'org-calendar-select)
14163 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14164 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14165 (org-defkey minibuffer-local-map [(meta shift left)]
14166 (lambda () (interactive)
14167 (org-eval-in-calendar '(calendar-backward-month 1))))
14168 (org-defkey minibuffer-local-map [(meta shift right)]
14169 (lambda () (interactive)
14170 (org-eval-in-calendar '(calendar-forward-month 1))))
14171 (org-defkey minibuffer-local-map [(meta shift up)]
14172 (lambda () (interactive)
14173 (org-eval-in-calendar '(calendar-backward-year 1))))
14174 (org-defkey minibuffer-local-map [(meta shift down)]
14175 (lambda () (interactive)
14176 (org-eval-in-calendar '(calendar-forward-year 1))))
14177 (org-defkey minibuffer-local-map [?\e (shift left)]
14178 (lambda () (interactive)
14179 (org-eval-in-calendar '(calendar-backward-month 1))))
14180 (org-defkey minibuffer-local-map [?\e (shift right)]
14181 (lambda () (interactive)
14182 (org-eval-in-calendar '(calendar-forward-month 1))))
14183 (org-defkey minibuffer-local-map [?\e (shift up)]
14184 (lambda () (interactive)
14185 (org-eval-in-calendar '(calendar-backward-year 1))))
14186 (org-defkey minibuffer-local-map [?\e (shift down)]
14187 (lambda () (interactive)
14188 (org-eval-in-calendar '(calendar-forward-year 1))))
14189 (org-defkey minibuffer-local-map [(shift up)]
14190 (lambda () (interactive)
14191 (org-eval-in-calendar '(calendar-backward-week 1))))
14192 (org-defkey minibuffer-local-map [(shift down)]
14193 (lambda () (interactive)
14194 (org-eval-in-calendar '(calendar-forward-week 1))))
14195 (org-defkey minibuffer-local-map [(shift left)]
14196 (lambda () (interactive)
14197 (org-eval-in-calendar '(calendar-backward-day 1))))
14198 (org-defkey minibuffer-local-map [(shift right)]
14199 (lambda () (interactive)
14200 (org-eval-in-calendar '(calendar-forward-day 1))))
14201 (org-defkey minibuffer-local-map ">"
14202 (lambda () (interactive)
14203 (org-eval-in-calendar '(scroll-calendar-left 1))))
14204 (org-defkey minibuffer-local-map "<"
14205 (lambda () (interactive)
14206 (org-eval-in-calendar '(scroll-calendar-right 1))))
14207 (org-defkey minibuffer-local-map "\C-v"
14208 (lambda () (interactive)
14209 (org-eval-in-calendar
14210 '(calendar-scroll-left-three-months 1))))
14211 (org-defkey minibuffer-local-map "\M-v"
14212 (lambda () (interactive)
14213 (org-eval-in-calendar
14214 '(calendar-scroll-right-three-months 1))))
14215 (run-hooks 'org-read-date-minibuffer-setup-hook)
14216 (unwind-protect
14217 (progn
14218 (use-local-map map)
14219 (add-hook 'post-command-hook 'org-read-date-display)
14220 (setq org-ans0 (read-string prompt default-input
14221 'org-read-date-history nil))
14222 ;; org-ans0: from prompt
14223 ;; org-ans1: from mouse click
14224 ;; org-ans2: from calendar motion
14225 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14226 (remove-hook 'post-command-hook 'org-read-date-display)
14227 (use-local-map old-map)
14228 (when org-read-date-overlay
14229 (delete-overlay org-read-date-overlay)
14230 (setq org-read-date-overlay nil)))))))
14232 (t ; Naked prompt only
14233 (unwind-protect
14234 (setq ans (read-string prompt default-input
14235 'org-read-date-history timestr))
14236 (when org-read-date-overlay
14237 (delete-overlay org-read-date-overlay)
14238 (setq org-read-date-overlay nil)))))
14240 (setq final (org-read-date-analyze ans def defdecode))
14241 (setq org-read-date-final-answer ans)
14243 (if to-time
14244 (apply 'encode-time final)
14245 (if (and (boundp 'org-time-was-given) org-time-was-given)
14246 (format "%04d-%02d-%02d %02d:%02d"
14247 (nth 5 final) (nth 4 final) (nth 3 final)
14248 (nth 2 final) (nth 1 final))
14249 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
14251 (defvar def)
14252 (defvar defdecode)
14253 (defvar with-time)
14254 (defvar org-read-date-analyze-futurep nil)
14255 (defun org-read-date-display ()
14256 "Display the current date prompt interpretation in the minibuffer."
14257 (when org-read-date-display-live
14258 (when org-read-date-overlay
14259 (delete-overlay org-read-date-overlay))
14260 (let ((p (point)))
14261 (end-of-line 1)
14262 (while (not (equal (buffer-substring
14263 (max (point-min) (- (point) 4)) (point))
14264 " "))
14265 (insert " "))
14266 (goto-char p))
14267 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
14268 " " (or org-ans1 org-ans2)))
14269 (org-end-time-was-given nil)
14270 (f (org-read-date-analyze ans def defdecode))
14271 (fmts (if org-dcst
14272 org-time-stamp-custom-formats
14273 org-time-stamp-formats))
14274 (fmt (if (or with-time
14275 (and (boundp 'org-time-was-given) org-time-was-given))
14276 (cdr fmts)
14277 (car fmts)))
14278 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
14279 (when (and org-end-time-was-given
14280 (string-match org-plain-time-of-day-regexp txt))
14281 (setq txt (concat (substring txt 0 (match-end 0)) "-"
14282 org-end-time-was-given
14283 (substring txt (match-end 0)))))
14284 (when org-read-date-analyze-futurep
14285 (setq txt (concat txt " (=>F)")))
14286 (setq org-read-date-overlay
14287 (make-overlay (1- (point-at-eol)) (point-at-eol)))
14288 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
14290 (defun org-read-date-analyze (ans def defdecode)
14291 "Analyse the combined answer of the date prompt."
14292 ;; FIXME: cleanup and comment
14293 (let ((nowdecode (decode-time (current-time)))
14294 delta deltan deltaw deltadef year month day
14295 hour minute second wday pm h2 m2 tl wday1
14296 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
14297 (setq org-read-date-analyze-futurep nil)
14298 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
14299 (setq ans "+0"))
14301 (when (setq delta (org-read-date-get-relative ans (current-time) def))
14302 (setq ans (replace-match "" t t ans)
14303 deltan (car delta)
14304 deltaw (nth 1 delta)
14305 deltadef (nth 2 delta)))
14307 ;; Check if there is an iso week date in there
14308 ;; If yes, store the info and postpone interpreting it until the rest
14309 ;; of the parsing is done
14310 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
14311 (setq iso-year (if (match-end 1)
14312 (org-small-year-to-year
14313 (string-to-number (match-string 1 ans))))
14314 iso-weekday (if (match-end 3)
14315 (string-to-number (match-string 3 ans)))
14316 iso-week (string-to-number (match-string 2 ans)))
14317 (setq ans (replace-match "" t t ans)))
14319 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
14320 (when (string-match
14321 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
14322 (setq year (if (match-end 2)
14323 (string-to-number (match-string 2 ans))
14324 (progn (setq kill-year t)
14325 (string-to-number (format-time-string "%Y"))))
14326 month (string-to-number (match-string 3 ans))
14327 day (string-to-number (match-string 4 ans)))
14328 (if (< year 100) (setq year (+ 2000 year)))
14329 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14330 t nil ans)))
14331 ;; Help matching american dates, like 5/30 or 5/30/7
14332 (when (string-match
14333 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
14334 (setq year (if (match-end 4)
14335 (string-to-number (match-string 4 ans))
14336 (progn (setq kill-year t)
14337 (string-to-number (format-time-string "%Y"))))
14338 month (string-to-number (match-string 1 ans))
14339 day (string-to-number (match-string 2 ans)))
14340 (if (< year 100) (setq year (+ 2000 year)))
14341 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14342 t nil ans)))
14343 ;; Help matching am/pm times, because `parse-time-string' does not do that.
14344 ;; If there is a time with am/pm, and *no* time without it, we convert
14345 ;; so that matching will be successful.
14346 (loop for i from 1 to 2 do ; twice, for end time as well
14347 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
14348 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
14349 (setq hour (string-to-number (match-string 1 ans))
14350 minute (if (match-end 3)
14351 (string-to-number (match-string 3 ans))
14353 pm (equal ?p
14354 (string-to-char (downcase (match-string 4 ans)))))
14355 (if (and (= hour 12) (not pm))
14356 (setq hour 0)
14357 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
14358 (setq ans (replace-match (format "%02d:%02d" hour minute)
14359 t t ans))))
14361 ;; Check if a time range is given as a duration
14362 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
14363 (setq hour (string-to-number (match-string 1 ans))
14364 h2 (+ hour (string-to-number (match-string 3 ans)))
14365 minute (string-to-number (match-string 2 ans))
14366 m2 (+ minute (if (match-end 5) (string-to-number
14367 (match-string 5 ans))0)))
14368 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
14369 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
14370 t t ans)))
14372 ;; Check if there is a time range
14373 (when (boundp 'org-end-time-was-given)
14374 (setq org-time-was-given nil)
14375 (when (and (string-match org-plain-time-of-day-regexp ans)
14376 (match-end 8))
14377 (setq org-end-time-was-given (match-string 8 ans))
14378 (setq ans (concat (substring ans 0 (match-beginning 7))
14379 (substring ans (match-end 7))))))
14381 (setq tl (parse-time-string ans)
14382 day (or (nth 3 tl) (nth 3 defdecode))
14383 month (or (nth 4 tl)
14384 (if (and org-read-date-prefer-future
14385 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
14386 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
14387 (nth 4 defdecode)))
14388 year (or (and (not kill-year) (nth 5 tl))
14389 (if (and org-read-date-prefer-future
14390 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
14391 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
14392 (nth 5 defdecode)))
14393 hour (or (nth 2 tl) (nth 2 defdecode))
14394 minute (or (nth 1 tl) (nth 1 defdecode))
14395 second (or (nth 0 tl) 0)
14396 wday (nth 6 tl))
14398 (when (and (eq org-read-date-prefer-future 'time)
14399 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
14400 (equal day (nth 3 nowdecode))
14401 (equal month (nth 4 nowdecode))
14402 (equal year (nth 5 nowdecode))
14403 (nth 2 tl)
14404 (or (< (nth 2 tl) (nth 2 nowdecode))
14405 (and (= (nth 2 tl) (nth 2 nowdecode))
14406 (nth 1 tl)
14407 (< (nth 1 tl) (nth 1 nowdecode)))))
14408 (setq day (1+ day)
14409 futurep t))
14411 ;; Special date definitions below
14412 (cond
14413 (iso-week
14414 ;; There was an iso week
14415 (require 'cal-iso)
14416 (setq futurep nil)
14417 (setq year (or iso-year year)
14418 day (or iso-weekday wday 1)
14419 wday nil ; to make sure that the trigger below does not match
14420 iso-date (calendar-gregorian-from-absolute
14421 (calendar-absolute-from-iso
14422 (list iso-week day year))))
14423 ; FIXME: Should we also push ISO weeks into the future?
14424 ; (when (and org-read-date-prefer-future
14425 ; (not iso-year)
14426 ; (< (calendar-absolute-from-gregorian iso-date)
14427 ; (time-to-days (current-time))))
14428 ; (setq year (1+ year)
14429 ; iso-date (calendar-gregorian-from-absolute
14430 ; (calendar-absolute-from-iso
14431 ; (list iso-week day year)))))
14432 (setq month (car iso-date)
14433 year (nth 2 iso-date)
14434 day (nth 1 iso-date)))
14435 (deltan
14436 (setq futurep nil)
14437 (unless deltadef
14438 (let ((now (decode-time (current-time))))
14439 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
14440 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
14441 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
14442 ((equal deltaw "m") (setq month (+ month deltan)))
14443 ((equal deltaw "y") (setq year (+ year deltan)))))
14444 ((and wday (not (nth 3 tl)))
14445 (setq futurep nil)
14446 ;; Weekday was given, but no day, so pick that day in the week
14447 ;; on or after the derived date.
14448 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
14449 (unless (equal wday wday1)
14450 (setq day (+ day (% (- wday wday1 -7) 7))))))
14451 (if (and (boundp 'org-time-was-given)
14452 (nth 2 tl))
14453 (setq org-time-was-given t))
14454 (if (< year 100) (setq year (+ 2000 year)))
14455 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
14456 (setq org-read-date-analyze-futurep futurep)
14457 (list second minute hour day month year)))
14459 (defvar parse-time-weekdays)
14461 (defun org-read-date-get-relative (s today default)
14462 "Check string S for special relative date string.
14463 TODAY and DEFAULT are internal times, for today and for a default.
14464 Return shift list (N what def-flag)
14465 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
14466 N is the number of WHATs to shift.
14467 DEF-FLAG is t when a double ++ or -- indicates shift relative to
14468 the DEFAULT date rather than TODAY."
14469 (when (and
14470 (string-match
14471 (concat
14472 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
14473 "\\([0-9]+\\)?"
14474 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
14475 "\\([ \t]\\|$\\)") s)
14476 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
14477 (let* ((dir (if (> (match-end 1) (match-beginning 1))
14478 (string-to-char (substring (match-string 1 s) -1))
14479 ?+))
14480 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
14481 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
14482 (what (if (match-end 3) (match-string 3 s) "d"))
14483 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
14484 (date (if rel default today))
14485 (wday (nth 6 (decode-time date)))
14486 delta)
14487 (if wday1
14488 (progn
14489 (setq delta (mod (+ 7 (- wday1 wday)) 7))
14490 (if (= dir ?-) (setq delta (- delta 7)))
14491 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
14492 (list delta "d" rel))
14493 (list (* n (if (= dir ?-) -1 1)) what rel)))))
14495 (defun org-order-calendar-date-args (arg1 arg2 arg3)
14496 "Turn a user-specified date into the internal representation.
14497 The internal representation needed by the calendar is (month day year).
14498 This is a wrapper to handle the brain-dead convention in calendar that
14499 user function argument order change dependent on argument order."
14500 (if (boundp 'calendar-date-style)
14501 (cond
14502 ((eq calendar-date-style 'american)
14503 (list arg1 arg2 arg3))
14504 ((eq calendar-date-style 'european)
14505 (list arg2 arg1 arg3))
14506 ((eq calendar-date-style 'iso)
14507 (list arg2 arg3 arg1)))
14508 (if (org-bound-and-true-p european-calendar-style)
14509 (list arg2 arg1 arg3)
14510 (list arg1 arg2 arg3))))
14512 (defun org-eval-in-calendar (form &optional keepdate)
14513 "Eval FORM in the calendar window and return to current window.
14514 Also, store the cursor date in variable org-ans2."
14515 (let ((sf (selected-frame))
14516 (sw (selected-window)))
14517 (select-window (get-buffer-window "*Calendar*" t))
14518 (eval form)
14519 (when (and (not keepdate) (calendar-cursor-to-date))
14520 (let* ((date (calendar-cursor-to-date))
14521 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14522 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
14523 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
14524 (select-window sw)
14525 (org-select-frame-set-input-focus sf)))
14527 (defun org-calendar-select ()
14528 "Return to `org-read-date' with the date currently selected.
14529 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14530 (interactive)
14531 (when (calendar-cursor-to-date)
14532 (let* ((date (calendar-cursor-to-date))
14533 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14534 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14535 (if (active-minibuffer-window) (exit-minibuffer))))
14537 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
14538 "Insert a date stamp for the date given by the internal TIME.
14539 WITH-HM means use the stamp format that includes the time of the day.
14540 INACTIVE means use square brackets instead of angular ones, so that the
14541 stamp will not contribute to the agenda.
14542 PRE and POST are optional strings to be inserted before and after the
14543 stamp.
14544 The command returns the inserted time stamp."
14545 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
14546 stamp)
14547 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
14548 (insert-before-markers (or pre ""))
14549 (insert-before-markers (setq stamp (format-time-string fmt time)))
14550 (when (listp extra)
14551 (setq extra (car extra))
14552 (if (and (stringp extra)
14553 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
14554 (setq extra (format "-%02d:%02d"
14555 (string-to-number (match-string 1 extra))
14556 (string-to-number (match-string 2 extra))))
14557 (setq extra nil)))
14558 (when extra
14559 (backward-char 1)
14560 (insert-before-markers extra)
14561 (forward-char 1))
14562 (insert-before-markers (or post ""))
14563 (setq org-last-inserted-timestamp stamp)))
14565 (defun org-toggle-time-stamp-overlays ()
14566 "Toggle the use of custom time stamp formats."
14567 (interactive)
14568 (setq org-display-custom-times (not org-display-custom-times))
14569 (unless org-display-custom-times
14570 (let ((p (point-min)) (bmp (buffer-modified-p)))
14571 (while (setq p (next-single-property-change p 'display))
14572 (if (and (get-text-property p 'display)
14573 (eq (get-text-property p 'face) 'org-date))
14574 (remove-text-properties
14575 p (setq p (next-single-property-change p 'display))
14576 '(display t))))
14577 (set-buffer-modified-p bmp)))
14578 (if (featurep 'xemacs)
14579 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
14580 (org-restart-font-lock)
14581 (setq org-table-may-need-update t)
14582 (if org-display-custom-times
14583 (message "Time stamps are overlayed with custom format")
14584 (message "Time stamp overlays removed")))
14586 (defun org-display-custom-time (beg end)
14587 "Overlay modified time stamp format over timestamp between BEG and END."
14588 (let* ((ts (buffer-substring beg end))
14589 t1 w1 with-hm tf time str w2 (off 0))
14590 (save-match-data
14591 (setq t1 (org-parse-time-string ts t))
14592 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
14593 (setq off (- (match-end 0) (match-beginning 0)))))
14594 (setq end (- end off))
14595 (setq w1 (- end beg)
14596 with-hm (and (nth 1 t1) (nth 2 t1))
14597 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
14598 time (org-fix-decoded-time t1)
14599 str (org-add-props
14600 (format-time-string
14601 (substring tf 1 -1) (apply 'encode-time time))
14602 nil 'mouse-face 'highlight)
14603 w2 (length str))
14604 (if (not (= w2 w1))
14605 (add-text-properties (1+ beg) (+ 2 beg)
14606 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
14607 (if (featurep 'xemacs)
14608 (progn
14609 (put-text-property beg end 'invisible t)
14610 (put-text-property beg end 'end-glyph (make-glyph str)))
14611 (put-text-property beg end 'display str))))
14613 (defun org-translate-time (string)
14614 "Translate all timestamps in STRING to custom format.
14615 But do this only if the variable `org-display-custom-times' is set."
14616 (when org-display-custom-times
14617 (save-match-data
14618 (let* ((start 0)
14619 (re org-ts-regexp-both)
14620 t1 with-hm inactive tf time str beg end)
14621 (while (setq start (string-match re string start))
14622 (setq beg (match-beginning 0)
14623 end (match-end 0)
14624 t1 (save-match-data
14625 (org-parse-time-string (substring string beg end) t))
14626 with-hm (and (nth 1 t1) (nth 2 t1))
14627 inactive (equal (substring string beg (1+ beg)) "[")
14628 tf (funcall (if with-hm 'cdr 'car)
14629 org-time-stamp-custom-formats)
14630 time (org-fix-decoded-time t1)
14631 str (format-time-string
14632 (concat
14633 (if inactive "[" "<") (substring tf 1 -1)
14634 (if inactive "]" ">"))
14635 (apply 'encode-time time))
14636 string (replace-match str t t string)
14637 start (+ start (length str)))))))
14638 string)
14640 (defun org-fix-decoded-time (time)
14641 "Set 0 instead of nil for the first 6 elements of time.
14642 Don't touch the rest."
14643 (let ((n 0))
14644 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
14646 (defun org-days-to-time (timestamp-string)
14647 "Difference between TIMESTAMP-STRING and now in days."
14648 (- (time-to-days (org-time-string-to-time timestamp-string))
14649 (time-to-days (current-time))))
14651 (defun org-deadline-close (timestamp-string &optional ndays)
14652 "Is the time in TIMESTAMP-STRING close to the current date?"
14653 (setq ndays (or ndays (org-get-wdays timestamp-string)))
14654 (and (< (org-days-to-time timestamp-string) ndays)
14655 (not (org-entry-is-done-p))))
14657 (defun org-get-wdays (ts)
14658 "Get the deadline lead time appropriate for timestring TS."
14659 (cond
14660 ((<= org-deadline-warning-days 0)
14661 ;; 0 or negative, enforce this value no matter what
14662 (- org-deadline-warning-days))
14663 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
14664 ;; lead time is specified.
14665 (floor (* (string-to-number (match-string 1 ts))
14666 (cdr (assoc (match-string 2 ts)
14667 '(("d" . 1) ("w" . 7)
14668 ("m" . 30.4) ("y" . 365.25)))))))
14669 ;; go for the default.
14670 (t org-deadline-warning-days)))
14672 (defun org-calendar-select-mouse (ev)
14673 "Return to `org-read-date' with the date currently selected.
14674 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14675 (interactive "e")
14676 (mouse-set-point ev)
14677 (when (calendar-cursor-to-date)
14678 (let* ((date (calendar-cursor-to-date))
14679 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14680 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14681 (if (active-minibuffer-window) (exit-minibuffer))))
14683 (defun org-check-deadlines (ndays)
14684 "Check if there are any deadlines due or past due.
14685 A deadline is considered due if it happens within `org-deadline-warning-days'
14686 days from today's date. If the deadline appears in an entry marked DONE,
14687 it is not shown. The prefix arg NDAYS can be used to test that many
14688 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
14689 (interactive "P")
14690 (let* ((org-warn-days
14691 (cond
14692 ((equal ndays '(4)) 100000)
14693 (ndays (prefix-numeric-value ndays))
14694 (t (abs org-deadline-warning-days))))
14695 (case-fold-search nil)
14696 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
14697 (callback
14698 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
14700 (message "%d deadlines past-due or due within %d days"
14701 (org-occur regexp nil callback)
14702 org-warn-days)))
14704 (defun org-check-before-date (date)
14705 "Check if there are deadlines or scheduled entries before DATE."
14706 (interactive (list (org-read-date)))
14707 (let ((case-fold-search nil)
14708 (regexp (concat "\\<\\(" org-deadline-string
14709 "\\|" org-scheduled-string
14710 "\\) *<\\([^>]+\\)>"))
14711 (callback
14712 (lambda () (time-less-p
14713 (org-time-string-to-time (match-string 2))
14714 (org-time-string-to-time date)))))
14715 (message "%d entries before %s"
14716 (org-occur regexp nil callback) date)))
14718 (defun org-check-after-date (date)
14719 "Check if there are deadlines or scheduled entries after DATE."
14720 (interactive (list (org-read-date)))
14721 (let ((case-fold-search nil)
14722 (regexp (concat "\\<\\(" org-deadline-string
14723 "\\|" org-scheduled-string
14724 "\\) *<\\([^>]+\\)>"))
14725 (callback
14726 (lambda () (not
14727 (time-less-p
14728 (org-time-string-to-time (match-string 2))
14729 (org-time-string-to-time date))))))
14730 (message "%d entries after %s"
14731 (org-occur regexp nil callback) date)))
14733 (defun org-evaluate-time-range (&optional to-buffer)
14734 "Evaluate a time range by computing the difference between start and end.
14735 Normally the result is just printed in the echo area, but with prefix arg
14736 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
14737 If the time range is actually in a table, the result is inserted into the
14738 next column.
14739 For time difference computation, a year is assumed to be exactly 365
14740 days in order to avoid rounding problems."
14741 (interactive "P")
14743 (org-clock-update-time-maybe)
14744 (save-excursion
14745 (unless (org-at-date-range-p t)
14746 (goto-char (point-at-bol))
14747 (re-search-forward org-tr-regexp-both (point-at-eol) t))
14748 (if (not (org-at-date-range-p t))
14749 (error "Not at a time-stamp range, and none found in current line")))
14750 (let* ((ts1 (match-string 1))
14751 (ts2 (match-string 2))
14752 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
14753 (match-end (match-end 0))
14754 (time1 (org-time-string-to-time ts1))
14755 (time2 (org-time-string-to-time ts2))
14756 (t1 (org-float-time time1))
14757 (t2 (org-float-time time2))
14758 (diff (abs (- t2 t1)))
14759 (negative (< (- t2 t1) 0))
14760 ;; (ys (floor (* 365 24 60 60)))
14761 (ds (* 24 60 60))
14762 (hs (* 60 60))
14763 (fy "%dy %dd %02d:%02d")
14764 (fy1 "%dy %dd")
14765 (fd "%dd %02d:%02d")
14766 (fd1 "%dd")
14767 (fh "%02d:%02d")
14768 y d h m align)
14769 (if havetime
14770 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14772 d (floor (/ diff ds)) diff (mod diff ds)
14773 h (floor (/ diff hs)) diff (mod diff hs)
14774 m (floor (/ diff 60)))
14775 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14777 d (floor (+ (/ diff ds) 0.5))
14778 h 0 m 0))
14779 (if (not to-buffer)
14780 (message "%s" (org-make-tdiff-string y d h m))
14781 (if (org-at-table-p)
14782 (progn
14783 (goto-char match-end)
14784 (setq align t)
14785 (and (looking-at " *|") (goto-char (match-end 0))))
14786 (goto-char match-end))
14787 (if (looking-at
14788 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
14789 (replace-match ""))
14790 (if negative (insert " -"))
14791 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
14792 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
14793 (insert " " (format fh h m))))
14794 (if align (org-table-align))
14795 (message "Time difference inserted")))))
14797 (defun org-make-tdiff-string (y d h m)
14798 (let ((fmt "")
14799 (l nil))
14800 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
14801 l (push y l)))
14802 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
14803 l (push d l)))
14804 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
14805 l (push h l)))
14806 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
14807 l (push m l)))
14808 (apply 'format fmt (nreverse l))))
14810 (defun org-time-string-to-time (s)
14811 (apply 'encode-time (org-parse-time-string s)))
14812 (defun org-time-string-to-seconds (s)
14813 (org-float-time (org-time-string-to-time s)))
14815 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
14816 "Convert a time stamp to an absolute day number.
14817 If there is a specifyer for a cyclic time stamp, get the closest date to
14818 DAYNR.
14819 PREFER and SHOW-ALL are passed through to `org-closest-date'.
14820 the variable date is bound by the calendar when this is called."
14821 (cond
14822 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
14823 (if (org-diary-sexp-entry (match-string 1 s) "" date)
14824 daynr
14825 (+ daynr 1000)))
14826 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
14827 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
14828 (time-to-days (current-time))) (match-string 0 s)
14829 prefer show-all))
14830 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
14832 (defun org-days-to-iso-week (days)
14833 "Return the iso week number."
14834 (require 'cal-iso)
14835 (car (calendar-iso-from-absolute days)))
14837 (defun org-small-year-to-year (year)
14838 "Convert 2-digit years into 4-digit years.
14839 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
14840 The year 2000 cannot be abbreviated. Any year larger than 99
14841 is returned unchanged."
14842 (if (< year 38)
14843 (setq year (+ 2000 year))
14844 (if (< year 100)
14845 (setq year (+ 1900 year))))
14846 year)
14848 (defun org-time-from-absolute (d)
14849 "Return the time corresponding to date D.
14850 D may be an absolute day number, or a calendar-type list (month day year)."
14851 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
14852 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
14854 (defun org-calendar-holiday ()
14855 "List of holidays, for Diary display in Org-mode."
14856 (require 'holidays)
14857 (let ((hl (funcall
14858 (if (fboundp 'calendar-check-holidays)
14859 'calendar-check-holidays 'check-calendar-holidays) date)))
14860 (if hl (mapconcat 'identity hl "; "))))
14862 (defun org-diary-sexp-entry (sexp entry date)
14863 "Process a SEXP diary ENTRY for DATE."
14864 (require 'diary-lib)
14865 (let ((result (if calendar-debug-sexp
14866 (let ((stack-trace-on-error t))
14867 (eval (car (read-from-string sexp))))
14868 (condition-case nil
14869 (eval (car (read-from-string sexp)))
14870 (error
14871 (beep)
14872 (message "Bad sexp at line %d in %s: %s"
14873 (org-current-line)
14874 (buffer-file-name) sexp)
14875 (sleep-for 2))))))
14876 (cond ((stringp result) result)
14877 ((and (consp result)
14878 (stringp (cdr result))) (cdr result))
14879 (result entry)
14880 (t nil))))
14882 (defun org-diary-to-ical-string (frombuf)
14883 "Get iCalendar entries from diary entries in buffer FROMBUF.
14884 This uses the icalendar.el library."
14885 (let* ((tmpdir (if (featurep 'xemacs)
14886 (temp-directory)
14887 temporary-file-directory))
14888 (tmpfile (make-temp-name
14889 (expand-file-name "orgics" tmpdir)))
14890 buf rtn b e)
14891 (with-current-buffer frombuf
14892 (icalendar-export-region (point-min) (point-max) tmpfile)
14893 (setq buf (find-buffer-visiting tmpfile))
14894 (set-buffer buf)
14895 (goto-char (point-min))
14896 (if (re-search-forward "^BEGIN:VEVENT" nil t)
14897 (setq b (match-beginning 0)))
14898 (goto-char (point-max))
14899 (if (re-search-backward "^END:VEVENT" nil t)
14900 (setq e (match-end 0)))
14901 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
14902 (kill-buffer buf)
14903 (delete-file tmpfile)
14904 rtn))
14906 (defun org-closest-date (start current change prefer show-all)
14907 "Find the date closest to CURRENT that is consistent with START and CHANGE.
14908 When PREFER is `past' return a date that is either CURRENT or past.
14909 When PREFER is `future', return a date that is either CURRENT or future.
14910 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
14911 ;; Make the proper lists from the dates
14912 (catch 'exit
14913 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
14914 dn dw sday cday n1 n2 n0
14915 d m y y1 y2 date1 date2 nmonths nm ny m2)
14917 (setq start (org-date-to-gregorian start)
14918 current (org-date-to-gregorian
14919 (if show-all
14920 current
14921 (time-to-days (current-time))))
14922 sday (calendar-absolute-from-gregorian start)
14923 cday (calendar-absolute-from-gregorian current))
14925 (if (<= cday sday) (throw 'exit sday))
14927 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
14928 (setq dn (string-to-number (match-string 1 change))
14929 dw (cdr (assoc (match-string 2 change) a1)))
14930 (error "Invalid change specifyer: %s" change))
14931 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
14932 (cond
14933 ((eq dw 'day)
14934 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
14935 n2 (+ n1 dn)))
14936 ((eq dw 'year)
14937 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
14938 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
14939 (setq date1 (list m d y1)
14940 n1 (calendar-absolute-from-gregorian date1)
14941 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
14942 n2 (calendar-absolute-from-gregorian date2)))
14943 ((eq dw 'month)
14944 ;; approx number of month between the two dates
14945 (setq nmonths (floor (/ (- cday sday) 30.436875)))
14946 ;; How often does dn fit in there?
14947 (setq d (nth 1 start) m (car start) y (nth 2 start)
14948 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
14949 m (+ m nm)
14950 ny (floor (/ m 12))
14951 y (+ y ny)
14952 m (- m (* ny 12)))
14953 (while (> m 12) (setq m (- m 12) y (1+ y)))
14954 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
14955 (setq m2 (+ m dn) y2 y)
14956 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14957 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
14958 (while (<= n2 cday)
14959 (setq n1 n2 m m2 y y2)
14960 (setq m2 (+ m dn) y2 y)
14961 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14962 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
14963 ;; Make sure n1 is the earlier date
14964 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
14965 (if show-all
14966 (cond
14967 ((eq prefer 'past) (if (= cday n2) n2 n1))
14968 ((eq prefer 'future) (if (= cday n1) n1 n2))
14969 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
14970 (cond
14971 ((eq prefer 'past) (if (= cday n2) n2 n1))
14972 ((eq prefer 'future) (if (= cday n1) n1 n2))
14973 (t (if (= cday n1) n1 n2)))))))
14975 (defun org-date-to-gregorian (date)
14976 "Turn any specification of DATE into a gregorian date for the calendar."
14977 (cond ((integerp date) (calendar-gregorian-from-absolute date))
14978 ((and (listp date) (= (length date) 3)) date)
14979 ((stringp date)
14980 (setq date (org-parse-time-string date))
14981 (list (nth 4 date) (nth 3 date) (nth 5 date)))
14982 ((listp date)
14983 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
14985 (defun org-parse-time-string (s &optional nodefault)
14986 "Parse the standard Org-mode time string.
14987 This should be a lot faster than the normal `parse-time-string'.
14988 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
14989 hour and minute fields will be nil if not given."
14990 (if (string-match org-ts-regexp0 s)
14991 (list 0
14992 (if (or (match-beginning 8) (not nodefault))
14993 (string-to-number (or (match-string 8 s) "0")))
14994 (if (or (match-beginning 7) (not nodefault))
14995 (string-to-number (or (match-string 7 s) "0")))
14996 (string-to-number (match-string 4 s))
14997 (string-to-number (match-string 3 s))
14998 (string-to-number (match-string 2 s))
14999 nil nil nil)
15000 (error "Not a standard Org-mode time string: %s" s)))
15002 (defun org-timestamp-up (&optional arg)
15003 "Increase the date item at the cursor by one.
15004 If the cursor is on the year, change the year. If it is on the month or
15005 the day, change that.
15006 With prefix ARG, change by that many units."
15007 (interactive "p")
15008 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15010 (defun org-timestamp-down (&optional arg)
15011 "Decrease the date item at the cursor by one.
15012 If the cursor is on the year, change the year. If it is on the month or
15013 the day, change that.
15014 With prefix ARG, change by that many units."
15015 (interactive "p")
15016 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15018 (defun org-timestamp-up-day (&optional arg)
15019 "Increase the date in the time stamp by one day.
15020 With prefix ARG, change that many days."
15021 (interactive "p")
15022 (if (and (not (org-at-timestamp-p t))
15023 (org-on-heading-p))
15024 (org-todo 'up)
15025 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15027 (defun org-timestamp-down-day (&optional arg)
15028 "Decrease the date in the time stamp by one day.
15029 With prefix ARG, change that many days."
15030 (interactive "p")
15031 (if (and (not (org-at-timestamp-p t))
15032 (org-on-heading-p))
15033 (org-todo 'down)
15034 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15036 (defun org-at-timestamp-p (&optional inactive-ok)
15037 "Determine if the cursor is in or at a timestamp."
15038 (interactive)
15039 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15040 (pos (point))
15041 (ans (or (looking-at tsr)
15042 (save-excursion
15043 (skip-chars-backward "^[<\n\r\t")
15044 (if (> (point) (point-min)) (backward-char 1))
15045 (and (looking-at tsr)
15046 (> (- (match-end 0) pos) -1))))))
15047 (and ans
15048 (boundp 'org-ts-what)
15049 (setq org-ts-what
15050 (cond
15051 ((= pos (match-beginning 0)) 'bracket)
15052 ((= pos (1- (match-end 0))) 'bracket)
15053 ((org-pos-in-match-range pos 2) 'year)
15054 ((org-pos-in-match-range pos 3) 'month)
15055 ((org-pos-in-match-range pos 7) 'hour)
15056 ((org-pos-in-match-range pos 8) 'minute)
15057 ((or (org-pos-in-match-range pos 4)
15058 (org-pos-in-match-range pos 5)) 'day)
15059 ((and (> pos (or (match-end 8) (match-end 5)))
15060 (< pos (match-end 0)))
15061 (- pos (or (match-end 8) (match-end 5))))
15062 (t 'day))))
15063 ans))
15065 (defun org-toggle-timestamp-type ()
15066 "Toggle the type (<active> or [inactive]) of a time stamp."
15067 (interactive)
15068 (when (org-at-timestamp-p t)
15069 (let ((beg (match-beginning 0)) (end (match-end 0))
15070 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
15071 (save-excursion
15072 (goto-char beg)
15073 (while (re-search-forward "[][<>]" end t)
15074 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
15075 t t)))
15076 (message "Timestamp is now %sactive"
15077 (if (equal (char-after beg) ?<) "" "in")))))
15079 (defun org-timestamp-change (n &optional what updown)
15080 "Change the date in the time stamp at point.
15081 The date will be changed by N times WHAT. WHAT can be `day', `month',
15082 `year', `minute', `second'. If WHAT is not given, the cursor position
15083 in the timestamp determines what will be changed."
15084 (let ((pos (point))
15085 with-hm inactive
15086 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
15087 org-ts-what
15088 extra rem
15089 ts time time0)
15090 (if (not (org-at-timestamp-p t))
15091 (error "Not at a timestamp"))
15092 (if (and (not what) (eq org-ts-what 'bracket))
15093 (org-toggle-timestamp-type)
15094 (if (and (not what) (not (eq org-ts-what 'day))
15095 org-display-custom-times
15096 (get-text-property (point) 'display)
15097 (not (get-text-property (1- (point)) 'display)))
15098 (setq org-ts-what 'day))
15099 (setq org-ts-what (or what org-ts-what)
15100 inactive (= (char-after (match-beginning 0)) ?\[)
15101 ts (match-string 0))
15102 (replace-match "")
15103 (if (string-match
15104 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
15106 (setq extra (match-string 1 ts)))
15107 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15108 (setq with-hm t))
15109 (setq time0 (org-parse-time-string ts))
15110 (when (and updown
15111 (eq org-ts-what 'minute)
15112 (not current-prefix-arg))
15113 ;; This looks like s-up and s-down. Change by one rounding step.
15114 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
15115 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
15116 (setcar (cdr time0) (+ (nth 1 time0)
15117 (if (> n 0) (- rem) (- dm rem))))))
15118 (setq time
15119 (encode-time (or (car time0) 0)
15120 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
15121 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
15122 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
15123 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
15124 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
15125 (nthcdr 6 time0)))
15126 (when (and (member org-ts-what '(hour minute))
15127 extra
15128 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
15129 (setq extra (org-modify-ts-extra
15130 extra
15131 (if (eq org-ts-what 'hour) 2 5)
15132 n dm)))
15133 (when (integerp org-ts-what)
15134 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
15135 (if (eq what 'calendar)
15136 (let ((cal-date (org-get-date-from-calendar)))
15137 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15138 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15139 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15140 (setcar time0 (or (car time0) 0))
15141 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15142 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15143 (setq time (apply 'encode-time time0))))
15144 (setq org-last-changed-timestamp
15145 (org-insert-time-stamp time with-hm inactive nil nil extra))
15146 (org-clock-update-time-maybe)
15147 (goto-char pos)
15148 ;; Try to recenter the calendar window, if any
15149 (if (and org-calendar-follow-timestamp-change
15150 (get-buffer-window "*Calendar*" t)
15151 (memq org-ts-what '(day month year)))
15152 (org-recenter-calendar (time-to-days time))))))
15154 (defun org-modify-ts-extra (s pos n dm)
15155 "Change the different parts of the lead-time and repeat fields in timestamp."
15156 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15157 ng h m new rem)
15158 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15159 (cond
15160 ((or (org-pos-in-match-range pos 2)
15161 (org-pos-in-match-range pos 3))
15162 (setq m (string-to-number (match-string 3 s))
15163 h (string-to-number (match-string 2 s)))
15164 (if (org-pos-in-match-range pos 2)
15165 (setq h (+ h n))
15166 (setq n (* dm (org-no-warnings (signum n))))
15167 (when (not (= 0 (setq rem (% m dm))))
15168 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
15169 (setq m (+ m n)))
15170 (if (< m 0) (setq m (+ m 60) h (1- h)))
15171 (if (> m 59) (setq m (- m 60) h (1+ h)))
15172 (setq h (min 24 (max 0 h)))
15173 (setq ng 1 new (format "-%02d:%02d" h m)))
15174 ((org-pos-in-match-range pos 6)
15175 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15176 ((org-pos-in-match-range pos 5)
15177 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
15179 ((org-pos-in-match-range pos 9)
15180 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
15181 ((org-pos-in-match-range pos 8)
15182 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
15184 (when ng
15185 (setq s (concat
15186 (substring s 0 (match-beginning ng))
15188 (substring s (match-end ng))))))
15191 (defun org-recenter-calendar (date)
15192 "If the calendar is visible, recenter it to DATE."
15193 (let* ((win (selected-window))
15194 (cwin (get-buffer-window "*Calendar*" t))
15195 (calendar-move-hook nil))
15196 (when cwin
15197 (select-window cwin)
15198 (calendar-goto-date (if (listp date) date
15199 (calendar-gregorian-from-absolute date)))
15200 (select-window win))))
15202 (defun org-goto-calendar (&optional arg)
15203 "Go to the Emacs calendar at the current date.
15204 If there is a time stamp in the current line, go to that date.
15205 A prefix ARG can be used to force the current date."
15206 (interactive "P")
15207 (let ((tsr org-ts-regexp) diff
15208 (calendar-move-hook nil)
15209 (calendar-view-holidays-initially-flag nil)
15210 (calendar-view-diary-initially-flag nil))
15211 (if (or (org-at-timestamp-p)
15212 (save-excursion
15213 (beginning-of-line 1)
15214 (looking-at (concat ".*" tsr))))
15215 (let ((d1 (time-to-days (current-time)))
15216 (d2 (time-to-days
15217 (org-time-string-to-time (match-string 1)))))
15218 (setq diff (- d2 d1))))
15219 (calendar)
15220 (calendar-goto-today)
15221 (if (and diff (not arg)) (calendar-forward-day diff))))
15223 (defun org-get-date-from-calendar ()
15224 "Return a list (month day year) of date at point in calendar."
15225 (with-current-buffer "*Calendar*"
15226 (save-match-data
15227 (calendar-cursor-to-date))))
15229 (defun org-date-from-calendar ()
15230 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
15231 If there is already a time stamp at the cursor position, update it."
15232 (interactive)
15233 (if (org-at-timestamp-p t)
15234 (org-timestamp-change 0 'calendar)
15235 (let ((cal-date (org-get-date-from-calendar)))
15236 (org-insert-time-stamp
15237 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
15239 (defun org-minutes-to-hh:mm-string (m)
15240 "Compute H:MM from a number of minutes."
15241 (let ((h (/ m 60)))
15242 (setq m (- m (* 60 h)))
15243 (format org-time-clocksum-format h m)))
15245 (defun org-hh:mm-string-to-minutes (s)
15246 "Convert a string H:MM to a number of minutes.
15247 If the string is just a number, interpret it as minutes.
15248 In fact, the first hh:mm or number in the string will be taken,
15249 there can be extra stuff in the string.
15250 If no number is found, the return value is 0."
15251 (cond
15252 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
15253 (+ (* (string-to-number (match-string 1 s)) 60)
15254 (string-to-number (match-string 2 s))))
15255 ((string-match "\\([0-9]+\\)" s)
15256 (string-to-number (match-string 1 s)))
15257 (t 0)))
15259 ;;;; Files
15261 (defun org-save-all-org-buffers ()
15262 "Save all Org-mode buffers without user confirmation."
15263 (interactive)
15264 (message "Saving all Org-mode buffers...")
15265 (save-some-buffers t 'org-mode-p)
15266 (when (featurep 'org-id) (org-id-locations-save))
15267 (message "Saving all Org-mode buffers... done"))
15269 (defun org-revert-all-org-buffers ()
15270 "Revert all Org-mode buffers.
15271 Prompt for confirmation when there are unsaved changes.
15272 Be sure you know what you are doing before letting this function
15273 overwrite your changes.
15275 This function is useful in a setup where one tracks org files
15276 with a version control system, to revert on one machine after pulling
15277 changes from another. I believe the procedure must be like this:
15279 1. M-x org-save-all-org-buffers
15280 2. Pull changes from the other machine, resolve conflicts
15281 3. M-x org-revert-all-org-buffers"
15282 (interactive)
15283 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
15284 (error "Abort"))
15285 (save-excursion
15286 (save-window-excursion
15287 (mapc
15288 (lambda (b)
15289 (when (and (with-current-buffer b (org-mode-p))
15290 (with-current-buffer b buffer-file-name))
15291 (switch-to-buffer b)
15292 (revert-buffer t 'no-confirm)))
15293 (buffer-list))
15294 (when (and (featurep 'org-id) org-id-track-globally)
15295 (org-id-locations-load)))))
15297 ;;;; Agenda files
15299 ;;;###autoload
15300 (defun org-switchb (&optional arg)
15301 "Switch between Org buffers.
15302 With a prefix argument, restrict available to files.
15303 With two prefix arguments, restrict available buffers to agenda files.
15305 Defaults to `iswitchb' for buffer name completion.
15306 Set `org-completion-use-ido' to make it use ido instead."
15307 (interactive "P")
15308 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
15309 ((equal arg '(16)) (org-buffer-list 'agenda))
15310 (t (org-buffer-list))))
15311 (org-completion-use-iswitchb org-completion-use-iswitchb)
15312 (org-completion-use-ido org-completion-use-ido))
15313 (unless (or org-completion-use-ido org-completion-use-iswitchb)
15314 (setq org-completion-use-iswitchb t))
15315 (switch-to-buffer
15316 (org-icompleting-read "Org buffer: "
15317 (mapcar 'list (mapcar 'buffer-name blist))
15318 nil t))))
15320 ;;; Define some older names previously used for this functionality
15321 ;;;###autoload
15322 (defalias 'org-ido-switchb 'org-switchb)
15323 ;;;###autoload
15324 (defalias 'org-iswitchb 'org-switchb)
15326 (defun org-buffer-list (&optional predicate exclude-tmp)
15327 "Return a list of Org buffers.
15328 PREDICATE can be `export', `files' or `agenda'.
15330 export restrict the list to Export buffers.
15331 files restrict the list to buffers visiting Org files.
15332 agenda restrict the list to buffers visiting agenda files.
15334 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
15335 (let* ((bfn nil)
15336 (agenda-files (and (eq predicate 'agenda)
15337 (mapcar 'file-truename (org-agenda-files t))))
15338 (filter
15339 (cond
15340 ((eq predicate 'files)
15341 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
15342 ((eq predicate 'export)
15343 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
15344 ((eq predicate 'agenda)
15345 (lambda (b)
15346 (with-current-buffer b
15347 (and (eq major-mode 'org-mode)
15348 (setq bfn (buffer-file-name b))
15349 (member (file-truename bfn) agenda-files)))))
15350 (t (lambda (b) (with-current-buffer b
15351 (or (eq major-mode 'org-mode)
15352 (string-match "\*Org .*Export"
15353 (buffer-name b)))))))))
15354 (delq nil
15355 (mapcar
15356 (lambda(b)
15357 (if (and (funcall filter b)
15358 (or (not exclude-tmp)
15359 (not (string-match "tmp" (buffer-name b)))))
15361 nil))
15362 (buffer-list)))))
15364 (defun org-agenda-files (&optional unrestricted archives)
15365 "Get the list of agenda files.
15366 Optional UNRESTRICTED means return the full list even if a restriction
15367 is currently in place.
15368 When ARCHIVES is t, include all archive files that are really being
15369 used by the agenda files. If ARCHIVE is `ifmode', do this only if
15370 `org-agenda-archives-mode' is t."
15371 (let ((files
15372 (cond
15373 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
15374 ((stringp org-agenda-files) (org-read-agenda-file-list))
15375 ((listp org-agenda-files) org-agenda-files)
15376 (t (error "Invalid value of `org-agenda-files'")))))
15377 (setq files (apply 'append
15378 (mapcar (lambda (f)
15379 (if (file-directory-p f)
15380 (directory-files
15381 f t org-agenda-file-regexp)
15382 (list f)))
15383 files)))
15384 (when org-agenda-skip-unavailable-files
15385 (setq files (delq nil
15386 (mapcar (function
15387 (lambda (file)
15388 (and (file-readable-p file) file)))
15389 files))))
15390 (when (or (eq archives t)
15391 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
15392 (setq files (org-add-archive-files files)))
15393 files))
15395 (defun org-agenda-file-p (&optional file)
15396 "Return non-nil, if FILE is an agenda file.
15397 If FILE is omitted, use the file associated with the current
15398 buffer."
15399 (member (or file (buffer-file-name))
15400 (org-agenda-files t)))
15402 (defun org-edit-agenda-file-list ()
15403 "Edit the list of agenda files.
15404 Depending on setup, this either uses customize to edit the variable
15405 `org-agenda-files', or it visits the file that is holding the list. In the
15406 latter case, the buffer is set up in a way that saving it automatically kills
15407 the buffer and restores the previous window configuration."
15408 (interactive)
15409 (if (stringp org-agenda-files)
15410 (let ((cw (current-window-configuration)))
15411 (find-file org-agenda-files)
15412 (org-set-local 'org-window-configuration cw)
15413 (org-add-hook 'after-save-hook
15414 (lambda ()
15415 (set-window-configuration
15416 (prog1 org-window-configuration
15417 (kill-buffer (current-buffer))))
15418 (org-install-agenda-files-menu)
15419 (message "New agenda file list installed"))
15420 nil 'local)
15421 (message "%s" (substitute-command-keys
15422 "Edit list and finish with \\[save-buffer]")))
15423 (customize-variable 'org-agenda-files)))
15425 (defun org-store-new-agenda-file-list (list)
15426 "Set new value for the agenda file list and save it correctly."
15427 (if (stringp org-agenda-files)
15428 (let ((fe (org-read-agenda-file-list t)) b u)
15429 (while (setq b (find-buffer-visiting org-agenda-files))
15430 (kill-buffer b))
15431 (with-temp-file org-agenda-files
15432 (insert
15433 (mapconcat
15434 (lambda (f) ;; Keep un-expanded entries.
15435 (if (setq u (assoc f fe))
15436 (cdr u)
15438 list "\n")
15439 "\n")))
15440 (let ((org-mode-hook nil) (org-inhibit-startup t)
15441 (org-insert-mode-line-in-empty-file nil))
15442 (setq org-agenda-files list)
15443 (customize-save-variable 'org-agenda-files org-agenda-files))))
15445 (defun org-read-agenda-file-list (&optional pair-with-expansion)
15446 "Read the list of agenda files from a file.
15447 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
15448 filenames, used by `org-store-new-agenda-file-list' to write back
15449 un-expanded file names."
15450 (when (file-directory-p org-agenda-files)
15451 (error "`org-agenda-files' cannot be a single directory"))
15452 (when (stringp org-agenda-files)
15453 (with-temp-buffer
15454 (insert-file-contents org-agenda-files)
15455 (mapcar
15456 (lambda (f)
15457 (let ((e (expand-file-name (substitute-in-file-name f)
15458 org-directory)))
15459 (if pair-with-expansion
15460 (cons e f)
15461 e)))
15462 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
15464 ;;;###autoload
15465 (defun org-cycle-agenda-files ()
15466 "Cycle through the files in `org-agenda-files'.
15467 If the current buffer visits an agenda file, find the next one in the list.
15468 If the current buffer does not, find the first agenda file."
15469 (interactive)
15470 (let* ((fs (org-agenda-files t))
15471 (files (append fs (list (car fs))))
15472 (tcf (if buffer-file-name (file-truename buffer-file-name)))
15473 file)
15474 (unless files (error "No agenda files"))
15475 (catch 'exit
15476 (while (setq file (pop files))
15477 (if (equal (file-truename file) tcf)
15478 (when (car files)
15479 (find-file (car files))
15480 (throw 'exit t))))
15481 (find-file (car fs)))
15482 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
15484 (defun org-agenda-file-to-front (&optional to-end)
15485 "Move/add the current file to the top of the agenda file list.
15486 If the file is not present in the list, it is added to the front. If it is
15487 present, it is moved there. With optional argument TO-END, add/move to the
15488 end of the list."
15489 (interactive "P")
15490 (let ((org-agenda-skip-unavailable-files nil)
15491 (file-alist (mapcar (lambda (x)
15492 (cons (file-truename x) x))
15493 (org-agenda-files t)))
15494 (ctf (file-truename buffer-file-name))
15495 x had)
15496 (setq x (assoc ctf file-alist) had x)
15498 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
15499 (if to-end
15500 (setq file-alist (append (delq x file-alist) (list x)))
15501 (setq file-alist (cons x (delq x file-alist))))
15502 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
15503 (org-install-agenda-files-menu)
15504 (message "File %s to %s of agenda file list"
15505 (if had "moved" "added") (if to-end "end" "front"))))
15507 (defun org-remove-file (&optional file)
15508 "Remove current file from the list of files in variable `org-agenda-files'.
15509 These are the files which are being checked for agenda entries.
15510 Optional argument FILE means use this file instead of the current."
15511 (interactive)
15512 (let* ((org-agenda-skip-unavailable-files nil)
15513 (file (or file buffer-file-name))
15514 (true-file (file-truename file))
15515 (afile (abbreviate-file-name file))
15516 (files (delq nil (mapcar
15517 (lambda (x)
15518 (if (equal true-file
15519 (file-truename x))
15520 nil x))
15521 (org-agenda-files t)))))
15522 (if (not (= (length files) (length (org-agenda-files t))))
15523 (progn
15524 (org-store-new-agenda-file-list files)
15525 (org-install-agenda-files-menu)
15526 (message "Removed file: %s" afile))
15527 (message "File was not in list: %s (not removed)" afile))))
15529 (defun org-file-menu-entry (file)
15530 (vector file (list 'find-file file) t))
15532 (defun org-check-agenda-file (file)
15533 "Make sure FILE exists. If not, ask user what to do."
15534 (when (not (file-exists-p file))
15535 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
15536 (abbreviate-file-name file))
15537 (let ((r (downcase (read-char-exclusive))))
15538 (cond
15539 ((equal r ?r)
15540 (org-remove-file file)
15541 (throw 'nextfile t))
15542 (t (error "Abort"))))))
15544 (defun org-get-agenda-file-buffer (file)
15545 "Get a buffer visiting FILE. If the buffer needs to be created, add
15546 it to the list of buffers which might be released later."
15547 (let ((buf (org-find-base-buffer-visiting file)))
15548 (if buf
15549 buf ; just return it
15550 ;; Make a new buffer and remember it
15551 (setq buf (find-file-noselect file))
15552 (if buf (push buf org-agenda-new-buffers))
15553 buf)))
15555 (defun org-release-buffers (blist)
15556 "Release all buffers in list, asking the user for confirmation when needed.
15557 When a buffer is unmodified, it is just killed. When modified, it is saved
15558 \(if the user agrees) and then killed."
15559 (let (buf file)
15560 (while (setq buf (pop blist))
15561 (setq file (buffer-file-name buf))
15562 (when (and (buffer-modified-p buf)
15563 file
15564 (y-or-n-p (format "Save file %s? " file)))
15565 (with-current-buffer buf (save-buffer)))
15566 (kill-buffer buf))))
15568 (defun org-prepare-agenda-buffers (files)
15569 "Create buffers for all agenda files, protect archived trees and comments."
15570 (interactive)
15571 (let ((pa '(:org-archived t))
15572 (pc '(:org-comment t))
15573 (pall '(:org-archived t :org-comment t))
15574 (inhibit-read-only t)
15575 (rea (concat ":" org-archive-tag ":"))
15576 bmp file re)
15577 (save-excursion
15578 (save-restriction
15579 (while (setq file (pop files))
15580 (catch 'nextfile
15581 (if (bufferp file)
15582 (set-buffer file)
15583 (org-check-agenda-file file)
15584 (set-buffer (org-get-agenda-file-buffer file)))
15585 (widen)
15586 (setq bmp (buffer-modified-p))
15587 (org-refresh-category-properties)
15588 (setq org-todo-keywords-for-agenda
15589 (append org-todo-keywords-for-agenda org-todo-keywords-1))
15590 (setq org-done-keywords-for-agenda
15591 (append org-done-keywords-for-agenda org-done-keywords))
15592 (setq org-todo-keyword-alist-for-agenda
15593 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
15594 (setq org-drawers-for-agenda
15595 (append org-drawers-for-agenda org-drawers))
15596 (setq org-tag-alist-for-agenda
15597 (append org-tag-alist-for-agenda org-tag-alist))
15599 (save-excursion
15600 (remove-text-properties (point-min) (point-max) pall)
15601 (when org-agenda-skip-archived-trees
15602 (goto-char (point-min))
15603 (while (re-search-forward rea nil t)
15604 (if (org-on-heading-p t)
15605 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
15606 (goto-char (point-min))
15607 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
15608 (while (re-search-forward re nil t)
15609 (add-text-properties
15610 (match-beginning 0) (org-end-of-subtree t) pc)))
15611 (set-buffer-modified-p bmp)))))
15612 (setq org-todo-keywords-for-agenda
15613 (org-uniquify org-todo-keywords-for-agenda))
15614 (setq org-todo-keyword-alist-for-agenda
15615 (org-uniquify org-todo-keyword-alist-for-agenda)
15616 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
15618 ;;;; Embedded LaTeX
15620 (defvar org-cdlatex-mode-map (make-sparse-keymap)
15621 "Keymap for the minor `org-cdlatex-mode'.")
15623 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
15624 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
15625 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
15626 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
15627 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
15629 (defvar org-cdlatex-texmathp-advice-is-done nil
15630 "Flag remembering if we have applied the advice to texmathp already.")
15632 (define-minor-mode org-cdlatex-mode
15633 "Toggle the minor `org-cdlatex-mode'.
15634 This mode supports entering LaTeX environment and math in LaTeX fragments
15635 in Org-mode.
15636 \\{org-cdlatex-mode-map}"
15637 nil " OCDL" nil
15638 (when org-cdlatex-mode (require 'cdlatex))
15639 (unless org-cdlatex-texmathp-advice-is-done
15640 (setq org-cdlatex-texmathp-advice-is-done t)
15641 (defadvice texmathp (around org-math-always-on activate)
15642 "Always return t in org-mode buffers.
15643 This is because we want to insert math symbols without dollars even outside
15644 the LaTeX math segments. If Orgmode thinks that point is actually inside
15645 an embedded LaTeX fragment, let texmathp do its job.
15646 \\[org-cdlatex-mode-map]"
15647 (interactive)
15648 (let (p)
15649 (cond
15650 ((not (org-mode-p)) ad-do-it)
15651 ((eq this-command 'cdlatex-math-symbol)
15652 (setq ad-return-value t
15653 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
15655 (let ((p (org-inside-LaTeX-fragment-p)))
15656 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
15657 (setq ad-return-value t
15658 texmathp-why '("Org-mode embedded math" . 0))
15659 (if p ad-do-it)))))))))
15661 (defun turn-on-org-cdlatex ()
15662 "Unconditionally turn on `org-cdlatex-mode'."
15663 (org-cdlatex-mode 1))
15665 (defun org-inside-LaTeX-fragment-p ()
15666 "Test if point is inside a LaTeX fragment.
15667 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
15668 sequence appearing also before point.
15669 Even though the matchers for math are configurable, this function assumes
15670 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
15671 delimiters are skipped when they have been removed by customization.
15672 The return value is nil, or a cons cell with the delimiter and
15673 and the position of this delimiter.
15675 This function does a reasonably good job, but can locally be fooled by
15676 for example currency specifications. For example it will assume being in
15677 inline math after \"$22.34\". The LaTeX fragment formatter will only format
15678 fragments that are properly closed, but during editing, we have to live
15679 with the uncertainty caused by missing closing delimiters. This function
15680 looks only before point, not after."
15681 (catch 'exit
15682 (let ((pos (point))
15683 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
15684 (lim (progn
15685 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
15686 (point)))
15687 dd-on str (start 0) m re)
15688 (goto-char pos)
15689 (when dodollar
15690 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
15691 re (nth 1 (assoc "$" org-latex-regexps)))
15692 (while (string-match re str start)
15693 (cond
15694 ((= (match-end 0) (length str))
15695 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
15696 ((= (match-end 0) (- (length str) 5))
15697 (throw 'exit nil))
15698 (t (setq start (match-end 0))))))
15699 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
15700 (goto-char pos)
15701 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
15702 (and (match-beginning 2) (throw 'exit nil))
15703 ;; count $$
15704 (while (re-search-backward "\\$\\$" lim t)
15705 (setq dd-on (not dd-on)))
15706 (goto-char pos)
15707 (if dd-on (cons "$$" m))))))
15709 (defun org-inside-latex-macro-p ()
15710 "Is point inside a LaTeX macro or its arguments?"
15711 (save-match-data
15712 (org-in-regexp
15713 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
15715 (defun org-try-cdlatex-tab ()
15716 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
15717 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
15718 - inside a LaTeX fragment, or
15719 - after the first word in a line, where an abbreviation expansion could
15720 insert a LaTeX environment."
15721 (when org-cdlatex-mode
15722 (cond
15723 ((save-excursion
15724 (skip-chars-backward "a-zA-Z0-9*")
15725 (skip-chars-backward " \t")
15726 (bolp))
15727 (cdlatex-tab) t)
15728 ((org-inside-LaTeX-fragment-p)
15729 (cdlatex-tab) t)
15730 (t nil))))
15732 (defun org-cdlatex-underscore-caret (&optional arg)
15733 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
15734 Revert to the normal definition outside of these fragments."
15735 (interactive "P")
15736 (if (org-inside-LaTeX-fragment-p)
15737 (call-interactively 'cdlatex-sub-superscript)
15738 (let (org-cdlatex-mode)
15739 (call-interactively (key-binding (vector last-input-event))))))
15741 (defun org-cdlatex-math-modify (&optional arg)
15742 "Execute `cdlatex-math-modify' in LaTeX fragments.
15743 Revert to the normal definition outside of these fragments."
15744 (interactive "P")
15745 (if (org-inside-LaTeX-fragment-p)
15746 (call-interactively 'cdlatex-math-modify)
15747 (let (org-cdlatex-mode)
15748 (call-interactively (key-binding (vector last-input-event))))))
15750 (defvar org-latex-fragment-image-overlays nil
15751 "List of overlays carrying the images of latex fragments.")
15752 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
15754 (defun org-remove-latex-fragment-image-overlays ()
15755 "Remove all overlays with LaTeX fragment images in current buffer."
15756 (mapc 'delete-overlay org-latex-fragment-image-overlays)
15757 (setq org-latex-fragment-image-overlays nil))
15759 (defun org-preview-latex-fragment (&optional subtree)
15760 "Preview the LaTeX fragment at point, or all locally or globally.
15761 If the cursor is in a LaTeX fragment, create the image and overlay
15762 it over the source code. If there is no fragment at point, display
15763 all fragments in the current text, from one headline to the next. With
15764 prefix SUBTREE, display all fragments in the current subtree. With a
15765 double prefix `C-u C-u', or when the cursor is before the first headline,
15766 display all fragments in the buffer.
15767 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
15768 (interactive "P")
15769 (org-remove-latex-fragment-image-overlays)
15770 (save-excursion
15771 (save-restriction
15772 (let (beg end at msg)
15773 (cond
15774 ((or (equal subtree '(16))
15775 (not (save-excursion
15776 (re-search-backward (concat "^" outline-regexp) nil t))))
15777 (setq beg (point-min) end (point-max)
15778 msg "Creating images for buffer...%s"))
15779 ((equal subtree '(4))
15780 (org-back-to-heading)
15781 (setq beg (point) end (org-end-of-subtree t)
15782 msg "Creating images for subtree...%s"))
15784 (if (setq at (org-inside-LaTeX-fragment-p))
15785 (goto-char (max (point-min) (- (cdr at) 2)))
15786 (org-back-to-heading))
15787 (setq beg (point) end (progn (outline-next-heading) (point))
15788 msg (if at "Creating image...%s"
15789 "Creating images for entry...%s"))))
15790 (message msg "")
15791 (narrow-to-region beg end)
15792 (goto-char beg)
15793 (org-format-latex
15794 (concat "ltxpng/" (file-name-sans-extension
15795 (file-name-nondirectory
15796 buffer-file-name)))
15797 default-directory 'overlays msg at 'forbuffer)
15798 (message msg "done. Use `C-c C-c' to remove images.")))))
15800 (defvar org-latex-regexps
15801 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
15802 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
15803 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
15804 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15805 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15806 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
15807 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
15808 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
15809 "Regular expressions for matching embedded LaTeX.")
15811 (defun org-format-latex (prefix &optional dir overlays msg at
15812 forbuffer protect-only)
15813 "Replace LaTeX fragments with links to an image, and produce images.
15814 Some of the options can be changed using the variable
15815 `org-format-latex-options'."
15816 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
15817 (let* ((prefixnodir (file-name-nondirectory prefix))
15818 (absprefix (expand-file-name prefix dir))
15819 (todir (file-name-directory absprefix))
15820 (opt org-format-latex-options)
15821 (matchers (plist-get opt :matchers))
15822 (re-list org-latex-regexps)
15823 (org-format-latex-header-extra
15824 (plist-get (org-infile-export-plist) :latex-header-extra))
15825 (cnt 0) txt hash link beg end re e checkdir
15826 executables-checked
15827 m n block linkfile movefile ov)
15828 ;; Check the different regular expressions
15829 (while (setq e (pop re-list))
15830 (setq m (car e) re (nth 1 e) n (nth 2 e)
15831 block (if (nth 3 e) "\n\n" ""))
15832 (when (member m matchers)
15833 (goto-char (point-min))
15834 (while (re-search-forward re nil t)
15835 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
15836 (not (get-text-property (match-beginning n)
15837 'org-protected))
15838 (or (not overlays)
15839 (not (eq (get-char-property (match-beginning n)
15840 'org-overlay-type)
15841 'org-latex-overlay))))
15842 (if protect-only
15843 (add-text-properties (match-beginning n) (match-end n)
15844 '(org-protected t))
15845 (setq txt (match-string n)
15846 beg (match-beginning n) end (match-end n)
15847 cnt (1+ cnt))
15848 (let (print-length print-level) ; make sure full list is printed
15849 (setq hash (sha1 (prin1-to-string
15850 (list org-format-latex-header
15851 org-format-latex-header-extra
15852 org-export-latex-default-packages-alist
15853 org-export-latex-packages-alist
15854 org-format-latex-options
15855 forbuffer txt)))
15856 linkfile (format "%s_%s.png" prefix hash)
15857 movefile (format "%s_%s.png" absprefix hash)))
15858 (setq link (concat block "[[file:" linkfile "]]" block))
15859 (if msg (message msg cnt))
15860 (goto-char beg)
15861 (unless checkdir ; make sure the directory exists
15862 (setq checkdir t)
15863 (or (file-directory-p todir) (make-directory todir)))
15865 (unless executables-checked
15866 (org-check-external-command
15867 "latex" "needed to convert LaTeX fragments to images")
15868 (org-check-external-command
15869 "dvipng" "needed to convert LaTeX fragments to images")
15870 (setq executables-checked t))
15872 (unless (file-exists-p movefile)
15873 (org-create-formula-image
15874 txt movefile opt forbuffer))
15875 (if overlays
15876 (progn
15877 (mapc (lambda (o)
15878 (if (eq (overlay-get o 'org-overlay-type)
15879 'org-latex-overlay)
15880 (delete-overlay o)))
15881 (overlays-in beg end))
15882 (setq ov (make-overlay beg end))
15883 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
15884 (if (featurep 'xemacs)
15885 (progn
15886 (overlay-put ov 'invisible t)
15887 (overlay-put
15888 ov 'end-glyph
15889 (make-glyph (vector 'png :file movefile))))
15890 (overlay-put
15891 ov 'display
15892 (list 'image :type 'png :file movefile :ascent 'center)))
15893 (push ov org-latex-fragment-image-overlays)
15894 (goto-char end))
15895 (delete-region beg end)
15896 (insert (org-add-props link
15897 (list 'org-latex-src
15898 (replace-regexp-in-string "\"" "" txt))))))))))))
15900 ;; This function borrows from Ganesh Swami's latex2png.el
15901 (defun org-create-formula-image (string tofile options buffer)
15902 "This calls dvipng."
15903 (require 'org-latex)
15904 (let* ((tmpdir (if (featurep 'xemacs)
15905 (temp-directory)
15906 temporary-file-directory))
15907 (texfilebase (make-temp-name
15908 (expand-file-name "orgtex" tmpdir)))
15909 (texfile (concat texfilebase ".tex"))
15910 (dvifile (concat texfilebase ".dvi"))
15911 (pngfile (concat texfilebase ".png"))
15912 (fnh (if (featurep 'xemacs)
15913 (font-height (get-face-font 'default))
15914 (face-attribute 'default :height nil)))
15915 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
15916 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
15917 (fg (or (plist-get options (if buffer :foreground :html-foreground))
15918 "Black"))
15919 (bg (or (plist-get options (if buffer :background :html-background))
15920 "Transparent")))
15921 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
15922 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
15923 (with-temp-file texfile
15924 (insert (org-splice-latex-header
15925 org-format-latex-header
15926 org-export-latex-default-packages-alist
15927 org-export-latex-packages-alist t
15928 org-format-latex-header-extra))
15929 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
15930 (require 'org-latex)
15931 (org-export-latex-fix-inputenc))
15932 (let ((dir default-directory))
15933 (condition-case nil
15934 (progn
15935 (cd tmpdir)
15936 (call-process "latex" nil nil nil texfile))
15937 (error nil))
15938 (cd dir))
15939 (if (not (file-exists-p dvifile))
15940 (progn (message "Failed to create dvi file from %s" texfile) nil)
15941 (condition-case nil
15942 (call-process "dvipng" nil nil nil
15943 "-fg" fg "-bg" bg
15944 "-D" dpi
15945 ;;"-x" scale "-y" scale
15946 "-T" "tight"
15947 "-o" pngfile
15948 dvifile)
15949 (error nil))
15950 (if (not (file-exists-p pngfile))
15951 (if org-format-latex-signal-error
15952 (error "Failed to create png file from %s" texfile)
15953 (message "Failed to create png file from %s" texfile)
15954 nil)
15955 ;; Use the requested file name and clean up
15956 (copy-file pngfile tofile 'replace)
15957 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15958 (delete-file (concat texfilebase e)))
15959 pngfile))))
15961 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
15962 "Fill a LaTeX header template TPL.
15963 In the template, the following place holders will be recognized:
15965 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
15966 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
15967 [PACKAGES] \\usepackage statements for PKG
15968 [NO-PACKAGES] do not include PKG
15969 [EXTRA] the string EXTRA
15970 [NO-EXTRA] do not include EXTRA
15972 For backward compatibility, if both the positive and the negative place
15973 holder is missing, the positive one (without the \"NO-\") will be
15974 assumed to be present at the end of the template.
15975 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
15976 EXTRA is a string.
15977 SNIPPETS-P indicates if this is run to create snippet images for HTML."
15978 (let (rpl (end ""))
15979 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
15980 (setq rpl (if (or (match-end 1) (not def-pkg))
15981 "" (org-latex-packages-to-string def-pkg snippets-p t))
15982 tpl (replace-match rpl t t tpl))
15983 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
15985 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
15986 (setq rpl (if (or (match-end 1) (not pkg))
15987 "" (org-latex-packages-to-string pkg snippets-p t))
15988 tpl (replace-match rpl t t tpl))
15989 (if pkg (setq end
15990 (concat end "\n"
15991 (org-latex-packages-to-string pkg snippets-p)))))
15993 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
15994 (setq rpl (if (or (match-end 1) (not extra))
15995 "" (concat extra "\n"))
15996 tpl (replace-match rpl t t tpl))
15997 (if (and extra (string-match "\\S-" extra))
15998 (setq end (concat end "\n" extra))))
16000 (if (string-match "\\S-" end)
16001 (concat tpl "\n" end)
16002 tpl)))
16004 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
16005 "Turn an alist of packages into a string with the \\usepackage macros."
16006 (setq pkg (mapconcat (lambda(p)
16007 (cond
16008 ((stringp p) p)
16009 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
16010 (format "%% Package %s omitted" (cadr p)))
16011 ((equal "" (car p))
16012 (format "\\usepackage{%s}" (cadr p)))
16014 (format "\\usepackage[%s]{%s}"
16015 (car p) (cadr p)))))
16017 "\n"))
16018 (if newline (concat pkg "\n") pkg))
16020 (defun org-dvipng-color (attr)
16021 "Return an rgb color specification for dvipng."
16022 (apply 'format "rgb %s %s %s"
16023 (mapcar 'org-normalize-color
16024 (color-values (face-attribute 'default attr nil)))))
16026 (defun org-normalize-color (value)
16027 "Return string to be used as color value for an RGB component."
16028 (format "%g" (/ value 65535.0)))
16030 ;; Image display
16033 (defvar org-inline-image-overlays nil)
16034 (make-variable-buffer-local 'org-inline-image-overlays)
16036 (defun org-toggle-inline-images (&optional include-linked)
16037 "Toggle the display of inline images.
16038 INCLUDE-LINKED is passed to `org-display-inline-images'."
16039 (interactive "P")
16040 (if org-inline-image-overlays
16041 (progn
16042 (org-remove-inline-images)
16043 (message "Inline image display turned off"))
16044 (org-display-inline-images include-linked)
16045 (if org-inline-image-overlays
16046 (message "%d images displayed inline"
16047 (length org-inline-image-overlays))
16048 (message "No images to display inline"))))
16050 (defun org-display-inline-images (&optional include-linked refresh beg end)
16051 "Display inline images.
16052 Normally only links without a description part are inlined, because this
16053 is how it will work for export. When INCLUDE-LINKED is set, also links
16054 with a description part will be inlined. This can be nice for a quick
16055 look at those images, but it does not reflect whatexported files will look
16056 like.
16057 When REFRESH is set, refresh existing images between BEG and END.
16058 This will create new image displays only if necessary.
16059 BEG and END default to the buffer boundaries."
16060 (interactive "P")
16061 (unless refresh
16062 (org-remove-inline-images)
16063 (clear-image-cache))
16064 (save-excursion
16065 (save-restriction
16066 (widen)
16067 (setq beg (or beg (point-min)) end (or end (point-max)))
16068 (goto-char (point-min))
16069 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([-+~.:/\\_0-9a-zA-Z ]+"
16070 (substring (org-image-file-name-regexp) 0 -2)
16071 "\\)\\]" (if include-linked "" "\\]")))
16072 old file ov img)
16073 (while (re-search-forward re end t)
16074 (setq old (get-char-property-and-overlay (match-beginning 1)
16075 'org-image-overlay))
16076 (setq file (expand-file-name
16077 (concat (or (match-string 3) "") (match-string 4))))
16078 (when (file-exists-p file)
16079 (if (and (car-safe old) refresh)
16080 (image-refresh (overlay-get (cdr old) 'display))
16081 (setq img (create-image file))
16082 (when img
16083 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
16084 (overlay-put ov 'display img)
16085 (overlay-put ov 'face 'default)
16086 (overlay-put ov 'org-image-overlay t)
16087 (overlay-put ov 'modification-hooks
16088 (list 'org-display-inline-modification-hook))
16089 (push ov org-inline-image-overlays)))))))))
16091 (defun org-display-inline-modification-hook (ov after beg end &optional len)
16092 "Remove inline-display overlay if a corresponding region is modified."
16093 (let ((inhibit-modification-hooks t))
16094 (when (and ov after)
16095 (delete ov org-inline-image-overlays)
16096 (delete-overlay ov))))
16098 (defun org-remove-inline-images ()
16099 "Remove inline display of images."
16100 (interactive)
16101 (mapc 'delete-overlay org-inline-image-overlays)
16102 (setq org-inline-image-overlays nil))
16104 ;;;; Key bindings
16106 ;; Make `C-c C-x' a prefix key
16107 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
16109 ;; TAB key with modifiers
16110 (org-defkey org-mode-map "\C-i" 'org-cycle)
16111 (org-defkey org-mode-map [(tab)] 'org-cycle)
16112 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
16113 (org-defkey org-mode-map [(meta tab)] 'org-complete)
16114 (org-defkey org-mode-map "\M-\t" 'org-complete)
16115 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
16116 ;; The following line is necessary under Suse GNU/Linux
16117 (unless (featurep 'xemacs)
16118 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
16119 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
16120 (define-key org-mode-map [backtab] 'org-shifttab)
16122 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
16123 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
16124 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
16126 ;; Cursor keys with modifiers
16127 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
16128 (org-defkey org-mode-map [(meta right)] 'org-metaright)
16129 (org-defkey org-mode-map [(meta up)] 'org-metaup)
16130 (org-defkey org-mode-map [(meta down)] 'org-metadown)
16132 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
16133 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
16134 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
16135 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
16137 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
16138 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
16139 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
16140 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
16142 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
16143 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
16145 ;; Babel keys
16146 (define-key org-mode-map org-babel-key-prefix org-babel-map)
16147 (mapc (lambda (pair)
16148 (define-key org-babel-map (car pair) (cdr pair)))
16149 org-babel-key-bindings)
16151 ;;; Extra keys for tty access.
16152 ;; We only set them when really needed because otherwise the
16153 ;; menus don't show the simple keys
16155 (when (or org-use-extra-keys
16156 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
16157 (not window-system))
16158 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
16159 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
16160 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
16161 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
16162 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
16163 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
16164 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
16165 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
16166 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
16167 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
16168 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
16169 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
16170 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
16171 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
16172 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
16173 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
16174 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
16175 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
16176 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
16177 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
16178 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
16179 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
16180 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
16181 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
16182 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
16183 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
16184 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
16185 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
16187 ;; All the other keys
16189 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
16190 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
16191 (if (boundp 'narrow-map)
16192 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
16193 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
16194 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
16195 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
16196 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
16197 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
16198 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
16199 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
16200 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
16201 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
16202 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
16203 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
16204 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
16205 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
16206 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
16207 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
16208 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
16209 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
16210 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
16211 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
16212 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
16213 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
16214 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
16215 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
16216 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
16217 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
16218 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
16219 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
16220 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
16221 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
16222 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
16223 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
16224 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
16225 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
16226 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
16227 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
16228 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
16229 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
16230 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
16231 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
16232 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
16233 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
16234 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16235 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
16236 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
16237 (org-defkey org-mode-map "\C-c^" 'org-sort)
16238 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
16239 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
16240 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
16241 (org-defkey org-mode-map "\C-m" 'org-return)
16242 (org-defkey org-mode-map "\C-j" 'org-return-indent)
16243 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
16244 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
16245 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
16246 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
16247 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
16248 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
16249 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
16250 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
16251 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
16252 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
16253 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
16254 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
16255 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
16256 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
16257 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
16258 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
16259 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
16260 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
16261 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
16262 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
16264 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
16265 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
16266 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
16267 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
16269 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
16270 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
16271 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
16272 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
16273 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
16274 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
16275 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
16276 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
16277 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
16278 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
16279 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
16280 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
16281 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
16282 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
16283 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
16284 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
16285 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
16287 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
16288 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
16289 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
16290 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
16292 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
16294 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
16296 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
16297 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
16299 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
16302 (when (featurep 'xemacs)
16303 (org-defkey org-mode-map 'button3 'popup-mode-menu))
16306 (defconst org-speed-commands-default
16308 ("Outline Navigation")
16309 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
16310 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
16311 ("f" . (org-speed-move-safe 'org-forward-same-level))
16312 ("b" . (org-speed-move-safe 'org-backward-same-level))
16313 ("u" . (org-speed-move-safe 'outline-up-heading))
16314 ("j" . org-goto)
16315 ("g" . (org-refile t))
16316 ("Outline Visibility")
16317 ("c" . org-cycle)
16318 ("C" . org-shifttab)
16319 (" " . org-display-outline-path)
16320 ("Outline Structure Editing")
16321 ("U" . org-shiftmetaup)
16322 ("D" . org-shiftmetadown)
16323 ("r" . org-metaright)
16324 ("l" . org-metaleft)
16325 ("R" . org-shiftmetaright)
16326 ("L" . org-shiftmetaleft)
16327 ("i" . (progn (forward-char 1) (call-interactively
16328 'org-insert-heading-respect-content)))
16329 ("^" . org-sort)
16330 ("w" . org-refile)
16331 ("a" . org-archive-subtree-default-with-confirmation)
16332 ("." . outline-mark-subtree)
16333 ("Clock Commands")
16334 ("I" . org-clock-in)
16335 ("O" . org-clock-out)
16336 ("Meta Data Editing")
16337 ("t" . org-todo)
16338 ("0" . (org-priority ?\ ))
16339 ("1" . (org-priority ?A))
16340 ("2" . (org-priority ?B))
16341 ("3" . (org-priority ?C))
16342 (";" . org-set-tags-command)
16343 ("e" . org-set-effort)
16344 ("Agenda Views etc")
16345 ("v" . org-agenda)
16346 ("/" . org-sparse-tree)
16347 ("Misc")
16348 ("o" . org-open-at-point)
16349 ("?" . org-speed-command-help)
16351 "The default speed commands.")
16353 (defun org-print-speed-command (e)
16354 (if (> (length (car e)) 1)
16355 (progn
16356 (princ "\n")
16357 (princ (car e))
16358 (princ "\n")
16359 (princ (make-string (length (car e)) ?-))
16360 (princ "\n"))
16361 (princ (car e))
16362 (princ " ")
16363 (if (symbolp (cdr e))
16364 (princ (symbol-name (cdr e)))
16365 (prin1 (cdr e)))
16366 (princ "\n")))
16368 (defun org-speed-command-help ()
16369 "Show the available speed commands."
16370 (interactive)
16371 (if (not org-use-speed-commands)
16372 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
16373 (with-output-to-temp-buffer "*Help*"
16374 (princ "User-defined Speed commands\n===========================\n")
16375 (mapc 'org-print-speed-command org-speed-commands-user)
16376 (princ "\n")
16377 (princ "Built-in Speed commands\n=======================\n")
16378 (mapc 'org-print-speed-command org-speed-commands-default))
16379 (with-current-buffer "*Help*"
16380 (setq truncate-lines t))))
16382 (defun org-speed-move-safe (cmd)
16383 "Execute CMD, but make sure that the cursor always ends up in a headline.
16384 If not, return to the original position and throw an error."
16385 (interactive)
16386 (let ((pos (point)))
16387 (call-interactively cmd)
16388 (unless (and (bolp) (org-on-heading-p))
16389 (goto-char pos)
16390 (error "Boundary reached while executing %s" cmd))))
16392 (defvar org-self-insert-command-undo-counter 0)
16394 (defvar org-table-auto-blank-field) ; defined in org-table.el
16395 (defvar org-speed-command nil)
16396 (defun org-self-insert-command (N)
16397 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
16398 If the cursor is in a table looking at whitespace, the whitespace is
16399 overwritten, and the table is not marked as requiring realignment."
16400 (interactive "p")
16401 (cond
16402 ((and org-use-speed-commands
16403 (or (and (bolp) (looking-at outline-regexp))
16404 (and (functionp org-use-speed-commands)
16405 (funcall org-use-speed-commands)))
16406 (setq
16407 org-speed-command
16408 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
16409 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
16410 (cond
16411 ((commandp org-speed-command)
16412 (setq this-command org-speed-command)
16413 (call-interactively org-speed-command))
16414 ((functionp org-speed-command)
16415 (funcall org-speed-command))
16416 ((and org-speed-command (listp org-speed-command))
16417 (eval org-speed-command))
16418 (t (let (org-use-speed-commands)
16419 (call-interactively 'org-self-insert-command)))))
16420 ((and
16421 (org-table-p)
16422 (progn
16423 ;; check if we blank the field, and if that triggers align
16424 (and (featurep 'org-table) org-table-auto-blank-field
16425 (member last-command
16426 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
16427 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
16428 ;; got extra space, this field does not determine column width
16429 (let (org-table-may-need-update) (org-table-blank-field))
16430 ;; no extra space, this field may determine column width
16431 (org-table-blank-field)))
16433 (eq N 1)
16434 (looking-at "[^|\n]* |"))
16435 (let (org-table-may-need-update)
16436 (goto-char (1- (match-end 0)))
16437 (delete-backward-char 1)
16438 (goto-char (match-beginning 0))
16439 (self-insert-command N)))
16441 (setq org-table-may-need-update t)
16442 (self-insert-command N)
16443 (org-fix-tags-on-the-fly)
16444 (if org-self-insert-cluster-for-undo
16445 (if (not (eq last-command 'org-self-insert-command))
16446 (setq org-self-insert-command-undo-counter 1)
16447 (if (>= org-self-insert-command-undo-counter 20)
16448 (setq org-self-insert-command-undo-counter 1)
16449 (and (> org-self-insert-command-undo-counter 0)
16450 buffer-undo-list
16451 (not (cadr buffer-undo-list)) ; remove nil entry
16452 (setcdr buffer-undo-list (cddr buffer-undo-list)))
16453 (setq org-self-insert-command-undo-counter
16454 (1+ org-self-insert-command-undo-counter))))))))
16456 (defun org-fix-tags-on-the-fly ()
16457 (when (and (equal (char-after (point-at-bol)) ?*)
16458 (org-on-heading-p))
16459 (org-align-tags-here org-tags-column)))
16461 (defun org-delete-backward-char (N)
16462 "Like `delete-backward-char', insert whitespace at field end in tables.
16463 When deleting backwards, in tables this function will insert whitespace in
16464 front of the next \"|\" separator, to keep the table aligned. The table will
16465 still be marked for re-alignment if the field did fill the entire column,
16466 because, in this case the deletion might narrow the column."
16467 (interactive "p")
16468 (if (and (org-table-p)
16469 (eq N 1)
16470 (string-match "|" (buffer-substring (point-at-bol) (point)))
16471 (looking-at ".*?|"))
16472 (let ((pos (point))
16473 (noalign (looking-at "[^|\n\r]* |"))
16474 (c org-table-may-need-update))
16475 (backward-delete-char N)
16476 (skip-chars-forward "^|")
16477 (insert " ")
16478 (goto-char (1- pos))
16479 ;; noalign: if there were two spaces at the end, this field
16480 ;; does not determine the width of the column.
16481 (if noalign (setq org-table-may-need-update c)))
16482 (backward-delete-char N)
16483 (org-fix-tags-on-the-fly)))
16485 (defun org-delete-char (N)
16486 "Like `delete-char', but insert whitespace at field end in tables.
16487 When deleting characters, in tables this function will insert whitespace in
16488 front of the next \"|\" separator, to keep the table aligned. The table will
16489 still be marked for re-alignment if the field did fill the entire column,
16490 because, in this case the deletion might narrow the column."
16491 (interactive "p")
16492 (if (and (org-table-p)
16493 (not (bolp))
16494 (not (= (char-after) ?|))
16495 (eq N 1))
16496 (if (looking-at ".*?|")
16497 (let ((pos (point))
16498 (noalign (looking-at "[^|\n\r]* |"))
16499 (c org-table-may-need-update))
16500 (replace-match (concat
16501 (substring (match-string 0) 1 -1)
16502 " |"))
16503 (goto-char pos)
16504 ;; noalign: if there were two spaces at the end, this field
16505 ;; does not determine the width of the column.
16506 (if noalign (setq org-table-may-need-update c)))
16507 (delete-char N))
16508 (delete-char N)
16509 (org-fix-tags-on-the-fly)))
16511 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
16512 (put 'org-self-insert-command 'delete-selection t)
16513 (put 'orgtbl-self-insert-command 'delete-selection t)
16514 (put 'org-delete-char 'delete-selection 'supersede)
16515 (put 'org-delete-backward-char 'delete-selection 'supersede)
16516 (put 'org-yank 'delete-selection 'yank)
16518 ;; Make `flyspell-mode' delay after some commands
16519 (put 'org-self-insert-command 'flyspell-delayed t)
16520 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
16521 (put 'org-delete-char 'flyspell-delayed t)
16522 (put 'org-delete-backward-char 'flyspell-delayed t)
16524 ;; Make pabbrev-mode expand after org-mode commands
16525 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
16526 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
16528 ;; How to do this: Measure non-white length of current string
16529 ;; If equal to column width, we should realign.
16531 (defun org-remap (map &rest commands)
16532 "In MAP, remap the functions given in COMMANDS.
16533 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
16534 (let (new old)
16535 (while commands
16536 (setq old (pop commands) new (pop commands))
16537 (if (fboundp 'command-remapping)
16538 (org-defkey map (vector 'remap old) new)
16539 (substitute-key-definition old new map global-map)))))
16541 (when (eq org-enable-table-editor 'optimized)
16542 ;; If the user wants maximum table support, we need to hijack
16543 ;; some standard editing functions
16544 (org-remap org-mode-map
16545 'self-insert-command 'org-self-insert-command
16546 'delete-char 'org-delete-char
16547 'delete-backward-char 'org-delete-backward-char)
16548 (org-defkey org-mode-map "|" 'org-force-self-insert))
16550 (defvar org-ctrl-c-ctrl-c-hook nil
16551 "Hook for functions attaching themselves to `C-c C-c'.
16552 This can be used to add additional functionality to the C-c C-c key which
16553 executes context-dependent commands.
16554 Each function will be called with no arguments. The function must check
16555 if the context is appropriate for it to act. If yes, it should do its
16556 thing and then return a non-nil value. If the context is wrong,
16557 just do nothing and return nil.")
16559 (defvar org-tab-first-hook nil
16560 "Hook for functions to attach themselves to TAB.
16561 See `org-ctrl-c-ctrl-c-hook' for more information.
16562 This hook runs as the first action when TAB is pressed, even before
16563 `org-cycle' messes around with the `outline-regexp' to cater for
16564 inline tasks and plain list item folding.
16565 If any function in this hook returns t, any other actions that
16566 would have been caused by TAB (such as table field motion or visibility
16567 cycling) will not occur.")
16569 (defvar org-tab-after-check-for-table-hook nil
16570 "Hook for functions to attach themselves to TAB.
16571 See `org-ctrl-c-ctrl-c-hook' for more information.
16572 This hook runs after it has been established that the cursor is not in a
16573 table, but before checking if the cursor is in a headline or if global cycling
16574 should be done.
16575 If any function in this hook returns t, not other actions like visibility
16576 cycling will be done.")
16578 (defvar org-tab-after-check-for-cycling-hook nil
16579 "Hook for functions to attach themselves to TAB.
16580 See `org-ctrl-c-ctrl-c-hook' for more information.
16581 This hook runs after it has been established that not table field motion and
16582 not visibility should be done because of current context. This is probably
16583 the place where a package like yasnippets can hook in.")
16585 (defvar org-tab-before-tab-emulation-hook nil
16586 "Hook for functions to attach themselves to TAB.
16587 See `org-ctrl-c-ctrl-c-hook' for more information.
16588 This hook runs after every other options for TAB have been exhausted, but
16589 before indentation and \t insertion takes place.")
16591 (defvar org-metaleft-hook nil
16592 "Hook for functions attaching themselves to `M-left'.
16593 See `org-ctrl-c-ctrl-c-hook' for more information.")
16594 (defvar org-metaright-hook nil
16595 "Hook for functions attaching themselves to `M-right'.
16596 See `org-ctrl-c-ctrl-c-hook' for more information.")
16597 (defvar org-metaup-hook nil
16598 "Hook for functions attaching themselves to `M-up'.
16599 See `org-ctrl-c-ctrl-c-hook' for more information.")
16600 (defvar org-metadown-hook nil
16601 "Hook for functions attaching themselves to `M-down'.
16602 See `org-ctrl-c-ctrl-c-hook' for more information.")
16603 (defvar org-shiftmetaleft-hook nil
16604 "Hook for functions attaching themselves to `M-S-left'.
16605 See `org-ctrl-c-ctrl-c-hook' for more information.")
16606 (defvar org-shiftmetaright-hook nil
16607 "Hook for functions attaching themselves to `M-S-right'.
16608 See `org-ctrl-c-ctrl-c-hook' for more information.")
16609 (defvar org-shiftmetaup-hook nil
16610 "Hook for functions attaching themselves to `M-S-up'.
16611 See `org-ctrl-c-ctrl-c-hook' for more information.")
16612 (defvar org-shiftmetadown-hook nil
16613 "Hook for functions attaching themselves to `M-S-down'.
16614 See `org-ctrl-c-ctrl-c-hook' for more information.")
16615 (defvar org-metareturn-hook nil
16616 "Hook for functions attaching themselves to `M-RET'.
16617 See `org-ctrl-c-ctrl-c-hook' for more information.")
16618 (defvar org-shiftup-hook nil
16619 "Hook for functions attaching themselves to `S-up'.
16620 See `org-ctrl-c-ctrl-c-hook' for more information.")
16621 (defvar org-shiftup-final-hook nil
16622 "Hook for functions attaching themselves to `S-up'.
16623 This one runs after all other options except shift-select have been excluded.
16624 See `org-ctrl-c-ctrl-c-hook' for more information.")
16625 (defvar org-shiftdown-hook nil
16626 "Hook for functions attaching themselves to `S-down'.
16627 See `org-ctrl-c-ctrl-c-hook' for more information.")
16628 (defvar org-shiftdown-final-hook nil
16629 "Hook for functions attaching themselves to `S-down'.
16630 This one runs after all other options except shift-select have been excluded.
16631 See `org-ctrl-c-ctrl-c-hook' for more information.")
16632 (defvar org-shiftleft-hook nil
16633 "Hook for functions attaching themselves to `S-left'.
16634 See `org-ctrl-c-ctrl-c-hook' for more information.")
16635 (defvar org-shiftleft-final-hook nil
16636 "Hook for functions attaching themselves to `S-left'.
16637 This one runs after all other options except shift-select have been excluded.
16638 See `org-ctrl-c-ctrl-c-hook' for more information.")
16639 (defvar org-shiftright-hook nil
16640 "Hook for functions attaching themselves to `S-right'.
16641 See `org-ctrl-c-ctrl-c-hook' for more information.")
16642 (defvar org-shiftright-final-hook nil
16643 "Hook for functions attaching themselves to `S-right'.
16644 This one runs after all other options except shift-select have been excluded.
16645 See `org-ctrl-c-ctrl-c-hook' for more information.")
16647 (defun org-modifier-cursor-error ()
16648 "Throw an error, a modified cursor command was applied in wrong context."
16649 (error "This command is active in special context like tables, headlines or items"))
16651 (defun org-shiftselect-error ()
16652 "Throw an error because Shift-Cursor command was applied in wrong context."
16653 (if (and (boundp 'shift-select-mode) shift-select-mode)
16654 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
16655 (error "This command works only in special context like headlines or timestamps")))
16657 (defun org-call-for-shift-select (cmd)
16658 (let ((this-command-keys-shift-translated t))
16659 (call-interactively cmd)))
16661 (defun org-shifttab (&optional arg)
16662 "Global visibility cycling or move to previous table field.
16663 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
16664 on context.
16665 See the individual commands for more information."
16666 (interactive "P")
16667 (cond
16668 ((org-at-table-p) (call-interactively 'org-table-previous-field))
16669 ((integerp arg)
16670 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
16671 (message "Content view to level: %d" arg)
16672 (org-content (prefix-numeric-value arg2))
16673 (setq org-cycle-global-status 'overview)))
16674 (t (call-interactively 'org-global-cycle))))
16676 (defun org-shiftmetaleft ()
16677 "Promote subtree or delete table column.
16678 Calls `org-promote-subtree', `org-outdent-item',
16679 or `org-table-delete-column', depending on context.
16680 See the individual commands for more information."
16681 (interactive)
16682 (cond
16683 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
16684 ((org-at-table-p) (call-interactively 'org-table-delete-column))
16685 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
16686 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
16687 (t (org-modifier-cursor-error))))
16689 (defun org-shiftmetaright ()
16690 "Demote subtree or insert table column.
16691 Calls `org-demote-subtree', `org-indent-item',
16692 or `org-table-insert-column', depending on context.
16693 See the individual commands for more information."
16694 (interactive)
16695 (cond
16696 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
16697 ((org-at-table-p) (call-interactively 'org-table-insert-column))
16698 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
16699 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
16700 (t (org-modifier-cursor-error))))
16702 (defun org-shiftmetaup (&optional arg)
16703 "Move subtree up or kill table row.
16704 Calls `org-move-subtree-up' or `org-table-kill-row' or
16705 `org-move-item-up' depending on context. See the individual commands
16706 for more information."
16707 (interactive "P")
16708 (cond
16709 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
16710 ((org-at-table-p) (call-interactively 'org-table-kill-row))
16711 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
16712 ((org-at-item-p) (call-interactively 'org-move-item-up))
16713 (t (org-modifier-cursor-error))))
16715 (defun org-shiftmetadown (&optional arg)
16716 "Move subtree down or insert table row.
16717 Calls `org-move-subtree-down' or `org-table-insert-row' or
16718 `org-move-item-down', depending on context. See the individual
16719 commands for more information."
16720 (interactive "P")
16721 (cond
16722 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
16723 ((org-at-table-p) (call-interactively 'org-table-insert-row))
16724 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16725 ((org-at-item-p) (call-interactively 'org-move-item-down))
16726 (t (org-modifier-cursor-error))))
16728 (defsubst org-hidden-tree-error ()
16729 (error
16730 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
16732 (defun org-metaleft (&optional arg)
16733 "Promote heading or move table column to left.
16734 Calls `org-do-promote' or `org-table-move-column', depending on context.
16735 With no specific context, calls the Emacs default `backward-word'.
16736 See the individual commands for more information."
16737 (interactive "P")
16738 (cond
16739 ((run-hook-with-args-until-success 'org-metaleft-hook))
16740 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
16741 ((or (org-on-heading-p)
16742 (and (org-region-active-p)
16743 (save-excursion
16744 (goto-char (region-beginning))
16745 (org-on-heading-p))))
16746 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
16747 (call-interactively 'org-do-promote))
16748 ((or (org-at-item-p)
16749 (and (org-region-active-p)
16750 (save-excursion
16751 (goto-char (region-beginning))
16752 (org-at-item-p))))
16753 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
16754 (call-interactively 'org-outdent-item))
16755 (t (call-interactively 'backward-word))))
16757 (defun org-metaright (&optional arg)
16758 "Demote subtree or move table column to right.
16759 Calls `org-do-demote' or `org-table-move-column', depending on context.
16760 With no specific context, calls the Emacs default `forward-word'.
16761 See the individual commands for more information."
16762 (interactive "P")
16763 (cond
16764 ((run-hook-with-args-until-success 'org-metaright-hook))
16765 ((org-at-table-p) (call-interactively 'org-table-move-column))
16766 ((or (org-on-heading-p)
16767 (and (org-region-active-p)
16768 (save-excursion
16769 (goto-char (region-beginning))
16770 (org-on-heading-p))))
16771 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
16772 (call-interactively 'org-do-demote))
16773 ((or (org-at-item-p)
16774 (and (org-region-active-p)
16775 (save-excursion
16776 (goto-char (region-beginning))
16777 (org-at-item-p))))
16778 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
16779 (call-interactively 'org-indent-item))
16780 (t (call-interactively 'forward-word))))
16782 (defun org-check-for-hidden (what)
16783 "Check if there are hidden headlines/items in the current visual line.
16784 WHAT can be either `headlines' or `items'. If the current line is
16785 an outline or item heading and it has a folded subtree below it,
16786 this fucntion returns t, nil otherwise."
16787 (let ((re (cond
16788 ((eq what 'headlines) (concat "^" org-outline-regexp))
16789 ((eq what 'items) (concat "^" (org-item-re t)))
16790 (t (error "This should not happen"))))
16791 beg end)
16792 (save-excursion
16793 (catch 'exit
16794 (unless (org-region-active-p)
16795 (setq beg (point-at-bol))
16796 (beginning-of-line 2)
16797 (while (and (not (eobp)) ;; this is like `next-line'
16798 (get-char-property (1- (point)) 'invisible))
16799 (beginning-of-line 2))
16800 (setq end (point))
16801 (goto-char beg)
16802 (goto-char (point-at-eol))
16803 (setq end (max end (point)))
16804 (while (re-search-forward re end t)
16805 (if (get-char-property (match-beginning 0) 'invisible)
16806 (throw 'exit t))))
16807 nil))))
16809 (defun org-metaup (&optional arg)
16810 "Move subtree up or move table row up.
16811 Calls `org-move-subtree-up' or `org-table-move-row' or
16812 `org-move-item-up', depending on context. See the individual commands
16813 for more information."
16814 (interactive "P")
16815 (cond
16816 ((run-hook-with-args-until-success 'org-metaup-hook))
16817 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
16818 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
16819 ((org-at-item-p) (call-interactively 'org-move-item-up))
16820 (t (transpose-lines 1) (beginning-of-line -1))))
16822 (defun org-metadown (&optional arg)
16823 "Move subtree down or move table row down.
16824 Calls `org-move-subtree-down' or `org-table-move-row' or
16825 `org-move-item-down', depending on context. See the individual
16826 commands for more information."
16827 (interactive "P")
16828 (cond
16829 ((run-hook-with-args-until-success 'org-metadown-hook))
16830 ((org-at-table-p) (call-interactively 'org-table-move-row))
16831 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16832 ((org-at-item-p) (call-interactively 'org-move-item-down))
16833 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
16835 (defun org-shiftup (&optional arg)
16836 "Increase item in timestamp or increase priority of current headline.
16837 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
16838 depending on context. See the individual commands for more information."
16839 (interactive "P")
16840 (cond
16841 ((run-hook-with-args-until-success 'org-shiftup-hook))
16842 ((and org-support-shift-select (org-region-active-p))
16843 (org-call-for-shift-select 'previous-line))
16844 ((org-at-timestamp-p t)
16845 (call-interactively (if org-edit-timestamp-down-means-later
16846 'org-timestamp-down 'org-timestamp-up)))
16847 ((and (not (eq org-support-shift-select 'always))
16848 org-enable-priority-commands
16849 (org-on-heading-p))
16850 (call-interactively 'org-priority-up))
16851 ((and (not org-support-shift-select) (org-at-item-p))
16852 (call-interactively 'org-previous-item))
16853 ((org-clocktable-try-shift 'up arg))
16854 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
16855 (org-support-shift-select
16856 (org-call-for-shift-select 'previous-line))
16857 (t (org-shiftselect-error))))
16859 (defun org-shiftdown (&optional arg)
16860 "Decrease item in timestamp or decrease priority of current headline.
16861 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
16862 depending on context. See the individual commands for more information."
16863 (interactive "P")
16864 (cond
16865 ((run-hook-with-args-until-success 'org-shiftdown-hook))
16866 ((and org-support-shift-select (org-region-active-p))
16867 (org-call-for-shift-select 'next-line))
16868 ((org-at-timestamp-p t)
16869 (call-interactively (if org-edit-timestamp-down-means-later
16870 'org-timestamp-up 'org-timestamp-down)))
16871 ((and (not (eq org-support-shift-select 'always))
16872 org-enable-priority-commands
16873 (org-on-heading-p))
16874 (call-interactively 'org-priority-down))
16875 ((and (not org-support-shift-select) (org-at-item-p))
16876 (call-interactively 'org-next-item))
16877 ((org-clocktable-try-shift 'down arg))
16878 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
16879 (org-support-shift-select
16880 (org-call-for-shift-select 'next-line))
16881 (t (org-shiftselect-error))))
16883 (defun org-shiftright (&optional arg)
16884 "Cycle the thing at point or in the current line, depending on context.
16885 Depending on context, this does one of the following:
16887 - switch a timestamp at point one day into the future
16888 - on a headline, switch to the next TODO keyword.
16889 - on an item, switch entire list to the next bullet type
16890 - on a property line, switch to the next allowed value
16891 - on a clocktable definition line, move time block into the future"
16892 (interactive "P")
16893 (cond
16894 ((run-hook-with-args-until-success 'org-shiftright-hook))
16895 ((and org-support-shift-select (org-region-active-p))
16896 (org-call-for-shift-select 'forward-char))
16897 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
16898 ((and (not (eq org-support-shift-select 'always))
16899 (org-on-heading-p))
16900 (let ((org-inhibit-logging
16901 (not org-treat-S-cursor-todo-selection-as-state-change))
16902 (org-inhibit-blocking
16903 (not org-treat-S-cursor-todo-selection-as-state-change)))
16904 (org-call-with-arg 'org-todo 'right)))
16905 ((or (and org-support-shift-select
16906 (not (eq org-support-shift-select 'always))
16907 (org-at-item-bullet-p))
16908 (and (not org-support-shift-select) (org-at-item-p)))
16909 (org-call-with-arg 'org-cycle-list-bullet nil))
16910 ((and (not (eq org-support-shift-select 'always))
16911 (org-at-property-p))
16912 (call-interactively 'org-property-next-allowed-value))
16913 ((org-clocktable-try-shift 'right arg))
16914 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
16915 (org-support-shift-select
16916 (org-call-for-shift-select 'forward-char))
16917 (t (org-shiftselect-error))))
16919 (defun org-shiftleft (&optional arg)
16920 "Cycle the thing at point or in the current line, depending on context.
16921 Depending on context, this does one of the following:
16923 - switch a timestamp at point one day into the past
16924 - on a headline, switch to the previous TODO keyword.
16925 - on an item, switch entire list to the previous bullet type
16926 - on a property line, switch to the previous allowed value
16927 - on a clocktable definition line, move time block into the past"
16928 (interactive "P")
16929 (cond
16930 ((run-hook-with-args-until-success 'org-shiftleft-hook))
16931 ((and org-support-shift-select (org-region-active-p))
16932 (org-call-for-shift-select 'backward-char))
16933 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
16934 ((and (not (eq org-support-shift-select 'always))
16935 (org-on-heading-p))
16936 (let ((org-inhibit-logging
16937 (not org-treat-S-cursor-todo-selection-as-state-change))
16938 (org-inhibit-blocking
16939 (not org-treat-S-cursor-todo-selection-as-state-change)))
16940 (org-call-with-arg 'org-todo 'left)))
16941 ((or (and org-support-shift-select
16942 (not (eq org-support-shift-select 'always))
16943 (org-at-item-bullet-p))
16944 (and (not org-support-shift-select) (org-at-item-p)))
16945 (org-call-with-arg 'org-cycle-list-bullet 'previous))
16946 ((and (not (eq org-support-shift-select 'always))
16947 (org-at-property-p))
16948 (call-interactively 'org-property-previous-allowed-value))
16949 ((org-clocktable-try-shift 'left arg))
16950 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
16951 (org-support-shift-select
16952 (org-call-for-shift-select 'backward-char))
16953 (t (org-shiftselect-error))))
16955 (defun org-shiftcontrolright ()
16956 "Switch to next TODO set."
16957 (interactive)
16958 (cond
16959 ((and org-support-shift-select (org-region-active-p))
16960 (org-call-for-shift-select 'forward-word))
16961 ((and (not (eq org-support-shift-select 'always))
16962 (org-on-heading-p))
16963 (org-call-with-arg 'org-todo 'nextset))
16964 (org-support-shift-select
16965 (org-call-for-shift-select 'forward-word))
16966 (t (org-shiftselect-error))))
16968 (defun org-shiftcontrolleft ()
16969 "Switch to previous TODO set."
16970 (interactive)
16971 (cond
16972 ((and org-support-shift-select (org-region-active-p))
16973 (org-call-for-shift-select 'backward-word))
16974 ((and (not (eq org-support-shift-select 'always))
16975 (org-on-heading-p))
16976 (org-call-with-arg 'org-todo 'previousset))
16977 (org-support-shift-select
16978 (org-call-for-shift-select 'backward-word))
16979 (t (org-shiftselect-error))))
16981 (defun org-ctrl-c-ret ()
16982 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
16983 (interactive)
16984 (cond
16985 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
16986 (t (call-interactively 'org-insert-heading))))
16988 (defun org-copy-special ()
16989 "Copy region in table or copy current subtree.
16990 Calls `org-table-copy' or `org-copy-subtree', depending on context.
16991 See the individual commands for more information."
16992 (interactive)
16993 (call-interactively
16994 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
16996 (defun org-cut-special ()
16997 "Cut region in table or cut current subtree.
16998 Calls `org-table-copy' or `org-cut-subtree', depending on context.
16999 See the individual commands for more information."
17000 (interactive)
17001 (call-interactively
17002 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
17004 (defun org-paste-special (arg)
17005 "Paste rectangular region into table, or past subtree relative to level.
17006 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
17007 See the individual commands for more information."
17008 (interactive "P")
17009 (if (org-at-table-p)
17010 (org-table-paste-rectangle)
17011 (org-paste-subtree arg)))
17013 (defun org-edit-special (&optional arg)
17014 "Call a special editor for the stuff at point.
17015 When at a table, call the formula editor with `org-table-edit-formulas'.
17016 When at the first line of an src example, call `org-edit-src-code'.
17017 When in an #+include line, visit the include file. Otherwise call
17018 `ffap' to visit the file at point."
17019 (interactive)
17020 ;; possibly prep session before editing source
17021 (when arg
17022 (let* ((info (org-babel-get-src-block-info))
17023 (lang (nth 0 info))
17024 (params (nth 2 info))
17025 (session (cdr (assoc :session params))))
17026 (when (and info session) ;; we are in a source-code block with a session
17027 (funcall
17028 (intern (concat "org-babel-prep-session:" lang)) session params))))
17029 (cond ;; proceed with `org-edit-special'
17030 ((save-excursion
17031 (beginning-of-line 1)
17032 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
17033 (find-file (org-trim (match-string 1))))
17034 ((org-edit-src-code))
17035 ((org-edit-fixed-width-region))
17036 ((org-at-table.el-p)
17037 (org-edit-src-code))
17038 ((org-at-table-p)
17039 (call-interactively 'org-table-edit-formulas))
17040 (t (call-interactively 'ffap))))
17043 (defun org-ctrl-c-ctrl-c (&optional arg)
17044 "Set tags in headline, or update according to changed information at point.
17046 This command does many different things, depending on context:
17048 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
17049 this is what we do.
17051 - If the cursor is on a statistics cookie, update it.
17053 - If the cursor is in a headline, prompt for tags and insert them
17054 into the current line, aligned to `org-tags-column'. When called
17055 with prefix arg, realign all tags in the current buffer.
17057 - If the cursor is in one of the special #+KEYWORD lines, this
17058 triggers scanning the buffer for these lines and updating the
17059 information.
17061 - If the cursor is inside a table, realign the table. This command
17062 works even if the automatic table editor has been turned off.
17064 - If the cursor is on a #+TBLFM line, re-apply the formulas to
17065 the entire table.
17067 - If the cursor is at a footnote reference or definition, jump to
17068 the corresponding definition or references, respectively.
17070 - If the cursor is a the beginning of a dynamic block, update it.
17072 - If the current buffer is a remember buffer, close note and file
17073 it. A prefix argument of 1 files to the default location
17074 without further interaction. A prefix argument of 2 files to
17075 the currently clocking task.
17077 - If the cursor is on a <<<target>>>, update radio targets and corresponding
17078 links in this buffer.
17080 - If the cursor is on a numbered item in a plain list, renumber the
17081 ordered list.
17083 - If the cursor is on a checkbox, toggle it.
17085 - If the cursor is on a code block, evaluate it. The variable
17086 `org-confirm-babel-evaluate' can be used to control prompting
17087 before code block evaluation, by default every code block
17088 evaluation requires confirmation. Code block evaluation can be
17089 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
17090 (interactive "P")
17091 (let ((org-enable-table-editor t))
17092 (cond
17093 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
17094 org-occur-highlights
17095 org-latex-fragment-image-overlays)
17096 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
17097 (org-remove-occur-highlights)
17098 (org-remove-latex-fragment-image-overlays)
17099 (message "Temporary highlights/overlays removed from current buffer"))
17100 ((and (local-variable-p 'org-finish-function (current-buffer))
17101 (fboundp org-finish-function))
17102 (funcall org-finish-function))
17103 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
17104 ((or (looking-at org-property-start-re)
17105 (org-at-property-p))
17106 (call-interactively 'org-property-action))
17107 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
17108 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
17109 (or (org-on-heading-p) (org-at-item-p)))
17110 (call-interactively 'org-update-statistics-cookies))
17111 ((org-on-heading-p) (call-interactively 'org-set-tags))
17112 ((org-at-table.el-p)
17113 (message "Use C-c ' to edit table.el tables"))
17114 ((org-at-table-p)
17115 (org-table-maybe-eval-formula)
17116 (if arg
17117 (call-interactively 'org-table-recalculate)
17118 (org-table-maybe-recalculate-line))
17119 (call-interactively 'org-table-align))
17120 ((or (org-footnote-at-reference-p)
17121 (org-footnote-at-definition-p))
17122 (call-interactively 'org-footnote-action))
17123 ((org-at-item-checkbox-p)
17124 (call-interactively 'org-toggle-checkbox))
17125 ((org-at-item-p)
17126 (if arg
17127 (call-interactively 'org-toggle-checkbox)
17128 (call-interactively 'org-maybe-renumber-ordered-list)))
17129 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
17130 ;; Dynamic block
17131 (beginning-of-line 1)
17132 (save-excursion (org-update-dblock)))
17133 ((save-excursion
17134 (beginning-of-line 1)
17135 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
17136 (cond
17137 ((equal (match-string 1) "TBLFM")
17138 ;; Recalculate the table before this line
17139 (save-excursion
17140 (beginning-of-line 1)
17141 (skip-chars-backward " \r\n\t")
17142 (if (org-at-table-p)
17143 (org-call-with-arg 'org-table-recalculate (or arg t)))))
17145 (let ((org-inhibit-startup-visibility-stuff t)
17146 (org-startup-align-all-tables nil))
17147 (org-save-outline-visibility 'use-markers (org-mode-restart)))
17148 (message "Local setup has been refreshed"))))
17149 ((org-clock-update-time-maybe))
17150 (t (error "C-c C-c can do nothing useful at this location")))))
17152 (defun org-mode-restart ()
17153 "Restart Org-mode, to scan again for special lines.
17154 Also updates the keyword regular expressions."
17155 (interactive)
17156 (org-mode)
17157 (message "Org-mode restarted"))
17159 (defun org-kill-note-or-show-branches ()
17160 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
17161 (interactive)
17162 (if (not org-finish-function)
17163 (progn
17164 (hide-subtree)
17165 (call-interactively 'show-branches))
17166 (let ((org-note-abort t))
17167 (funcall org-finish-function))))
17169 (defun org-return (&optional indent)
17170 "Goto next table row or insert a newline.
17171 Calls `org-table-next-row' or `newline', depending on context.
17172 See the individual commands for more information."
17173 (interactive)
17174 (cond
17175 ((bobp) (if indent (newline-and-indent) (newline)))
17176 ((org-at-table-p)
17177 (org-table-justify-field-maybe)
17178 (call-interactively 'org-table-next-row))
17179 ((and org-return-follows-link
17180 (eq (get-text-property (point) 'face) 'org-link))
17181 (call-interactively 'org-open-at-point))
17182 ((and (org-at-heading-p)
17183 (looking-at
17184 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
17185 (org-show-entry)
17186 (end-of-line 1)
17187 (newline))
17188 (t (if indent (newline-and-indent) (newline)))))
17190 (defun org-return-indent ()
17191 "Goto next table row or insert a newline and indent.
17192 Calls `org-table-next-row' or `newline-and-indent', depending on
17193 context. See the individual commands for more information."
17194 (interactive)
17195 (org-return t))
17197 (defun org-ctrl-c-star ()
17198 "Compute table, or change heading status of lines.
17199 Calls `org-table-recalculate' or `org-toggle-heading',
17200 depending on context."
17201 (interactive)
17202 (cond
17203 ((org-at-table-p)
17204 (call-interactively 'org-table-recalculate))
17206 ;; Convert all lines in region to list items
17207 (call-interactively 'org-toggle-heading))))
17209 (defun org-ctrl-c-minus ()
17210 "Insert separator line in table or modify bullet status of line.
17211 Also turns a plain line or a region of lines into list items.
17212 Calls `org-table-insert-hline', `org-toggle-item', or
17213 `org-cycle-list-bullet', depending on context."
17214 (interactive)
17215 (cond
17216 ((org-at-table-p)
17217 (call-interactively 'org-table-insert-hline))
17218 ((org-region-active-p)
17219 (call-interactively 'org-toggle-item))
17220 ((org-in-item-p)
17221 (call-interactively 'org-cycle-list-bullet))
17223 (call-interactively 'org-toggle-item))))
17225 (defun org-toggle-item ()
17226 "Convert headings or normal lines to items, items to normal lines.
17227 If there is no active region, only the current line is considered.
17229 If the first line in the region is a headline, convert all headlines to items.
17231 If the first line in the region is an item, convert all items to normal lines.
17233 If the first line is normal text, add an item bullet to each line."
17234 (interactive)
17235 (let (l2 l beg end)
17236 (if (org-region-active-p)
17237 (setq beg (region-beginning) end (region-end))
17238 (setq beg (point-at-bol)
17239 end (min (1+ (point-at-eol)) (point-max))))
17240 (save-excursion
17241 (goto-char end)
17242 (setq l2 (org-current-line))
17243 (goto-char beg)
17244 (beginning-of-line 1)
17245 (setq l (1- (org-current-line)))
17246 (if (org-at-item-p)
17247 ;; We already have items, de-itemize
17248 (while (< (setq l (1+ l)) l2)
17249 (when (org-at-item-p)
17250 (goto-char (match-beginning 2))
17251 (delete-region (match-beginning 2) (match-end 2))
17252 (and (looking-at "[ \t]+") (replace-match "")))
17253 (beginning-of-line 2))
17254 (if (org-on-heading-p)
17255 ;; Headings, convert to items
17256 (while (< (setq l (1+ l)) l2)
17257 (if (looking-at org-outline-regexp)
17258 (replace-match "- " t t))
17259 (beginning-of-line 2))
17260 ;; normal lines, turn them into items
17261 (while (< (setq l (1+ l)) l2)
17262 (unless (org-at-item-p)
17263 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
17264 (replace-match "\\1- \\2")))
17265 (beginning-of-line 2)))))))
17267 (defun org-toggle-heading (&optional nstars)
17268 "Convert headings to normal text, or items or text to headings.
17269 If there is no active region, only the current line is considered.
17271 If the first line is a heading, remove the stars from all headlines
17272 in the region.
17274 If the first line is a plain list item, turn all plain list items
17275 into headings.
17277 If the first line is a normal line, turn each and every line in the
17278 region into a heading.
17280 When converting a line into a heading, the number of stars is chosen
17281 such that the lines become children of the current entry. However,
17282 when a prefix argument is given, its value determines the number of
17283 stars to add."
17284 (interactive "P")
17285 (let (l2 l itemp beg end)
17286 (if (org-region-active-p)
17287 (setq beg (region-beginning) end (region-end))
17288 (setq beg (point-at-bol)
17289 end (min (1+ (point-at-eol)) (point-max))))
17290 (save-excursion
17291 (goto-char end)
17292 (setq l2 (org-current-line))
17293 (goto-char beg)
17294 (beginning-of-line 1)
17295 (setq l (1- (org-current-line)))
17296 (if (org-on-heading-p)
17297 ;; We already have headlines, de-star them
17298 (while (< (setq l (1+ l)) l2)
17299 (when (org-on-heading-p t)
17300 (and (looking-at outline-regexp) (replace-match "")))
17301 (beginning-of-line 2))
17302 (setq itemp (org-at-item-p))
17303 (let* ((stars
17304 (if nstars
17305 (make-string (prefix-numeric-value current-prefix-arg)
17307 (save-excursion
17308 (if (re-search-backward org-complex-heading-regexp nil t)
17309 (match-string 1) ""))))
17310 (add-stars (cond (nstars "")
17311 ((equal stars "") "*")
17312 (org-odd-levels-only "**")
17313 (t "*")))
17314 (rpl (concat stars add-stars " ")))
17315 (while (< (setq l (1+ l)) l2)
17316 (if itemp
17317 (and (org-at-item-p) (replace-match rpl t t))
17318 (unless (org-on-heading-p)
17319 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
17320 (replace-match (concat rpl (match-string 2))))))
17321 (beginning-of-line 2)))))))
17323 (defun org-meta-return (&optional arg)
17324 "Insert a new heading or wrap a region in a table.
17325 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
17326 See the individual commands for more information."
17327 (interactive "P")
17328 (cond
17329 ((run-hook-with-args-until-success 'org-metareturn-hook))
17330 ((org-at-table-p)
17331 (call-interactively 'org-table-wrap-region))
17332 (t (call-interactively 'org-insert-heading))))
17334 ;;; Menu entries
17336 ;; Define the Org-mode menus
17337 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
17338 '("Tbl"
17339 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
17340 ["Next Field" org-cycle (org-at-table-p)]
17341 ["Previous Field" org-shifttab (org-at-table-p)]
17342 ["Next Row" org-return (org-at-table-p)]
17343 "--"
17344 ["Blank Field" org-table-blank-field (org-at-table-p)]
17345 ["Edit Field" org-table-edit-field (org-at-table-p)]
17346 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
17347 "--"
17348 ("Column"
17349 ["Move Column Left" org-metaleft (org-at-table-p)]
17350 ["Move Column Right" org-metaright (org-at-table-p)]
17351 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
17352 ["Insert Column" org-shiftmetaright (org-at-table-p)])
17353 ("Row"
17354 ["Move Row Up" org-metaup (org-at-table-p)]
17355 ["Move Row Down" org-metadown (org-at-table-p)]
17356 ["Delete Row" org-shiftmetaup (org-at-table-p)]
17357 ["Insert Row" org-shiftmetadown (org-at-table-p)]
17358 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
17359 "--"
17360 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
17361 ("Rectangle"
17362 ["Copy Rectangle" org-copy-special (org-at-table-p)]
17363 ["Cut Rectangle" org-cut-special (org-at-table-p)]
17364 ["Paste Rectangle" org-paste-special (org-at-table-p)]
17365 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
17366 "--"
17367 ("Calculate"
17368 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
17369 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
17370 ["Edit Formulas" org-edit-special (org-at-table-p)]
17371 "--"
17372 ["Recalculate line" org-table-recalculate (org-at-table-p)]
17373 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
17374 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
17375 "--"
17376 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
17377 "--"
17378 ["Sum Column/Rectangle" org-table-sum
17379 (or (org-at-table-p) (org-region-active-p))]
17380 ["Which Column?" org-table-current-column (org-at-table-p)])
17381 ["Debug Formulas"
17382 org-table-toggle-formula-debugger
17383 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
17384 ["Show Col/Row Numbers"
17385 org-table-toggle-coordinate-overlays
17386 :style toggle
17387 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
17388 "--"
17389 ["Create" org-table-create (and (not (org-at-table-p))
17390 org-enable-table-editor)]
17391 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
17392 ["Import from File" org-table-import (not (org-at-table-p))]
17393 ["Export to File" org-table-export (org-at-table-p)]
17394 "--"
17395 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
17397 (easy-menu-define org-org-menu org-mode-map "Org menu"
17398 '("Org"
17399 ("Show/Hide"
17400 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
17401 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
17402 ["Sparse Tree..." org-sparse-tree t]
17403 ["Reveal Context" org-reveal t]
17404 ["Show All" show-all t]
17405 "--"
17406 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
17407 "--"
17408 ["New Heading" org-insert-heading t]
17409 ("Navigate Headings"
17410 ["Up" outline-up-heading t]
17411 ["Next" outline-next-visible-heading t]
17412 ["Previous" outline-previous-visible-heading t]
17413 ["Next Same Level" outline-forward-same-level t]
17414 ["Previous Same Level" outline-backward-same-level t]
17415 "--"
17416 ["Jump" org-goto t])
17417 ("Edit Structure"
17418 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
17419 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
17420 "--"
17421 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
17422 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
17423 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
17424 "--"
17425 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
17426 "--"
17427 ["Promote Heading" org-metaleft (not (org-at-table-p))]
17428 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
17429 ["Demote Heading" org-metaright (not (org-at-table-p))]
17430 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
17431 "--"
17432 ["Sort Region/Children" org-sort (not (org-at-table-p))]
17433 "--"
17434 ["Convert to odd levels" org-convert-to-odd-levels t]
17435 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
17436 ("Editing"
17437 ["Emphasis..." org-emphasize t]
17438 ["Edit Source Example" org-edit-special t]
17439 "--"
17440 ["Footnote new/jump" org-footnote-action t]
17441 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
17442 ("Archive"
17443 ["Archive (default method)" org-archive-subtree-default t]
17444 "--"
17445 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
17446 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
17447 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
17449 "--"
17450 ("Hyperlinks"
17451 ["Store Link (Global)" org-store-link t]
17452 ["Find existing link to here" org-occur-link-in-agenda-files t]
17453 ["Insert Link" org-insert-link t]
17454 ["Follow Link" org-open-at-point t]
17455 "--"
17456 ["Next link" org-next-link t]
17457 ["Previous link" org-previous-link t]
17458 "--"
17459 ["Descriptive Links"
17460 (progn (add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
17461 :style radio
17462 :selected (member '(org-link) buffer-invisibility-spec)]
17463 ["Literal Links"
17464 (progn
17465 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
17466 :style radio
17467 :selected (not (member '(org-link) buffer-invisibility-spec))])
17468 "--"
17469 ("TODO Lists"
17470 ["TODO/DONE/-" org-todo t]
17471 ("Select keyword"
17472 ["Next keyword" org-shiftright (org-on-heading-p)]
17473 ["Previous keyword" org-shiftleft (org-on-heading-p)]
17474 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
17475 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
17476 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
17477 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
17478 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
17479 "--"
17480 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
17481 :selected org-enforce-todo-dependencies :style toggle :active t]
17482 "Settings for tree at point"
17483 ["Do Children sequentially" org-toggle-ordered-property :style radio
17484 :selected (ignore-errors (org-entry-get nil "ORDERED"))
17485 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
17486 ["Do Children parallel" org-toggle-ordered-property :style radio
17487 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
17488 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
17489 "--"
17490 ["Set Priority" org-priority t]
17491 ["Priority Up" org-shiftup t]
17492 ["Priority Down" org-shiftdown t]
17493 "--"
17494 ["Get news from all feeds" org-feed-update-all t]
17495 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
17496 ["Customize feeds" (customize-variable 'org-feed-alist) t])
17497 ("TAGS and Properties"
17498 ["Set Tags" org-set-tags-command t]
17499 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
17500 "--"
17501 ["Set property" org-set-property t]
17502 ["Column view of properties" org-columns t]
17503 ["Insert Column View DBlock" org-insert-columns-dblock t])
17504 ("Dates and Scheduling"
17505 ["Timestamp" org-time-stamp t]
17506 ["Timestamp (inactive)" org-time-stamp-inactive t]
17507 ("Change Date"
17508 ["1 Day Later" org-shiftright t]
17509 ["1 Day Earlier" org-shiftleft t]
17510 ["1 ... Later" org-shiftup t]
17511 ["1 ... Earlier" org-shiftdown t])
17512 ["Compute Time Range" org-evaluate-time-range t]
17513 ["Schedule Item" org-schedule t]
17514 ["Deadline" org-deadline t]
17515 "--"
17516 ["Custom time format" org-toggle-time-stamp-overlays
17517 :style radio :selected org-display-custom-times]
17518 "--"
17519 ["Goto Calendar" org-goto-calendar t]
17520 ["Date from Calendar" org-date-from-calendar t]
17521 "--"
17522 ["Start/Restart Timer" org-timer-start t]
17523 ["Pause/Continue Timer" org-timer-pause-or-continue t]
17524 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
17525 ["Insert Timer String" org-timer t]
17526 ["Insert Timer Item" org-timer-item t])
17527 ("Logging work"
17528 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
17529 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
17530 ["Clock out" org-clock-out t]
17531 ["Clock cancel" org-clock-cancel t]
17532 "--"
17533 ["Mark as default task" org-clock-mark-default-task t]
17534 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
17535 ["Goto running clock" org-clock-goto t]
17536 "--"
17537 ["Display times" org-clock-display t]
17538 ["Create clock table" org-clock-report t]
17539 "--"
17540 ["Record DONE time"
17541 (progn (setq org-log-done (not org-log-done))
17542 (message "Switching to %s will %s record a timestamp"
17543 (car org-done-keywords)
17544 (if org-log-done "automatically" "not")))
17545 :style toggle :selected org-log-done])
17546 "--"
17547 ["Agenda Command..." org-agenda t]
17548 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
17549 ("File List for Agenda")
17550 ("Special views current file"
17551 ["TODO Tree" org-show-todo-tree t]
17552 ["Check Deadlines" org-check-deadlines t]
17553 ["Timeline" org-timeline t]
17554 ["Tags/Property tree" org-match-sparse-tree t])
17555 "--"
17556 ["Export/Publish..." org-export t]
17557 ("LaTeX"
17558 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
17559 :selected org-cdlatex-mode]
17560 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
17561 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
17562 ["Modify math symbol" org-cdlatex-math-modify
17563 (org-inside-LaTeX-fragment-p)]
17564 ["Insert citation" org-reftex-citation t]
17565 "--"
17566 ["Export LaTeX fragments as images"
17567 (if (featurep 'org-exp)
17568 (setq org-export-with-LaTeX-fragments
17569 (not org-export-with-LaTeX-fragments))
17570 (require 'org-exp))
17571 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
17572 org-export-with-LaTeX-fragments)]
17573 "--"
17574 ["Template for BEAMER" org-insert-beamer-options-template t])
17575 "--"
17576 ("MobileOrg"
17577 ["Push Files and Views" org-mobile-push t]
17578 ["Get Captured and Flagged" org-mobile-pull t]
17579 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
17580 "--"
17581 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
17582 "--"
17583 ("Documentation"
17584 ["Show Version" org-version t]
17585 ["Info Documentation" org-info t])
17586 ("Customize"
17587 ["Browse Org Group" org-customize t]
17588 "--"
17589 ["Expand This Menu" org-create-customize-menu
17590 (fboundp 'customize-menu-create)])
17591 ["Send bug report" org-submit-bug-report t]
17592 "--"
17593 ("Refresh/Reload"
17594 ["Refresh setup current buffer" org-mode-restart t]
17595 ["Reload Org (after update)" org-reload t]
17596 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
17599 (defun org-info (&optional node)
17600 "Read documentation for Org-mode in the info system.
17601 With optional NODE, go directly to that node."
17602 (interactive)
17603 (info (format "(org)%s" (or node ""))))
17605 ;;;###autoload
17606 (defun org-submit-bug-report ()
17607 "Submit a bug report on Org-mode via mail.
17609 Don't hesitate to report any problems or inaccurate documentation.
17611 If you don't have setup sending mail from (X)Emacs, please copy the
17612 output buffer into your mail program, as it gives us important
17613 information about your Org-mode version and configuration."
17614 (interactive)
17615 (require 'reporter)
17616 (org-load-modules-maybe)
17617 (org-require-autoloaded-modules)
17618 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
17619 (reporter-submit-bug-report
17620 "emacs-orgmode@gnu.org"
17621 (org-version)
17622 (let (list)
17623 (save-window-excursion
17624 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
17625 (delete-other-windows)
17626 (erase-buffer)
17627 (insert "You are about to submit a bug report to the Org-mode mailing list.
17629 We would like to add your full Org-mode and Outline configuration to the
17630 bug report. This greatly simplifies the work of the maintainer and
17631 other experts on the mailing list.
17633 HOWEVER, some variables you have customized may contain private
17634 information. The names of customers, colleagues, or friends, might
17635 appear in the form of file names, tags, todo states, or search strings.
17636 If you answer yes to the prompt, you might want to check and remove
17637 such private information before sending the email.")
17638 (add-text-properties (point-min) (point-max) '(face org-warning))
17639 (when (yes-or-no-p "Include your Org-mode configuration ")
17640 (mapatoms
17641 (lambda (v)
17642 (and (boundp v)
17643 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
17644 (or (and (symbol-value v)
17645 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
17646 (and
17647 (get v 'custom-type) (get v 'standard-value)
17648 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
17649 (push v list)))))
17650 (kill-buffer (get-buffer "*Warn about privacy*"))
17651 list))
17652 nil nil
17653 "Remember to cover the basics, that is, what you expected to happen and
17654 what in fact did happen. You don't know how to make a good report? See
17656 http://orgmode.org/manual/Feedback.html#Feedback
17658 Your bug report will be posted to the Org-mode mailing list.
17659 ------------------------------------------------------------------------")
17660 (save-excursion
17661 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
17662 (replace-match "\\1Bug: \\3 [\\2]")))))
17665 (defun org-install-agenda-files-menu ()
17666 (let ((bl (buffer-list)))
17667 (save-excursion
17668 (while bl
17669 (set-buffer (pop bl))
17670 (if (org-mode-p) (setq bl nil)))
17671 (when (org-mode-p)
17672 (easy-menu-change
17673 '("Org") "File List for Agenda"
17674 (append
17675 (list
17676 ["Edit File List" (org-edit-agenda-file-list) t]
17677 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
17678 ["Remove Current File from List" org-remove-file t]
17679 ["Cycle through agenda files" org-cycle-agenda-files t]
17680 ["Occur in all agenda files" org-occur-in-agenda-files t]
17681 "--")
17682 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
17684 ;;;; Documentation
17686 ;;;###autoload
17687 (defun org-require-autoloaded-modules ()
17688 (interactive)
17689 (mapc 'require
17690 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
17691 org-docbook org-exp org-html org-icalendar
17692 org-id org-latex
17693 org-publish org-remember org-table
17694 org-timer org-xoxo)))
17696 ;;;###autoload
17697 (defun org-reload (&optional uncompiled)
17698 "Reload all org lisp files.
17699 With prefix arg UNCOMPILED, load the uncompiled versions."
17700 (interactive "P")
17701 (require 'find-func)
17702 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
17703 (dir-org (file-name-directory (org-find-library-name "org")))
17704 (dir-org-contrib (ignore-errors
17705 (file-name-directory
17706 (org-find-library-name "org-contribdir"))))
17707 (files
17708 (append (directory-files dir-org t file-re)
17709 (and dir-org-contrib
17710 (directory-files dir-org-contrib t file-re))))
17711 (remove-re (concat (if (featurep 'xemacs)
17712 "org-colview" "org-colview-xemacs")
17713 "\\'")))
17714 (setq files (mapcar 'file-name-sans-extension files))
17715 (setq files (mapcar
17716 (lambda (x) (if (string-match remove-re x) nil x))
17717 files))
17718 (setq files (delq nil files))
17719 (mapc
17720 (lambda (f)
17721 (when (featurep (intern (file-name-nondirectory f)))
17722 (if (and (not uncompiled)
17723 (file-exists-p (concat f ".elc")))
17724 (load (concat f ".elc") nil nil t)
17725 (load (concat f ".el") nil nil t))))
17726 files))
17727 (org-version))
17729 ;;;###autoload
17730 (defun org-customize ()
17731 "Call the customize function with org as argument."
17732 (interactive)
17733 (org-load-modules-maybe)
17734 (org-require-autoloaded-modules)
17735 (customize-browse 'org))
17737 (defun org-create-customize-menu ()
17738 "Create a full customization menu for Org-mode, insert it into the menu."
17739 (interactive)
17740 (org-load-modules-maybe)
17741 (org-require-autoloaded-modules)
17742 (if (fboundp 'customize-menu-create)
17743 (progn
17744 (easy-menu-change
17745 '("Org") "Customize"
17746 `(["Browse Org group" org-customize t]
17747 "--"
17748 ,(customize-menu-create 'org)
17749 ["Set" Custom-set t]
17750 ["Save" Custom-save t]
17751 ["Reset to Current" Custom-reset-current t]
17752 ["Reset to Saved" Custom-reset-saved t]
17753 ["Reset to Standard Settings" Custom-reset-standard t]))
17754 (message "\"Org\"-menu now contains full customization menu"))
17755 (error "Cannot expand menu (outdated version of cus-edit.el)")))
17757 ;;;; Miscellaneous stuff
17759 ;;; Generally useful functions
17761 (defun org-get-at-bol (property)
17762 "Get text property PROPERTY at beginning of line."
17763 (get-text-property (point-at-bol) property))
17765 (defun org-find-text-property-in-string (prop s)
17766 "Return the first non-nil value of property PROP in string S."
17767 (or (get-text-property 0 prop s)
17768 (get-text-property (or (next-single-property-change 0 prop s) 0)
17769 prop s)))
17771 (defun org-display-warning (message) ;; Copied from Emacs-Muse
17772 "Display the given MESSAGE as a warning."
17773 (if (fboundp 'display-warning)
17774 (display-warning 'org message
17775 (if (featurep 'xemacs) 'warning :warning))
17776 (let ((buf (get-buffer-create "*Org warnings*")))
17777 (with-current-buffer buf
17778 (goto-char (point-max))
17779 (insert "Warning (Org): " message)
17780 (unless (bolp)
17781 (newline)))
17782 (display-buffer buf)
17783 (sit-for 0))))
17785 (defun org-in-commented-line ()
17786 "Is point in a line starting with `#'?"
17787 (equal (char-after (point-at-bol)) ?#))
17789 (defun org-in-indented-comment-line ()
17790 "Is point in a line starting with `#' after some white space?"
17791 (save-excursion
17792 (save-match-data
17793 (goto-char (point-at-bol))
17794 (looking-at "[ \t]*#"))))
17796 (defun org-in-verbatim-emphasis ()
17797 (save-match-data
17798 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
17800 (defun org-goto-marker-or-bmk (marker &optional bookmark)
17801 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
17802 (if (and marker (marker-buffer marker)
17803 (buffer-live-p (marker-buffer marker)))
17804 (progn
17805 (switch-to-buffer (marker-buffer marker))
17806 (if (or (> marker (point-max)) (< marker (point-min)))
17807 (widen))
17808 (goto-char marker)
17809 (org-show-context 'org-goto))
17810 (if bookmark
17811 (bookmark-jump bookmark)
17812 (error "Cannot find location"))))
17814 (defun org-quote-csv-field (s)
17815 "Quote field for inclusion in CSV material."
17816 (if (string-match "[\",]" s)
17817 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
17820 (defun org-plist-delete (plist property)
17821 "Delete PROPERTY from PLIST.
17822 This is in contrast to merely setting it to 0."
17823 (let (p)
17824 (while plist
17825 (if (not (eq property (car plist)))
17826 (setq p (plist-put p (car plist) (nth 1 plist))))
17827 (setq plist (cddr plist)))
17830 (defun org-force-self-insert (N)
17831 "Needed to enforce self-insert under remapping."
17832 (interactive "p")
17833 (self-insert-command N))
17835 (defun org-string-width (s)
17836 "Compute width of string, ignoring invisible characters.
17837 This ignores character with invisibility property `org-link', and also
17838 characters with property `org-cwidth', because these will become invisible
17839 upon the next fontification round."
17840 (let (b l)
17841 (when (or (eq t buffer-invisibility-spec)
17842 (assq 'org-link buffer-invisibility-spec))
17843 (while (setq b (text-property-any 0 (length s)
17844 'invisible 'org-link s))
17845 (setq s (concat (substring s 0 b)
17846 (substring s (or (next-single-property-change
17847 b 'invisible s) (length s)))))))
17848 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
17849 (setq s (concat (substring s 0 b)
17850 (substring s (or (next-single-property-change
17851 b 'org-cwidth s) (length s))))))
17852 (setq l (string-width s) b -1)
17853 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
17854 (setq l (- l (get-text-property b 'org-dwidth-n s))))
17857 (defun org-get-indentation (&optional line)
17858 "Get the indentation of the current line, interpreting tabs.
17859 When LINE is given, assume it represents a line and compute its indentation."
17860 (if line
17861 (if (string-match "^ *" (org-remove-tabs line))
17862 (match-end 0))
17863 (save-excursion
17864 (beginning-of-line 1)
17865 (skip-chars-forward " \t")
17866 (current-column))))
17868 (defun org-remove-tabs (s &optional width)
17869 "Replace tabulators in S with spaces.
17870 Assumes that s is a single line, starting in column 0."
17871 (setq width (or width tab-width))
17872 (while (string-match "\t" s)
17873 (setq s (replace-match
17874 (make-string
17875 (- (* width (/ (+ (match-beginning 0) width) width))
17876 (match-beginning 0)) ?\ )
17877 t t s)))
17880 (defun org-fix-indentation (line ind)
17881 "Fix indentation in LINE.
17882 IND is a cons cell with target and minimum indentation.
17883 If the current indentation in LINE is smaller than the minimum,
17884 leave it alone. If it is larger than ind, set it to the target."
17885 (let* ((l (org-remove-tabs line))
17886 (i (org-get-indentation l))
17887 (i1 (car ind)) (i2 (cdr ind)))
17888 (if (>= i i2) (setq l (substring line i2)))
17889 (if (> i1 0)
17890 (concat (make-string i1 ?\ ) l)
17891 l)))
17893 (defun org-remove-indentation (code &optional n)
17894 "Remove the maximum common indentation from the lines in CODE.
17895 N may optionally be the number of spaces to remove."
17896 (with-temp-buffer
17897 (insert code)
17898 (org-do-remove-indentation n)
17899 (buffer-string)))
17901 (defun org-do-remove-indentation (&optional n)
17902 "Remove the maximum common indentation from the buffer."
17903 (untabify (point-min) (point-max))
17904 (let ((min 10000) re)
17905 (if n
17906 (setq min n)
17907 (goto-char (point-min))
17908 (while (re-search-forward "^ *[^ \n]" nil t)
17909 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
17910 (unless (or (= min 0) (= min 10000))
17911 (setq re (format "^ \\{%d\\}" min))
17912 (goto-char (point-min))
17913 (while (re-search-forward re nil t)
17914 (replace-match "")
17915 (end-of-line 1))
17916 min)))
17918 (defun org-fill-template (template alist)
17919 "Find each %key of ALIST in TEMPLATE and replace it."
17920 (let ((case-fold-search nil)
17921 entry key value)
17922 (setq alist (sort (copy-sequence alist)
17923 (lambda (a b) (< (length (car a)) (length (car b))))))
17924 (while (setq entry (pop alist))
17925 (setq template
17926 (replace-regexp-in-string
17927 (concat "%" (regexp-quote (car entry)))
17928 (cdr entry) template t t)))
17929 template))
17931 (defun org-base-buffer (buffer)
17932 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
17933 (if (not buffer)
17934 buffer
17935 (or (buffer-base-buffer buffer)
17936 buffer)))
17938 (defun org-trim (s)
17939 "Remove whitespace at beginning and end of string."
17940 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
17941 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
17944 (defun org-wrap (string &optional width lines)
17945 "Wrap string to either a number of lines, or a width in characters.
17946 If WIDTH is non-nil, the string is wrapped to that width, however many lines
17947 that costs. If there is a word longer than WIDTH, the text is actually
17948 wrapped to the length of that word.
17949 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
17950 many lines, whatever width that takes.
17951 The return value is a list of lines, without newlines at the end."
17952 (let* ((words (org-split-string string "[ \t\n]+"))
17953 (maxword (apply 'max (mapcar 'org-string-width words)))
17954 w ll)
17955 (cond (width
17956 (org-do-wrap words (max maxword width)))
17957 (lines
17958 (setq w maxword)
17959 (setq ll (org-do-wrap words maxword))
17960 (if (<= (length ll) lines)
17962 (setq ll words)
17963 (while (> (length ll) lines)
17964 (setq w (1+ w))
17965 (setq ll (org-do-wrap words w)))
17966 ll))
17967 (t (error "Cannot wrap this")))))
17969 (defun org-do-wrap (words width)
17970 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
17971 (let (lines line)
17972 (while words
17973 (setq line (pop words))
17974 (while (and words (< (+ (length line) (length (car words))) width))
17975 (setq line (concat line " " (pop words))))
17976 (setq lines (push line lines)))
17977 (nreverse lines)))
17979 (defun org-split-string (string &optional separators)
17980 "Splits STRING into substrings at SEPARATORS.
17981 No empty strings are returned if there are matches at the beginning
17982 and end of string."
17983 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
17984 (start 0)
17985 notfirst
17986 (list nil))
17987 (while (and (string-match rexp string
17988 (if (and notfirst
17989 (= start (match-beginning 0))
17990 (< start (length string)))
17991 (1+ start) start))
17992 (< (match-beginning 0) (length string)))
17993 (setq notfirst t)
17994 (or (eq (match-beginning 0) 0)
17995 (and (eq (match-beginning 0) (match-end 0))
17996 (eq (match-beginning 0) start))
17997 (setq list
17998 (cons (substring string start (match-beginning 0))
17999 list)))
18000 (setq start (match-end 0)))
18001 (or (eq start (length string))
18002 (setq list
18003 (cons (substring string start)
18004 list)))
18005 (nreverse list)))
18007 (defun org-quote-vert (s)
18008 "Replace \"|\" with \"\\vert\"."
18009 (while (string-match "|" s)
18010 (setq s (replace-match "\\vert" t t s)))
18013 (defun org-uuidgen-p (s)
18014 "Is S an ID created by UUIDGEN?"
18015 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
18017 (defun org-context ()
18018 "Return a list of contexts of the current cursor position.
18019 If several contexts apply, all are returned.
18020 Each context entry is a list with a symbol naming the context, and
18021 two positions indicating start and end of the context. Possible
18022 contexts are:
18024 :headline anywhere in a headline
18025 :headline-stars on the leading stars in a headline
18026 :todo-keyword on a TODO keyword (including DONE) in a headline
18027 :tags on the TAGS in a headline
18028 :priority on the priority cookie in a headline
18029 :item on the first line of a plain list item
18030 :item-bullet on the bullet/number of a plain list item
18031 :checkbox on the checkbox in a plain list item
18032 :table in an org-mode table
18033 :table-special on a special filed in a table
18034 :table-table in a table.el table
18035 :link on a hyperlink
18036 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
18037 :target on a <<target>>
18038 :radio-target on a <<<radio-target>>>
18039 :latex-fragment on a LaTeX fragment
18040 :latex-preview on a LaTeX fragment with overlayed preview image
18042 This function expects the position to be visible because it uses font-lock
18043 faces as a help to recognize the following contexts: :table-special, :link,
18044 and :keyword."
18045 (let* ((f (get-text-property (point) 'face))
18046 (faces (if (listp f) f (list f)))
18047 (p (point)) clist o)
18048 ;; First the large context
18049 (cond
18050 ((org-on-heading-p t)
18051 (push (list :headline (point-at-bol) (point-at-eol)) clist)
18052 (when (progn
18053 (beginning-of-line 1)
18054 (looking-at org-todo-line-tags-regexp))
18055 (push (org-point-in-group p 1 :headline-stars) clist)
18056 (push (org-point-in-group p 2 :todo-keyword) clist)
18057 (push (org-point-in-group p 4 :tags) clist))
18058 (goto-char p)
18059 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
18060 (if (looking-at "\\[#[A-Z0-9]\\]")
18061 (push (org-point-in-group p 0 :priority) clist)))
18063 ((org-at-item-p)
18064 (push (org-point-in-group p 2 :item-bullet) clist)
18065 (push (list :item (point-at-bol)
18066 (save-excursion (org-end-of-item) (point)))
18067 clist)
18068 (and (org-at-item-checkbox-p)
18069 (push (org-point-in-group p 0 :checkbox) clist)))
18071 ((org-at-table-p)
18072 (push (list :table (org-table-begin) (org-table-end)) clist)
18073 (if (memq 'org-formula faces)
18074 (push (list :table-special
18075 (previous-single-property-change p 'face)
18076 (next-single-property-change p 'face)) clist)))
18077 ((org-at-table-p 'any)
18078 (push (list :table-table) clist)))
18079 (goto-char p)
18081 ;; Now the small context
18082 (cond
18083 ((org-at-timestamp-p)
18084 (push (org-point-in-group p 0 :timestamp) clist))
18085 ((memq 'org-link faces)
18086 (push (list :link
18087 (previous-single-property-change p 'face)
18088 (next-single-property-change p 'face)) clist))
18089 ((memq 'org-special-keyword faces)
18090 (push (list :keyword
18091 (previous-single-property-change p 'face)
18092 (next-single-property-change p 'face)) clist))
18093 ((org-on-target-p)
18094 (push (org-point-in-group p 0 :target) clist)
18095 (goto-char (1- (match-beginning 0)))
18096 (if (looking-at org-radio-target-regexp)
18097 (push (org-point-in-group p 0 :radio-target) clist))
18098 (goto-char p))
18099 ((setq o (car (delq nil
18100 (mapcar
18101 (lambda (x)
18102 (if (memq x org-latex-fragment-image-overlays) x))
18103 (overlays-at (point))))))
18104 (push (list :latex-fragment
18105 (overlay-start o) (overlay-end o)) clist)
18106 (push (list :latex-preview
18107 (overlay-start o) (overlay-end o)) clist))
18108 ((org-inside-LaTeX-fragment-p)
18109 ;; FIXME: positions wrong.
18110 (push (list :latex-fragment (point) (point)) clist)))
18112 (setq clist (nreverse (delq nil clist)))
18113 clist))
18115 ;; FIXME: Compare with at-regexp-p Do we need both?
18116 (defun org-in-regexp (re &optional nlines visually)
18117 "Check if point is inside a match of regexp.
18118 Normally only the current line is checked, but you can include NLINES extra
18119 lines both before and after point into the search.
18120 If VISUALLY is set, require that the cursor is not after the match but
18121 really on, so that the block visually is on the match."
18122 (catch 'exit
18123 (let ((pos (point))
18124 (eol (point-at-eol (+ 1 (or nlines 0))))
18125 (inc (if visually 1 0)))
18126 (save-excursion
18127 (beginning-of-line (- 1 (or nlines 0)))
18128 (while (re-search-forward re eol t)
18129 (if (and (<= (match-beginning 0) pos)
18130 (>= (+ inc (match-end 0)) pos))
18131 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
18133 (defun org-at-regexp-p (regexp)
18134 "Is point inside a match of REGEXP in the current line?"
18135 (catch 'exit
18136 (save-excursion
18137 (let ((pos (point)) (end (point-at-eol)))
18138 (beginning-of-line 1)
18139 (while (re-search-forward regexp end t)
18140 (if (and (<= (match-beginning 0) pos)
18141 (>= (match-end 0) pos))
18142 (throw 'exit t)))
18143 nil))))
18145 (defun org-in-regexps-block-p (start-re end-re)
18146 "Returns t if the current point is between matches of START-RE and END-RE.
18147 This will also return to if point is on one of the two matches."
18148 (interactive)
18149 (let ((p (point)))
18150 (save-excursion
18151 (and (or (org-at-regexp-p start-re)
18152 (re-search-backward start-re nil t))
18153 (re-search-forward end-re nil t)
18154 (>= (point) p)))))
18156 (defun org-occur-in-agenda-files (regexp &optional nlines)
18157 "Call `multi-occur' with buffers for all agenda files."
18158 (interactive "sOrg-files matching: \np")
18159 (let* ((files (org-agenda-files))
18160 (tnames (mapcar 'file-truename files))
18161 (extra org-agenda-text-search-extra-files)
18163 (when (eq (car extra) 'agenda-archives)
18164 (setq extra (cdr extra))
18165 (setq files (org-add-archive-files files)))
18166 (while (setq f (pop extra))
18167 (unless (member (file-truename f) tnames)
18168 (add-to-list 'files f 'append)
18169 (add-to-list 'tnames (file-truename f) 'append)))
18170 (multi-occur
18171 (mapcar (lambda (x)
18172 (with-current-buffer
18173 (or (get-file-buffer x) (find-file-noselect x))
18174 (widen)
18175 (current-buffer)))
18176 files)
18177 regexp)))
18179 (if (boundp 'occur-mode-find-occurrence-hook)
18180 ;; Emacs 23
18181 (add-hook 'occur-mode-find-occurrence-hook
18182 (lambda ()
18183 (when (org-mode-p)
18184 (org-reveal))))
18185 ;; Emacs 22
18186 (defadvice occur-mode-goto-occurrence
18187 (after org-occur-reveal activate)
18188 (and (org-mode-p) (org-reveal)))
18189 (defadvice occur-mode-goto-occurrence-other-window
18190 (after org-occur-reveal activate)
18191 (and (org-mode-p) (org-reveal)))
18192 (defadvice occur-mode-display-occurrence
18193 (after org-occur-reveal activate)
18194 (when (org-mode-p)
18195 (let ((pos (occur-mode-find-occurrence)))
18196 (with-current-buffer (marker-buffer pos)
18197 (save-excursion
18198 (goto-char pos)
18199 (org-reveal)))))))
18201 (defun org-occur-link-in-agenda-files ()
18202 "Create a link and search for it in the agendas.
18203 The link is not stored in `org-stored-links', it is just created
18204 for the search purpose."
18205 (interactive)
18206 (let ((link (condition-case nil
18207 (org-store-link nil)
18208 (error "Unable to create a link to here"))))
18209 (org-occur-in-agenda-files (regexp-quote link))))
18211 (defun org-uniquify (list)
18212 "Remove duplicate elements from LIST."
18213 (let (res)
18214 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
18215 res))
18217 (defun org-delete-all (elts list)
18218 "Remove all elements in ELTS from LIST."
18219 (while elts
18220 (setq list (delete (pop elts) list)))
18221 list)
18223 (defun org-remove-if (predicate seq)
18224 "Remove everything from SEQ that fulfills PREDICATE."
18225 (let (res e)
18226 (while seq
18227 (setq e (pop seq))
18228 (if (not (funcall predicate e)) (push e res)))
18229 (nreverse res)))
18231 (defun org-remove-if-not (predicate seq)
18232 "Remove everything from SEQ that does not fulfill PREDICATE."
18233 (let (res e)
18234 (while seq
18235 (setq e (pop seq))
18236 (if (funcall predicate e) (push e res)))
18237 (nreverse res)))
18239 (defun org-back-over-empty-lines ()
18240 "Move backwards over whitespace, to the beginning of the first empty line.
18241 Returns the number of empty lines passed."
18242 (let ((pos (point)))
18243 (skip-chars-backward " \t\n\r")
18244 (beginning-of-line 2)
18245 (goto-char (min (point) pos))
18246 (count-lines (point) pos)))
18248 (defun org-skip-whitespace ()
18249 (skip-chars-forward " \t\n\r"))
18251 (defun org-point-in-group (point group &optional context)
18252 "Check if POINT is in match-group GROUP.
18253 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
18254 match. If the match group does ot exist or point is not inside it,
18255 return nil."
18256 (and (match-beginning group)
18257 (>= point (match-beginning group))
18258 (<= point (match-end group))
18259 (if context
18260 (list context (match-beginning group) (match-end group))
18261 t)))
18263 (defun org-switch-to-buffer-other-window (&rest args)
18264 "Switch to buffer in a second window on the current frame.
18265 In particular, do not allow pop-up frames.
18266 Returns the newly created buffer."
18267 (let (pop-up-frames special-display-buffer-names special-display-regexps
18268 special-display-function)
18269 (apply 'switch-to-buffer-other-window args)))
18271 (defun org-combine-plists (&rest plists)
18272 "Create a single property list from all plists in PLISTS.
18273 The process starts by copying the first list, and then setting properties
18274 from the other lists. Settings in the last list are the most significant
18275 ones and overrule settings in the other lists."
18276 (let ((rtn (copy-sequence (pop plists)))
18277 p v ls)
18278 (while plists
18279 (setq ls (pop plists))
18280 (while ls
18281 (setq p (pop ls) v (pop ls))
18282 (setq rtn (plist-put rtn p v))))
18283 rtn))
18285 (defun org-move-line-down (arg)
18286 "Move the current line down. With prefix argument, move it past ARG lines."
18287 (interactive "p")
18288 (let ((col (current-column))
18289 beg end pos)
18290 (beginning-of-line 1) (setq beg (point))
18291 (beginning-of-line 2) (setq end (point))
18292 (beginning-of-line (+ 1 arg))
18293 (setq pos (move-marker (make-marker) (point)))
18294 (insert (delete-and-extract-region beg end))
18295 (goto-char pos)
18296 (org-move-to-column col)))
18298 (defun org-move-line-up (arg)
18299 "Move the current line up. With prefix argument, move it past ARG lines."
18300 (interactive "p")
18301 (let ((col (current-column))
18302 beg end pos)
18303 (beginning-of-line 1) (setq beg (point))
18304 (beginning-of-line 2) (setq end (point))
18305 (beginning-of-line (- arg))
18306 (setq pos (move-marker (make-marker) (point)))
18307 (insert (delete-and-extract-region beg end))
18308 (goto-char pos)
18309 (org-move-to-column col)))
18311 (defun org-replace-escapes (string table)
18312 "Replace %-escapes in STRING with values in TABLE.
18313 TABLE is an association list with keys like \"%a\" and string values.
18314 The sequences in STRING may contain normal field width and padding information,
18315 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
18316 so values can contain further %-escapes if they are define later in TABLE."
18317 (let ((tbl (copy-alist table))
18318 (case-fold-search nil)
18319 (pchg 0)
18320 e re rpl)
18321 (while (setq e (pop tbl))
18322 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
18323 (when (and (cdr e) (string-match re (cdr e)))
18324 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
18325 (safe "SREF"))
18326 (add-text-properties 0 3 (list 'sref sref) safe)
18327 (setcdr e (replace-match safe t t (cdr e)))))
18328 (while (string-match re string)
18329 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
18330 (cdr e)))
18331 (setq string (replace-match rpl t t string))))
18332 (while (setq pchg (next-property-change pchg string))
18333 (let ((sref (get-text-property pchg 'sref string)))
18334 (when (and sref (string-match "SREF" string pchg))
18335 (setq string (replace-match sref t t string)))))
18336 string))
18338 (defun org-sublist (list start end)
18339 "Return a section of LIST, from START to END.
18340 Counting starts at 1."
18341 (let (rtn (c start))
18342 (setq list (nthcdr (1- start) list))
18343 (while (and list (<= c end))
18344 (push (pop list) rtn)
18345 (setq c (1+ c)))
18346 (nreverse rtn)))
18348 (defun org-find-base-buffer-visiting (file)
18349 "Like `find-buffer-visiting' but always return the base buffer and
18350 not an indirect buffer."
18351 (let ((buf (or (get-file-buffer file)
18352 (find-buffer-visiting file))))
18353 (if buf
18354 (or (buffer-base-buffer buf) buf)
18355 nil)))
18357 (defun org-image-file-name-regexp (&optional extensions)
18358 "Return regexp matching the file names of images.
18359 If EXTENSIONS is given, only match these."
18360 (if (and (not extensions) (fboundp 'image-file-name-regexp))
18361 (image-file-name-regexp)
18362 (let ((image-file-name-extensions
18363 (or extensions
18364 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
18365 "xbm" "xpm" "pbm" "pgm" "ppm"))))
18366 (concat "\\."
18367 (regexp-opt (nconc (mapcar 'upcase
18368 image-file-name-extensions)
18369 image-file-name-extensions)
18371 "\\'"))))
18373 (defun org-file-image-p (file &optional extensions)
18374 "Return non-nil if FILE is an image."
18375 (save-match-data
18376 (string-match (org-image-file-name-regexp extensions) file)))
18378 (defun org-get-cursor-date ()
18379 "Return the date at cursor in as a time.
18380 This works in the calendar and in the agenda, anywhere else it just
18381 returns the current time."
18382 (let (date day defd)
18383 (cond
18384 ((eq major-mode 'calendar-mode)
18385 (setq date (calendar-cursor-to-date)
18386 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18387 ((eq major-mode 'org-agenda-mode)
18388 (setq day (get-text-property (point) 'day))
18389 (if day
18390 (setq date (calendar-gregorian-from-absolute day)
18391 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
18392 (nth 2 date))))))
18393 (or defd (current-time))))
18395 (defvar org-agenda-action-marker (make-marker)
18396 "Marker pointing to the entry for the next agenda action.")
18398 (defun org-mark-entry-for-agenda-action ()
18399 "Mark the current entry as target of an agenda action.
18400 Agenda actions are actions executed from the agenda with the key `k',
18401 which make use of the date at the cursor."
18402 (interactive)
18403 (move-marker org-agenda-action-marker
18404 (save-excursion (org-back-to-heading t) (point))
18405 (current-buffer))
18406 (message
18407 "Entry marked for action; press `k' at desired date in agenda or calendar"))
18409 ;;; Paragraph filling stuff.
18410 ;; We want this to be just right, so use the full arsenal.
18412 (defun org-indent-line-function ()
18413 "Indent line like previous, but further if previous was headline or item."
18414 (interactive)
18415 (let* ((pos (point))
18416 (itemp (org-at-item-p))
18417 (case-fold-search t)
18418 (org-drawer-regexp (or org-drawer-regexp "\000"))
18419 column bpos bcol tpos tcol bullet btype bullet-type)
18420 ;; Find the previous relevant line
18421 (beginning-of-line 1)
18422 (cond
18423 ((looking-at "#") (setq column 0))
18424 ((looking-at "\\*+ ") (setq column 0))
18425 ((and (looking-at "[ \t]*:END:")
18426 (save-excursion (re-search-backward org-drawer-regexp nil t)))
18427 (save-excursion
18428 (goto-char (1- (match-beginning 1)))
18429 (setq column (current-column))))
18430 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
18431 (save-excursion
18432 (re-search-backward
18433 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
18434 (setq column (org-get-indentation (match-string 0))))
18436 (beginning-of-line 0)
18437 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
18438 (not (looking-at "[ \t]*:END:"))
18439 (not (looking-at org-drawer-regexp)))
18440 (beginning-of-line 0))
18441 (cond
18442 ((looking-at "\\*+[ \t]+")
18443 (if (not org-adapt-indentation)
18444 (setq column 0)
18445 (goto-char (match-end 0))
18446 (setq column (current-column))))
18447 ((looking-at org-drawer-regexp)
18448 (goto-char (1- (match-beginning 1)))
18449 (setq column (current-column)))
18450 ((looking-at "\\([ \t]*\\):END:")
18451 (goto-char (match-end 1))
18452 (setq column (current-column)))
18453 ((org-in-item-p)
18454 (org-beginning-of-item)
18455 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
18456 (setq bpos (match-beginning 1) tpos (match-end 0)
18457 bcol (progn (goto-char bpos) (current-column))
18458 tcol (progn (goto-char tpos) (current-column))
18459 bullet (match-string 1)
18460 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
18461 (if (> tcol (+ bcol org-description-max-indent))
18462 (setq tcol (+ bcol 5)))
18463 (if (not itemp)
18464 (setq column tcol)
18465 (goto-char pos)
18466 (beginning-of-line 1)
18467 (if (looking-at "\\S-")
18468 (progn
18469 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
18470 (setq bullet (match-string 1)
18471 btype (if (string-match "[0-9]" bullet) "n" bullet))
18472 (setq column (if (equal btype bullet-type) bcol tcol)))
18473 (setq column (org-get-indentation)))))
18474 (t (setq column (org-get-indentation))))))
18475 (goto-char pos)
18476 (if (<= (current-column) (current-indentation))
18477 (org-indent-line-to column)
18478 (save-excursion (org-indent-line-to column)))
18479 (setq column (current-column))
18480 (beginning-of-line 1)
18481 (if (looking-at
18482 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
18483 (replace-match (concat (match-string 1)
18484 (format org-property-format
18485 (match-string 2) (match-string 3)))
18486 t t))
18487 (org-move-to-column column)))
18489 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
18490 "Variable to store copy of `adaptive-fill-regexp'.
18491 Since `adaptive-fill-regexp' is set to never match, we need to
18492 store a backup of its value before entering `org-mode' so that
18493 the functionality can be provided as a fall-back.")
18495 (defun org-set-autofill-regexps ()
18496 (interactive)
18497 ;; In the paragraph separator we include headlines, because filling
18498 ;; text in a line directly attached to a headline would otherwise
18499 ;; fill the headline as well.
18500 (org-set-local 'comment-start-skip "^#+[ \t]*")
18501 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
18502 ;; The paragraph starter includes hand-formatted lists.
18503 (org-set-local
18504 'paragraph-start
18505 (concat
18506 "\f" "\\|"
18507 "[ ]*$" "\\|"
18508 "\\*+ " "\\|"
18509 "[ \t]*#" "\\|"
18510 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
18511 "[ \t]*[:|]" "\\|"
18512 "\\$\\$" "\\|"
18513 "\\\\\\(begin\\|end\\|[][]\\)"))
18514 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
18515 ;; But only if the user has not turned off tables or fixed-width regions
18516 (org-set-local
18517 'auto-fill-inhibit-regexp
18518 (concat "\\*+ \\|#\\+"
18519 "\\|[ \t]*" org-keyword-time-regexp
18520 (if (or org-enable-table-editor org-enable-fixed-width-editor)
18521 (concat
18522 "\\|[ \t]*["
18523 (if org-enable-table-editor "|" "")
18524 (if org-enable-fixed-width-editor ":" "")
18525 "]"))))
18526 ;; We use our own fill-paragraph function, to make sure that tables
18527 ;; and fixed-width regions are not wrapped. That function will pass
18528 ;; through to `fill-paragraph' when appropriate.
18529 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
18530 ;; Adaptive filling: To get full control, first make sure that
18531 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
18532 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
18533 (org-set-local 'org-adaptive-fill-regexp-backup
18534 adaptive-fill-regexp))
18535 (org-set-local 'adaptive-fill-regexp "\000")
18536 (org-set-local 'adaptive-fill-function
18537 'org-adaptive-fill-function)
18538 (org-set-local
18539 'align-mode-rules-list
18540 '((org-in-buffer-settings
18541 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
18542 (modes . '(org-mode))))))
18544 (defun org-fill-paragraph (&optional justify)
18545 "Re-align a table, pass through to fill-paragraph if no table."
18546 (let ((table-p (org-at-table-p))
18547 (table.el-p (org-at-table.el-p)))
18548 (cond ((and (equal (char-after (point-at-bol)) ?*)
18549 (save-excursion (goto-char (point-at-bol))
18550 (looking-at outline-regexp)))
18551 t) ; skip headlines
18552 (table.el-p t) ; skip table.el tables
18553 (table-p (org-table-align) t) ; align org-mode tables
18554 (t nil)))) ; call paragraph-fill
18556 ;; For reference, this is the default value of adaptive-fill-regexp
18557 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
18559 (defun org-adaptive-fill-function ()
18560 "Return a fill prefix for org-mode files.
18561 In particular, this makes sure hanging paragraphs for hand-formatted lists
18562 work correctly."
18563 (cond
18564 ;; Comment line
18565 ((looking-at "#[ \t]+")
18566 (match-string-no-properties 0))
18567 ;; Description list
18568 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
18569 (save-excursion
18570 (if (> (match-end 1) (+ (match-beginning 1)
18571 org-description-max-indent))
18572 (goto-char (+ (match-beginning 1) 5))
18573 (goto-char (match-end 0)))
18574 (make-string (current-column) ?\ )))
18575 ;; Ordered or unordered list
18576 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)")
18577 (save-excursion
18578 (goto-char (match-end 0))
18579 (make-string (current-column) ?\ )))
18580 ;; Other text
18581 ((looking-at org-adaptive-fill-regexp-backup)
18582 (match-string-no-properties 0))))
18584 ;;; Other stuff.
18586 (defun org-toggle-fixed-width-section (arg)
18587 "Toggle the fixed-width export.
18588 If there is no active region, the QUOTE keyword at the current headline is
18589 inserted or removed. When present, it causes the text between this headline
18590 and the next to be exported as fixed-width text, and unmodified.
18591 If there is an active region, this command adds or removes a colon as the
18592 first character of this line. If the first character of a line is a colon,
18593 this line is also exported in fixed-width font."
18594 (interactive "P")
18595 (let* ((cc 0)
18596 (regionp (org-region-active-p))
18597 (beg (if regionp (region-beginning) (point)))
18598 (end (if regionp (region-end)))
18599 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
18600 (case-fold-search nil)
18601 (re "[ \t]*\\(: \\)")
18602 off)
18603 (if regionp
18604 (save-excursion
18605 (goto-char beg)
18606 (setq cc (current-column))
18607 (beginning-of-line 1)
18608 (setq off (looking-at re))
18609 (while (> nlines 0)
18610 (setq nlines (1- nlines))
18611 (beginning-of-line 1)
18612 (cond
18613 (arg
18614 (org-move-to-column cc t)
18615 (insert ": \n")
18616 (forward-line -1))
18617 ((and off (looking-at re))
18618 (replace-match "" t t nil 1))
18619 ((not off) (org-move-to-column cc t) (insert ": ")))
18620 (forward-line 1)))
18621 (save-excursion
18622 (org-back-to-heading)
18623 (if (looking-at (concat outline-regexp
18624 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
18625 (replace-match "" t t nil 1)
18626 (if (looking-at outline-regexp)
18627 (progn
18628 (goto-char (match-end 0))
18629 (insert org-quote-string " "))))))))
18631 (defun org-reftex-citation ()
18632 "Use reftex-citation to insert a citation into the buffer.
18633 This looks for a line like
18635 #+BIBLIOGRAPHY: foo plain option:-d
18637 and derives from it that foo.bib is the bibliography file relevant
18638 for this document. It then installs the necessary environment for RefTeX
18639 to work in this buffer and calls `reftex-citation' to insert a citation
18640 into the buffer.
18642 Export of such citations to both LaTeX and HTML is handled by the contributed
18643 package org-exp-bibtex by Taru Karttunen."
18644 (interactive)
18645 (let ((reftex-docstruct-symbol 'rds)
18646 (reftex-cite-format "\\cite{%l}")
18647 rds bib)
18648 (save-excursion
18649 (save-restriction
18650 (widen)
18651 (let ((case-fold-search t)
18652 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
18653 (if (not (save-excursion
18654 (or (re-search-forward re nil t)
18655 (re-search-backward re nil t))))
18656 (error "No bibliography defined in file")
18657 (setq bib (concat (match-string 1) ".bib")
18658 rds (list (list 'bib bib)))))))
18659 (call-interactively 'reftex-citation)))
18661 ;;;; Functions extending outline functionality
18663 (defun org-beginning-of-line (&optional arg)
18664 "Go to the beginning of the current line. If that is invisible, continue
18665 to a visible line beginning. This makes the function of C-a more intuitive.
18666 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
18667 first attempt, and only move to after the tags when the cursor is already
18668 beyond the end of the headline."
18669 (interactive "P")
18670 (let ((pos (point))
18671 (special (if (consp org-special-ctrl-a/e)
18672 (car org-special-ctrl-a/e)
18673 org-special-ctrl-a/e))
18674 refpos)
18675 (if (org-bound-and-true-p line-move-visual)
18676 (beginning-of-visual-line 1)
18677 (beginning-of-line 1))
18678 (if (and arg (fboundp 'move-beginning-of-line))
18679 (call-interactively 'move-beginning-of-line)
18680 (if (bobp)
18682 (backward-char 1)
18683 (if (org-truely-invisible-p)
18684 (while (and (not (bobp)) (org-truely-invisible-p))
18685 (backward-char 1)
18686 (beginning-of-line 1))
18687 (forward-char 1))))
18688 (when special
18689 (cond
18690 ((and (looking-at org-complex-heading-regexp)
18691 (= (char-after (match-end 1)) ?\ ))
18692 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
18693 (point-at-eol)))
18694 (goto-char
18695 (if (eq special t)
18696 (cond ((> pos refpos) refpos)
18697 ((= pos (point)) refpos)
18698 (t (point)))
18699 (cond ((> pos (point)) (point))
18700 ((not (eq last-command this-command)) (point))
18701 (t refpos)))))
18702 ((org-at-item-p)
18703 (goto-char
18704 (if (eq special t)
18705 (cond ((> pos (match-end 4)) (match-end 4))
18706 ((= pos (point)) (match-end 4))
18707 (t (point)))
18708 (cond ((> pos (point)) (point))
18709 ((not (eq last-command this-command)) (point))
18710 (t (match-end 4))))))))
18711 (org-no-warnings
18712 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
18714 (defun org-end-of-line (&optional arg)
18715 "Go to the end of the line.
18716 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
18717 first attempt, and only move to after the tags when the cursor is already
18718 beyond the end of the headline."
18719 (interactive "P")
18720 (let ((special (if (consp org-special-ctrl-a/e)
18721 (cdr org-special-ctrl-a/e)
18722 org-special-ctrl-a/e)))
18723 (if (or (not special)
18724 (not (org-on-heading-p))
18725 arg)
18726 (call-interactively
18727 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
18728 ((fboundp 'move-end-of-line) 'move-end-of-line)
18729 (t 'end-of-line)))
18730 (let ((pos (point)))
18731 (beginning-of-line 1)
18732 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
18733 (if (eq special t)
18734 (if (or (< pos (match-beginning 1))
18735 (= pos (match-end 0)))
18736 (goto-char (match-beginning 1))
18737 (goto-char (match-end 0)))
18738 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
18739 (goto-char (match-end 0))
18740 (goto-char (match-beginning 1))))
18741 (call-interactively (if (fboundp 'move-end-of-line)
18742 'move-end-of-line
18743 'end-of-line)))))
18744 (org-no-warnings
18745 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
18747 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
18748 (define-key org-mode-map "\C-e" 'org-end-of-line)
18749 (define-key org-mode-map [home] 'org-beginning-of-line)
18750 (define-key org-mode-map [end] 'org-end-of-line)
18752 (defun org-backward-sentence (&optional arg)
18753 "Go to beginning of sentence, or beginning of table field.
18754 This will call `backward-sentence' or `org-table-beginning-of-field',
18755 depending on context."
18756 (interactive "P")
18757 (cond
18758 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
18759 (t (call-interactively 'backward-sentence))))
18761 (defun org-forward-sentence (&optional arg)
18762 "Go to end of sentence, or end of table field.
18763 This will call `forward-sentence' or `org-table-end-of-field',
18764 depending on context."
18765 (interactive "P")
18766 (cond
18767 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
18768 (t (call-interactively 'forward-sentence))))
18770 (define-key org-mode-map "\M-a" 'org-backward-sentence)
18771 (define-key org-mode-map "\M-e" 'org-forward-sentence)
18773 (defun org-kill-line (&optional arg)
18774 "Kill line, to tags or end of line."
18775 (interactive "P")
18776 (cond
18777 ((or (not org-special-ctrl-k)
18778 (bolp)
18779 (not (org-on-heading-p)))
18780 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
18781 org-ctrl-k-protect-subtree)
18782 (if (or (eq org-ctrl-k-protect-subtree 'error)
18783 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
18784 (error "C-k aborted - would kill hidden subtree")))
18785 (call-interactively 'kill-line))
18786 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
18787 (kill-region (point) (match-beginning 1))
18788 (org-set-tags nil t))
18789 (t (kill-region (point) (point-at-eol)))))
18791 (define-key org-mode-map "\C-k" 'org-kill-line)
18793 (defun org-yank (&optional arg)
18794 "Yank. If the kill is a subtree, treat it specially.
18795 This command will look at the current kill and check if is a single
18796 subtree, or a series of subtrees[1]. If it passes the test, and if the
18797 cursor is at the beginning of a line or after the stars of a currently
18798 empty headline, then the yank is handled specially. How exactly depends
18799 on the value of the following variables, both set by default.
18801 org-yank-folded-subtrees
18802 When set, the subtree(s) will be folded after insertion, but only
18803 if doing so would now swallow text after the yanked text.
18805 org-yank-adjusted-subtrees
18806 When set, the subtree will be promoted or demoted in order to
18807 fit into the local outline tree structure, which means that the level
18808 will be adjusted so that it becomes the smaller one of the two
18809 *visible* surrounding headings.
18811 Any prefix to this command will cause `yank' to be called directly with
18812 no special treatment. In particular, a simple `C-u' prefix will just
18813 plainly yank the text as it is.
18815 \[1] The test checks if the first non-white line is a heading
18816 and if there are no other headings with fewer stars."
18817 (interactive "P")
18818 (org-yank-generic 'yank arg))
18820 (defun org-yank-generic (command arg)
18821 "Perform some yank-like command.
18823 This function implements the behavior described in the `org-yank'
18824 documentation. However, it has been generalized to work for any
18825 interactive command with similar behavior."
18827 ;; pretend to be command COMMAND
18828 (setq this-command command)
18830 (if arg
18831 (call-interactively command)
18833 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
18834 (and (org-kill-is-subtree-p)
18835 (or (bolp)
18836 (and (looking-at "[ \t]*$")
18837 (string-match
18838 "\\`\\*+\\'"
18839 (buffer-substring (point-at-bol) (point)))))))
18840 swallowp)
18841 (cond
18842 ((and subtreep org-yank-folded-subtrees)
18843 (let ((beg (point))
18844 end)
18845 (if (and subtreep org-yank-adjusted-subtrees)
18846 (org-paste-subtree nil nil 'for-yank)
18847 (call-interactively command))
18849 (setq end (point))
18850 (goto-char beg)
18851 (when (and (bolp) subtreep
18852 (not (setq swallowp
18853 (org-yank-folding-would-swallow-text beg end))))
18854 (or (looking-at outline-regexp)
18855 (re-search-forward (concat "^" outline-regexp) end t))
18856 (while (and (< (point) end) (looking-at outline-regexp))
18857 (hide-subtree)
18858 (org-cycle-show-empty-lines 'folded)
18859 (condition-case nil
18860 (outline-forward-same-level 1)
18861 (error (goto-char end)))))
18862 (when swallowp
18863 (message
18864 "Inserted text not folded because that would swallow text"))
18866 (goto-char end)
18867 (skip-chars-forward " \t\n\r")
18868 (beginning-of-line 1)
18869 (push-mark beg 'nomsg)))
18870 ((and subtreep org-yank-adjusted-subtrees)
18871 (let ((beg (point-at-bol)))
18872 (org-paste-subtree nil nil 'for-yank)
18873 (push-mark beg 'nomsg)))
18875 (call-interactively command))))))
18877 (defun org-yank-folding-would-swallow-text (beg end)
18878 "Would hide-subtree at BEG swallow any text after END?"
18879 (let (level)
18880 (save-excursion
18881 (goto-char beg)
18882 (when (or (looking-at outline-regexp)
18883 (re-search-forward (concat "^" outline-regexp) end t))
18884 (setq level (org-outline-level)))
18885 (goto-char end)
18886 (skip-chars-forward " \t\r\n\v\f")
18887 (if (or (eobp)
18888 (and (bolp) (looking-at org-outline-regexp)
18889 (<= (org-outline-level) level)))
18890 nil ; Nothing would be swallowed
18891 t)))) ; something would swallow
18893 (define-key org-mode-map "\C-y" 'org-yank)
18895 (defun org-invisible-p ()
18896 "Check if point is at a character currently not visible."
18897 ;; Early versions of noutline don't have `outline-invisible-p'.
18898 (if (fboundp 'outline-invisible-p)
18899 (outline-invisible-p)
18900 (get-char-property (point) 'invisible)))
18902 (defun org-truely-invisible-p ()
18903 "Check if point is at a character currently not visible.
18904 This version does not only check the character property, but also
18905 `visible-mode'."
18906 ;; Early versions of noutline don't have `outline-invisible-p'.
18907 (if (org-bound-and-true-p visible-mode)
18909 (if (fboundp 'outline-invisible-p)
18910 (outline-invisible-p)
18911 (get-char-property (point) 'invisible))))
18913 (defun org-invisible-p2 ()
18914 "Check if point is at a character currently not visible."
18915 (save-excursion
18916 (if (and (eolp) (not (bobp))) (backward-char 1))
18917 ;; Early versions of noutline don't have `outline-invisible-p'.
18918 (if (fboundp 'outline-invisible-p)
18919 (outline-invisible-p)
18920 (get-char-property (point) 'invisible))))
18922 (defun org-back-to-heading (&optional invisible-ok)
18923 "Call `outline-back-to-heading', but provide a better error message."
18924 (condition-case nil
18925 (outline-back-to-heading invisible-ok)
18926 (error (error "Before first headline at position %d in buffer %s"
18927 (point) (current-buffer)))))
18929 (defun org-beginning-of-defun ()
18930 "Go to the beginning of the subtree, i.e. back to the heading."
18931 (org-back-to-heading))
18932 (defun org-end-of-defun ()
18933 "Go to the end of the subtree."
18934 (org-end-of-subtree nil t))
18936 (defun org-before-first-heading-p ()
18937 "Before first heading?"
18938 (save-excursion
18939 (null (re-search-backward "^\\*+ " nil t))))
18941 (defun org-on-heading-p (&optional ignored)
18942 (outline-on-heading-p t))
18943 (defun org-at-heading-p (&optional ignored)
18944 (outline-on-heading-p t))
18946 (defun org-point-at-end-of-empty-headline ()
18947 "If point is at the end of an empty headline, return t, else nil.
18948 If the heading only contains a TODO keyword, it is still still considered
18949 empty."
18950 (and (looking-at "[ \t]*$")
18951 (save-excursion
18952 (beginning-of-line 1)
18953 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
18954 "\\)?[ \t]*$")))))
18955 (defun org-at-heading-or-item-p ()
18956 (or (org-on-heading-p) (org-at-item-p)))
18958 (defun org-on-target-p ()
18959 (or (org-in-regexp org-radio-target-regexp)
18960 (org-in-regexp org-target-regexp)))
18962 (defun org-up-heading-all (arg)
18963 "Move to the heading line of which the present line is a subheading.
18964 This function considers both visible and invisible heading lines.
18965 With argument, move up ARG levels."
18966 (if (fboundp 'outline-up-heading-all)
18967 (outline-up-heading-all arg) ; emacs 21 version of outline.el
18968 (outline-up-heading arg t))) ; emacs 22 version of outline.el
18970 (defun org-up-heading-safe ()
18971 "Move to the heading line of which the present line is a subheading.
18972 This version will not throw an error. It will return the level of the
18973 headline found, or nil if no higher level is found.
18975 Also, this function will be a lot faster than `outline-up-heading',
18976 because it relies on stars being the outline starters. This can really
18977 make a significant difference in outlines with very many siblings."
18978 (let (start-level re)
18979 (org-back-to-heading t)
18980 (setq start-level (funcall outline-level))
18981 (if (equal start-level 1)
18983 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
18984 (if (re-search-backward re nil t)
18985 (funcall outline-level)))))
18987 (defun org-first-sibling-p ()
18988 "Is this heading the first child of its parents?"
18989 (interactive)
18990 (let ((re (concat "^" outline-regexp))
18991 level l)
18992 (unless (org-at-heading-p t)
18993 (error "Not at a heading"))
18994 (setq level (funcall outline-level))
18995 (save-excursion
18996 (if (not (re-search-backward re nil t))
18998 (setq l (funcall outline-level))
18999 (< l level)))))
19001 (defun org-goto-sibling (&optional previous)
19002 "Goto the next sibling, even if it is invisible.
19003 When PREVIOUS is set, go to the previous sibling instead. Returns t
19004 when a sibling was found. When none is found, return nil and don't
19005 move point."
19006 (let ((fun (if previous 're-search-backward 're-search-forward))
19007 (pos (point))
19008 (re (concat "^" outline-regexp))
19009 level l)
19010 (when (condition-case nil (org-back-to-heading t) (error nil))
19011 (setq level (funcall outline-level))
19012 (catch 'exit
19013 (or previous (forward-char 1))
19014 (while (funcall fun re nil t)
19015 (setq l (funcall outline-level))
19016 (when (< l level) (goto-char pos) (throw 'exit nil))
19017 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
19018 (goto-char pos)
19019 nil))))
19021 (defun org-show-siblings ()
19022 "Show all siblings of the current headline."
19023 (save-excursion
19024 (while (org-goto-sibling) (org-flag-heading nil)))
19025 (save-excursion
19026 (while (org-goto-sibling 'previous)
19027 (org-flag-heading nil))))
19029 (defun org-show-hidden-entry ()
19030 "Show an entry where even the heading is hidden."
19031 (save-excursion
19032 (org-show-entry)))
19034 (defun org-flag-heading (flag &optional entry)
19035 "Flag the current heading. FLAG non-nil means make invisible.
19036 When ENTRY is non-nil, show the entire entry."
19037 (save-excursion
19038 (org-back-to-heading t)
19039 ;; Check if we should show the entire entry
19040 (if entry
19041 (progn
19042 (org-show-entry)
19043 (save-excursion
19044 (and (outline-next-heading)
19045 (org-flag-heading nil))))
19046 (outline-flag-region (max (point-min) (1- (point)))
19047 (save-excursion (outline-end-of-heading) (point))
19048 flag))))
19050 (defun org-get-next-sibling ()
19051 "Move to next heading of the same level, and return point.
19052 If there is no such heading, return nil.
19053 This is like outline-next-sibling, but invisible headings are ok."
19054 (let ((level (funcall outline-level)))
19055 (outline-next-heading)
19056 (while (and (not (eobp)) (> (funcall outline-level) level))
19057 (outline-next-heading))
19058 (if (or (eobp) (< (funcall outline-level) level))
19060 (point))))
19062 (defun org-get-last-sibling ()
19063 "Move to previous heading of the same level, and return point.
19064 If there is no such heading, return nil."
19065 (let ((opoint (point))
19066 (level (funcall outline-level)))
19067 (outline-previous-heading)
19068 (when (and (/= (point) opoint) (outline-on-heading-p t))
19069 (while (and (> (funcall outline-level) level)
19070 (not (bobp)))
19071 (outline-previous-heading))
19072 (if (< (funcall outline-level) level)
19074 (point)))))
19076 (defun org-end-of-subtree (&optional invisible-OK to-heading)
19077 ;; This contains an exact copy of the original function, but it uses
19078 ;; `org-back-to-heading', to make it work also in invisible
19079 ;; trees. And is uses an invisible-OK argument.
19080 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
19081 ;; Furthermore, when used inside Org, finding the end of a large subtree
19082 ;; with many children and grandchildren etc, this can be much faster
19083 ;; than the outline version.
19084 (org-back-to-heading invisible-OK)
19085 (let ((first t)
19086 (level (funcall outline-level)))
19087 (if (and (org-mode-p) (< level 1000))
19088 ;; A true heading (not a plain list item), in Org-mode
19089 ;; This means we can easily find the end by looking
19090 ;; only for the right number of stars. Using a regexp to do
19091 ;; this is so much faster than using a Lisp loop.
19092 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
19093 (forward-char 1)
19094 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
19095 ;; something else, do it the slow way
19096 (while (and (not (eobp))
19097 (or first (> (funcall outline-level) level)))
19098 (setq first nil)
19099 (outline-next-heading)))
19100 (unless to-heading
19101 (if (memq (preceding-char) '(?\n ?\^M))
19102 (progn
19103 ;; Go to end of line before heading
19104 (forward-char -1)
19105 (if (memq (preceding-char) '(?\n ?\^M))
19106 ;; leave blank line before heading
19107 (forward-char -1))))))
19108 (point))
19110 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
19111 "Use Org version in org-mode, for dramatic speed-up."
19112 (if (eq major-mode 'org-mode)
19113 (progn
19114 (org-end-of-subtree nil t)
19115 (unless (eobp) (backward-char 1)))
19116 ad-do-it))
19118 (defun org-forward-same-level (arg &optional invisible-ok)
19119 "Move forward to the arg'th subheading at same level as this one.
19120 Stop at the first and last subheadings of a superior heading."
19121 (interactive "p")
19122 (org-back-to-heading invisible-ok)
19123 (org-on-heading-p)
19124 (let* ((level (- (match-end 0) (match-beginning 0) 1))
19125 (re (format "^\\*\\{1,%d\\} " level))
19127 (forward-char 1)
19128 (while (> arg 0)
19129 (while (and (re-search-forward re nil 'move)
19130 (setq l (- (match-end 0) (match-beginning 0) 1))
19131 (= l level)
19132 (not invisible-ok)
19133 (progn (backward-char 1) (org-invisible-p)))
19134 (if (< l level) (setq arg 1)))
19135 (setq arg (1- arg)))
19136 (beginning-of-line 1)))
19138 (defun org-backward-same-level (arg &optional invisible-ok)
19139 "Move backward to the arg'th subheading at same level as this one.
19140 Stop at the first and last subheadings of a superior heading."
19141 (interactive "p")
19142 (org-back-to-heading)
19143 (org-on-heading-p)
19144 (let* ((level (- (match-end 0) (match-beginning 0) 1))
19145 (re (format "^\\*\\{1,%d\\} " level))
19147 (while (> arg 0)
19148 (while (and (re-search-backward re nil 'move)
19149 (setq l (- (match-end 0) (match-beginning 0) 1))
19150 (= l level)
19151 (not invisible-ok)
19152 (org-invisible-p))
19153 (if (< l level) (setq arg 1)))
19154 (setq arg (1- arg)))))
19156 (defun org-show-subtree ()
19157 "Show everything after this heading at deeper levels."
19158 (outline-flag-region
19159 (point)
19160 (save-excursion
19161 (org-end-of-subtree t t))
19162 nil))
19164 (defun org-show-entry ()
19165 "Show the body directly following this heading.
19166 Show the heading too, if it is currently invisible."
19167 (interactive)
19168 (save-excursion
19169 (condition-case nil
19170 (progn
19171 (org-back-to-heading t)
19172 (outline-flag-region
19173 (max (point-min) (1- (point)))
19174 (save-excursion
19175 (if (re-search-forward
19176 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
19177 (match-beginning 1)
19178 (point-max)))
19179 nil)
19180 (org-cycle-hide-drawers 'children))
19181 (error nil))))
19183 (defun org-make-options-regexp (kwds &optional extra)
19184 "Make a regular expression for keyword lines."
19185 (concat
19187 "#?[ \t]*\\+\\("
19188 (mapconcat 'regexp-quote kwds "\\|")
19189 (if extra (concat "\\|" extra))
19190 "\\):[ \t]*"
19191 "\\(.*\\)"))
19193 ;; Make isearch reveal the necessary context
19194 (defun org-isearch-end ()
19195 "Reveal context after isearch exits."
19196 (when isearch-success ; only if search was successful
19197 (if (featurep 'xemacs)
19198 ;; Under XEmacs, the hook is run in the correct place,
19199 ;; we directly show the context.
19200 (org-show-context 'isearch)
19201 ;; In Emacs the hook runs *before* restoring the overlays.
19202 ;; So we have to use a one-time post-command-hook to do this.
19203 ;; (Emacs 22 has a special variable, see function `org-mode')
19204 (unless (and (boundp 'isearch-mode-end-hook-quit)
19205 isearch-mode-end-hook-quit)
19206 ;; Only when the isearch was not quitted.
19207 (org-add-hook 'post-command-hook 'org-isearch-post-command
19208 'append 'local)))))
19210 (defun org-isearch-post-command ()
19211 "Remove self from hook, and show context."
19212 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
19213 (org-show-context 'isearch))
19216 ;;;; Integration with and fixes for other packages
19218 ;;; Imenu support
19220 (defvar org-imenu-markers nil
19221 "All markers currently used by Imenu.")
19222 (make-variable-buffer-local 'org-imenu-markers)
19224 (defun org-imenu-new-marker (&optional pos)
19225 "Return a new marker for use by Imenu, and remember the marker."
19226 (let ((m (make-marker)))
19227 (move-marker m (or pos (point)))
19228 (push m org-imenu-markers)
19231 (defun org-imenu-get-tree ()
19232 "Produce the index for Imenu."
19233 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
19234 (setq org-imenu-markers nil)
19235 (let* ((n org-imenu-depth)
19236 (re (concat "^" outline-regexp))
19237 (subs (make-vector (1+ n) nil))
19238 (last-level 0)
19239 m level head)
19240 (save-excursion
19241 (save-restriction
19242 (widen)
19243 (goto-char (point-max))
19244 (while (re-search-backward re nil t)
19245 (setq level (org-reduced-level (funcall outline-level)))
19246 (when (<= level n)
19247 (looking-at org-complex-heading-regexp)
19248 (setq head (org-link-display-format
19249 (org-match-string-no-properties 4))
19250 m (org-imenu-new-marker))
19251 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
19252 (if (>= level last-level)
19253 (push (cons head m) (aref subs level))
19254 (push (cons head (aref subs (1+ level))) (aref subs level))
19255 (loop for i from (1+ level) to n do (aset subs i nil)))
19256 (setq last-level level)))))
19257 (aref subs 1)))
19259 (eval-after-load "imenu"
19260 '(progn
19261 (add-hook 'imenu-after-jump-hook
19262 (lambda ()
19263 (if (eq major-mode 'org-mode)
19264 (org-show-context 'org-goto))))))
19266 (defun org-link-display-format (link)
19267 "Replace a link with either the description, or the link target
19268 if no description is present"
19269 (save-match-data
19270 (if (string-match org-bracket-link-analytic-regexp link)
19271 (replace-match (if (match-end 5)
19272 (match-string 5 link)
19273 (concat (match-string 1 link)
19274 (match-string 3 link)))
19275 nil t link)
19276 link)))
19278 ;; Speedbar support
19280 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
19281 "Overlay marking the agenda restriction line in speedbar.")
19282 (overlay-put org-speedbar-restriction-lock-overlay
19283 'face 'org-agenda-restriction-lock)
19284 (overlay-put org-speedbar-restriction-lock-overlay
19285 'help-echo "Agendas are currently limited to this item.")
19286 (org-detach-overlay org-speedbar-restriction-lock-overlay)
19288 (defun org-speedbar-set-agenda-restriction ()
19289 "Restrict future agenda commands to the location at point in speedbar.
19290 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
19291 (interactive)
19292 (require 'org-agenda)
19293 (let (p m tp np dir txt)
19294 (cond
19295 ((setq p (text-property-any (point-at-bol) (point-at-eol)
19296 'org-imenu t))
19297 (setq m (get-text-property p 'org-imenu-marker))
19298 (with-current-buffer (marker-buffer m)
19299 (goto-char m)
19300 (org-agenda-set-restriction-lock 'subtree)))
19301 ((setq p (text-property-any (point-at-bol) (point-at-eol)
19302 'speedbar-function 'speedbar-find-file))
19303 (setq tp (previous-single-property-change
19304 (1+ p) 'speedbar-function)
19305 np (next-single-property-change
19306 tp 'speedbar-function)
19307 dir (speedbar-line-directory)
19308 txt (buffer-substring-no-properties (or tp (point-min))
19309 (or np (point-max))))
19310 (with-current-buffer (find-file-noselect
19311 (let ((default-directory dir))
19312 (expand-file-name txt)))
19313 (unless (org-mode-p)
19314 (error "Cannot restrict to non-Org-mode file"))
19315 (org-agenda-set-restriction-lock 'file)))
19316 (t (error "Don't know how to restrict Org-mode's agenda")))
19317 (move-overlay org-speedbar-restriction-lock-overlay
19318 (point-at-bol) (point-at-eol))
19319 (setq current-prefix-arg nil)
19320 (org-agenda-maybe-redo)))
19322 (eval-after-load "speedbar"
19323 '(progn
19324 (speedbar-add-supported-extension ".org")
19325 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
19326 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
19327 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
19328 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19329 (add-hook 'speedbar-visiting-tag-hook
19330 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
19332 ;;; Fixes and Hacks for problems with other packages
19334 ;; Make flyspell not check words in links, to not mess up our keymap
19335 (defun org-mode-flyspell-verify ()
19336 "Don't let flyspell put overlays at active buttons."
19337 (and (not (get-text-property (point) 'keymap))
19338 (not (get-text-property (point) 'org-no-flyspell))))
19340 (defun org-remove-flyspell-overlays-in (beg end)
19341 "Remove flyspell overlays in region."
19342 (and (org-bound-and-true-p flyspell-mode)
19343 (fboundp 'flyspell-delete-region-overlays)
19344 (flyspell-delete-region-overlays beg end))
19345 (add-text-properties beg end '(org-no-flyspell t)))
19347 ;; Make `bookmark-jump' shows the jump location if it was hidden.
19348 (eval-after-load "bookmark"
19349 '(if (boundp 'bookmark-after-jump-hook)
19350 ;; We can use the hook
19351 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
19352 ;; Hook not available, use advice
19353 (defadvice bookmark-jump (after org-make-visible activate)
19354 "Make the position visible."
19355 (org-bookmark-jump-unhide))))
19357 ;; Make sure saveplace shows the location if it was hidden
19358 (eval-after-load "saveplace"
19359 '(defadvice save-place-find-file-hook (after org-make-visible activate)
19360 "Make the position visible."
19361 (org-bookmark-jump-unhide)))
19363 ;; Make sure ecb shows the location if it was hidden
19364 (eval-after-load "ecb"
19365 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
19366 "Make hierarchy visible when jumping into location from ECB tree buffer."
19367 (if (eq major-mode 'org-mode)
19368 (org-show-context))))
19370 (defun org-bookmark-jump-unhide ()
19371 "Unhide the current position, to show the bookmark location."
19372 (and (org-mode-p)
19373 (or (org-invisible-p)
19374 (save-excursion (goto-char (max (point-min) (1- (point))))
19375 (org-invisible-p)))
19376 (org-show-context 'bookmark-jump)))
19378 ;; Make session.el ignore our circular variable
19379 (eval-after-load "session"
19380 '(add-to-list 'session-globals-exclude 'org-mark-ring))
19382 ;;;; Experimental code
19384 (defun org-closed-in-range ()
19385 "Sparse tree of items closed in a certain time range.
19386 Still experimental, may disappear in the future."
19387 (interactive)
19388 ;; Get the time interval from the user.
19389 (let* ((time1 (org-float-time
19390 (org-read-date nil 'to-time nil "Starting date: ")))
19391 (time2 (org-float-time
19392 (org-read-date nil 'to-time nil "End date:")))
19393 ;; callback function
19394 (callback (lambda ()
19395 (let ((time
19396 (org-float-time
19397 (apply 'encode-time
19398 (org-parse-time-string
19399 (match-string 1))))))
19400 ;; check if time in interval
19401 (and (>= time time1) (<= time time2))))))
19402 ;; make tree, check each match with the callback
19403 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
19405 ;;;; Finish up
19407 (provide 'org)
19409 (run-hooks 'org-load-hook)
19411 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
19413 ;;; org.el ends here