Make org-edit-special call the formula editor if cursor is in TBLFM line
[org-mode/org-jambu.git] / lisp / org.el
blob6049f2f27ff63533fdc1ff19edbbf1ed1581e137
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: 7.3
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 (require 'outline) (require 'noutline)
90 ;; Other stuff we need.
91 (require 'time-date)
92 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
93 (require 'easymenu)
94 (require 'overlay)
96 (require 'org-macs)
97 (require 'org-entities)
98 (require 'org-compat)
99 (require 'org-faces)
100 (require 'org-list)
101 (require 'org-src)
102 (require 'org-footnote)
104 ;; babel
105 (require 'ob)
106 (require 'ob-table)
107 (require 'ob-lob)
108 (require 'ob-ref)
109 (require 'ob-tangle)
110 (require 'ob-comint)
111 (require 'ob-keys)
113 ;; load languages based on value of `org-babel-load-languages'
114 (defvar org-babel-load-languages)
115 ;;;###autoload
116 (defun org-babel-do-load-languages (sym value)
117 "Load the languages defined in `org-babel-load-languages'."
118 (set-default sym value)
119 (mapc (lambda (pair)
120 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
121 (if active
122 (progn
123 (require (intern (concat "ob-" lang))))
124 (progn
125 (funcall 'fmakunbound
126 (intern (concat "org-babel-execute:" lang)))
127 (funcall 'fmakunbound
128 (intern (concat "org-babel-expand-body:" lang)))))))
129 org-babel-load-languages))
131 (defcustom org-babel-load-languages '((emacs-lisp . t))
132 "Languages which can be evaluated in Org-mode buffers.
133 This list can be used to load support for any of the languages
134 below, note that each language will depend on a different set of
135 system executables and/or Emacs modes. When a language is
136 \"loaded\", then code blocks in that language can be evaluated
137 with `org-babel-execute-src-block' bound by default to C-c
138 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
139 be set to remove code block evaluation from the C-c C-c
140 keybinding. By default only Emacs Lisp (which has no
141 requirements) is loaded."
142 :group 'org-babel
143 :set 'org-babel-do-load-languages
144 :type '(alist :tag "Babel Languages"
145 :key-type
146 (choice
147 (const :tag "C" C)
148 (const :tag "R" R)
149 (const :tag "Asymptote" asymptote)
150 (const :tag "Calc" calc)
151 (const :tag "Clojure" clojure)
152 (const :tag "CSS" css)
153 (const :tag "Ditaa" ditaa)
154 (const :tag "Dot" dot)
155 (const :tag "Emacs Lisp" emacs-lisp)
156 (const :tag "Gnuplot" gnuplot)
157 (const :tag "Haskell" haskell)
158 (const :tag "Javascript" js)
159 (const :tag "Latex" latex)
160 (const :tag "Ledger" ledger)
161 (const :tag "Matlab" matlab)
162 (const :tag "Mscgen" mscgen)
163 (const :tag "Ocaml" ocaml)
164 (const :tag "Octave" octave)
165 (const :tag "Org" org)
166 (const :tag "Perl" perl)
167 (const :tag "PlantUML" plantuml)
168 (const :tag "Python" python)
169 (const :tag "Ruby" ruby)
170 (const :tag "Sass" sass)
171 (const :tag "Scheme" scheme)
172 (const :tag "Screen" screen)
173 (const :tag "Shell Script" sh)
174 (const :tag "Sql" sql)
175 (const :tag "Sqlite" sqlite))
176 :value-type (boolean :tag "Activate" :value t)))
178 ;;;; Customization variables
179 (defcustom org-clone-delete-id nil
180 "Remove ID property of clones of a subtree.
181 When non-nil, clones of a subtree don't inherit the ID property.
182 Otherwise they inherit the ID property with a new unique
183 identifier."
184 :type 'boolean
185 :group 'org-id)
187 ;;; Version
189 (defconst org-version "7.3"
190 "The version number of the file org.el.")
192 (defun org-version (&optional here)
193 "Show the org-mode version in the echo area.
194 With prefix arg HERE, insert it at point."
195 (interactive "P")
196 (let* ((origin default-directory)
197 (version org-version)
198 (git-version)
199 (dir (concat (file-name-directory (locate-library "org")) "../" )))
200 (when (and (file-exists-p (expand-file-name ".git" dir))
201 (executable-find "git"))
202 (unwind-protect
203 (progn
204 (cd dir)
205 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
206 (with-current-buffer "*Shell Command Output*"
207 (goto-char (point-min))
208 (setq git-version (buffer-substring (point) (point-at-eol))))
209 (subst-char-in-string ?- ?. git-version t)
210 (when (string-match "\\S-"
211 (shell-command-to-string
212 "git diff-index --name-only HEAD --"))
213 (setq git-version (concat git-version ".dirty")))
214 (setq version (concat version " (" git-version ")"))))
215 (cd origin)))
216 (setq version (format "Org-mode version %s" version))
217 (if here (insert version))
218 (message version)))
220 ;;; Compatibility constants
222 ;;; The custom variables
224 (defgroup org nil
225 "Outline-based notes management and organizer."
226 :tag "Org"
227 :group 'outlines
228 :group 'calendar)
230 (defcustom org-mode-hook nil
231 "Mode hook for Org-mode, run after the mode was turned on."
232 :group 'org
233 :type 'hook)
235 (defcustom org-load-hook nil
236 "Hook that is run after org.el has been loaded."
237 :group 'org
238 :type 'hook)
240 (defvar org-modules) ; defined below
241 (defvar org-modules-loaded nil
242 "Have the modules been loaded already?")
244 (defun org-load-modules-maybe (&optional force)
245 "Load all extensions listed in `org-modules'."
246 (when (or force (not org-modules-loaded))
247 (mapc (lambda (ext)
248 (condition-case nil (require ext)
249 (error (message "Problems while trying to load feature `%s'" ext))))
250 org-modules)
251 (setq org-modules-loaded t)))
253 (defun org-set-modules (var value)
254 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
255 (set var value)
256 (when (featurep 'org)
257 (org-load-modules-maybe 'force)))
259 (when (org-bound-and-true-p org-modules)
260 (let ((a (member 'org-infojs org-modules)))
261 (and a (setcar a 'org-jsinfo))))
263 (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)
264 "Modules that should always be loaded together with org.el.
265 If a description starts with <C>, the file is not part of Emacs
266 and loading it will require that you have downloaded and properly installed
267 the org-mode distribution.
269 You can also use this system to load external packages (i.e. neither Org
270 core modules, nor modules from the CONTRIB directory). Just add symbols
271 to the end of the list. If the package is called org-xyz.el, then you need
272 to add the symbol `xyz', and the package must have a call to
274 (provide 'org-xyz)"
275 :group 'org
276 :set 'org-set-modules
277 :type
278 '(set :greedy t
279 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
280 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
281 (const :tag " crypt: Encryption of subtrees" org-crypt)
282 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
283 (const :tag " docview: Links to doc-view buffers" org-docview)
284 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
285 (const :tag " id: Global IDs for identifying entries" org-id)
286 (const :tag " info: Links to Info nodes" org-info)
287 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
288 (const :tag " habit: Track your consistency with habits" org-habit)
289 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
290 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
291 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
292 (const :tag " mew Links to Mew folders/messages" org-mew)
293 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
294 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
295 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
296 (const :tag " vm: Links to VM folders/messages" org-vm)
297 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
298 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
299 (const :tag " mouse: Additional mouse support" org-mouse)
300 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
302 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
303 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
304 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
305 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
306 (const :tag "C collector: Collect properties into tables" org-collector)
307 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
308 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
309 (const :tag "C eval: Include command output as text" org-eval)
310 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
311 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
312 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
313 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
314 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
316 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
318 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
319 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
320 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
321 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
322 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
323 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
324 (const :tag "C mtags: Support for muse-like tags" org-mtags)
325 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
326 (const :tag "C registry: A registry for Org-mode links" org-registry)
327 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
328 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
329 (const :tag "C secretary: Team management with org-mode" org-secretary)
330 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
331 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
332 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
333 (const :tag "C track: Keep up with Org-mode development" org-track)
334 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
335 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
336 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
338 (defcustom org-support-shift-select nil
339 "Non-nil means make shift-cursor commands select text when possible.
341 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
342 selecting a region, or enlarge regions started in this way.
343 In Org-mode, in special contexts, these same keys are used for other
344 purposes, important enough to compete with shift selection. Org tries
345 to balance these needs by supporting `shift-select-mode' outside these
346 special contexts, under control of this variable.
348 The default of this variable is nil, to avoid confusing behavior. Shifted
349 cursor keys will then execute Org commands in the following contexts:
350 - on a headline, changing TODO state (left/right) and priority (up/down)
351 - on a time stamp, changing the time
352 - in a plain list item, changing the bullet type
353 - in a property definition line, switching between allowed values
354 - in the BEGIN line of a clock table (changing the time block).
355 Outside these contexts, the commands will throw an error.
357 When this variable is t and the cursor is not in a special context,
358 Org-mode will support shift-selection for making and enlarging regions.
359 To make this more effective, the bullet cycling will no longer happen
360 anywhere in an item line, but only if the cursor is exactly on the bullet.
362 If you set this variable to the symbol `always', then the keys
363 will not be special in headlines, property lines, and item lines, to make
364 shift selection work there as well. If this is what you want, you can
365 use the following alternative commands: `C-c C-t' and `C-c ,' to
366 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
367 TODO sets, `C-c -' to cycle item bullet types, and properties can be
368 edited by hand or in column view.
370 However, when the cursor is on a timestamp, shift-cursor commands
371 will still edit the time stamp - this is just too good to give up.
373 XEmacs user should have this variable set to nil, because shift-select-mode
374 is Emacs 23 only."
375 :group 'org
376 :type '(choice
377 (const :tag "Never" nil)
378 (const :tag "When outside special context" t)
379 (const :tag "Everywhere except timestamps" always)))
381 (defgroup org-startup nil
382 "Options concerning startup of Org-mode."
383 :tag "Org Startup"
384 :group 'org)
386 (defcustom org-startup-folded t
387 "Non-nil means entering Org-mode will switch to OVERVIEW.
388 This can also be configured on a per-file basis by adding one of
389 the following lines anywhere in the buffer:
391 #+STARTUP: fold (or `overview', this is equivalent)
392 #+STARTUP: nofold (or `showall', this is equivalent)
393 #+STARTUP: content
394 #+STARTUP: showeverything"
395 :group 'org-startup
396 :type '(choice
397 (const :tag "nofold: show all" nil)
398 (const :tag "fold: overview" t)
399 (const :tag "content: all headlines" content)
400 (const :tag "show everything, even drawers" showeverything)))
402 (defcustom org-startup-truncated t
403 "Non-nil means entering Org-mode will set `truncate-lines'.
404 This is useful since some lines containing links can be very long and
405 uninteresting. Also tables look terrible when wrapped."
406 :group 'org-startup
407 :type 'boolean)
409 (defcustom org-startup-indented nil
410 "Non-nil means turn on `org-indent-mode' on startup.
411 This can also be configured on a per-file basis by adding one of
412 the following lines anywhere in the buffer:
414 #+STARTUP: indent
415 #+STARTUP: noindent"
416 :group 'org-structure
417 :type '(choice
418 (const :tag "Not" nil)
419 (const :tag "Globally (slow on startup in large files)" t)))
421 (defcustom org-use-sub-superscripts t
422 "Non-nil means interpret \"_\" and \"^\" for export.
423 When this option is turned on, you can use TeX-like syntax for sub- and
424 superscripts. Several characters after \"_\" or \"^\" will be
425 considered as a single item - so grouping with {} is normally not
426 needed. For example, the following things will be parsed as single
427 sub- or superscripts.
429 10^24 or 10^tau several digits will be considered 1 item.
430 10^-12 or 10^-tau a leading sign with digits or a word
431 x^2-y^3 will be read as x^2 - y^3, because items are
432 terminated by almost any nonword/nondigit char.
433 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
435 Still, ambiguity is possible - so when in doubt use {} to enclose the
436 sub/superscript. If you set this variable to the symbol `{}',
437 the braces are *required* in order to trigger interpretations as
438 sub/superscript. This can be helpful in documents that need \"_\"
439 frequently in plain text.
441 Not all export backends support this, but HTML does.
443 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
444 :group 'org-startup
445 :group 'org-export-translation
446 :type '(choice
447 (const :tag "Always interpret" t)
448 (const :tag "Only with braces" {})
449 (const :tag "Never interpret" nil)))
451 (if (fboundp 'defvaralias)
452 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
455 (defcustom org-startup-with-beamer-mode nil
456 "Non-nil means turn on `org-beamer-mode' on startup.
457 This can also be configured on a per-file basis by adding one of
458 the following lines anywhere in the buffer:
460 #+STARTUP: beamer"
461 :group 'org-startup
462 :type 'boolean)
464 (defcustom org-startup-align-all-tables nil
465 "Non-nil means align all tables when visiting a file.
466 This is useful when the column width in tables is forced with <N> cookies
467 in table fields. Such tables will look correct only after the first re-align.
468 This can also be configured on a per-file basis by adding one of
469 the following lines anywhere in the buffer:
470 #+STARTUP: align
471 #+STARTUP: noalign"
472 :group 'org-startup
473 :type 'boolean)
475 (defcustom org-startup-with-inline-images nil
476 "Non-nil means show inline images when loading a new Org file.
477 This can also be configured on a per-file basis by adding one of
478 the following lines anywhere in the buffer:
479 #+STARTUP: inlineimages
480 #+STARTUP: noinlineimages"
481 :group 'org-startup
482 :type 'boolean)
484 (defcustom org-insert-mode-line-in-empty-file nil
485 "Non-nil means insert the first line setting Org-mode in empty files.
486 When the function `org-mode' is called interactively in an empty file, this
487 normally means that the file name does not automatically trigger Org-mode.
488 To ensure that the file will always be in Org-mode in the future, a
489 line enforcing Org-mode will be inserted into the buffer, if this option
490 has been set."
491 :group 'org-startup
492 :type 'boolean)
494 (defcustom org-replace-disputed-keys nil
495 "Non-nil means use alternative key bindings for some keys.
496 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
497 These keys are also used by other packages like shift-selection-mode'
498 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
499 If you want to use Org-mode together with one of these other modes,
500 or more generally if you would like to move some Org-mode commands to
501 other keys, set this variable and configure the keys with the variable
502 `org-disputed-keys'.
504 This option is only relevant at load-time of Org-mode, and must be set
505 *before* org.el is loaded. Changing it requires a restart of Emacs to
506 become effective."
507 :group 'org-startup
508 :type 'boolean)
510 (defcustom org-use-extra-keys nil
511 "Non-nil means use extra key sequence definitions for certain commands.
512 This happens automatically if you run XEmacs or if `window-system'
513 is nil. This variable lets you do the same manually. You must
514 set it before loading org.
516 Example: on Carbon Emacs 22 running graphically, with an external
517 keyboard on a Powerbook, the default way of setting M-left might
518 not work for either Alt or ESC. Setting this variable will make
519 it work for ESC."
520 :group 'org-startup
521 :type 'boolean)
523 (if (fboundp 'defvaralias)
524 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
526 (defcustom org-disputed-keys
527 '(([(shift up)] . [(meta p)])
528 ([(shift down)] . [(meta n)])
529 ([(shift left)] . [(meta -)])
530 ([(shift right)] . [(meta +)])
531 ([(control shift right)] . [(meta shift +)])
532 ([(control shift left)] . [(meta shift -)]))
533 "Keys for which Org-mode and other modes compete.
534 This is an alist, cars are the default keys, second element specifies
535 the alternative to use when `org-replace-disputed-keys' is t.
537 Keys can be specified in any syntax supported by `define-key'.
538 The value of this option takes effect only at Org-mode's startup,
539 therefore you'll have to restart Emacs to apply it after changing."
540 :group 'org-startup
541 :type 'alist)
543 (defun org-key (key)
544 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
545 Or return the original if not disputed.
546 Also apply the translations defined in `org-xemacs-key-equivalents'."
547 (when org-replace-disputed-keys
548 (let* ((nkey (key-description key))
549 (x (org-find-if (lambda (x)
550 (equal (key-description (car x)) nkey))
551 org-disputed-keys)))
552 (setq key (if x (cdr x) key))))
553 (when (featurep 'xemacs)
554 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
555 key)
557 (defun org-find-if (predicate seq)
558 (catch 'exit
559 (while seq
560 (if (funcall predicate (car seq))
561 (throw 'exit (car seq))
562 (pop seq)))))
564 (defun org-defkey (keymap key def)
565 "Define a key, possibly translated, as returned by `org-key'."
566 (define-key keymap (org-key key) def))
568 (defcustom org-ellipsis nil
569 "The ellipsis to use in the Org-mode outline.
570 When nil, just use the standard three dots. When a string, use that instead,
571 When a face, use the standard 3 dots, but with the specified face.
572 The change affects only Org-mode (which will then use its own display table).
573 Changing this requires executing `M-x org-mode' in a buffer to become
574 effective."
575 :group 'org-startup
576 :type '(choice (const :tag "Default" nil)
577 (face :tag "Face" :value org-warning)
578 (string :tag "String" :value "...#")))
580 (defvar org-display-table nil
581 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
583 (defgroup org-keywords nil
584 "Keywords in Org-mode."
585 :tag "Org Keywords"
586 :group 'org)
588 (defcustom org-deadline-string "DEADLINE:"
589 "String to mark deadline entries.
590 A deadline is this string, followed by a time stamp. Should be a word,
591 terminated by a colon. You can insert a schedule keyword and
592 a timestamp with \\[org-deadline].
593 Changes become only effective after restarting Emacs."
594 :group 'org-keywords
595 :type 'string)
597 (defcustom org-scheduled-string "SCHEDULED:"
598 "String to mark scheduled TODO entries.
599 A schedule is this string, followed by a time stamp. Should be a word,
600 terminated by a colon. You can insert a schedule keyword and
601 a timestamp with \\[org-schedule].
602 Changes become only effective after restarting Emacs."
603 :group 'org-keywords
604 :type 'string)
606 (defcustom org-closed-string "CLOSED:"
607 "String used as the prefix for timestamps logging closing a TODO entry."
608 :group 'org-keywords
609 :type 'string)
611 (defcustom org-clock-string "CLOCK:"
612 "String used as prefix for timestamps clocking work hours on an item."
613 :group 'org-keywords
614 :type 'string)
616 (defcustom org-comment-string "COMMENT"
617 "Entries starting with this keyword will never be exported.
618 An entry can be toggled between COMMENT and normal with
619 \\[org-toggle-comment].
620 Changes become only effective after restarting Emacs."
621 :group 'org-keywords
622 :type 'string)
624 (defcustom org-quote-string "QUOTE"
625 "Entries starting with this keyword will be exported in fixed-width font.
626 Quoting applies only to the text in the entry following the headline, and does
627 not extend beyond the next headline, even if that is lower level.
628 An entry can be toggled between QUOTE and normal with
629 \\[org-toggle-fixed-width-section]."
630 :group 'org-keywords
631 :type 'string)
633 (defconst org-repeat-re
634 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
635 "Regular expression for specifying repeated events.
636 After a match, group 1 contains the repeat expression.")
638 (defgroup org-structure nil
639 "Options concerning the general structure of Org-mode files."
640 :tag "Org Structure"
641 :group 'org)
643 (defgroup org-reveal-location nil
644 "Options about how to make context of a location visible."
645 :tag "Org Reveal Location"
646 :group 'org-structure)
648 (defconst org-context-choice
649 '(choice
650 (const :tag "Always" t)
651 (const :tag "Never" nil)
652 (repeat :greedy t :tag "Individual contexts"
653 (cons
654 (choice :tag "Context"
655 (const agenda)
656 (const org-goto)
657 (const occur-tree)
658 (const tags-tree)
659 (const link-search)
660 (const mark-goto)
661 (const bookmark-jump)
662 (const isearch)
663 (const default))
664 (boolean))))
665 "Contexts for the reveal options.")
667 (defcustom org-show-hierarchy-above '((default . t))
668 "Non-nil means show full hierarchy when revealing a location.
669 Org-mode often shows locations in an org-mode file which might have
670 been invisible before. When this is set, the hierarchy of headings
671 above the exposed location is shown.
672 Turning this off for example for sparse trees makes them very compact.
673 Instead of t, this can also be an alist specifying this option for different
674 contexts. Valid contexts are
675 agenda when exposing an entry from the agenda
676 org-goto when using the command `org-goto' on key C-c C-j
677 occur-tree when using the command `org-occur' on key C-c /
678 tags-tree when constructing a sparse tree based on tags matches
679 link-search when exposing search matches associated with a link
680 mark-goto when exposing the jump goal of a mark
681 bookmark-jump when exposing a bookmark location
682 isearch when exiting from an incremental search
683 default default for all contexts not set explicitly"
684 :group 'org-reveal-location
685 :type org-context-choice)
687 (defcustom org-show-following-heading '((default . nil))
688 "Non-nil means show following heading when revealing a location.
689 Org-mode often shows locations in an org-mode file which might have
690 been invisible before. When this is set, the heading following the
691 match is shown.
692 Turning this off for example for sparse trees makes them very compact,
693 but makes it harder to edit the location of the match. In such a case,
694 use the command \\[org-reveal] to show more context.
695 Instead of t, this can also be an alist specifying this option for different
696 contexts. See `org-show-hierarchy-above' for valid contexts."
697 :group 'org-reveal-location
698 :type org-context-choice)
700 (defcustom org-show-siblings '((default . nil) (isearch t))
701 "Non-nil means show all sibling heading when revealing a location.
702 Org-mode often shows locations in an org-mode file which might have
703 been invisible before. When this is set, the sibling of the current entry
704 heading are all made visible. If `org-show-hierarchy-above' is t,
705 the same happens on each level of the hierarchy above the current entry.
707 By default this is on for the isearch context, off for all other contexts.
708 Turning this off for example for sparse trees makes them very compact,
709 but makes it harder to edit the location of the match. In such a case,
710 use the command \\[org-reveal] to show more context.
711 Instead of t, this can also be an alist specifying this option for different
712 contexts. See `org-show-hierarchy-above' for valid contexts."
713 :group 'org-reveal-location
714 :type org-context-choice)
716 (defcustom org-show-entry-below '((default . nil))
717 "Non-nil means show the entry below a headline when revealing a location.
718 Org-mode often shows locations in an org-mode file which might have
719 been invisible before. When this is set, the text below the headline that is
720 exposed is also shown.
722 By default this is off for all contexts.
723 Instead of t, this can also be an alist specifying this option for different
724 contexts. See `org-show-hierarchy-above' for valid contexts."
725 :group 'org-reveal-location
726 :type org-context-choice)
728 (defcustom org-indirect-buffer-display 'other-window
729 "How should indirect tree buffers be displayed?
730 This applies to indirect buffers created with the commands
731 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
732 Valid values are:
733 current-window Display in the current window
734 other-window Just display in another window.
735 dedicated-frame Create one new frame, and re-use it each time.
736 new-frame Make a new frame each time. Note that in this case
737 previously-made indirect buffers are kept, and you need to
738 kill these buffers yourself."
739 :group 'org-structure
740 :group 'org-agenda-windows
741 :type '(choice
742 (const :tag "In current window" current-window)
743 (const :tag "In current frame, other window" other-window)
744 (const :tag "Each time a new frame" new-frame)
745 (const :tag "One dedicated frame" dedicated-frame)))
747 (defcustom org-use-speed-commands nil
748 "Non-nil means activate single letter commands at beginning of a headline.
749 This may also be a function to test for appropriate locations where speed
750 commands should be active."
751 :group 'org-structure
752 :type '(choice
753 (const :tag "Never" nil)
754 (const :tag "At beginning of headline stars" t)
755 (function)))
757 (defcustom org-speed-commands-user nil
758 "Alist of additional speed commands.
759 This list will be checked before `org-speed-commands-default'
760 when the variable `org-use-speed-commands' is non-nil
761 and when the cursor is at the beginning of a headline.
762 The car if each entry is a string with a single letter, which must
763 be assigned to `self-insert-command' in the global map.
764 The cdr is either a command to be called interactively, a function
765 to be called, or a form to be evaluated.
766 An entry that is just a list with a single string will be interpreted
767 as a descriptive headline that will be added when listing the speed
768 commands in the Help buffer using the `?' speed command."
769 :group 'org-structure
770 :type '(repeat :value ("k" . ignore)
771 (choice :value ("k" . ignore)
772 (list :tag "Descriptive Headline" (string :tag "Headline"))
773 (cons :tag "Letter and Command"
774 (string :tag "Command letter")
775 (choice
776 (function)
777 (sexp))))))
779 (defgroup org-cycle nil
780 "Options concerning visibility cycling in Org-mode."
781 :tag "Org Cycle"
782 :group 'org-structure)
784 (defcustom org-cycle-skip-children-state-if-no-children t
785 "Non-nil means skip CHILDREN state in entries that don't have any."
786 :group 'org-cycle
787 :type 'boolean)
789 (defcustom org-cycle-max-level nil
790 "Maximum level which should still be subject to visibility cycling.
791 Levels higher than this will, for cycling, be treated as text, not a headline.
792 When `org-odd-levels-only' is set, a value of N in this variable actually
793 means 2N-1 stars as the limiting headline.
794 When nil, cycle all levels.
795 Note that the limiting level of cycling is also influenced by
796 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
797 `org-inlinetask-min-level' is, cycling will be limited to levels one less
798 than its value."
799 :group 'org-cycle
800 :type '(choice
801 (const :tag "No limit" nil)
802 (integer :tag "Maximum level")))
804 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
805 "Names of drawers. Drawers are not opened by cycling on the headline above.
806 Drawers only open with a TAB on the drawer line itself. A drawer looks like
807 this:
808 :DRAWERNAME:
809 .....
810 :END:
811 The drawer \"PROPERTIES\" is special for capturing properties through
812 the property API.
814 Drawers can be defined on the per-file basis with a line like:
816 #+DRAWERS: HIDDEN STATE PROPERTIES"
817 :group 'org-structure
818 :group 'org-cycle
819 :type '(repeat (string :tag "Drawer Name")))
821 (defcustom org-hide-block-startup nil
822 "Non-nil means entering Org-mode will fold all blocks.
823 This can also be set in on a per-file basis with
825 #+STARTUP: hideblocks
826 #+STARTUP: showblocks"
827 :group 'org-startup
828 :group 'org-cycle
829 :type 'boolean)
831 (defcustom org-cycle-global-at-bob nil
832 "Cycle globally if cursor is at beginning of buffer and not at a headline.
833 This makes it possible to do global cycling without having to use S-TAB or
834 \\[universal-argument] TAB. For this special case to work, the first line \
835 of the buffer
836 must not be a headline - it may be empty or some other text. When used in
837 this way, `org-cycle-hook' is disables temporarily, to make sure the
838 cursor stays at the beginning of the buffer.
839 When this option is nil, don't do anything special at the beginning
840 of the buffer."
841 :group 'org-cycle
842 :type 'boolean)
844 (defcustom org-cycle-level-after-item/entry-creation t
845 "Non-nil means cycle entry level or item indentation in new empty entries.
847 When the cursor is at the end of an empty headline, i.e with only stars
848 and maybe a TODO keyword, TAB will then switch the entry to become a child,
849 and then all possible ancestor states, before returning to the original state.
850 This makes data entry extremely fast: M-RET to create a new headline,
851 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
853 When the cursor is at the end of an empty plain list item, one TAB will
854 make it a subitem, two or more tabs will back up to make this an item
855 higher up in the item hierarchy."
856 :group 'org-cycle
857 :type 'boolean)
859 (defcustom org-cycle-emulate-tab t
860 "Where should `org-cycle' emulate TAB.
861 nil Never
862 white Only in completely white lines
863 whitestart Only at the beginning of lines, before the first non-white char
864 t Everywhere except in headlines
865 exc-hl-bol Everywhere except at the start of a headline
866 If TAB is used in a place where it does not emulate TAB, the current subtree
867 visibility is cycled."
868 :group 'org-cycle
869 :type '(choice (const :tag "Never" nil)
870 (const :tag "Only in completely white lines" white)
871 (const :tag "Before first char in a line" whitestart)
872 (const :tag "Everywhere except in headlines" t)
873 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
876 (defcustom org-cycle-separator-lines 2
877 "Number of empty lines needed to keep an empty line between collapsed trees.
878 If you leave an empty line between the end of a subtree and the following
879 headline, this empty line is hidden when the subtree is folded.
880 Org-mode will leave (exactly) one empty line visible if the number of
881 empty lines is equal or larger to the number given in this variable.
882 So the default 2 means at least 2 empty lines after the end of a subtree
883 are needed to produce free space between a collapsed subtree and the
884 following headline.
886 If the number is negative, and the number of empty lines is at least -N,
887 all empty lines are shown.
889 Special case: when 0, never leave empty lines in collapsed view."
890 :group 'org-cycle
891 :type 'integer)
892 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
894 (defcustom org-pre-cycle-hook nil
895 "Hook that is run before visibility cycling is happening.
896 The function(s) in this hook must accept a single argument which indicates
897 the new state that will be set right after running this hook. The
898 argument is a symbol. Before a global state change, it can have the values
899 `overview', `content', or `all'. Before a local state change, it can have
900 the values `folded', `children', or `subtree'."
901 :group 'org-cycle
902 :type 'hook)
904 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
905 org-cycle-hide-drawers
906 org-cycle-show-empty-lines
907 org-optimize-window-after-visibility-change)
908 "Hook that is run after `org-cycle' has changed the buffer visibility.
909 The function(s) in this hook must accept a single argument which indicates
910 the new state that was set by the most recent `org-cycle' command. The
911 argument is a symbol. After a global state change, it can have the values
912 `overview', `content', or `all'. After a local state change, it can have
913 the values `folded', `children', or `subtree'."
914 :group 'org-cycle
915 :type 'hook)
917 (defgroup org-edit-structure nil
918 "Options concerning structure editing in Org-mode."
919 :tag "Org Edit Structure"
920 :group 'org-structure)
922 (defcustom org-odd-levels-only nil
923 "Non-nil means skip even levels and only use odd levels for the outline.
924 This has the effect that two stars are being added/taken away in
925 promotion/demotion commands. It also influences how levels are
926 handled by the exporters.
927 Changing it requires restart of `font-lock-mode' to become effective
928 for fontification also in regions already fontified.
929 You may also set this on a per-file basis by adding one of the following
930 lines to the buffer:
932 #+STARTUP: odd
933 #+STARTUP: oddeven"
934 :group 'org-edit-structure
935 :group 'org-appearance
936 :type 'boolean)
938 (defcustom org-adapt-indentation t
939 "Non-nil means adapt indentation to outline node level.
941 When this variable is set, Org assumes that you write outlines by
942 indenting text in each node to align with the headline (after the stars).
943 The following issues are influenced by this variable:
945 - When this is set and the *entire* text in an entry is indented, the
946 indentation is increased by one space in a demotion command, and
947 decreased by one in a promotion command. If any line in the entry
948 body starts with text at column 0, indentation is not changed at all.
950 - Property drawers and planning information is inserted indented when
951 this variable s set. When nil, they will not be indented.
953 - TAB indents a line relative to context. The lines below a headline
954 will be indented when this variable is set.
956 Note that this is all about true indentation, by adding and removing
957 space characters. See also `org-indent.el' which does level-dependent
958 indentation in a virtual way, i.e. at display time in Emacs."
959 :group 'org-edit-structure
960 :type 'boolean)
962 (defcustom org-special-ctrl-a/e nil
963 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
965 When t, `C-a' will bring back the cursor to the beginning of the
966 headline text, i.e. after the stars and after a possible TODO keyword.
967 In an item, this will be the position after the bullet.
968 When the cursor is already at that position, another `C-a' will bring
969 it to the beginning of the line.
971 `C-e' will jump to the end of the headline, ignoring the presence of tags
972 in the headline. A second `C-e' will then jump to the true end of the
973 line, after any tags. This also means that, when this variable is
974 non-nil, `C-e' also will never jump beyond the end of the heading of a
975 folded section, i.e. not after the ellipses.
977 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
978 going to the true line boundary first. Only a directly following, identical
979 keypress will bring the cursor to the special positions.
981 This may also be a cons cell where the behavior for `C-a' and `C-e' is
982 set separately."
983 :group 'org-edit-structure
984 :type '(choice
985 (const :tag "off" nil)
986 (const :tag "on: after stars/bullet and before tags first" t)
987 (const :tag "reversed: true line boundary first" reversed)
988 (cons :tag "Set C-a and C-e separately"
989 (choice :tag "Special C-a"
990 (const :tag "off" nil)
991 (const :tag "on: after stars/bullet first" t)
992 (const :tag "reversed: before stars/bullet first" reversed))
993 (choice :tag "Special C-e"
994 (const :tag "off" nil)
995 (const :tag "on: before tags first" t)
996 (const :tag "reversed: after tags first" reversed)))))
997 (if (fboundp 'defvaralias)
998 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1000 (defcustom org-special-ctrl-k nil
1001 "Non-nil means `C-k' will behave specially in headlines.
1002 When nil, `C-k' will call the default `kill-line' command.
1003 When t, the following will happen while the cursor is in the headline:
1005 - When the cursor is at the beginning of a headline, kill the entire
1006 line and possible the folded subtree below the line.
1007 - When in the middle of the headline text, kill the headline up to the tags.
1008 - When after the headline text, kill the tags."
1009 :group 'org-edit-structure
1010 :type 'boolean)
1012 (defcustom org-ctrl-k-protect-subtree nil
1013 "Non-nil means, do not delete a hidden subtree with C-k.
1014 When set to the symbol `error', simply throw an error when C-k is
1015 used to kill (part-of) a headline that has hidden text behind it.
1016 Any other non-nil value will result in a query to the user, if it is
1017 OK to kill that hidden subtree. When nil, kill without remorse."
1018 :group 'org-edit-structure
1019 :type '(choice
1020 (const :tag "Do not protect hidden subtrees" nil)
1021 (const :tag "Protect hidden subtrees with a security query" t)
1022 (const :tag "Never kill a hidden subtree with C-k" error)))
1024 (defcustom org-yank-folded-subtrees t
1025 "Non-nil means when yanking subtrees, fold them.
1026 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1027 it starts with a heading and all other headings in it are either children
1028 or siblings, then fold all the subtrees. However, do this only if no
1029 text after the yank would be swallowed into a folded tree by this action."
1030 :group 'org-edit-structure
1031 :type 'boolean)
1033 (defcustom org-yank-adjusted-subtrees nil
1034 "Non-nil means when yanking subtrees, adjust the level.
1035 With this setting, `org-paste-subtree' is used to insert the subtree, see
1036 this function for details."
1037 :group 'org-edit-structure
1038 :type 'boolean)
1040 (defcustom org-M-RET-may-split-line '((default . t))
1041 "Non-nil means M-RET will split the line at the cursor position.
1042 When nil, it will go to the end of the line before making a
1043 new line.
1044 You may also set this option in a different way for different
1045 contexts. Valid contexts are:
1047 headline when creating a new headline
1048 item when creating a new item
1049 table in a table field
1050 default the value to be used for all contexts not explicitly
1051 customized"
1052 :group 'org-structure
1053 :group 'org-table
1054 :type '(choice
1055 (const :tag "Always" t)
1056 (const :tag "Never" nil)
1057 (repeat :greedy t :tag "Individual contexts"
1058 (cons
1059 (choice :tag "Context"
1060 (const headline)
1061 (const item)
1062 (const table)
1063 (const default))
1064 (boolean)))))
1067 (defcustom org-insert-heading-respect-content nil
1068 "Non-nil means insert new headings after the current subtree.
1069 When nil, the new heading is created directly after the current line.
1070 The commands \\[org-insert-heading-respect-content] and
1071 \\[org-insert-todo-heading-respect-content] turn this variable on
1072 for the duration of the command."
1073 :group 'org-structure
1074 :type 'boolean)
1076 (defcustom org-blank-before-new-entry '((heading . auto)
1077 (plain-list-item . auto))
1078 "Should `org-insert-heading' leave a blank line before new heading/item?
1079 The value is an alist, with `heading' and `plain-list-item' as car,
1080 and a boolean flag as cdr. The cdr may lso be the symbol `auto', and then
1081 Org will look at the surrounding headings/items and try to make an
1082 intelligent decision wether to insert a blank line or not.
1084 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1085 set, the setting here is ignored and no empty line is inserted, to avoid
1086 breaking the list structure."
1087 :group 'org-edit-structure
1088 :type '(list
1089 (cons (const heading)
1090 (choice (const :tag "Never" nil)
1091 (const :tag "Always" t)
1092 (const :tag "Auto" auto)))
1093 (cons (const plain-list-item)
1094 (choice (const :tag "Never" nil)
1095 (const :tag "Always" t)
1096 (const :tag "Auto" auto)))))
1098 (defcustom org-insert-heading-hook nil
1099 "Hook being run after inserting a new heading."
1100 :group 'org-edit-structure
1101 :type 'hook)
1103 (defcustom org-enable-fixed-width-editor t
1104 "Non-nil means lines starting with \":\" are treated as fixed-width.
1105 This currently only means they are never auto-wrapped.
1106 When nil, such lines will be treated like ordinary lines.
1107 See also the QUOTE keyword."
1108 :group 'org-edit-structure
1109 :type 'boolean)
1111 (defcustom org-goto-auto-isearch t
1112 "Non-nil means typing characters in `org-goto' starts incremental search."
1113 :group 'org-edit-structure
1114 :type 'boolean)
1116 (defgroup org-sparse-trees nil
1117 "Options concerning sparse trees in Org-mode."
1118 :tag "Org Sparse Trees"
1119 :group 'org-structure)
1121 (defcustom org-highlight-sparse-tree-matches t
1122 "Non-nil means highlight all matches that define a sparse tree.
1123 The highlights will automatically disappear the next time the buffer is
1124 changed by an edit command."
1125 :group 'org-sparse-trees
1126 :type 'boolean)
1128 (defcustom org-remove-highlights-with-change t
1129 "Non-nil means any change to the buffer will remove temporary highlights.
1130 Such highlights are created by `org-occur' and `org-clock-display'.
1131 When nil, `C-c C-c needs to be used to get rid of the highlights.
1132 The highlights created by `org-preview-latex-fragment' always need
1133 `C-c C-c' to be removed."
1134 :group 'org-sparse-trees
1135 :group 'org-time
1136 :type 'boolean)
1139 (defcustom org-occur-hook '(org-first-headline-recenter)
1140 "Hook that is run after `org-occur' has constructed a sparse tree.
1141 This can be used to recenter the window to show as much of the structure
1142 as possible."
1143 :group 'org-sparse-trees
1144 :type 'hook)
1146 (defgroup org-imenu-and-speedbar nil
1147 "Options concerning imenu and speedbar in Org-mode."
1148 :tag "Org Imenu and Speedbar"
1149 :group 'org-structure)
1151 (defcustom org-imenu-depth 2
1152 "The maximum level for Imenu access to Org-mode headlines.
1153 This also applied for speedbar access."
1154 :group 'org-imenu-and-speedbar
1155 :type 'integer)
1157 (defgroup org-table nil
1158 "Options concerning tables in Org-mode."
1159 :tag "Org Table"
1160 :group 'org)
1162 (defcustom org-enable-table-editor 'optimized
1163 "Non-nil means lines starting with \"|\" are handled by the table editor.
1164 When nil, such lines will be treated like ordinary lines.
1166 When equal to the symbol `optimized', the table editor will be optimized to
1167 do the following:
1168 - Automatic overwrite mode in front of whitespace in table fields.
1169 This makes the structure of the table stay in tact as long as the edited
1170 field does not exceed the column width.
1171 - Minimize the number of realigns. Normally, the table is aligned each time
1172 TAB or RET are pressed to move to another field. With optimization this
1173 happens only if changes to a field might have changed the column width.
1174 Optimization requires replacing the functions `self-insert-command',
1175 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1176 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1177 very good at guessing when a re-align will be necessary, but you can always
1178 force one with \\[org-ctrl-c-ctrl-c].
1180 If you would like to use the optimized version in Org-mode, but the
1181 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1183 This variable can be used to turn on and off the table editor during a session,
1184 but in order to toggle optimization, a restart is required.
1186 See also the variable `org-table-auto-blank-field'."
1187 :group 'org-table
1188 :type '(choice
1189 (const :tag "off" nil)
1190 (const :tag "on" t)
1191 (const :tag "on, optimized" optimized)))
1193 (defcustom org-self-insert-cluster-for-undo t
1194 "Non-nil means cluster self-insert commands for undo when possible.
1195 If this is set, then, like in the Emacs command loop, 20 consecutive
1196 characters will be undone together.
1197 This is configurable, because there is some impact on typing performance."
1198 :group 'org-table
1199 :type 'boolean)
1201 (defcustom org-table-tab-recognizes-table.el t
1202 "Non-nil means TAB will automatically notice a table.el table.
1203 When it sees such a table, it moves point into it and - if necessary -
1204 calls `table-recognize-table'."
1205 :group 'org-table-editing
1206 :type 'boolean)
1208 (defgroup org-link nil
1209 "Options concerning links in Org-mode."
1210 :tag "Org Link"
1211 :group 'org)
1213 (defvar org-link-abbrev-alist-local nil
1214 "Buffer-local version of `org-link-abbrev-alist', which see.
1215 The value of this is taken from the #+LINK lines.")
1216 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1218 (defcustom org-link-abbrev-alist nil
1219 "Alist of link abbreviations.
1220 The car of each element is a string, to be replaced at the start of a link.
1221 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1222 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1224 [[linkkey:tag][description]]
1226 The 'linkkey' must be a word word, starting with a letter, followed
1227 by letters, numbers, '-' or '_'.
1229 If REPLACE is a string, the tag will simply be appended to create the link.
1230 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1231 the placeholder \"%h\" will cause a url-encoded version of the tag to
1232 be inserted at that point (see the function `url-hexify-string').
1234 REPLACE may also be a function that will be called with the tag as the
1235 only argument to create the link, which should be returned as a string.
1237 See the manual for examples."
1238 :group 'org-link
1239 :type '(repeat
1240 (cons
1241 (string :tag "Protocol")
1242 (choice
1243 (string :tag "Format")
1244 (function)))))
1246 (defcustom org-descriptive-links t
1247 "Non-nil means hide link part and only show description of bracket links.
1248 Bracket links are like [[link][description]]. This variable sets the initial
1249 state in new org-mode buffers. The setting can then be toggled on a
1250 per-buffer basis from the Org->Hyperlinks menu."
1251 :group 'org-link
1252 :type 'boolean)
1254 (defcustom org-link-file-path-type 'adaptive
1255 "How the path name in file links should be stored.
1256 Valid values are:
1258 relative Relative to the current directory, i.e. the directory of the file
1259 into which the link is being inserted.
1260 absolute Absolute path, if possible with ~ for home directory.
1261 noabbrev Absolute path, no abbreviation of home directory.
1262 adaptive Use relative path for files in the current directory and sub-
1263 directories of it. For other files, use an absolute path."
1264 :group 'org-link
1265 :type '(choice
1266 (const relative)
1267 (const absolute)
1268 (const noabbrev)
1269 (const adaptive)))
1271 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1272 "Types of links that should be activated in Org-mode files.
1273 This is a list of symbols, each leading to the activation of a certain link
1274 type. In principle, it does not hurt to turn on most link types - there may
1275 be a small gain when turning off unused link types. The types are:
1277 bracket The recommended [[link][description]] or [[link]] links with hiding.
1278 angle Links in angular brackets that may contain whitespace like
1279 <bbdb:Carsten Dominik>.
1280 plain Plain links in normal text, no whitespace, like http://google.com.
1281 radio Text that is matched by a radio target, see manual for details.
1282 tag Tag settings in a headline (link to tag search).
1283 date Time stamps (link to calendar).
1284 footnote Footnote labels.
1286 Changing this variable requires a restart of Emacs to become effective."
1287 :group 'org-link
1288 :type '(set :greedy t
1289 (const :tag "Double bracket links" bracket)
1290 (const :tag "Angular bracket links" angle)
1291 (const :tag "Plain text links" plain)
1292 (const :tag "Radio target matches" radio)
1293 (const :tag "Tags" tag)
1294 (const :tag "Timestamps" date)
1295 (const :tag "Footnotes" footnote)))
1297 (defcustom org-make-link-description-function nil
1298 "Function to use to generate link descriptions from links.
1299 If nil the link location will be used. This function must take
1300 two parameters; the first is the link and the second the
1301 description `org-insert-link' has generated, and should return the
1302 description to use."
1303 :group 'org-link
1304 :type 'function)
1306 (defgroup org-link-store nil
1307 "Options concerning storing links in Org-mode."
1308 :tag "Org Store Link"
1309 :group 'org-link)
1311 (defcustom org-email-link-description-format "Email %c: %.30s"
1312 "Format of the description part of a link to an email or usenet message.
1313 The following %-escapes will be replaced by corresponding information:
1315 %F full \"From\" field
1316 %f name, taken from \"From\" field, address if no name
1317 %T full \"To\" field
1318 %t first name in \"To\" field, address if no name
1319 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1320 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1321 %s subject
1322 %m message-id.
1324 You may use normal field width specification between the % and the letter.
1325 This is for example useful to limit the length of the subject.
1327 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1328 :group 'org-link-store
1329 :type 'string)
1331 (defcustom org-from-is-user-regexp
1332 (let (r1 r2)
1333 (when (and user-mail-address (not (string= user-mail-address "")))
1334 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1335 (when (and user-full-name (not (string= user-full-name "")))
1336 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1337 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1338 "Regexp matched against the \"From:\" header of an email or usenet message.
1339 It should match if the message is from the user him/herself."
1340 :group 'org-link-store
1341 :type 'regexp)
1343 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1344 "Non-nil means storing a link to an Org file will use entry IDs.
1346 Note that before this variable is even considered, org-id must be loaded,
1347 so please customize `org-modules' and turn it on.
1349 The variable can have the following values:
1351 t Create an ID if needed to make a link to the current entry.
1353 create-if-interactive
1354 If `org-store-link' is called directly (interactively, as a user
1355 command), do create an ID to support the link. But when doing the
1356 job for remember, only use the ID if it already exists. The
1357 purpose of this setting is to avoid proliferation of unwanted
1358 IDs, just because you happen to be in an Org file when you
1359 call `org-remember' that automatically and preemptively
1360 creates a link. If you do want to get an ID link in a remember
1361 template to an entry not having an ID, create it first by
1362 explicitly creating a link to it, using `C-c C-l' first.
1364 create-if-interactive-and-no-custom-id
1365 Like create-if-interactive, but do not create an ID if there is
1366 a CUSTOM_ID property defined in the entry. This is the default.
1368 use-existing
1369 Use existing ID, do not create one.
1371 nil Never use an ID to make a link, instead link using a text search for
1372 the headline text."
1373 :group 'org-link-store
1374 :type '(choice
1375 (const :tag "Create ID to make link" t)
1376 (const :tag "Create if storing link interactively"
1377 create-if-interactive)
1378 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1379 create-if-interactive-and-no-custom-id)
1380 (const :tag "Only use existing" use-existing)
1381 (const :tag "Do not use ID to create link" nil)))
1383 (defcustom org-context-in-file-links t
1384 "Non-nil means file links from `org-store-link' contain context.
1385 A search string will be added to the file name with :: as separator and
1386 used to find the context when the link is activated by the command
1387 `org-open-at-point'.
1388 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1389 negates this setting for the duration of the command."
1390 :group 'org-link-store
1391 :type 'boolean)
1393 (defcustom org-keep-stored-link-after-insertion nil
1394 "Non-nil means keep link in list for entire session.
1396 The command `org-store-link' adds a link pointing to the current
1397 location to an internal list. These links accumulate during a session.
1398 The command `org-insert-link' can be used to insert links into any
1399 Org-mode file (offering completion for all stored links). When this
1400 option is nil, every link which has been inserted once using \\[org-insert-link]
1401 will be removed from the list, to make completing the unused links
1402 more efficient."
1403 :group 'org-link-store
1404 :type 'boolean)
1406 (defgroup org-link-follow nil
1407 "Options concerning following links in Org-mode."
1408 :tag "Org Follow Link"
1409 :group 'org-link)
1411 (defcustom org-link-translation-function nil
1412 "Function to translate links with different syntax to Org syntax.
1413 This can be used to translate links created for example by the Planner
1414 or emacs-wiki packages to Org syntax.
1415 The function must accept two parameters, a TYPE containing the link
1416 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1417 which is everything after the link protocol. It should return a cons
1418 with possibly modified values of type and path.
1419 Org contains a function for this, so if you set this variable to
1420 `org-translate-link-from-planner', you should be able follow many
1421 links created by planner."
1422 :group 'org-link-follow
1423 :type 'function)
1425 (defcustom org-follow-link-hook nil
1426 "Hook that is run after a link has been followed."
1427 :group 'org-link-follow
1428 :type 'hook)
1430 (defcustom org-tab-follows-link nil
1431 "Non-nil means on links TAB will follow the link.
1432 Needs to be set before org.el is loaded.
1433 This really should not be used, it does not make sense, and the
1434 implementation is bad."
1435 :group 'org-link-follow
1436 :type 'boolean)
1438 (defcustom org-return-follows-link nil
1439 "Non-nil means on links RET will follow the link."
1440 :group 'org-link-follow
1441 :type 'boolean)
1443 (defcustom org-mouse-1-follows-link
1444 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1445 "Non-nil means mouse-1 on a link will follow the link.
1446 A longer mouse click will still set point. Does not work on XEmacs.
1447 Needs to be set before org.el is loaded."
1448 :group 'org-link-follow
1449 :type 'boolean)
1451 (defcustom org-mark-ring-length 4
1452 "Number of different positions to be recorded in the ring.
1453 Changing this requires a restart of Emacs to work correctly."
1454 :group 'org-link-follow
1455 :type 'integer)
1457 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1458 "Non-nil means internal links in Org files must exactly match a headline.
1459 When nil, the link search tries to match a phrase will all words
1460 in the search text."
1461 :group 'org-link-follow
1462 :type '(choice
1463 (const :tag "Use fuzy text search" nil)
1464 (const :tag "Match only exact headline" t)
1465 (const :tag "Match extact headline or query to create it"
1466 query-to-create)))
1468 (defcustom org-link-frame-setup
1469 '((vm . vm-visit-folder-other-frame)
1470 (gnus . org-gnus-no-new-news)
1471 (file . find-file-other-window)
1472 (wl . wl-other-frame))
1473 "Setup the frame configuration for following links.
1474 When following a link with Emacs, it may often be useful to display
1475 this link in another window or frame. This variable can be used to
1476 set this up for the different types of links.
1477 For VM, use any of
1478 `vm-visit-folder'
1479 `vm-visit-folder-other-frame'
1480 For Gnus, use any of
1481 `gnus'
1482 `gnus-other-frame'
1483 `org-gnus-no-new-news'
1484 For FILE, use any of
1485 `find-file'
1486 `find-file-other-window'
1487 `find-file-other-frame'
1488 For Wanderlust use any of
1489 `wl'
1490 `wl-other-frame'
1491 For the calendar, use the variable `calendar-setup'.
1492 For BBDB, it is currently only possible to display the matches in
1493 another window."
1494 :group 'org-link-follow
1495 :type '(list
1496 (cons (const vm)
1497 (choice
1498 (const vm-visit-folder)
1499 (const vm-visit-folder-other-window)
1500 (const vm-visit-folder-other-frame)))
1501 (cons (const gnus)
1502 (choice
1503 (const gnus)
1504 (const gnus-other-frame)
1505 (const org-gnus-no-new-news)))
1506 (cons (const file)
1507 (choice
1508 (const find-file)
1509 (const find-file-other-window)
1510 (const find-file-other-frame)))
1511 (cons (const wl)
1512 (choice
1513 (const wl)
1514 (const wl-other-frame)))))
1516 (defcustom org-display-internal-link-with-indirect-buffer nil
1517 "Non-nil means use indirect buffer to display infile links.
1518 Activating internal links (from one location in a file to another location
1519 in the same file) normally just jumps to the location. When the link is
1520 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1521 is displayed in
1522 another window. When this option is set, the other window actually displays
1523 an indirect buffer clone of the current buffer, to avoid any visibility
1524 changes to the current buffer."
1525 :group 'org-link-follow
1526 :type 'boolean)
1528 (defcustom org-open-non-existing-files nil
1529 "Non-nil means `org-open-file' will open non-existing files.
1530 When nil, an error will be generated.
1531 This variable applies only to external applications because they
1532 might choke on non-existing files. If the link is to a file that
1533 will be opened in Emacs, the variable is ignored."
1534 :group 'org-link-follow
1535 :type 'boolean)
1537 (defcustom org-open-directory-means-index-dot-org nil
1538 "Non-nil means a link to a directory really means to index.org.
1539 When nil, following a directory link will run dired or open a finder/explorer
1540 window on that directory."
1541 :group 'org-link-follow
1542 :type 'boolean)
1544 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1545 "Function and arguments to call for following mailto links.
1546 This is a list with the first element being a Lisp function, and the
1547 remaining elements being arguments to the function. In string arguments,
1548 %a will be replaced by the address, and %s will be replaced by the subject
1549 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1550 :group 'org-link-follow
1551 :type '(choice
1552 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1553 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1554 (const :tag "message-mail" (message-mail "%a" "%s"))
1555 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1557 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1558 "Non-nil means ask for confirmation before executing shell links.
1559 Shell links can be dangerous: just think about a link
1561 [[shell:rm -rf ~/*][Google Search]]
1563 This link would show up in your Org-mode document as \"Google Search\",
1564 but really it would remove your entire home directory.
1565 Therefore we advise against setting this variable to nil.
1566 Just change it to `y-or-n-p' if you want to confirm with a
1567 single keystroke rather than having to type \"yes\"."
1568 :group 'org-link-follow
1569 :type '(choice
1570 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1571 (const :tag "with y-or-n (faster)" y-or-n-p)
1572 (const :tag "no confirmation (dangerous)" nil)))
1573 (put 'org-confirm-shell-link-function
1574 'safe-local-variable
1575 '(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1577 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1578 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1579 Elisp links can be dangerous: just think about a link
1581 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1583 This link would show up in your Org-mode document as \"Google Search\",
1584 but really it would remove your entire home directory.
1585 Therefore we advise against setting this variable to nil.
1586 Just change it to `y-or-n-p' if you want to confirm with a
1587 single keystroke rather than having to type \"yes\"."
1588 :group 'org-link-follow
1589 :type '(choice
1590 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1591 (const :tag "with y-or-n (faster)" y-or-n-p)
1592 (const :tag "no confirmation (dangerous)" nil)))
1593 (put 'org-confirm-shell-link-function
1594 'safe-local-variable
1595 '(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1597 (defconst org-file-apps-defaults-gnu
1598 '((remote . emacs)
1599 (system . mailcap)
1600 (t . mailcap))
1601 "Default file applications on a UNIX or GNU/Linux system.
1602 See `org-file-apps'.")
1604 (defconst org-file-apps-defaults-macosx
1605 '((remote . emacs)
1606 (t . "open %s")
1607 (system . "open %s")
1608 ("ps.gz" . "gv %s")
1609 ("eps.gz" . "gv %s")
1610 ("dvi" . "xdvi %s")
1611 ("fig" . "xfig %s"))
1612 "Default file applications on a MacOS X system.
1613 The system \"open\" is known as a default, but we use X11 applications
1614 for some files for which the OS does not have a good default.
1615 See `org-file-apps'.")
1617 (defconst org-file-apps-defaults-windowsnt
1618 (list
1619 '(remote . emacs)
1620 (cons t
1621 (list (if (featurep 'xemacs)
1622 'mswindows-shell-execute
1623 'w32-shell-execute)
1624 "open" 'file))
1625 (cons 'system
1626 (list (if (featurep 'xemacs)
1627 'mswindows-shell-execute
1628 'w32-shell-execute)
1629 "open" 'file)))
1630 "Default file applications on a Windows NT system.
1631 The system \"open\" is used for most files.
1632 See `org-file-apps'.")
1634 (defcustom org-file-apps
1636 (auto-mode . emacs)
1637 ("\\.mm\\'" . default)
1638 ("\\.x?html?\\'" . default)
1639 ("\\.pdf\\'" . default)
1641 "External applications for opening `file:path' items in a document.
1642 Org-mode uses system defaults for different file types, but
1643 you can use this variable to set the application for a given file
1644 extension. The entries in this list are cons cells where the car identifies
1645 files and the cdr the corresponding command. Possible values for the
1646 file identifier are
1647 \"string\" A string as a file identifier can be interpreted in different
1648 ways, depending on its contents:
1650 - Alphanumeric characters only:
1651 Match links with this file extension.
1652 Example: (\"pdf\" . \"evince %s\")
1653 to open PDFs with evince.
1655 - Regular expression: Match links where the
1656 filename matches the regexp. If you want to
1657 use groups here, use shy groups.
1659 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1660 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1661 to open *.html and *.xhtml with firefox.
1663 - Regular expression which contains (non-shy) groups:
1664 Match links where the whole link, including \"::\", and
1665 anything after that, matches the regexp.
1666 In a custom command string, %1, %2, etc. are replaced with
1667 the parts of the link that were matched by the groups.
1668 For backwards compatibility, if a command string is given
1669 that does not use any of the group matches, this case is
1670 handled identically to the second one (i.e. match against
1671 file name only).
1672 In a custom lisp form, you can access the group matches with
1673 (match-string n link).
1675 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1676 to open [[file:document.pdf::5]] with evince at page 5.
1678 `directory' Matches a directory
1679 `remote' Matches a remote file, accessible through tramp or efs.
1680 Remote files most likely should be visited through Emacs
1681 because external applications cannot handle such paths.
1682 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1683 so all files Emacs knows how to handle. Using this with
1684 command `emacs' will open most files in Emacs. Beware that this
1685 will also open html files inside Emacs, unless you add
1686 (\"html\" . default) to the list as well.
1687 t Default for files not matched by any of the other options.
1688 `system' The system command to open files, like `open' on Windows
1689 and Mac OS X, and mailcap under GNU/Linux. This is the command
1690 that will be selected if you call `C-c C-o' with a double
1691 \\[universal-argument] \\[universal-argument] prefix.
1693 Possible values for the command are:
1694 `emacs' The file will be visited by the current Emacs process.
1695 `default' Use the default application for this file type, which is the
1696 association for t in the list, most likely in the system-specific
1697 part.
1698 This can be used to overrule an unwanted setting in the
1699 system-specific variable.
1700 `system' Use the system command for opening files, like \"open\".
1701 This command is specified by the entry whose car is `system'.
1702 Most likely, the system-specific version of this variable
1703 does define this command, but you can overrule/replace it
1704 here.
1705 string A command to be executed by a shell; %s will be replaced
1706 by the path to the file.
1707 sexp A Lisp form which will be evaluated. The file path will
1708 be available in the Lisp variable `file'.
1709 For more examples, see the system specific constants
1710 `org-file-apps-defaults-macosx'
1711 `org-file-apps-defaults-windowsnt'
1712 `org-file-apps-defaults-gnu'."
1713 :group 'org-link-follow
1714 :type '(repeat
1715 (cons (choice :value ""
1716 (string :tag "Extension")
1717 (const :tag "System command to open files" system)
1718 (const :tag "Default for unrecognized files" t)
1719 (const :tag "Remote file" remote)
1720 (const :tag "Links to a directory" directory)
1721 (const :tag "Any files that have Emacs modes"
1722 auto-mode))
1723 (choice :value ""
1724 (const :tag "Visit with Emacs" emacs)
1725 (const :tag "Use default" default)
1726 (const :tag "Use the system command" system)
1727 (string :tag "Command")
1728 (sexp :tag "Lisp form")))))
1732 (defgroup org-refile nil
1733 "Options concerning refiling entries in Org-mode."
1734 :tag "Org Refile"
1735 :group 'org)
1737 (defcustom org-directory "~/org"
1738 "Directory with org files.
1739 This is just a default location to look for Org files. There is no need
1740 at all to put your files into this directory. It is only used in the
1741 following situations:
1743 1. When a remember template specifies a target file that is not an
1744 absolute path. The path will then be interpreted relative to
1745 `org-directory'
1746 2. When a remember note is filed away in an interactive way (when exiting the
1747 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1748 with `org-directory' as the default path."
1749 :group 'org-refile
1750 :group 'org-remember
1751 :type 'directory)
1753 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1754 "Default target for storing notes.
1755 Used as a fall back file for org-remember.el and org-capture.el, for
1756 templates that do not specify a target file."
1757 :group 'org-refile
1758 :group 'org-remember
1759 :type '(choice
1760 (const :tag "Default from remember-data-file" nil)
1761 file))
1763 (defcustom org-goto-interface 'outline
1764 "The default interface to be used for `org-goto'.
1765 Allowed values are:
1766 outline The interface shows an outline of the relevant file
1767 and the correct heading is found by moving through
1768 the outline or by searching with incremental search.
1769 outline-path-completion Headlines in the current buffer are offered via
1770 completion. This is the interface also used by
1771 the refile command."
1772 :group 'org-refile
1773 :type '(choice
1774 (const :tag "Outline" outline)
1775 (const :tag "Outline-path-completion" outline-path-completion)))
1777 (defcustom org-goto-max-level 5
1778 "Maximum target level when running `org-goto' with refile interface."
1779 :group 'org-refile
1780 :type 'integer)
1782 (defcustom org-reverse-note-order nil
1783 "Non-nil means store new notes at the beginning of a file or entry.
1784 When nil, new notes will be filed to the end of a file or entry.
1785 This can also be a list with cons cells of regular expressions that
1786 are matched against file names, and values."
1787 :group 'org-remember
1788 :group 'org-refile
1789 :type '(choice
1790 (const :tag "Reverse always" t)
1791 (const :tag "Reverse never" nil)
1792 (repeat :tag "By file name regexp"
1793 (cons regexp boolean))))
1795 (defcustom org-log-refile nil
1796 "Information to record when a task is refiled.
1798 Possible values are:
1800 nil Don't add anything
1801 time Add a time stamp to the task
1802 note Prompt for a note and add it with template `org-log-note-headings'
1804 This option can also be set with on a per-file-basis with
1806 #+STARTUP: nologrefile
1807 #+STARTUP: logrefile
1808 #+STARTUP: lognoterefile
1810 You can have local logging settings for a subtree by setting the LOGGING
1811 property to one or more of these keywords.
1813 When bulk-refiling from the agenda, the value `note' is forbidden and
1814 will temporarily be changed to `time'."
1815 :group 'org-refile
1816 :group 'org-progress
1817 :type '(choice
1818 (const :tag "No logging" nil)
1819 (const :tag "Record timestamp" time)
1820 (const :tag "Record timestamp with note." note)))
1822 (defcustom org-refile-targets nil
1823 "Targets for refiling entries with \\[org-refile].
1824 This is list of cons cells. Each cell contains:
1825 - a specification of the files to be considered, either a list of files,
1826 or a symbol whose function or variable value will be used to retrieve
1827 a file name or a list of file names. If you use `org-agenda-files' for
1828 that, all agenda files will be scanned for targets. Nil means consider
1829 headings in the current buffer.
1830 - A specification of how to find candidate refile targets. This may be
1831 any of:
1832 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1833 This tag has to be present in all target headlines, inheritance will
1834 not be considered.
1835 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1836 todo keyword.
1837 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1838 headlines that are refiling targets.
1839 - a cons cell (:level . N). Any headline of level N is considered a target.
1840 Note that, when `org-odd-levels-only' is set, level corresponds to
1841 order in hierarchy, not to the number of stars.
1842 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1843 Note that, when `org-odd-levels-only' is set, level corresponds to
1844 order in hierarchy, not to the number of stars.
1846 You can set the variable `org-refile-target-verify-function' to a function
1847 to verify each headline found by the simple criteria above.
1849 When this variable is nil, all top-level headlines in the current buffer
1850 are used, equivalent to the value `((nil . (:level . 1))'."
1851 :group 'org-refile
1852 :type '(repeat
1853 (cons
1854 (choice :value org-agenda-files
1855 (const :tag "All agenda files" org-agenda-files)
1856 (const :tag "Current buffer" nil)
1857 (function) (variable) (file))
1858 (choice :tag "Identify target headline by"
1859 (cons :tag "Specific tag" (const :value :tag) (string))
1860 (cons :tag "TODO keyword" (const :value :todo) (string))
1861 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1862 (cons :tag "Level number" (const :value :level) (integer))
1863 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1865 (defcustom org-refile-target-verify-function nil
1866 "Function to verify if the headline at point should be a refile target.
1867 The function will be called without arguments, with point at the
1868 beginning of the headline. It should return t and leave point
1869 where it is if the headline is a valid target for refiling.
1871 If the target should not be selected, the function must return nil.
1872 In addition to this, it may move point to a place from where the search
1873 should be continued. For example, the function may decide that the entire
1874 subtree of the current entry should be excluded and move point to the end
1875 of the subtree."
1876 :group 'org-refile
1877 :type 'function)
1879 (defcustom org-refile-use-cache nil
1880 "Non-nil means cache refile targets to speed up the process.
1881 The cache for a particular file will be updated automatically when
1882 the buffer has been killed, or when any of the marker used for flagging
1883 refile targets no longer points at a live buffer.
1884 If you have added new entries to a buffer that might themselves be targets,
1885 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1886 find that easier, `C-u C-u C-u C-c C-w'."
1887 :group 'org-refile
1888 :type 'boolean)
1890 (defcustom org-refile-use-outline-path nil
1891 "Non-nil means provide refile targets as paths.
1892 So a level 3 headline will be available as level1/level2/level3.
1894 When the value is `file', also include the file name (without directory)
1895 into the path. In this case, you can also stop the completion after
1896 the file name, to get entries inserted as top level in the file.
1898 When `full-file-path', include the full file path."
1899 :group 'org-refile
1900 :type '(choice
1901 (const :tag "Not" nil)
1902 (const :tag "Yes" t)
1903 (const :tag "Start with file name" file)
1904 (const :tag "Start with full file path" full-file-path)))
1906 (defcustom org-outline-path-complete-in-steps t
1907 "Non-nil means complete the outline path in hierarchical steps.
1908 When Org-mode uses the refile interface to select an outline path
1909 \(see variable `org-refile-use-outline-path'), the completion of
1910 the path can be done is a single go, or if can be done in steps down
1911 the headline hierarchy. Going in steps is probably the best if you
1912 do not use a special completion package like `ido' or `icicles'.
1913 However, when using these packages, going in one step can be very
1914 fast, while still showing the whole path to the entry."
1915 :group 'org-refile
1916 :type 'boolean)
1918 (defcustom org-refile-allow-creating-parent-nodes nil
1919 "Non-nil means allow to create new nodes as refile targets.
1920 New nodes are then created by adding \"/new node name\" to the completion
1921 of an existing node. When the value of this variable is `confirm',
1922 new node creation must be confirmed by the user (recommended)
1923 When nil, the completion must match an existing entry.
1925 Note that, if the new heading is not seen by the criteria
1926 listed in `org-refile-targets', multiple instances of the same
1927 heading would be created by trying again to file under the new
1928 heading."
1929 :group 'org-refile
1930 :type '(choice
1931 (const :tag "Never" nil)
1932 (const :tag "Always" t)
1933 (const :tag "Prompt for confirmation" confirm)))
1935 (defgroup org-todo nil
1936 "Options concerning TODO items in Org-mode."
1937 :tag "Org TODO"
1938 :group 'org)
1940 (defgroup org-progress nil
1941 "Options concerning Progress logging in Org-mode."
1942 :tag "Org Progress"
1943 :group 'org-time)
1945 (defvar org-todo-interpretation-widgets
1947 (:tag "Sequence (cycling hits every state)" sequence)
1948 (:tag "Type (cycling directly to DONE)" type))
1949 "The available interpretation symbols for customizing `org-todo-keywords'.
1950 Interested libraries should add to this list.")
1952 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1953 "List of TODO entry keyword sequences and their interpretation.
1954 \\<org-mode-map>This is a list of sequences.
1956 Each sequence starts with a symbol, either `sequence' or `type',
1957 indicating if the keywords should be interpreted as a sequence of
1958 action steps, or as different types of TODO items. The first
1959 keywords are states requiring action - these states will select a headline
1960 for inclusion into the global TODO list Org-mode produces. If one of
1961 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
1962 signify that no further action is necessary. If \"|\" is not found,
1963 the last keyword is treated as the only DONE state of the sequence.
1965 The command \\[org-todo] cycles an entry through these states, and one
1966 additional state where no keyword is present. For details about this
1967 cycling, see the manual.
1969 TODO keywords and interpretation can also be set on a per-file basis with
1970 the special #+SEQ_TODO and #+TYP_TODO lines.
1972 Each keyword can optionally specify a character for fast state selection
1973 \(in combination with the variable `org-use-fast-todo-selection')
1974 and specifiers for state change logging, using the same syntax
1975 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1976 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1977 indicates to record a time stamp each time this state is selected.
1979 Each keyword may also specify if a timestamp or a note should be
1980 recorded when entering or leaving the state, by adding additional
1981 characters in the parenthesis after the keyword. This looks like this:
1982 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1983 record only the time of the state change. With X and Y being either
1984 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1985 Y when leaving the state if and only if the *target* state does not
1986 define X. You may omit any of the fast-selection key or X or /Y,
1987 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1989 For backward compatibility, this variable may also be just a list
1990 of keywords - in this case the interpretation (sequence or type) will be
1991 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1992 :group 'org-todo
1993 :group 'org-keywords
1994 :type '(choice
1995 (repeat :tag "Old syntax, just keywords"
1996 (string :tag "Keyword"))
1997 (repeat :tag "New syntax"
1998 (cons
1999 (choice
2000 :tag "Interpretation"
2001 ;;Quick and dirty way to see
2002 ;;`org-todo-interpretations'. This takes the
2003 ;;place of item arguments
2004 :convert-widget
2005 (lambda (widget)
2006 (widget-put widget
2007 :args (mapcar
2008 #'(lambda (x)
2009 (widget-convert
2010 (cons 'const x)))
2011 org-todo-interpretation-widgets))
2012 widget))
2013 (repeat
2014 (string :tag "Keyword"))))))
2016 (defvar org-todo-keywords-1 nil
2017 "All TODO and DONE keywords active in a buffer.")
2018 (make-variable-buffer-local 'org-todo-keywords-1)
2019 (defvar org-todo-keywords-for-agenda nil)
2020 (defvar org-done-keywords-for-agenda nil)
2021 (defvar org-drawers-for-agenda nil)
2022 (defvar org-todo-keyword-alist-for-agenda nil)
2023 (defvar org-tag-alist-for-agenda nil)
2024 (defvar org-agenda-contributing-files nil)
2025 (defvar org-not-done-keywords nil)
2026 (make-variable-buffer-local 'org-not-done-keywords)
2027 (defvar org-done-keywords nil)
2028 (make-variable-buffer-local 'org-done-keywords)
2029 (defvar org-todo-heads nil)
2030 (make-variable-buffer-local 'org-todo-heads)
2031 (defvar org-todo-sets nil)
2032 (make-variable-buffer-local 'org-todo-sets)
2033 (defvar org-todo-log-states nil)
2034 (make-variable-buffer-local 'org-todo-log-states)
2035 (defvar org-todo-kwd-alist nil)
2036 (make-variable-buffer-local 'org-todo-kwd-alist)
2037 (defvar org-todo-key-alist nil)
2038 (make-variable-buffer-local 'org-todo-key-alist)
2039 (defvar org-todo-key-trigger nil)
2040 (make-variable-buffer-local 'org-todo-key-trigger)
2042 (defcustom org-todo-interpretation 'sequence
2043 "Controls how TODO keywords are interpreted.
2044 This variable is in principle obsolete and is only used for
2045 backward compatibility, if the interpretation of todo keywords is
2046 not given already in `org-todo-keywords'. See that variable for
2047 more information."
2048 :group 'org-todo
2049 :group 'org-keywords
2050 :type '(choice (const sequence)
2051 (const type)))
2053 (defcustom org-use-fast-todo-selection t
2054 "Non-nil means use the fast todo selection scheme with C-c C-t.
2055 This variable describes if and under what circumstances the cycling
2056 mechanism for TODO keywords will be replaced by a single-key, direct
2057 selection scheme.
2059 When nil, fast selection is never used.
2061 When the symbol `prefix', it will be used when `org-todo' is called with
2062 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2063 in an agenda buffer.
2065 When t, fast selection is used by default. In this case, the prefix
2066 argument forces cycling instead.
2068 In all cases, the special interface is only used if access keys have actually
2069 been assigned by the user, i.e. if keywords in the configuration are followed
2070 by a letter in parenthesis, like TODO(t)."
2071 :group 'org-todo
2072 :type '(choice
2073 (const :tag "Never" nil)
2074 (const :tag "By default" t)
2075 (const :tag "Only with C-u C-c C-t" prefix)))
2077 (defcustom org-provide-todo-statistics t
2078 "Non-nil means update todo statistics after insert and toggle.
2079 ALL-HEADLINES means update todo statistics by including headlines
2080 with no TODO keyword as well, counting them as not done.
2081 A list of TODO keywords means the same, but skip keywords that are
2082 not in this list.
2084 When this is set, todo statistics is updated in the parent of the
2085 current entry each time a todo state is changed."
2086 :group 'org-todo
2087 :type '(choice
2088 (const :tag "Yes, only for TODO entries" t)
2089 (const :tag "Yes, including all entries" 'all-headlines)
2090 (repeat :tag "Yes, for TODOs in this list"
2091 (string :tag "TODO keyword"))
2092 (other :tag "No TODO statistics" nil)))
2094 (defcustom org-hierarchical-todo-statistics t
2095 "Non-nil means TODO statistics covers just direct children.
2096 When nil, all entries in the subtree are considered.
2097 This has only an effect if `org-provide-todo-statistics' is set.
2098 To set this to nil for only a single subtree, use a COOKIE_DATA
2099 property and include the word \"recursive\" into the value."
2100 :group 'org-todo
2101 :type 'boolean)
2103 (defcustom org-after-todo-state-change-hook nil
2104 "Hook which is run after the state of a TODO item was changed.
2105 The new state (a string with a TODO keyword, or nil) is available in the
2106 Lisp variable `state'."
2107 :group 'org-todo
2108 :type 'hook)
2110 (defvar org-blocker-hook nil
2111 "Hook for functions that are allowed to block a state change.
2113 Each function gets as its single argument a property list, see
2114 `org-trigger-hook' for more information about this list.
2116 If any of the functions in this hook returns nil, the state change
2117 is blocked.")
2119 (defvar org-trigger-hook nil
2120 "Hook for functions that are triggered by a state change.
2122 Each function gets as its single argument a property list with at least
2123 the following elements:
2125 (:type type-of-change :position pos-at-entry-start
2126 :from old-state :to new-state)
2128 Depending on the type, more properties may be present.
2130 This mechanism is currently implemented for:
2132 TODO state changes
2133 ------------------
2134 :type todo-state-change
2135 :from previous state (keyword as a string), or nil, or a symbol
2136 'todo' or 'done', to indicate the general type of state.
2137 :to new state, like in :from")
2139 (defcustom org-enforce-todo-dependencies nil
2140 "Non-nil means undone TODO entries will block switching the parent to DONE.
2141 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2142 be blocked if any prior sibling is not yet done.
2143 Finally, if the parent is blocked because of ordered siblings of its own,
2144 the child will also be blocked.
2145 This variable needs to be set before org.el is loaded, and you need to
2146 restart Emacs after a change to make the change effective. The only way
2147 to change is while Emacs is running is through the customize interface."
2148 :set (lambda (var val)
2149 (set var val)
2150 (if val
2151 (add-hook 'org-blocker-hook
2152 'org-block-todo-from-children-or-siblings-or-parent)
2153 (remove-hook 'org-blocker-hook
2154 'org-block-todo-from-children-or-siblings-or-parent)))
2155 :group 'org-todo
2156 :type 'boolean)
2158 (defcustom org-enforce-todo-checkbox-dependencies nil
2159 "Non-nil means unchecked boxes will block switching the parent to DONE.
2160 When this is nil, checkboxes have no influence on switching TODO states.
2161 When non-nil, you first need to check off all check boxes before the TODO
2162 entry can be switched to DONE.
2163 This variable needs to be set before org.el is loaded, and you need to
2164 restart Emacs after a change to make the change effective. The only way
2165 to change is while Emacs is running is through the customize interface."
2166 :set (lambda (var val)
2167 (set var val)
2168 (if val
2169 (add-hook 'org-blocker-hook
2170 'org-block-todo-from-checkboxes)
2171 (remove-hook 'org-blocker-hook
2172 'org-block-todo-from-checkboxes)))
2173 :group 'org-todo
2174 :type 'boolean)
2176 (defcustom org-treat-insert-todo-heading-as-state-change nil
2177 "Non-nil means inserting a TODO heading is treated as state change.
2178 So when the command \\[org-insert-todo-heading] is used, state change
2179 logging will apply if appropriate. When nil, the new TODO item will
2180 be inserted directly, and no logging will take place."
2181 :group 'org-todo
2182 :type 'boolean)
2184 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2185 "Non-nil means switching TODO states with S-cursor counts as state change.
2186 This is the default behavior. However, setting this to nil allows a
2187 convenient way to select a TODO state and bypass any logging associated
2188 with that."
2189 :group 'org-todo
2190 :type 'boolean)
2192 (defcustom org-todo-state-tags-triggers nil
2193 "Tag changes that should be triggered by TODO state changes.
2194 This is a list. Each entry is
2196 (state-change (tag . flag) .......)
2198 State-change can be a string with a state, and empty string to indicate the
2199 state that has no TODO keyword, or it can be one of the symbols `todo'
2200 or `done', meaning any not-done or done state, respectively."
2201 :group 'org-todo
2202 :group 'org-tags
2203 :type '(repeat
2204 (cons (choice :tag "When changing to"
2205 (const :tag "Not-done state" todo)
2206 (const :tag "Done state" done)
2207 (string :tag "State"))
2208 (repeat
2209 (cons :tag "Tag action"
2210 (string :tag "Tag")
2211 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2213 (defcustom org-log-done nil
2214 "Information to record when a task moves to the DONE state.
2216 Possible values are:
2218 nil Don't add anything, just change the keyword
2219 time Add a time stamp to the task
2220 note Prompt for a note and add it with template `org-log-note-headings'
2222 This option can also be set with on a per-file-basis with
2224 #+STARTUP: nologdone
2225 #+STARTUP: logdone
2226 #+STARTUP: lognotedone
2228 You can have local logging settings for a subtree by setting the LOGGING
2229 property to one or more of these keywords."
2230 :group 'org-todo
2231 :group 'org-progress
2232 :type '(choice
2233 (const :tag "No logging" nil)
2234 (const :tag "Record CLOSED timestamp" time)
2235 (const :tag "Record CLOSED timestamp with note." note)))
2237 ;; Normalize old uses of org-log-done.
2238 (cond
2239 ((eq org-log-done t) (setq org-log-done 'time))
2240 ((and (listp org-log-done) (memq 'done org-log-done))
2241 (setq org-log-done 'note)))
2243 (defcustom org-log-reschedule nil
2244 "Information to record when the scheduling date of a tasks is modified.
2246 Possible values are:
2248 nil Don't add anything, just change the date
2249 time Add a time stamp to the task
2250 note Prompt for a note and add it with template `org-log-note-headings'
2252 This option can also be set with on a per-file-basis with
2254 #+STARTUP: nologreschedule
2255 #+STARTUP: logreschedule
2256 #+STARTUP: lognotereschedule"
2257 :group 'org-todo
2258 :group 'org-progress
2259 :type '(choice
2260 (const :tag "No logging" nil)
2261 (const :tag "Record timestamp" time)
2262 (const :tag "Record timestamp with note." note)))
2264 (defcustom org-log-redeadline nil
2265 "Information to record when the deadline date of a tasks is modified.
2267 Possible values are:
2269 nil Don't add anything, just change the date
2270 time Add a time stamp to the task
2271 note Prompt for a note and add it with template `org-log-note-headings'
2273 This option can also be set with on a per-file-basis with
2275 #+STARTUP: nologredeadline
2276 #+STARTUP: logredeadline
2277 #+STARTUP: lognoteredeadline
2279 You can have local logging settings for a subtree by setting the LOGGING
2280 property to one or more of these keywords."
2281 :group 'org-todo
2282 :group 'org-progress
2283 :type '(choice
2284 (const :tag "No logging" nil)
2285 (const :tag "Record timestamp" time)
2286 (const :tag "Record timestamp with note." note)))
2288 (defcustom org-log-note-clock-out nil
2289 "Non-nil means record a note when clocking out of an item.
2290 This can also be configured on a per-file basis by adding one of
2291 the following lines anywhere in the buffer:
2293 #+STARTUP: lognoteclock-out
2294 #+STARTUP: nolognoteclock-out"
2295 :group 'org-todo
2296 :group 'org-progress
2297 :type 'boolean)
2299 (defcustom org-log-done-with-time t
2300 "Non-nil means the CLOSED time stamp will contain date and time.
2301 When nil, only the date will be recorded."
2302 :group 'org-progress
2303 :type 'boolean)
2305 (defcustom org-log-note-headings
2306 '((done . "CLOSING NOTE %t")
2307 (state . "State %-12s from %-12S %t")
2308 (note . "Note taken on %t")
2309 (reschedule . "Rescheduled from %S on %t")
2310 (delschedule . "Not scheduled, was %S on %t")
2311 (redeadline . "New deadline from %S on %t")
2312 (deldeadline . "Removed deadline, was %S on %t")
2313 (refile . "Refiled on %t")
2314 (clock-out . ""))
2315 "Headings for notes added to entries.
2316 The value is an alist, with the car being a symbol indicating the note
2317 context, and the cdr is the heading to be used. The heading may also be the
2318 empty string.
2319 %t in the heading will be replaced by a time stamp.
2320 %T will be an active time stamp instead the default inactive one
2321 %s will be replaced by the new TODO state, in double quotes.
2322 %S will be replaced by the old TODO state, in double quotes.
2323 %u will be replaced by the user name.
2324 %U will be replaced by the full user name.
2326 In fact, it is not a good idea to change the `state' entry, because
2327 agenda log mode depends on the format of these entries."
2328 :group 'org-todo
2329 :group 'org-progress
2330 :type '(list :greedy t
2331 (cons (const :tag "Heading when closing an item" done) string)
2332 (cons (const :tag
2333 "Heading when changing todo state (todo sequence only)"
2334 state) string)
2335 (cons (const :tag "Heading when just taking a note" note) string)
2336 (cons (const :tag "Heading when clocking out" clock-out) string)
2337 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2338 (cons (const :tag "Heading when rescheduling" reschedule) string)
2339 (cons (const :tag "Heading when changing deadline" redeadline) string)
2340 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2341 (cons (const :tag "Heading when refiling" refile) string)))
2343 (unless (assq 'note org-log-note-headings)
2344 (push '(note . "%t") org-log-note-headings))
2346 (defcustom org-log-into-drawer nil
2347 "Non-nil means insert state change notes and time stamps into a drawer.
2348 When nil, state changes notes will be inserted after the headline and
2349 any scheduling and clock lines, but not inside a drawer.
2351 The value of this variable should be the name of the drawer to use.
2352 LOGBOOK is proposed at the default drawer for this purpose, you can
2353 also set this to a string to define the drawer of your choice.
2355 A value of t is also allowed, representing \"LOGBOOK\".
2357 If this variable is set, `org-log-state-notes-insert-after-drawers'
2358 will be ignored.
2360 You can set the property LOG_INTO_DRAWER to overrule this setting for
2361 a subtree."
2362 :group 'org-todo
2363 :group 'org-progress
2364 :type '(choice
2365 (const :tag "Not into a drawer" nil)
2366 (const :tag "LOGBOOK" t)
2367 (string :tag "Other")))
2369 (if (fboundp 'defvaralias)
2370 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2372 (defun org-log-into-drawer ()
2373 "Return the value of `org-log-into-drawer', but let properties overrule.
2374 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2375 used instead of the default value."
2376 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2377 (cond
2378 ((or (not p) (equal p "nil")) org-log-into-drawer)
2379 ((equal p "t") "LOGBOOK")
2380 (t p))))
2382 (defcustom org-log-state-notes-insert-after-drawers nil
2383 "Non-nil means insert state change notes after any drawers in entry.
2384 Only the drawers that *immediately* follow the headline and the
2385 deadline/scheduled line are skipped.
2386 When nil, insert notes right after the heading and perhaps the line
2387 with deadline/scheduling if present.
2389 This variable will have no effect if `org-log-into-drawer' is
2390 set."
2391 :group 'org-todo
2392 :group 'org-progress
2393 :type 'boolean)
2395 (defcustom org-log-states-order-reversed t
2396 "Non-nil means the latest state note will be directly after heading.
2397 When nil, the state change notes will be ordered according to time."
2398 :group 'org-todo
2399 :group 'org-progress
2400 :type 'boolean)
2402 (defcustom org-todo-repeat-to-state nil
2403 "The TODO state to which a repeater should return the repeating task.
2404 By default this is the first task in a TODO sequence, or the previous state
2405 in a TODO_TYP set. But you can specify another task here.
2406 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2407 :group 'org-todo
2408 :type '(choice (const :tag "Head of sequence" nil)
2409 (string :tag "Specific state")))
2411 (defcustom org-log-repeat 'time
2412 "Non-nil means record moving through the DONE state when triggering repeat.
2413 An auto-repeating task is immediately switched back to TODO when
2414 marked DONE. If you are not logging state changes (by adding \"@\"
2415 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2416 record a closing note, there will be no record of the task moving
2417 through DONE. This variable forces taking a note anyway.
2419 nil Don't force a record
2420 time Record a time stamp
2421 note Record a note
2423 This option can also be set with on a per-file-basis with
2425 #+STARTUP: logrepeat
2426 #+STARTUP: lognoterepeat
2427 #+STARTUP: nologrepeat
2429 You can have local logging settings for a subtree by setting the LOGGING
2430 property to one or more of these keywords."
2431 :group 'org-todo
2432 :group 'org-progress
2433 :type '(choice
2434 (const :tag "Don't force a record" nil)
2435 (const :tag "Force recording the DONE state" time)
2436 (const :tag "Force recording a note with the DONE state" note)))
2439 (defgroup org-priorities nil
2440 "Priorities in Org-mode."
2441 :tag "Org Priorities"
2442 :group 'org-todo)
2444 (defcustom org-enable-priority-commands t
2445 "Non-nil means priority commands are active.
2446 When nil, these commands will be disabled, so that you never accidentally
2447 set a priority."
2448 :group 'org-priorities
2449 :type 'boolean)
2451 (defcustom org-highest-priority ?A
2452 "The highest priority of TODO items. A character like ?A, ?B etc.
2453 Must have a smaller ASCII number than `org-lowest-priority'."
2454 :group 'org-priorities
2455 :type 'character)
2457 (defcustom org-lowest-priority ?C
2458 "The lowest priority of TODO items. A character like ?A, ?B etc.
2459 Must have a larger ASCII number than `org-highest-priority'."
2460 :group 'org-priorities
2461 :type 'character)
2463 (defcustom org-default-priority ?B
2464 "The default priority of TODO items.
2465 This is the priority an item get if no explicit priority is given."
2466 :group 'org-priorities
2467 :type 'character)
2469 (defcustom org-priority-start-cycle-with-default t
2470 "Non-nil means start with default priority when starting to cycle.
2471 When this is nil, the first step in the cycle will be (depending on the
2472 command used) one higher or lower that the default priority."
2473 :group 'org-priorities
2474 :type 'boolean)
2476 (defcustom org-get-priority-function nil
2477 "Function to extract the priority from a string.
2478 The string is normally the headline. If this is nil Org computes the
2479 priority from the priority cookie like [#A] in the headline. It returns
2480 an integer, increasing by 1000 for each priority level.
2481 The user can set a different function here, which should take a string
2482 as an argument and return the numeric priority."
2483 :group 'org-priorities
2484 :type 'function)
2486 (defgroup org-time nil
2487 "Options concerning time stamps and deadlines in Org-mode."
2488 :tag "Org Time"
2489 :group 'org)
2491 (defcustom org-insert-labeled-timestamps-at-point nil
2492 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2493 When nil, these labeled time stamps are forces into the second line of an
2494 entry, just after the headline. When scheduling from the global TODO list,
2495 the time stamp will always be forced into the second line."
2496 :group 'org-time
2497 :type 'boolean)
2499 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2500 "Formats for `format-time-string' which are used for time stamps.
2501 It is not recommended to change this constant.")
2503 (defcustom org-time-stamp-rounding-minutes '(0 5)
2504 "Number of minutes to round time stamps to.
2505 These are two values, the first applies when first creating a time stamp.
2506 The second applies when changing it with the commands `S-up' and `S-down'.
2507 When changing the time stamp, this means that it will change in steps
2508 of N minutes, as given by the second value.
2510 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2511 numbers should be factors of 60, so for example 5, 10, 15.
2513 When this is larger than 1, you can still force an exact time stamp by using
2514 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2515 and by using a prefix arg to `S-up/down' to specify the exact number
2516 of minutes to shift."
2517 :group 'org-time
2518 :get '(lambda (var) ; Make sure both elements are there
2519 (if (integerp (default-value var))
2520 (list (default-value var) 5)
2521 (default-value var)))
2522 :type '(list
2523 (integer :tag "when inserting times")
2524 (integer :tag "when modifying times")))
2526 ;; Normalize old customizations of this variable.
2527 (when (integerp org-time-stamp-rounding-minutes)
2528 (setq org-time-stamp-rounding-minutes
2529 (list org-time-stamp-rounding-minutes
2530 org-time-stamp-rounding-minutes)))
2532 (defcustom org-display-custom-times nil
2533 "Non-nil means overlay custom formats over all time stamps.
2534 The formats are defined through the variable `org-time-stamp-custom-formats'.
2535 To turn this on on a per-file basis, insert anywhere in the file:
2536 #+STARTUP: customtime"
2537 :group 'org-time
2538 :set 'set-default
2539 :type 'sexp)
2540 (make-variable-buffer-local 'org-display-custom-times)
2542 (defcustom org-time-stamp-custom-formats
2543 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2544 "Custom formats for time stamps. See `format-time-string' for the syntax.
2545 These are overlayed over the default ISO format if the variable
2546 `org-display-custom-times' is set. Time like %H:%M should be at the
2547 end of the second format. The custom formats are also honored by export
2548 commands, if custom time display is turned on at the time of export."
2549 :group 'org-time
2550 :type 'sexp)
2552 (defun org-time-stamp-format (&optional long inactive)
2553 "Get the right format for a time string."
2554 (let ((f (if long (cdr org-time-stamp-formats)
2555 (car org-time-stamp-formats))))
2556 (if inactive
2557 (concat "[" (substring f 1 -1) "]")
2558 f)))
2560 (defcustom org-time-clocksum-format "%d:%02d"
2561 "The format string used when creating CLOCKSUM lines.
2562 This is also used when org-mode generates a time duration."
2563 :group 'org-time
2564 :type 'string)
2566 (defcustom org-time-clocksum-use-fractional nil
2567 "If non-nil, \\[org-clock-display] uses fractional times.
2568 org-mode generates a time duration."
2569 :group 'org-time
2570 :type 'boolean)
2572 (defcustom org-time-clocksum-fractional-format "%.2f"
2573 "The format string used when creating CLOCKSUM lines, or when
2574 org-mode generates a time duration."
2575 :group 'org-time
2576 :type 'string)
2578 (defcustom org-deadline-warning-days 14
2579 "No. of days before expiration during which a deadline becomes active.
2580 This variable governs the display in sparse trees and in the agenda.
2581 When 0 or negative, it means use this number (the absolute value of it)
2582 even if a deadline has a different individual lead time specified.
2584 Custom commands can set this variable in the options section."
2585 :group 'org-time
2586 :group 'org-agenda-daily/weekly
2587 :type 'integer)
2589 (defcustom org-read-date-prefer-future t
2590 "Non-nil means assume future for incomplete date input from user.
2591 This affects the following situations:
2592 1. The user gives a month but not a year.
2593 For example, if it is April and you enter \"feb 2\", this will be read
2594 as Feb 2, *next* year. \"May 5\", however, will be this year.
2595 2. The user gives a day, but no month.
2596 For example, if today is the 15th, and you enter \"3\", Org-mode will
2597 read this as the third of *next* month. However, if you enter \"17\",
2598 it will be considered as *this* month.
2600 If you set this variable to the symbol `time', then also the following
2601 will work:
2603 3. If the user gives a time, but no day. If the time is before now,
2604 to will be interpreted as tomorrow.
2606 Currently none of this works for ISO week specifications.
2608 When this option is nil, the current day, month and year will always be
2609 used as defaults.
2611 See also `org-agenda-jump-prefer-future'."
2612 :group 'org-time
2613 :type '(choice
2614 (const :tag "Never" nil)
2615 (const :tag "Check month and day" t)
2616 (const :tag "Check month, day, and time" time)))
2618 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2619 "Should the agenda jump command prefer the future for incomplete dates?
2620 The default is to do the same as configured in `org-read-date-prefer-future'.
2621 But you can alse set a deviating value here.
2622 This may t or nil, or the symbol `org-read-date-prefer-future'."
2623 :group 'org-agenda
2624 :group 'org-time
2625 :type '(choice
2626 (const :tag "Use org-aread-date-prefer-future"
2627 org-read-date-prefer-future)
2628 (const :tag "Never" nil)
2629 (const :tag "Always" t)))
2631 (defcustom org-read-date-display-live t
2632 "Non-nil means display current interpretation of date prompt live.
2633 This display will be in an overlay, in the minibuffer."
2634 :group 'org-time
2635 :type 'boolean)
2637 (defcustom org-read-date-popup-calendar t
2638 "Non-nil means pop up a calendar when prompting for a date.
2639 In the calendar, the date can be selected with mouse-1. However, the
2640 minibuffer will also be active, and you can simply enter the date as well.
2641 When nil, only the minibuffer will be available."
2642 :group 'org-time
2643 :type 'boolean)
2644 (if (fboundp 'defvaralias)
2645 (defvaralias 'org-popup-calendar-for-date-prompt
2646 'org-read-date-popup-calendar))
2648 (defcustom org-read-date-minibuffer-setup-hook nil
2649 "Hook to be used to set up keys for the date/time interface.
2650 Add key definitions to `minibuffer-local-map', which will be a temporary
2651 copy."
2652 :group 'org-time
2653 :type 'hook)
2655 (defcustom org-extend-today-until 0
2656 "The hour when your day really ends. Must be an integer.
2657 This has influence for the following applications:
2658 - When switching the agenda to \"today\". It it is still earlier than
2659 the time given here, the day recognized as TODAY is actually yesterday.
2660 - When a date is read from the user and it is still before the time given
2661 here, the current date and time will be assumed to be yesterday, 23:59.
2662 Also, timestamps inserted in remember templates follow this rule.
2664 IMPORTANT: This is a feature whose implementation is and likely will
2665 remain incomplete. Really, it is only here because past midnight seems to
2666 be the favorite working time of John Wiegley :-)"
2667 :group 'org-time
2668 :type 'integer)
2670 (defcustom org-edit-timestamp-down-means-later nil
2671 "Non-nil means S-down will increase the time in a time stamp.
2672 When nil, S-up will increase."
2673 :group 'org-time
2674 :type 'boolean)
2676 (defcustom org-calendar-follow-timestamp-change t
2677 "Non-nil means make the calendar window follow timestamp changes.
2678 When a timestamp is modified and the calendar window is visible, it will be
2679 moved to the new date."
2680 :group 'org-time
2681 :type 'boolean)
2683 (defgroup org-tags nil
2684 "Options concerning tags in Org-mode."
2685 :tag "Org Tags"
2686 :group 'org)
2688 (defcustom org-tag-alist nil
2689 "List of tags allowed in Org-mode files.
2690 When this list is nil, Org-mode will base TAG input on what is already in the
2691 buffer.
2692 The value of this variable is an alist, the car of each entry must be a
2693 keyword as a string, the cdr may be a character that is used to select
2694 that tag through the fast-tag-selection interface.
2695 See the manual for details."
2696 :group 'org-tags
2697 :type '(repeat
2698 (choice
2699 (cons (string :tag "Tag name")
2700 (character :tag "Access char"))
2701 (list :tag "Start radio group"
2702 (const :startgroup)
2703 (option (string :tag "Group description")))
2704 (list :tag "End radio group"
2705 (const :endgroup)
2706 (option (string :tag "Group description")))
2707 (const :tag "New line" (:newline)))))
2709 (defcustom org-tag-persistent-alist nil
2710 "List of tags that will always appear in all Org-mode files.
2711 This is in addition to any in buffer settings or customizations
2712 of `org-tag-alist'.
2713 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2714 The value of this variable is an alist, the car of each entry must be a
2715 keyword as a string, the cdr may be a character that is used to select
2716 that tag through the fast-tag-selection interface.
2717 See the manual for details.
2718 To disable these tags on a per-file basis, insert anywhere in the file:
2719 #+STARTUP: noptag"
2720 :group 'org-tags
2721 :type '(repeat
2722 (choice
2723 (cons (string :tag "Tag name")
2724 (character :tag "Access char"))
2725 (const :tag "Start radio group" (:startgroup))
2726 (const :tag "End radio group" (:endgroup))
2727 (const :tag "New line" (:newline)))))
2729 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2730 "If non-nil, always offer completion for all tags of all agenda files.
2731 Instead of customizing this variable directly, you might want to
2732 set it locally for remember buffers, because there no list of
2733 tags in that file can be created dynamically (there are none).
2735 (add-hook 'org-remember-mode-hook
2736 (lambda ()
2737 (set (make-local-variable
2738 'org-complete-tags-always-offer-all-agenda-tags)
2739 t)))"
2740 :group 'org-tags
2741 :type 'boolean)
2743 (defvar org-file-tags nil
2744 "List of tags that can be inherited by all entries in the file.
2745 The tags will be inherited if the variable `org-use-tag-inheritance'
2746 says they should be.
2747 This variable is populated from #+FILETAGS lines.")
2749 (defcustom org-use-fast-tag-selection 'auto
2750 "Non-nil means use fast tag selection scheme.
2751 This is a special interface to select and deselect tags with single keys.
2752 When nil, fast selection is never used.
2753 When the symbol `auto', fast selection is used if and only if selection
2754 characters for tags have been configured, either through the variable
2755 `org-tag-alist' or through a #+TAGS line in the buffer.
2756 When t, fast selection is always used and selection keys are assigned
2757 automatically if necessary."
2758 :group 'org-tags
2759 :type '(choice
2760 (const :tag "Always" t)
2761 (const :tag "Never" nil)
2762 (const :tag "When selection characters are configured" 'auto)))
2764 (defcustom org-fast-tag-selection-single-key nil
2765 "Non-nil means fast tag selection exits after first change.
2766 When nil, you have to press RET to exit it.
2767 During fast tag selection, you can toggle this flag with `C-c'.
2768 This variable can also have the value `expert'. In this case, the window
2769 displaying the tags menu is not even shown, until you press C-c again."
2770 :group 'org-tags
2771 :type '(choice
2772 (const :tag "No" nil)
2773 (const :tag "Yes" t)
2774 (const :tag "Expert" expert)))
2776 (defvar org-fast-tag-selection-include-todo nil
2777 "Non-nil means fast tags selection interface will also offer TODO states.
2778 This is an undocumented feature, you should not rely on it.")
2780 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2781 "The column to which tags should be indented in a headline.
2782 If this number is positive, it specifies the column. If it is negative,
2783 it means that the tags should be flushright to that column. For example,
2784 -80 works well for a normal 80 character screen."
2785 :group 'org-tags
2786 :type 'integer)
2788 (defcustom org-auto-align-tags t
2789 "Non-nil means realign tags after pro/demotion of TODO state change.
2790 These operations change the length of a headline and therefore shift
2791 the tags around. With this options turned on, after each such operation
2792 the tags are again aligned to `org-tags-column'."
2793 :group 'org-tags
2794 :type 'boolean)
2796 (defcustom org-use-tag-inheritance t
2797 "Non-nil means tags in levels apply also for sublevels.
2798 When nil, only the tags directly given in a specific line apply there.
2799 This may also be a list of tags that should be inherited, or a regexp that
2800 matches tags that should be inherited. Additional control is possible
2801 with the variable `org-tags-exclude-from-inheritance' which gives an
2802 explicit list of tags to be excluded from inheritance., even if the value of
2803 `org-use-tag-inheritance' would select it for inheritance.
2805 If this option is t, a match early-on in a tree can lead to a large
2806 number of matches in the subtree when constructing the agenda or creating
2807 a sparse tree. If you only want to see the first match in a tree during
2808 a search, check out the variable `org-tags-match-list-sublevels'."
2809 :group 'org-tags
2810 :type '(choice
2811 (const :tag "Not" nil)
2812 (const :tag "Always" t)
2813 (repeat :tag "Specific tags" (string :tag "Tag"))
2814 (regexp :tag "Tags matched by regexp")))
2816 (defcustom org-tags-exclude-from-inheritance nil
2817 "List of tags that should never be inherited.
2818 This is a way to exclude a few tags from inheritance. For way to do
2819 the opposite, to actively allow inheritance for selected tags,
2820 see the variable `org-use-tag-inheritance'."
2821 :group 'org-tags
2822 :type '(repeat (string :tag "Tag")))
2824 (defun org-tag-inherit-p (tag)
2825 "Check if TAG is one that should be inherited."
2826 (cond
2827 ((member tag org-tags-exclude-from-inheritance) nil)
2828 ((eq org-use-tag-inheritance t) t)
2829 ((not org-use-tag-inheritance) nil)
2830 ((stringp org-use-tag-inheritance)
2831 (string-match org-use-tag-inheritance tag))
2832 ((listp org-use-tag-inheritance)
2833 (member tag org-use-tag-inheritance))
2834 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2836 (defcustom org-tags-match-list-sublevels t
2837 "Non-nil means list also sublevels of headlines matching a search.
2838 This variable applies to tags/property searches, and also to stuck
2839 projects because this search is based on a tags match as well.
2841 When set to the symbol `indented', sublevels are indented with
2842 leading dots.
2844 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2845 the sublevels of a headline matching a tag search often also match
2846 the same search. Listing all of them can create very long lists.
2847 Setting this variable to nil causes subtrees of a match to be skipped.
2849 This variable is semi-obsolete and probably should always be true. It
2850 is better to limit inheritance to certain tags using the variables
2851 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2852 :group 'org-tags
2853 :type '(choice
2854 (const :tag "No, don't list them" nil)
2855 (const :tag "Yes, do list them" t)
2856 (const :tag "List them, indented with leading dots" indented)))
2858 (defcustom org-tags-sort-function nil
2859 "When set, tags are sorted using this function as a comparator."
2860 :group 'org-tags
2861 :type '(choice
2862 (const :tag "No sorting" nil)
2863 (const :tag "Alphabetical" string<)
2864 (const :tag "Reverse alphabetical" string>)
2865 (function :tag "Custom function" nil)))
2867 (defvar org-tags-history nil
2868 "History of minibuffer reads for tags.")
2869 (defvar org-last-tags-completion-table nil
2870 "The last used completion table for tags.")
2871 (defvar org-after-tags-change-hook nil
2872 "Hook that is run after the tags in a line have changed.")
2874 (defgroup org-properties nil
2875 "Options concerning properties in Org-mode."
2876 :tag "Org Properties"
2877 :group 'org)
2879 (defcustom org-property-format "%-10s %s"
2880 "How property key/value pairs should be formatted by `indent-line'.
2881 When `indent-line' hits a property definition, it will format the line
2882 according to this format, mainly to make sure that the values are
2883 lined-up with respect to each other."
2884 :group 'org-properties
2885 :type 'string)
2887 (defcustom org-use-property-inheritance nil
2888 "Non-nil means properties apply also for sublevels.
2890 This setting is chiefly used during property searches. Turning it on can
2891 cause significant overhead when doing a search, which is why it is not
2892 on by default.
2894 When nil, only the properties directly given in the current entry count.
2895 When t, every property is inherited. The value may also be a list of
2896 properties that should have inheritance, or a regular expression matching
2897 properties that should be inherited.
2899 However, note that some special properties use inheritance under special
2900 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2901 and the properties ending in \"_ALL\" when they are used as descriptor
2902 for valid values of a property.
2904 Note for programmers:
2905 When querying an entry with `org-entry-get', you can control if inheritance
2906 should be used. By default, `org-entry-get' looks only at the local
2907 properties. You can request inheritance by setting the inherit argument
2908 to t (to force inheritance) or to `selective' (to respect the setting
2909 in this variable)."
2910 :group 'org-properties
2911 :type '(choice
2912 (const :tag "Not" nil)
2913 (const :tag "Always" t)
2914 (repeat :tag "Specific properties" (string :tag "Property"))
2915 (regexp :tag "Properties matched by regexp")))
2917 (defun org-property-inherit-p (property)
2918 "Check if PROPERTY is one that should be inherited."
2919 (cond
2920 ((eq org-use-property-inheritance t) t)
2921 ((not org-use-property-inheritance) nil)
2922 ((stringp org-use-property-inheritance)
2923 (string-match org-use-property-inheritance property))
2924 ((listp org-use-property-inheritance)
2925 (member property org-use-property-inheritance))
2926 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2928 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2929 "The default column format, if no other format has been defined.
2930 This variable can be set on the per-file basis by inserting a line
2932 #+COLUMNS: %25ITEM ....."
2933 :group 'org-properties
2934 :type 'string)
2936 (defcustom org-columns-ellipses ".."
2937 "The ellipses to be used when a field in column view is truncated.
2938 When this is the empty string, as many characters as possible are shown,
2939 but then there will be no visual indication that the field has been truncated.
2940 When this is a string of length N, the last N characters of a truncated
2941 field are replaced by this string. If the column is narrower than the
2942 ellipses string, only part of the ellipses string will be shown."
2943 :group 'org-properties
2944 :type 'string)
2946 (defcustom org-columns-modify-value-for-display-function nil
2947 "Function that modifies values for display in column view.
2948 For example, it can be used to cut out a certain part from a time stamp.
2949 The function must take 2 arguments:
2951 column-title The title of the column (*not* the property name)
2952 value The value that should be modified.
2954 The function should return the value that should be displayed,
2955 or nil if the normal value should be used."
2956 :group 'org-properties
2957 :type 'function)
2959 (defcustom org-effort-property "Effort"
2960 "The property that is being used to keep track of effort estimates.
2961 Effort estimates given in this property need to have the format H:MM."
2962 :group 'org-properties
2963 :group 'org-progress
2964 :type '(string :tag "Property"))
2966 (defconst org-global-properties-fixed
2967 '(("VISIBILITY_ALL" . "folded children content all")
2968 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2969 "List of property/value pairs that can be inherited by any entry.
2971 These are fixed values, for the preset properties. The user variable
2972 that can be used to add to this list is `org-global-properties'.
2974 The entries in this list are cons cells where the car is a property
2975 name and cdr is a string with the value. If the value represents
2976 multiple items like an \"_ALL\" property, separate the items by
2977 spaces.")
2979 (defcustom org-global-properties nil
2980 "List of property/value pairs that can be inherited by any entry.
2982 This list will be combined with the constant `org-global-properties-fixed'.
2984 The entries in this list are cons cells where the car is a property
2985 name and cdr is a string with the value.
2987 You can set buffer-local values for the same purpose in the variable
2988 `org-file-properties' this by adding lines like
2990 #+PROPERTY: NAME VALUE"
2991 :group 'org-properties
2992 :type '(repeat
2993 (cons (string :tag "Property")
2994 (string :tag "Value"))))
2996 (defvar org-file-properties nil
2997 "List of property/value pairs that can be inherited by any entry.
2998 Valid for the current buffer.
2999 This variable is populated from #+PROPERTY lines.")
3000 (make-variable-buffer-local 'org-file-properties)
3002 (defgroup org-agenda nil
3003 "Options concerning agenda views in Org-mode."
3004 :tag "Org Agenda"
3005 :group 'org)
3007 (defvar org-category nil
3008 "Variable used by org files to set a category for agenda display.
3009 Such files should use a file variable to set it, for example
3011 # -*- mode: org; org-category: \"ELisp\"
3013 or contain a special line
3015 #+CATEGORY: ELisp
3017 If the file does not specify a category, then file's base name
3018 is used instead.")
3019 (make-variable-buffer-local 'org-category)
3020 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
3022 (defcustom org-agenda-files nil
3023 "The files to be used for agenda display.
3024 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3025 \\[org-remove-file]. You can also use customize to edit the list.
3027 If an entry is a directory, all files in that directory that are matched by
3028 `org-agenda-file-regexp' will be part of the file list.
3030 If the value of the variable is not a list but a single file name, then
3031 the list of agenda files is actually stored and maintained in that file, one
3032 agenda file per line. In this file paths can be given relative to
3033 `org-directory'. Tilde expansion and environment variable substitution
3034 are also made."
3035 :group 'org-agenda
3036 :type '(choice
3037 (repeat :tag "List of files and directories" file)
3038 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3040 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3041 "Regular expression to match files for `org-agenda-files'.
3042 If any element in the list in that variable contains a directory instead
3043 of a normal file, all files in that directory that are matched by this
3044 regular expression will be included."
3045 :group 'org-agenda
3046 :type 'regexp)
3048 (defcustom org-agenda-text-search-extra-files nil
3049 "List of extra files to be searched by text search commands.
3050 These files will be search in addition to the agenda files by the
3051 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3052 Note that these files will only be searched for text search commands,
3053 not for the other agenda views like todo lists, tag searches or the weekly
3054 agenda. This variable is intended to list notes and possibly archive files
3055 that should also be searched by these two commands.
3056 In fact, if the first element in the list is the symbol `agenda-archives',
3057 than all archive files of all agenda files will be added to the search
3058 scope."
3059 :group 'org-agenda
3060 :type '(set :greedy t
3061 (const :tag "Agenda Archives" agenda-archives)
3062 (repeat :inline t (file))))
3064 (if (fboundp 'defvaralias)
3065 (defvaralias 'org-agenda-multi-occur-extra-files
3066 'org-agenda-text-search-extra-files))
3068 (defcustom org-agenda-skip-unavailable-files nil
3069 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3070 A nil value means to remove them, after a query, from the list."
3071 :group 'org-agenda
3072 :type 'boolean)
3074 (defcustom org-calendar-to-agenda-key [?c]
3075 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3076 The command `org-calendar-goto-agenda' will be bound to this key. The
3077 default is the character `c' because then `c' can be used to switch back and
3078 forth between agenda and calendar."
3079 :group 'org-agenda
3080 :type 'sexp)
3082 (defcustom org-calendar-agenda-action-key [?k]
3083 "The key to be installed in `calendar-mode-map' for agenda-action.
3084 The command `org-agenda-action' will be bound to this key. The
3085 default is the character `k' because we use the same key in the agenda."
3086 :group 'org-agenda
3087 :type 'sexp)
3089 (defcustom org-calendar-insert-diary-entry-key [?i]
3090 "The key to be installed in `calendar-mode-map' for adding diary entries.
3091 This option is irrelevant until `org-agenda-diary-file' has been configured
3092 to point to an Org-mode file. When that is the case, the command
3093 `org-agenda-diary-entry' will be bound to the key given here, by default
3094 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3095 if you want to continue doing this, you need to change this to a different
3096 key."
3097 :group 'org-agenda
3098 :type 'sexp)
3100 (defcustom org-agenda-diary-file 'diary-file
3101 "File to which to add new entries with the `i' key in agenda and calendar.
3102 When this is the symbol `diary-file', the functionality in the Emacs
3103 calendar will be used to add entries to the `diary-file'. But when this
3104 points to a file, `org-agenda-diary-entry' will be used instead."
3105 :group 'org-agenda
3106 :type '(choice
3107 (const :tag "The standard Emacs diary file" diary-file)
3108 (file :tag "Special Org file diary entries")))
3110 (eval-after-load "calendar"
3111 '(progn
3112 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3113 'org-calendar-goto-agenda)
3114 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3115 'org-agenda-action)
3116 (add-hook 'calendar-mode-hook
3117 (lambda ()
3118 (unless (eq org-agenda-diary-file 'diary-file)
3119 (define-key calendar-mode-map
3120 org-calendar-insert-diary-entry-key
3121 'org-agenda-diary-entry))))))
3123 (defgroup org-latex nil
3124 "Options for embedding LaTeX code into Org-mode."
3125 :tag "Org LaTeX"
3126 :group 'org)
3128 (defcustom org-format-latex-options
3129 '(:foreground default :background default :scale 1.0
3130 :html-foreground "Black" :html-background "Transparent"
3131 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3132 "Options for creating images from LaTeX fragments.
3133 This is a property list with the following properties:
3134 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3135 `default' means use the foreground of the default face.
3136 :background the background color, or \"Transparent\".
3137 `default' means use the background of the default face.
3138 :scale a scaling factor for the size of the images, to get more pixels
3139 :html-foreground, :html-background, :html-scale
3140 the same numbers for HTML export.
3141 :matchers a list indicating which matchers should be used to
3142 find LaTeX fragments. Valid members of this list are:
3143 \"begin\" find environments
3144 \"$1\" find single characters surrounded by $.$
3145 \"$\" find math expressions surrounded by $...$
3146 \"$$\" find math expressions surrounded by $$....$$
3147 \"\\(\" find math expressions surrounded by \\(...\\)
3148 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3149 :group 'org-latex
3150 :type 'plist)
3152 (defcustom org-format-latex-signal-error t
3153 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3154 When nil, just push out a message."
3155 :group 'org-latex
3156 :type 'boolean)
3158 (defcustom org-format-latex-header "\\documentclass{article}
3159 \\usepackage[usenames]{color}
3160 \\usepackage{amsmath}
3161 \\usepackage[mathscr]{eucal}
3162 \\pagestyle{empty} % do not remove
3163 \[PACKAGES]
3164 \[DEFAULT-PACKAGES]
3165 % The settings below are copied from fullpage.sty
3166 \\setlength{\\textwidth}{\\paperwidth}
3167 \\addtolength{\\textwidth}{-3cm}
3168 \\setlength{\\oddsidemargin}{1.5cm}
3169 \\addtolength{\\oddsidemargin}{-2.54cm}
3170 \\setlength{\\evensidemargin}{\\oddsidemargin}
3171 \\setlength{\\textheight}{\\paperheight}
3172 \\addtolength{\\textheight}{-\\headheight}
3173 \\addtolength{\\textheight}{-\\headsep}
3174 \\addtolength{\\textheight}{-\\footskip}
3175 \\addtolength{\\textheight}{-3cm}
3176 \\setlength{\\topmargin}{1.5cm}
3177 \\addtolength{\\topmargin}{-2.54cm}"
3178 "The document header used for processing LaTeX fragments.
3179 It is imperative that this header make sure that no page number
3180 appears on the page. The package defined in the variables
3181 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3182 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3183 will be appended."
3184 :group 'org-latex
3185 :type 'string)
3187 (defvar org-format-latex-header-extra nil)
3189 (defun org-set-packages-alist (var val)
3190 "Set the packages alist and make sure it has 3 elements per entry."
3191 (set var (mapcar (lambda (x)
3192 (if (and (consp x) (= (length x) 2))
3193 (list (car x) (nth 1 x) t)
3195 val)))
3197 (defun org-get-packages-alist (var)
3199 "Get the packages alist and make sure it has 3 elements per entry."
3200 (mapcar (lambda (x)
3201 (if (and (consp x) (= (length x) 2))
3202 (list (car x) (nth 1 x) t)
3204 (default-value var)))
3206 ;; The following variables are defined here because is it also used
3207 ;; when formatting latex fragments. Originally it was part of the
3208 ;; LaTeX exporter, which is why the name includes "export".
3209 (defcustom org-export-latex-default-packages-alist
3210 '(("AUTO" "inputenc" t)
3211 ("T1" "fontenc" t)
3212 ("" "fixltx2e" nil)
3213 ("" "graphicx" t)
3214 ("" "longtable" nil)
3215 ("" "float" nil)
3216 ("" "wrapfig" nil)
3217 ("" "soul" t)
3218 ("" "textcomp" t)
3219 ("" "marvosym" t)
3220 ("" "wasysym" t)
3221 ("" "latexsym" t)
3222 ("" "amssymb" t)
3223 ("" "hyperref" nil)
3224 "\\tolerance=1000"
3226 "Alist of default packages to be inserted in the header.
3227 Change this only if one of the packages here causes an incompatibility
3228 with another package you are using.
3229 The packages in this list are needed by one part or another of Org-mode
3230 to function properly.
3232 - inputenc, fontenc: for basic font and character selection
3233 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3234 for interpreting the entities in `org-entities'. You can skip some of these
3235 packages if you don't use any of the symbols in it.
3236 - graphicx: for including images
3237 - float, wrapfig: for figure placement
3238 - longtable: for long tables
3239 - hyperref: for cross references
3241 Therefore you should not modify this variable unless you know what you
3242 are doing. The one reason to change it anyway is that you might be loading
3243 some other package that conflicts with one of the default packages.
3244 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3245 If SNIPPET-FLAG is t, the package also needs to be included when
3246 compiling LaTeX snippets into images for inclusion into HTML."
3247 :group 'org-export-latex
3248 :set 'org-set-packages-alist
3249 :get 'org-get-packages-alist
3250 :type '(repeat
3251 (choice
3252 (list :tag "options/package pair"
3253 (string :tag "options")
3254 (string :tag "package")
3255 (boolean :tag "Snippet"))
3256 (string :tag "A line of LaTeX"))))
3258 (defcustom org-export-latex-packages-alist nil
3259 "Alist of packages to be inserted in every LaTeX header.
3260 These will be inserted after `org-export-latex-default-packages-alist'.
3261 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3262 SNIPPET-FLAG, when t, indicates that this package is also needed when
3263 turning LaTeX snippets into images for inclusion into HTML.
3264 Make sure that you only list packages here which:
3265 - you want in every file
3266 - do not conflict with the default packages in
3267 `org-export-latex-default-packages-alist'
3268 - do not conflict with the setup in `org-format-latex-header'."
3269 :group 'org-export-latex
3270 :set 'org-set-packages-alist
3271 :get 'org-get-packages-alist
3272 :type '(repeat
3273 (choice
3274 (list :tag "options/package pair"
3275 (string :tag "options")
3276 (string :tag "package")
3277 (boolean :tag "Snippet"))
3278 (string :tag "A line of LaTeX"))))
3281 (defgroup org-appearance nil
3282 "Settings for Org-mode appearance."
3283 :tag "Org Appearance"
3284 :group 'org)
3286 (defcustom org-level-color-stars-only nil
3287 "Non-nil means fontify only the stars in each headline.
3288 When nil, the entire headline is fontified.
3289 Changing it requires restart of `font-lock-mode' to become effective
3290 also in regions already fontified."
3291 :group 'org-appearance
3292 :type 'boolean)
3294 (defcustom org-hide-leading-stars nil
3295 "Non-nil means hide the first N-1 stars in a headline.
3296 This works by using the face `org-hide' for these stars. This
3297 face is white for a light background, and black for a dark
3298 background. You may have to customize the face `org-hide' to
3299 make this work.
3300 Changing it requires restart of `font-lock-mode' to become effective
3301 also in regions already fontified.
3302 You may also set this on a per-file basis by adding one of the following
3303 lines to the buffer:
3305 #+STARTUP: hidestars
3306 #+STARTUP: showstars"
3307 :group 'org-appearance
3308 :type 'boolean)
3310 (defcustom org-hidden-keywords nil
3311 "List of keywords that should be hidden when typed in the org buffer.
3312 For example, add #+TITLE to this list in order to make the
3313 document title appear in the buffer without the initial #+TITLE:
3314 keyword."
3315 :group 'org-appearance
3316 :type '(set (const :tag "#+AUTHOR" author)
3317 (const :tag "#+DATE" date)
3318 (const :tag "#+EMAIL" email)
3319 (const :tag "#+TITLE" title)))
3321 (defcustom org-fontify-done-headline nil
3322 "Non-nil means change the face of a headline if it is marked DONE.
3323 Normally, only the TODO/DONE keyword indicates the state of a headline.
3324 When this is non-nil, the headline after the keyword is set to the
3325 `org-headline-done' as an additional indication."
3326 :group 'org-appearance
3327 :type 'boolean)
3329 (defcustom org-fontify-emphasized-text t
3330 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3331 Changing this variable requires a restart of Emacs to take effect."
3332 :group 'org-appearance
3333 :type 'boolean)
3335 (defcustom org-fontify-whole-heading-line nil
3336 "Non-nil means fontify the whole line for headings.
3337 This is useful when setting a background color for the
3338 org-level-* faces."
3339 :group 'org-appearance
3340 :type 'boolean)
3342 (defcustom org-highlight-latex-fragments-and-specials nil
3343 "Non-nil means fontify what is treated specially by the exporters."
3344 :group 'org-appearance
3345 :type 'boolean)
3347 (defcustom org-hide-emphasis-markers nil
3348 "Non-nil mean font-lock should hide the emphasis marker characters."
3349 :group 'org-appearance
3350 :type 'boolean)
3352 (defcustom org-pretty-entities nil
3353 "Non-nil means show entities as UTF8 characters.
3354 When nil, the \\name form remains in the buffer."
3355 :group 'org-appearance
3356 :type 'boolean)
3358 (defcustom org-pretty-entities-include-sub-superscripts t
3359 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3360 :group 'org-appearance
3361 :type 'boolean)
3363 (defvar org-emph-re nil
3364 "Regular expression for matching emphasis.
3365 After a match, the match groups contain these elements:
3366 0 The match of the full regular expression, including the characters
3367 before and after the proper match
3368 1 The character before the proper match, or empty at beginning of line
3369 2 The proper match, including the leading and trailing markers
3370 3 The leading marker like * or /, indicating the type of highlighting
3371 4 The text between the emphasis markers, not including the markers
3372 5 The character after the match, empty at the end of a line")
3373 (defvar org-verbatim-re nil
3374 "Regular expression for matching verbatim text.")
3375 (defvar org-emphasis-regexp-components) ; defined just below
3376 (defvar org-emphasis-alist) ; defined just below
3377 (defun org-set-emph-re (var val)
3378 "Set variable and compute the emphasis regular expression."
3379 (set var val)
3380 (when (and (boundp 'org-emphasis-alist)
3381 (boundp 'org-emphasis-regexp-components)
3382 org-emphasis-alist org-emphasis-regexp-components)
3383 (let* ((e org-emphasis-regexp-components)
3384 (pre (car e))
3385 (post (nth 1 e))
3386 (border (nth 2 e))
3387 (body (nth 3 e))
3388 (nl (nth 4 e))
3389 (body1 (concat body "*?"))
3390 (markers (mapconcat 'car org-emphasis-alist ""))
3391 (vmarkers (mapconcat
3392 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3393 org-emphasis-alist "")))
3394 ;; make sure special characters appear at the right position in the class
3395 (if (string-match "\\^" markers)
3396 (setq markers (concat (replace-match "" t t markers) "^")))
3397 (if (string-match "-" markers)
3398 (setq markers (concat (replace-match "" t t markers) "-")))
3399 (if (string-match "\\^" vmarkers)
3400 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3401 (if (string-match "-" vmarkers)
3402 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3403 (if (> nl 0)
3404 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3405 (int-to-string nl) "\\}")))
3406 ;; Make the regexp
3407 (setq org-emph-re
3408 (concat "\\([" pre "]\\|^\\)"
3409 "\\("
3410 "\\([" markers "]\\)"
3411 "\\("
3412 "[^" border "]\\|"
3413 "[^" border "]"
3414 body1
3415 "[^" border "]"
3416 "\\)"
3417 "\\3\\)"
3418 "\\([" post "]\\|$\\)"))
3419 (setq org-verbatim-re
3420 (concat "\\([" pre "]\\|^\\)"
3421 "\\("
3422 "\\([" vmarkers "]\\)"
3423 "\\("
3424 "[^" border "]\\|"
3425 "[^" border "]"
3426 body1
3427 "[^" border "]"
3428 "\\)"
3429 "\\3\\)"
3430 "\\([" post "]\\|$\\)")))))
3432 (defcustom org-emphasis-regexp-components
3433 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3434 "Components used to build the regular expression for emphasis.
3435 This is a list with five entries. Terminology: In an emphasis string
3436 like \" *strong word* \", we call the initial space PREMATCH, the final
3437 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3438 and \"trong wor\" is the body. The different components in this variable
3439 specify what is allowed/forbidden in each part:
3441 pre Chars allowed as prematch. Beginning of line will be allowed too.
3442 post Chars allowed as postmatch. End of line will be allowed too.
3443 border The chars *forbidden* as border characters.
3444 body-regexp A regexp like \".\" to match a body character. Don't use
3445 non-shy groups here, and don't allow newline here.
3446 newline The maximum number of newlines allowed in an emphasis exp.
3448 Use customize to modify this, or restart Emacs after changing it."
3449 :group 'org-appearance
3450 :set 'org-set-emph-re
3451 :type '(list
3452 (sexp :tag "Allowed chars in pre ")
3453 (sexp :tag "Allowed chars in post ")
3454 (sexp :tag "Forbidden chars in border ")
3455 (sexp :tag "Regexp for body ")
3456 (integer :tag "number of newlines allowed")
3457 (option (boolean :tag "Please ignore this button"))))
3459 (defcustom org-emphasis-alist
3460 `(("*" bold "<b>" "</b>")
3461 ("/" italic "<i>" "</i>")
3462 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3463 ("=" org-code "<code>" "</code>" verbatim)
3464 ("~" org-verbatim "<code>" "</code>" verbatim)
3465 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3466 "<del>" "</del>")
3468 "Special syntax for emphasized text.
3469 Text starting and ending with a special character will be emphasized, for
3470 example *bold*, _underlined_ and /italic/. This variable sets the marker
3471 characters, the face to be used by font-lock for highlighting in Org-mode
3472 Emacs buffers, and the HTML tags to be used for this.
3473 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3474 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3475 Use customize to modify this, or restart Emacs after changing it."
3476 :group 'org-appearance
3477 :set 'org-set-emph-re
3478 :type '(repeat
3479 (list
3480 (string :tag "Marker character")
3481 (choice
3482 (face :tag "Font-lock-face")
3483 (plist :tag "Face property list"))
3484 (string :tag "HTML start tag")
3485 (string :tag "HTML end tag")
3486 (option (const verbatim)))))
3488 (defvar org-protecting-blocks
3489 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3490 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3491 This is needed for font-lock setup.")
3493 ;;; Miscellaneous options
3495 (defgroup org-completion nil
3496 "Completion in Org-mode."
3497 :tag "Org Completion"
3498 :group 'org)
3500 (defcustom org-completion-use-ido nil
3501 "Non-nil means use ido completion wherever possible.
3502 Note that `ido-mode' must be active for this variable to be relevant.
3503 If you decide to turn this variable on, you might well want to turn off
3504 `org-outline-path-complete-in-steps'.
3505 See also `org-completion-use-iswitchb'."
3506 :group 'org-completion
3507 :type 'boolean)
3509 (defcustom org-completion-use-iswitchb nil
3510 "Non-nil means use iswitchb completion wherever possible.
3511 Note that `iswitchb-mode' must be active for this variable to be relevant.
3512 If you decide to turn this variable on, you might well want to turn off
3513 `org-outline-path-complete-in-steps'.
3514 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3515 :group 'org-completion
3516 :type 'boolean)
3518 (defcustom org-completion-fallback-command 'hippie-expand
3519 "The expansion command called by \\[org-complete] in normal context.
3520 Normal means no org-mode-specific context."
3521 :group 'org-completion
3522 :type 'function)
3524 ;;; Functions and variables from their packages
3525 ;; Declared here to avoid compiler warnings
3527 ;; XEmacs only
3528 (defvar outline-mode-menu-heading)
3529 (defvar outline-mode-menu-show)
3530 (defvar outline-mode-menu-hide)
3531 (defvar zmacs-regions) ; XEmacs regions
3533 ;; Emacs only
3534 (defvar mark-active)
3536 ;; Various packages
3537 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3538 (declare-function calendar-forward-day "cal-move" (arg))
3539 (declare-function calendar-goto-date "cal-move" (date))
3540 (declare-function calendar-goto-today "cal-move" ())
3541 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3542 (defvar calc-embedded-close-formula)
3543 (defvar calc-embedded-open-formula)
3544 (declare-function cdlatex-tab "ext:cdlatex" ())
3545 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3546 (defvar font-lock-unfontify-region-function)
3547 (declare-function iswitchb-read-buffer "iswitchb"
3548 (prompt &optional default require-match start matches-set))
3549 (defvar iswitchb-temp-buflist)
3550 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3551 (defvar org-agenda-tags-todo-honor-ignore-options)
3552 (declare-function org-agenda-skip "org-agenda" ())
3553 (declare-function
3554 org-format-agenda-item "org-agenda"
3555 (extra txt &optional category tags dotime noprefix remove-re habitp))
3556 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3557 (declare-function org-agenda-change-all-lines "org-agenda"
3558 (newhead hdmarker &optional fixface just-this))
3559 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3560 (declare-function org-agenda-maybe-redo "org-agenda" ())
3561 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3562 (beg end))
3563 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3564 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3565 "org-agenda" (&optional end))
3566 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3567 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3568 (declare-function org-indent-mode "org-indent" (&optional arg))
3569 (declare-function parse-time-string "parse-time" (string))
3570 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3571 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3572 (defvar remember-data-file)
3573 (defvar texmathp-why)
3574 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3575 (declare-function table--at-cell-p "table" (position &optional object at-column))
3577 (defvar w3m-current-url)
3578 (defvar w3m-current-title)
3580 (defvar org-latex-regexps)
3582 ;;; Autoload and prepare some org modules
3584 ;; Some table stuff that needs to be defined here, because it is used
3585 ;; by the functions setting up org-mode or checking for table context.
3587 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3588 "Detect an org-type or table-type table.")
3589 (defconst org-table-line-regexp "^[ \t]*|"
3590 "Detect an org-type table line.")
3591 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3592 "Detect an org-type table line.")
3593 (defconst org-table-hline-regexp "^[ \t]*|-"
3594 "Detect an org-type table hline.")
3595 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3596 "Detect a table-type table hline.")
3597 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3598 "Detect the first line outside a table when searching from within it.
3599 This works for both table types.")
3601 ;; Autoload the functions in org-table.el that are needed by functions here.
3603 (eval-and-compile
3604 (org-autoload "org-table"
3605 '(org-table-align org-table-begin org-table-blank-field
3606 org-table-convert org-table-convert-region org-table-copy-down
3607 org-table-copy-region org-table-create
3608 org-table-create-or-convert-from-region
3609 org-table-create-with-table.el org-table-current-dline
3610 org-table-cut-region org-table-delete-column org-table-edit-field
3611 org-table-edit-formulas org-table-end org-table-eval-formula
3612 org-table-export org-table-field-info
3613 org-table-get-stored-formulas org-table-goto-column
3614 org-table-hline-and-move org-table-import org-table-insert-column
3615 org-table-insert-hline org-table-insert-row org-table-iterate
3616 org-table-justify-field-maybe org-table-kill-row
3617 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3618 org-table-move-column org-table-move-column-left
3619 org-table-move-column-right org-table-move-row
3620 org-table-move-row-down org-table-move-row-up
3621 org-table-next-field org-table-next-row org-table-paste-rectangle
3622 org-table-previous-field org-table-recalculate
3623 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3624 org-table-toggle-coordinate-overlays
3625 org-table-toggle-formula-debugger org-table-wrap-region
3626 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3627 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3628 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3630 (defun org-at-table-p (&optional table-type)
3631 "Return t if the cursor is inside an org-type table.
3632 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3633 (if org-enable-table-editor
3634 (save-excursion
3635 (beginning-of-line 1)
3636 (looking-at (if table-type org-table-any-line-regexp
3637 org-table-line-regexp)))
3638 nil))
3639 (defsubst org-table-p () (org-at-table-p))
3641 (defun org-at-table.el-p ()
3642 "Return t if and only if we are at a table.el table."
3643 (and (org-at-table-p 'any)
3644 (save-excursion
3645 (goto-char (org-table-begin 'any))
3646 (looking-at org-table1-hline-regexp))))
3647 (defun org-table-recognize-table.el ()
3648 "If there is a table.el table nearby, recognize it and move into it."
3649 (if org-table-tab-recognizes-table.el
3650 (if (org-at-table.el-p)
3651 (progn
3652 (beginning-of-line 1)
3653 (if (looking-at org-table-dataline-regexp)
3655 (if (looking-at org-table1-hline-regexp)
3656 (progn
3657 (beginning-of-line 2)
3658 (if (looking-at org-table-any-border-regexp)
3659 (beginning-of-line -1)))))
3660 (if (re-search-forward "|" (org-table-end t) t)
3661 (progn
3662 (require 'table)
3663 (if (table--at-cell-p (point))
3665 (message "recognizing table.el table...")
3666 (table-recognize-table)
3667 (message "recognizing table.el table...done")))
3668 (error "This should not happen"))
3670 nil)
3671 nil))
3673 (defun org-at-table-hline-p ()
3674 "Return t if the cursor is inside a hline in a table."
3675 (if org-enable-table-editor
3676 (save-excursion
3677 (beginning-of-line 1)
3678 (looking-at org-table-hline-regexp))
3679 nil))
3681 (defvar org-table-clean-did-remove-column nil)
3683 (defun org-table-map-tables (function &optional quietly)
3684 "Apply FUNCTION to the start of all tables in the buffer."
3685 (save-excursion
3686 (save-restriction
3687 (widen)
3688 (goto-char (point-min))
3689 (while (re-search-forward org-table-any-line-regexp nil t)
3690 (unless quietly
3691 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3692 (beginning-of-line 1)
3693 (when (looking-at org-table-line-regexp)
3694 (save-excursion (funcall function))
3695 (or (looking-at org-table-line-regexp)
3696 (forward-char 1)))
3697 (re-search-forward org-table-any-border-regexp nil 1))))
3698 (unless quietly (message "Mapping tables: done")))
3700 ;; Declare and autoload functions from org-exp.el & Co
3702 (declare-function org-default-export-plist "org-exp")
3703 (declare-function org-infile-export-plist "org-exp")
3704 (declare-function org-get-current-options "org-exp")
3705 (eval-and-compile
3706 (org-autoload "org-exp"
3707 '(org-export org-export-visible
3708 org-insert-export-options-template
3709 org-table-clean-before-export))
3710 (org-autoload "org-ascii"
3711 '(org-export-as-ascii org-export-ascii-preprocess
3712 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3713 org-export-region-as-ascii))
3714 (org-autoload "org-latex"
3715 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3716 org-replace-region-by-latex org-export-region-as-latex
3717 org-export-as-latex org-export-as-pdf
3718 org-export-as-pdf-and-open))
3719 (org-autoload "org-html"
3720 '(org-export-as-html-and-open
3721 org-export-as-html-batch org-export-as-html-to-buffer
3722 org-replace-region-by-html org-export-region-as-html
3723 org-export-as-html))
3724 (org-autoload "org-docbook"
3725 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3726 org-replace-region-by-docbook org-export-region-as-docbook
3727 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3728 org-export-as-docbook))
3729 (org-autoload "org-icalendar"
3730 '(org-export-icalendar-this-file
3731 org-export-icalendar-all-agenda-files
3732 org-export-icalendar-combine-agenda-files))
3733 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3734 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3736 ;; Declare and autoload functions from org-agenda.el
3738 (eval-and-compile
3739 (org-autoload "org-agenda"
3740 '(org-agenda org-agenda-list org-search-view
3741 org-todo-list org-tags-view org-agenda-list-stuck-projects
3742 org-diary org-agenda-to-appt
3743 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3745 ;; Autoload org-remember
3747 (eval-and-compile
3748 (org-autoload "org-remember"
3749 '(org-remember-insinuate org-remember-annotation
3750 org-remember-apply-template org-remember org-remember-handler)))
3752 (eval-and-compile
3753 (org-autoload "org-capture"
3754 '(org-capture org-capture-insert-template-here
3755 org-capture-import-remember-templates)))
3757 ;; Autoload org-clock.el
3759 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3760 (beg end))
3761 (declare-function org-clock-update-mode-line "org-clock" ())
3762 (declare-function org-resolve-clocks "org-clock"
3763 (&optional also-non-dangling-p prompt last-valid))
3764 (defvar org-clock-start-time)
3765 (defvar org-clock-marker (make-marker)
3766 "Marker recording the last clock-in.")
3767 (defvar org-clock-hd-marker (make-marker)
3768 "Marker recording the last clock-in, but the headline position.")
3769 (defvar org-clock-heading ""
3770 "The heading of the current clock entry.")
3771 (defun org-clock-is-active ()
3772 "Return non-nil if clock is currently running.
3773 The return value is actually the clock marker."
3774 (marker-buffer org-clock-marker))
3776 (eval-and-compile
3777 (org-autoload
3778 "org-clock"
3779 '(org-clock-in org-clock-out org-clock-cancel
3780 org-clock-goto org-clock-sum org-clock-display
3781 org-clock-remove-overlays org-clock-report
3782 org-clocktable-shift org-dblock-write:clocktable
3783 org-get-clocktable org-resolve-clocks)))
3785 (defun org-clock-update-time-maybe ()
3786 "If this is a CLOCK line, update it and return t.
3787 Otherwise, return nil."
3788 (interactive)
3789 (save-excursion
3790 (beginning-of-line 1)
3791 (skip-chars-forward " \t")
3792 (when (looking-at org-clock-string)
3793 (let ((re (concat "[ \t]*" org-clock-string
3794 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3795 "\\([ \t]*=>.*\\)?\\)?"))
3796 ts te h m s neg)
3797 (cond
3798 ((not (looking-at re))
3799 nil)
3800 ((not (match-end 2))
3801 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3802 (> org-clock-marker (point))
3803 (<= org-clock-marker (point-at-eol)))
3804 ;; The clock is running here
3805 (setq org-clock-start-time
3806 (apply 'encode-time
3807 (org-parse-time-string (match-string 1))))
3808 (org-clock-update-mode-line)))
3810 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3811 (end-of-line 1)
3812 (setq ts (match-string 1)
3813 te (match-string 3))
3814 (setq s (- (org-float-time
3815 (apply 'encode-time (org-parse-time-string te)))
3816 (org-float-time
3817 (apply 'encode-time (org-parse-time-string ts))))
3818 neg (< s 0)
3819 s (abs s)
3820 h (floor (/ s 3600))
3821 s (- s (* 3600 h))
3822 m (floor (/ s 60))
3823 s (- s (* 60 s)))
3824 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3825 t))))))
3827 (defun org-check-running-clock ()
3828 "Check if the current buffer contains the running clock.
3829 If yes, offer to stop it and to save the buffer with the changes."
3830 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3831 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3832 (buffer-name))))
3833 (org-clock-out)
3834 (when (y-or-n-p "Save changed buffer?")
3835 (save-buffer))))
3837 (defun org-clocktable-try-shift (dir n)
3838 "Check if this line starts a clock table, if yes, shift the time block."
3839 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3840 (org-clocktable-shift dir n)))
3842 ;; Autoload org-timer.el
3844 (eval-and-compile
3845 (org-autoload
3846 "org-timer"
3847 '(org-timer-start org-timer org-timer-item
3848 org-timer-change-times-in-region
3849 org-timer-set-timer
3850 org-timer-reset-timers
3851 org-timer-show-remaining-time)))
3853 ;; Autoload org-feed.el
3855 (eval-and-compile
3856 (org-autoload
3857 "org-feed"
3858 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3861 ;; Autoload org-indent.el
3863 ;; Define the variable already here, to make sure we have it.
3864 (defvar org-indent-mode nil
3865 "Non-nil if Org-Indent mode is enabled.
3866 Use the command `org-indent-mode' to change this variable.")
3868 (eval-and-compile
3869 (org-autoload
3870 "org-indent"
3871 '(org-indent-mode)))
3873 ;; Autoload org-mobile.el
3875 (eval-and-compile
3876 (org-autoload
3877 "org-mobile"
3878 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3880 ;; Autoload archiving code
3881 ;; The stuff that is needed for cycling and tags has to be defined here.
3883 (defgroup org-archive nil
3884 "Options concerning archiving in Org-mode."
3885 :tag "Org Archive"
3886 :group 'org-structure)
3888 (defcustom org-archive-location "%s_archive::"
3889 "The location where subtrees should be archived.
3891 The value of this variable is a string, consisting of two parts,
3892 separated by a double-colon. The first part is a filename and
3893 the second part is a headline.
3895 When the filename is omitted, archiving happens in the same file.
3896 %s in the filename will be replaced by the current file
3897 name (without the directory part). Archiving to a different file
3898 is useful to keep archived entries from contributing to the
3899 Org-mode Agenda.
3901 The archived entries will be filed as subtrees of the specified
3902 headline. When the headline is omitted, the subtrees are simply
3903 filed away at the end of the file, as top-level entries. Also in
3904 the heading you can use %s to represent the file name, this can be
3905 useful when using the same archive for a number of different files.
3907 Here are a few examples:
3908 \"%s_archive::\"
3909 If the current file is Projects.org, archive in file
3910 Projects.org_archive, as top-level trees. This is the default.
3912 \"::* Archived Tasks\"
3913 Archive in the current file, under the top-level headline
3914 \"* Archived Tasks\".
3916 \"~/org/archive.org::\"
3917 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3919 \"~/org/archive.org::From %s\"
3920 Archive in file ~/org/archive.org (absolute path), under headlines
3921 \"From FILENAME\" where file name is the current file name.
3923 \"basement::** Finished Tasks\"
3924 Archive in file ./basement (relative path), as level 3 trees
3925 below the level 2 heading \"** Finished Tasks\".
3927 You may set this option on a per-file basis by adding to the buffer a
3928 line like
3930 #+ARCHIVE: basement::** Finished Tasks
3932 You may also define it locally for a subtree by setting an ARCHIVE property
3933 in the entry. If such a property is found in an entry, or anywhere up
3934 the hierarchy, it will be used."
3935 :group 'org-archive
3936 :type 'string)
3938 (defcustom org-archive-tag "ARCHIVE"
3939 "The tag that marks a subtree as archived.
3940 An archived subtree does not open during visibility cycling, and does
3941 not contribute to the agenda listings.
3942 After changing this, font-lock must be restarted in the relevant buffers to
3943 get the proper fontification."
3944 :group 'org-archive
3945 :group 'org-keywords
3946 :type 'string)
3948 (defcustom org-agenda-skip-archived-trees t
3949 "Non-nil means the agenda will skip any items located in archived trees.
3950 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3951 variable is no longer recommended, you should leave it at the value t.
3952 Instead, use the key `v' to cycle the archives-mode in the agenda."
3953 :group 'org-archive
3954 :group 'org-agenda-skip
3955 :type 'boolean)
3957 (defcustom org-columns-skip-archived-trees t
3958 "Non-nil means ignore archived trees when creating column view."
3959 :group 'org-archive
3960 :group 'org-properties
3961 :type 'boolean)
3963 (defcustom org-cycle-open-archived-trees nil
3964 "Non-nil means `org-cycle' will open archived trees.
3965 An archived tree is a tree marked with the tag ARCHIVE.
3966 When nil, archived trees will stay folded. You can still open them with
3967 normal outline commands like `show-all', but not with the cycling commands."
3968 :group 'org-archive
3969 :group 'org-cycle
3970 :type 'boolean)
3972 (defcustom org-sparse-tree-open-archived-trees nil
3973 "Non-nil means sparse tree construction shows matches in archived trees.
3974 When nil, matches in these trees are highlighted, but the trees are kept in
3975 collapsed state."
3976 :group 'org-archive
3977 :group 'org-sparse-trees
3978 :type 'boolean)
3980 (defun org-cycle-hide-archived-subtrees (state)
3981 "Re-hide all archived subtrees after a visibility state change."
3982 (when (and (not org-cycle-open-archived-trees)
3983 (not (memq state '(overview folded))))
3984 (save-excursion
3985 (let* ((globalp (memq state '(contents all)))
3986 (beg (if globalp (point-min) (point)))
3987 (end (if globalp (point-max) (org-end-of-subtree t))))
3988 (org-hide-archived-subtrees beg end)
3989 (goto-char beg)
3990 (if (looking-at (concat ".*:" org-archive-tag ":"))
3991 (message "%s" (substitute-command-keys
3992 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3994 (defun org-force-cycle-archived ()
3995 "Cycle subtree even if it is archived."
3996 (interactive)
3997 (setq this-command 'org-cycle)
3998 (let ((org-cycle-open-archived-trees t))
3999 (call-interactively 'org-cycle)))
4001 (defun org-hide-archived-subtrees (beg end)
4002 "Re-hide all archived subtrees after a visibility state change."
4003 (save-excursion
4004 (let* ((re (concat ":" org-archive-tag ":")))
4005 (goto-char beg)
4006 (while (re-search-forward re end t)
4007 (when (org-on-heading-p)
4008 (org-flag-subtree t)
4009 (org-end-of-subtree t))))))
4011 (defun org-flag-subtree (flag)
4012 (save-excursion
4013 (org-back-to-heading t)
4014 (outline-end-of-heading)
4015 (outline-flag-region (point)
4016 (progn (org-end-of-subtree t) (point))
4017 flag)))
4019 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4021 (eval-and-compile
4022 (org-autoload "org-archive"
4023 '(org-add-archive-files org-archive-subtree
4024 org-archive-to-archive-sibling org-toggle-archive-tag
4025 org-archive-subtree-default
4026 org-archive-subtree-default-with-confirmation)))
4028 ;; Autoload Column View Code
4030 (declare-function org-columns-number-to-string "org-colview")
4031 (declare-function org-columns-get-format-and-top-level "org-colview")
4032 (declare-function org-columns-compute "org-colview")
4034 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4035 '(org-columns-number-to-string org-columns-get-format-and-top-level
4036 org-columns-compute org-agenda-columns org-columns-remove-overlays
4037 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4039 ;; Autoload ID code
4041 (declare-function org-id-store-link "org-id")
4042 (declare-function org-id-locations-load "org-id")
4043 (declare-function org-id-locations-save "org-id")
4044 (defvar org-id-track-globally)
4045 (org-autoload "org-id"
4046 '(org-id-get-create org-id-new org-id-copy org-id-get
4047 org-id-get-with-outline-path-completion
4048 org-id-get-with-outline-drilling org-id-store-link
4049 org-id-goto org-id-find org-id-store-link))
4051 ;; Autoload Plotting Code
4053 (org-autoload "org-plot"
4054 '(org-plot/gnuplot))
4056 ;;; Variables for pre-computed regular expressions, all buffer local
4058 (defvar org-drawer-regexp nil
4059 "Matches first line of a hidden block.")
4060 (make-variable-buffer-local 'org-drawer-regexp)
4061 (defvar org-todo-regexp nil
4062 "Matches any of the TODO state keywords.")
4063 (make-variable-buffer-local 'org-todo-regexp)
4064 (defvar org-not-done-regexp nil
4065 "Matches any of the TODO state keywords except the last one.")
4066 (make-variable-buffer-local 'org-not-done-regexp)
4067 (defvar org-not-done-heading-regexp nil
4068 "Matches a TODO headline that is not done.")
4069 (make-variable-buffer-local 'org-not-done-regexp)
4070 (defvar org-todo-line-regexp nil
4071 "Matches a headline and puts TODO state into group 2 if present.")
4072 (make-variable-buffer-local 'org-todo-line-regexp)
4073 (defvar org-complex-heading-regexp nil
4074 "Matches a headline and puts everything into groups:
4075 group 1: the stars
4076 group 2: The todo keyword, maybe
4077 group 3: Priority cookie
4078 group 4: True headline
4079 group 5: Tags")
4080 (make-variable-buffer-local 'org-complex-heading-regexp)
4081 (defvar org-complex-heading-regexp-format nil
4082 "Printf format to make regexp to match an exact headline.
4083 This regexp will match the headline of any node which hase the exact
4084 headline text that is put into the format, but may have any TODO state,
4085 priority and tags.")
4086 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4087 (defvar org-todo-line-tags-regexp nil
4088 "Matches a headline and puts TODO state into group 2 if present.
4089 Also put tags into group 4 if tags are present.")
4090 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4091 (defvar org-nl-done-regexp nil
4092 "Matches newline followed by a headline with the DONE keyword.")
4093 (make-variable-buffer-local 'org-nl-done-regexp)
4094 (defvar org-looking-at-done-regexp nil
4095 "Matches the DONE keyword a point.")
4096 (make-variable-buffer-local 'org-looking-at-done-regexp)
4097 (defvar org-ds-keyword-length 12
4098 "Maximum length of the Deadline and SCHEDULED keywords.")
4099 (make-variable-buffer-local 'org-ds-keyword-length)
4100 (defvar org-deadline-regexp nil
4101 "Matches the DEADLINE keyword.")
4102 (make-variable-buffer-local 'org-deadline-regexp)
4103 (defvar org-deadline-time-regexp nil
4104 "Matches the DEADLINE keyword together with a time stamp.")
4105 (make-variable-buffer-local 'org-deadline-time-regexp)
4106 (defvar org-deadline-line-regexp nil
4107 "Matches the DEADLINE keyword and the rest of the line.")
4108 (make-variable-buffer-local 'org-deadline-line-regexp)
4109 (defvar org-scheduled-regexp nil
4110 "Matches the SCHEDULED keyword.")
4111 (make-variable-buffer-local 'org-scheduled-regexp)
4112 (defvar org-scheduled-time-regexp nil
4113 "Matches the SCHEDULED keyword together with a time stamp.")
4114 (make-variable-buffer-local 'org-scheduled-time-regexp)
4115 (defvar org-closed-time-regexp nil
4116 "Matches the CLOSED keyword together with a time stamp.")
4117 (make-variable-buffer-local 'org-closed-time-regexp)
4119 (defvar org-keyword-time-regexp nil
4120 "Matches any of the 4 keywords, together with the time stamp.")
4121 (make-variable-buffer-local 'org-keyword-time-regexp)
4122 (defvar org-keyword-time-not-clock-regexp nil
4123 "Matches any of the 3 keywords, together with the time stamp.")
4124 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4125 (defvar org-maybe-keyword-time-regexp nil
4126 "Matches a timestamp, possibly preceded by a keyword.")
4127 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4128 (defvar org-planning-or-clock-line-re nil
4129 "Matches a line with planning or clock info.")
4130 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4131 (defvar org-all-time-keywords nil
4132 "List of time keywords.")
4133 (make-variable-buffer-local 'org-all-time-keywords)
4135 (defconst org-plain-time-of-day-regexp
4136 (concat
4137 "\\(\\<[012]?[0-9]"
4138 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4139 "\\(--?"
4140 "\\(\\<[012]?[0-9]"
4141 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4142 "\\)?")
4143 "Regular expression to match a plain time or time range.
4144 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4145 groups carry important information:
4146 0 the full match
4147 1 the first time, range or not
4148 8 the second time, if it is a range.")
4150 (defconst org-plain-time-extension-regexp
4151 (concat
4152 "\\(\\<[012]?[0-9]"
4153 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4154 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4155 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4156 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4157 groups carry important information:
4158 0 the full match
4159 7 hours of duration
4160 9 minutes of duration")
4162 (defconst org-stamp-time-of-day-regexp
4163 (concat
4164 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4165 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4166 "\\(--?"
4167 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4168 "Regular expression to match a timestamp time or time range.
4169 After a match, the following groups carry important information:
4170 0 the full match
4171 1 date plus weekday, for back referencing to make sure both times are on the same day
4172 2 the first time, range or not
4173 4 the second time, if it is a range.")
4175 (defconst org-startup-options
4176 '(("fold" org-startup-folded t)
4177 ("overview" org-startup-folded t)
4178 ("nofold" org-startup-folded nil)
4179 ("showall" org-startup-folded nil)
4180 ("showeverything" org-startup-folded showeverything)
4181 ("content" org-startup-folded content)
4182 ("indent" org-startup-indented t)
4183 ("noindent" org-startup-indented nil)
4184 ("hidestars" org-hide-leading-stars t)
4185 ("showstars" org-hide-leading-stars nil)
4186 ("odd" org-odd-levels-only t)
4187 ("oddeven" org-odd-levels-only nil)
4188 ("align" org-startup-align-all-tables t)
4189 ("noalign" org-startup-align-all-tables nil)
4190 ("inlineimages" org-startup-with-inline-images t)
4191 ("noinlineimages" org-startup-with-inline-images nil)
4192 ("customtime" org-display-custom-times t)
4193 ("logdone" org-log-done time)
4194 ("lognotedone" org-log-done note)
4195 ("nologdone" org-log-done nil)
4196 ("lognoteclock-out" org-log-note-clock-out t)
4197 ("nolognoteclock-out" org-log-note-clock-out nil)
4198 ("logrepeat" org-log-repeat state)
4199 ("lognoterepeat" org-log-repeat note)
4200 ("nologrepeat" org-log-repeat nil)
4201 ("logreschedule" org-log-reschedule time)
4202 ("lognotereschedule" org-log-reschedule note)
4203 ("nologreschedule" org-log-reschedule nil)
4204 ("logredeadline" org-log-redeadline time)
4205 ("lognoteredeadline" org-log-redeadline note)
4206 ("nologredeadline" org-log-redeadline nil)
4207 ("logrefile" org-log-refile time)
4208 ("lognoterefile" org-log-refile note)
4209 ("nologrefile" org-log-refile nil)
4210 ("fninline" org-footnote-define-inline t)
4211 ("nofninline" org-footnote-define-inline nil)
4212 ("fnlocal" org-footnote-section nil)
4213 ("fnauto" org-footnote-auto-label t)
4214 ("fnprompt" org-footnote-auto-label nil)
4215 ("fnconfirm" org-footnote-auto-label confirm)
4216 ("fnplain" org-footnote-auto-label plain)
4217 ("fnadjust" org-footnote-auto-adjust t)
4218 ("nofnadjust" org-footnote-auto-adjust nil)
4219 ("constcgs" constants-unit-system cgs)
4220 ("constSI" constants-unit-system SI)
4221 ("noptag" org-tag-persistent-alist nil)
4222 ("hideblocks" org-hide-block-startup t)
4223 ("nohideblocks" org-hide-block-startup nil)
4224 ("beamer" org-startup-with-beamer-mode t)
4225 ("entitiespretty" org-pretty-entities t)
4226 ("entitiesplain" org-pretty-entities nil))
4227 "Variable associated with STARTUP options for org-mode.
4228 Each element is a list of three items: The startup options as written
4229 in the #+STARTUP line, the corresponding variable, and the value to
4230 set this variable to if the option is found. An optional forth element PUSH
4231 means to push this value onto the list in the variable.")
4233 (defun org-set-regexps-and-options ()
4234 "Precompute regular expressions for current buffer."
4235 (when (org-mode-p)
4236 (org-set-local 'org-todo-kwd-alist nil)
4237 (org-set-local 'org-todo-key-alist nil)
4238 (org-set-local 'org-todo-key-trigger nil)
4239 (org-set-local 'org-todo-keywords-1 nil)
4240 (org-set-local 'org-done-keywords nil)
4241 (org-set-local 'org-todo-heads nil)
4242 (org-set-local 'org-todo-sets nil)
4243 (org-set-local 'org-todo-log-states nil)
4244 (org-set-local 'org-file-properties nil)
4245 (org-set-local 'org-file-tags nil)
4246 (let ((re (org-make-options-regexp
4247 '("CATEGORY" "TODO" "COLUMNS"
4248 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4249 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4250 "OPTIONS")
4251 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4252 (splitre "[ \t]+")
4253 (scripts org-use-sub-superscripts)
4254 kwds kws0 kwsa key log value cat arch tags const links hw dws
4255 tail sep kws1 prio props ftags drawers beamer-p
4256 ext-setup-or-nil setup-contents (start 0))
4257 (save-excursion
4258 (save-restriction
4259 (widen)
4260 (goto-char (point-min))
4261 (while (or (and ext-setup-or-nil
4262 (string-match re ext-setup-or-nil start)
4263 (setq start (match-end 0)))
4264 (and (setq ext-setup-or-nil nil start 0)
4265 (re-search-forward re nil t)))
4266 (setq key (upcase (match-string 1 ext-setup-or-nil))
4267 value (org-match-string-no-properties 2 ext-setup-or-nil))
4268 (if (stringp value) (setq value (org-trim value)))
4269 (cond
4270 ((equal key "CATEGORY")
4271 (setq cat value))
4272 ((member key '("SEQ_TODO" "TODO"))
4273 (push (cons 'sequence (org-split-string value splitre)) kwds))
4274 ((equal key "TYP_TODO")
4275 (push (cons 'type (org-split-string value splitre)) kwds))
4276 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4277 ;; general TODO-like setup
4278 (push (cons (intern (downcase (match-string 1 key)))
4279 (org-split-string value splitre)) kwds))
4280 ((equal key "TAGS")
4281 (setq tags (append tags (if tags '("\\n") nil)
4282 (org-split-string value splitre))))
4283 ((equal key "COLUMNS")
4284 (org-set-local 'org-columns-default-format value))
4285 ((equal key "LINK")
4286 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4287 (push (cons (match-string 1 value)
4288 (org-trim (match-string 2 value)))
4289 links)))
4290 ((equal key "PRIORITIES")
4291 (setq prio (org-split-string value " +")))
4292 ((equal key "PROPERTY")
4293 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4294 (push (cons (match-string 1 value) (match-string 2 value))
4295 props)))
4296 ((equal key "FILETAGS")
4297 (when (string-match "\\S-" value)
4298 (setq ftags
4299 (append
4300 ftags
4301 (apply 'append
4302 (mapcar (lambda (x) (org-split-string x ":"))
4303 (org-split-string value)))))))
4304 ((equal key "DRAWERS")
4305 (setq drawers (org-split-string value splitre)))
4306 ((equal key "CONSTANTS")
4307 (setq const (append const (org-split-string value splitre))))
4308 ((equal key "STARTUP")
4309 (let ((opts (org-split-string value splitre))
4310 l var val)
4311 (while (setq l (pop opts))
4312 (when (setq l (assoc l org-startup-options))
4313 (setq var (nth 1 l) val (nth 2 l))
4314 (if (not (nth 3 l))
4315 (set (make-local-variable var) val)
4316 (if (not (listp (symbol-value var)))
4317 (set (make-local-variable var) nil))
4318 (set (make-local-variable var) (symbol-value var))
4319 (add-to-list var val))))))
4320 ((equal key "ARCHIVE")
4321 (setq arch value)
4322 (remove-text-properties 0 (length arch)
4323 '(face t fontified t) arch))
4324 ((equal key "LATEX_CLASS")
4325 (setq beamer-p (equal value "beamer")))
4326 ((equal key "OPTIONS")
4327 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4328 (setq scripts (read (match-string 2 value)))))
4329 ((equal key "SETUPFILE")
4330 (setq setup-contents (org-file-contents
4331 (expand-file-name
4332 (org-remove-double-quotes value))
4333 'noerror))
4334 (if (not ext-setup-or-nil)
4335 (setq ext-setup-or-nil setup-contents start 0)
4336 (setq ext-setup-or-nil
4337 (concat (substring ext-setup-or-nil 0 start)
4338 "\n" setup-contents "\n"
4339 (substring ext-setup-or-nil start)))))
4340 ))))
4341 (org-set-local 'org-use-sub-superscripts scripts)
4342 (when cat
4343 (org-set-local 'org-category (intern cat))
4344 (push (cons "CATEGORY" cat) props))
4345 (when prio
4346 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4347 (setq prio (mapcar 'string-to-char prio))
4348 (org-set-local 'org-highest-priority (nth 0 prio))
4349 (org-set-local 'org-lowest-priority (nth 1 prio))
4350 (org-set-local 'org-default-priority (nth 2 prio)))
4351 (and props (org-set-local 'org-file-properties (nreverse props)))
4352 (and ftags (org-set-local 'org-file-tags
4353 (mapcar 'org-add-prop-inherited ftags)))
4354 (and drawers (org-set-local 'org-drawers drawers))
4355 (and arch (org-set-local 'org-archive-location arch))
4356 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4357 ;; Process the TODO keywords
4358 (unless kwds
4359 ;; Use the global values as if they had been given locally.
4360 (setq kwds (default-value 'org-todo-keywords))
4361 (if (stringp (car kwds))
4362 (setq kwds (list (cons org-todo-interpretation
4363 (default-value 'org-todo-keywords)))))
4364 (setq kwds (reverse kwds)))
4365 (setq kwds (nreverse kwds))
4366 (let (inter kws kw)
4367 (while (setq kws (pop kwds))
4368 (let ((kws (or
4369 (run-hook-with-args-until-success
4370 'org-todo-setup-filter-hook kws)
4371 kws)))
4372 (setq inter (pop kws) sep (member "|" kws)
4373 kws0 (delete "|" (copy-sequence kws))
4374 kwsa nil
4375 kws1 (mapcar
4376 (lambda (x)
4377 ;; 1 2
4378 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4379 (progn
4380 (setq kw (match-string 1 x)
4381 key (and (match-end 2) (match-string 2 x))
4382 log (org-extract-log-state-settings x))
4383 (push (cons kw (and key (string-to-char key))) kwsa)
4384 (and log (push log org-todo-log-states))
4386 (error "Invalid TODO keyword %s" x)))
4387 kws0)
4388 kwsa (if kwsa (append '((:startgroup))
4389 (nreverse kwsa)
4390 '((:endgroup))))
4391 hw (car kws1)
4392 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4393 tail (list inter hw (car dws) (org-last dws))))
4394 (add-to-list 'org-todo-heads hw 'append)
4395 (push kws1 org-todo-sets)
4396 (setq org-done-keywords (append org-done-keywords dws nil))
4397 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4398 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4399 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4400 (setq org-todo-sets (nreverse org-todo-sets)
4401 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4402 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4403 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4404 ;; Process the constants
4405 (when const
4406 (let (e cst)
4407 (while (setq e (pop const))
4408 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4409 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4410 (setq org-table-formula-constants-local cst)))
4412 ;; Process the tags.
4413 (when tags
4414 (let (e tgs)
4415 (while (setq e (pop tags))
4416 (cond
4417 ((equal e "{") (push '(:startgroup) tgs))
4418 ((equal e "}") (push '(:endgroup) tgs))
4419 ((equal e "\\n") (push '(:newline) tgs))
4420 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4421 (push (cons (match-string 1 e)
4422 (string-to-char (match-string 2 e)))
4423 tgs))
4424 (t (push (list e) tgs))))
4425 (org-set-local 'org-tag-alist nil)
4426 (while (setq e (pop tgs))
4427 (or (and (stringp (car e))
4428 (assoc (car e) org-tag-alist))
4429 (push e org-tag-alist)))))
4431 ;; Compute the regular expressions and other local variables
4432 (if (not org-done-keywords)
4433 (setq org-done-keywords (and org-todo-keywords-1
4434 (list (org-last org-todo-keywords-1)))))
4435 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4436 (length org-scheduled-string)
4437 (length org-clock-string)
4438 (length org-closed-string)))
4439 org-drawer-regexp
4440 (concat "^[ \t]*:\\("
4441 (mapconcat 'regexp-quote org-drawers "\\|")
4442 "\\):[ \t]*$")
4443 org-not-done-keywords
4444 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4445 org-todo-regexp
4446 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4447 "\\|") "\\)\\>")
4448 org-not-done-regexp
4449 (concat "\\<\\("
4450 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4451 "\\)\\>")
4452 org-not-done-heading-regexp
4453 (concat "^\\(\\*+\\)[ \t]+\\("
4454 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4455 "\\)\\>")
4456 org-todo-line-regexp
4457 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4458 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4459 "\\)\\>\\)?[ \t]*\\(.*\\)")
4460 org-complex-heading-regexp
4461 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4462 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4463 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4464 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
4465 org-complex-heading-regexp-format
4466 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4467 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4468 "\\)\\>\\)?"
4469 "\\(?:[ \t]*\\(\\[#.\\]\\)\\)?"
4470 "\\(?:[ \t]*\\(?:\\[[0-9%%/]+\\]\\)\\)?" ;; stats cookie
4471 "[ \t]*\\(%s\\)"
4472 "\\(?:[ \t]*\\(?:\\[[0-9%%/]+\\]\\)\\)?" ;; stats cookie
4473 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?[ \t]*$")
4474 org-nl-done-regexp
4475 (concat "\n\\*+[ \t]+"
4476 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4477 "\\)" "\\>")
4478 org-todo-line-tags-regexp
4479 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4480 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4481 (org-re
4482 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@#%]+:[ \t]*\\)?$\\)"))
4483 org-looking-at-done-regexp
4484 (concat "^" "\\(?:"
4485 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4486 "\\>")
4487 org-deadline-regexp (concat "\\<" org-deadline-string)
4488 org-deadline-time-regexp
4489 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4490 org-deadline-line-regexp
4491 (concat "\\<\\(" org-deadline-string "\\).*")
4492 org-scheduled-regexp
4493 (concat "\\<" org-scheduled-string)
4494 org-scheduled-time-regexp
4495 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4496 org-closed-time-regexp
4497 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4498 org-keyword-time-regexp
4499 (concat "\\<\\(" org-scheduled-string
4500 "\\|" org-deadline-string
4501 "\\|" org-closed-string
4502 "\\|" org-clock-string "\\)"
4503 " *[[<]\\([^]>]+\\)[]>]")
4504 org-keyword-time-not-clock-regexp
4505 (concat "\\<\\(" org-scheduled-string
4506 "\\|" org-deadline-string
4507 "\\|" org-closed-string
4508 "\\)"
4509 " *[[<]\\([^]>]+\\)[]>]")
4510 org-maybe-keyword-time-regexp
4511 (concat "\\(\\<\\(" org-scheduled-string
4512 "\\|" org-deadline-string
4513 "\\|" org-closed-string
4514 "\\|" org-clock-string "\\)\\)?"
4515 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4516 org-planning-or-clock-line-re
4517 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4518 "\\|" org-deadline-string
4519 "\\|" org-closed-string "\\|" org-clock-string
4520 "\\)\\>\\)")
4521 org-all-time-keywords
4522 (mapcar (lambda (w) (substring w 0 -1))
4523 (list org-scheduled-string org-deadline-string
4524 org-clock-string org-closed-string))
4526 (org-compute-latex-and-specials-regexp)
4527 (org-set-font-lock-defaults))))
4529 (defun org-file-contents (file &optional noerror)
4530 "Return the contents of FILE, as a string."
4531 (if (or (not file)
4532 (not (file-readable-p file)))
4533 (if noerror
4534 (progn
4535 (message "Cannot read file \"%s\"" file)
4536 (ding) (sit-for 2)
4538 (error "Cannot read file \"%s\"" file))
4539 (with-temp-buffer
4540 (insert-file-contents file)
4541 (buffer-string))))
4543 (defun org-extract-log-state-settings (x)
4544 "Extract the log state setting from a TODO keyword string.
4545 This will extract info from a string like \"WAIT(w@/!)\"."
4546 (let (kw key log1 log2)
4547 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4548 (setq kw (match-string 1 x)
4549 key (and (match-end 2) (match-string 2 x))
4550 log1 (and (match-end 3) (match-string 3 x))
4551 log2 (and (match-end 4) (match-string 4 x)))
4552 (and (or log1 log2)
4553 (list kw
4554 (and log1 (if (equal log1 "!") 'time 'note))
4555 (and log2 (if (equal log2 "!") 'time 'note)))))))
4557 (defun org-remove-keyword-keys (list)
4558 "Remove a pair of parenthesis at the end of each string in LIST."
4559 (mapcar (lambda (x)
4560 (if (string-match "(.*)$" x)
4561 (substring x 0 (match-beginning 0))
4563 list))
4565 (defun org-assign-fast-keys (alist)
4566 "Assign fast keys to a keyword-key alist.
4567 Respect keys that are already there."
4568 (let (new e (alt ?0))
4569 (while (setq e (pop alist))
4570 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4571 (cdr e)) ;; Key already assigned.
4572 (push e new)
4573 (let ((clist (string-to-list (downcase (car e))))
4574 (used (append new alist)))
4575 (when (= (car clist) ?@)
4576 (pop clist))
4577 (while (and clist (rassoc (car clist) used))
4578 (pop clist))
4579 (unless clist
4580 (while (rassoc alt used)
4581 (incf alt)))
4582 (push (cons (car e) (or (car clist) alt)) new))))
4583 (nreverse new)))
4585 ;;; Some variables used in various places
4587 (defvar org-window-configuration nil
4588 "Used in various places to store a window configuration.")
4589 (defvar org-selected-window nil
4590 "Used in various places to store a window configuration.")
4591 (defvar org-finish-function nil
4592 "Function to be called when `C-c C-c' is used.
4593 This is for getting out of special buffers like remember.")
4596 ;; FIXME: Occasionally check by commenting these, to make sure
4597 ;; no other functions uses these, forgetting to let-bind them.
4598 (defvar entry)
4599 (defvar last-state)
4600 (defvar date)
4602 ;; Defined somewhere in this file, but used before definition.
4603 (defvar org-entities) ;; defined in org-entities.el
4604 (defvar org-struct-menu)
4605 (defvar org-org-menu)
4606 (defvar org-tbl-menu)
4608 ;;;; Define the Org-mode
4610 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4611 (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"))
4614 ;; We use a before-change function to check if a table might need
4615 ;; an update.
4616 (defvar org-table-may-need-update t
4617 "Indicates that a table might need an update.
4618 This variable is set by `org-before-change-function'.
4619 `org-table-align' sets it back to nil.")
4620 (defun org-before-change-function (beg end)
4621 "Every change indicates that a table might need an update."
4622 (setq org-table-may-need-update t))
4623 (defvar org-mode-map)
4624 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4625 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4626 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4627 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4628 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4629 (defvar org-table-buffer-is-an nil)
4630 (defconst org-outline-regexp "\\*+ ")
4632 ;;;###autoload
4633 (define-derived-mode org-mode outline-mode "Org"
4634 "Outline-based notes management and organizer, alias
4635 \"Carsten's outline-mode for keeping track of everything.\"
4637 Org-mode develops organizational tasks around a NOTES file which
4638 contains information about projects as plain text. Org-mode is
4639 implemented on top of outline-mode, which is ideal to keep the content
4640 of large files well structured. It supports ToDo items, deadlines and
4641 time stamps, which magically appear in the diary listing of the Emacs
4642 calendar. Tables are easily created with a built-in table editor.
4643 Plain text URL-like links connect to websites, emails (VM), Usenet
4644 messages (Gnus), BBDB entries, and any files related to the project.
4645 For printing and sharing of notes, an Org-mode file (or a part of it)
4646 can be exported as a structured ASCII or HTML file.
4648 The following commands are available:
4650 \\{org-mode-map}"
4652 ;; Get rid of Outline menus, they are not needed
4653 ;; Need to do this here because define-derived-mode sets up
4654 ;; the keymap so late. Still, it is a waste to call this each time
4655 ;; we switch another buffer into org-mode.
4656 (if (featurep 'xemacs)
4657 (when (boundp 'outline-mode-menu-heading)
4658 ;; Assume this is Greg's port, it uses easymenu
4659 (easy-menu-remove outline-mode-menu-heading)
4660 (easy-menu-remove outline-mode-menu-show)
4661 (easy-menu-remove outline-mode-menu-hide))
4662 (define-key org-mode-map [menu-bar headings] 'undefined)
4663 (define-key org-mode-map [menu-bar hide] 'undefined)
4664 (define-key org-mode-map [menu-bar show] 'undefined))
4666 (org-load-modules-maybe)
4667 (easy-menu-add org-org-menu)
4668 (easy-menu-add org-tbl-menu)
4669 (org-install-agenda-files-menu)
4670 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4671 (add-to-invisibility-spec '(org-cwidth))
4672 (add-to-invisibility-spec '(org-hide-block . t))
4673 (when (featurep 'xemacs)
4674 (org-set-local 'line-move-ignore-invisible t))
4675 (org-set-local 'outline-regexp org-outline-regexp)
4676 (org-set-local 'outline-level 'org-outline-level)
4677 (when (and org-ellipsis
4678 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4679 (fboundp 'make-glyph-code))
4680 (unless org-display-table
4681 (setq org-display-table (make-display-table)))
4682 (set-display-table-slot
4683 org-display-table 4
4684 (vconcat (mapcar
4685 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4686 org-ellipsis)))
4687 (if (stringp org-ellipsis) org-ellipsis "..."))))
4688 (setq buffer-display-table org-display-table))
4689 (org-set-regexps-and-options)
4690 (when (and org-tag-faces (not org-tags-special-faces-re))
4691 ;; tag faces set outside customize.... force initialization.
4692 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4693 ;; Calc embedded
4694 (org-set-local 'calc-embedded-open-mode "# ")
4695 (modify-syntax-entry ?@ "w")
4696 (if org-startup-truncated (setq truncate-lines t))
4697 (org-set-local 'font-lock-unfontify-region-function
4698 'org-unfontify-region)
4699 ;; Activate before-change-function
4700 (org-set-local 'org-table-may-need-update t)
4701 (org-add-hook 'before-change-functions 'org-before-change-function nil
4702 'local)
4703 ;; Check for running clock before killing a buffer
4704 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4705 ;; Paragraphs and auto-filling
4706 (org-set-autofill-regexps)
4707 (setq indent-line-function 'org-indent-line-function)
4708 (org-update-radio-target-regexp)
4709 ;; Beginning/end of defun
4710 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
4711 (org-set-local 'end-of-defun-function 'org-end-of-defun)
4712 ;; Make sure dependence stuff works reliably, even for users who set it
4713 ;; too late :-(
4714 (if org-enforce-todo-dependencies
4715 (add-hook 'org-blocker-hook
4716 'org-block-todo-from-children-or-siblings-or-parent)
4717 (remove-hook 'org-blocker-hook
4718 'org-block-todo-from-children-or-siblings-or-parent))
4719 (if org-enforce-todo-checkbox-dependencies
4720 (add-hook 'org-blocker-hook
4721 'org-block-todo-from-checkboxes)
4722 (remove-hook 'org-blocker-hook
4723 'org-block-todo-from-checkboxes))
4725 ;; Comment characters
4726 (org-set-local 'comment-start "#")
4727 (org-set-local 'comment-padding " ")
4729 ;; Align options lines
4730 (org-set-local
4731 'align-mode-rules-list
4732 '((org-in-buffer-settings
4733 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4734 (modes . '(org-mode)))))
4736 ;; Imenu
4737 (org-set-local 'imenu-create-index-function
4738 'org-imenu-get-tree)
4740 ;; Make isearch reveal context
4741 (if (or (featurep 'xemacs)
4742 (not (boundp 'outline-isearch-open-invisible-function)))
4743 ;; Emacs 21 and XEmacs make use of the hook
4744 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4745 ;; Emacs 22 deals with this through a special variable
4746 (org-set-local 'outline-isearch-open-invisible-function
4747 (lambda (&rest ignore) (org-show-context 'isearch))))
4749 ;; Turn on org-beamer-mode?
4750 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4752 ;; If empty file that did not turn on org-mode automatically, make it to.
4753 (if (and org-insert-mode-line-in-empty-file
4754 (interactive-p)
4755 (= (point-min) (point-max)))
4756 (insert "# -*- mode: org -*-\n\n"))
4757 (unless org-inhibit-startup
4758 (when org-startup-align-all-tables
4759 (let ((bmp (buffer-modified-p)))
4760 (org-table-map-tables 'org-table-align 'quietly)
4761 (set-buffer-modified-p bmp)))
4762 (when org-startup-with-inline-images
4763 (org-display-inline-images))
4764 (when org-startup-indented
4765 (require 'org-indent)
4766 (org-indent-mode 1))
4767 (unless org-inhibit-startup-visibility-stuff
4768 (org-set-startup-visibility))))
4770 (when (fboundp 'abbrev-table-put)
4771 (abbrev-table-put org-mode-abbrev-table
4772 :parents (list text-mode-abbrev-table)))
4774 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4776 (defun org-current-time ()
4777 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4778 (if (> (car org-time-stamp-rounding-minutes) 1)
4779 (let ((r (car org-time-stamp-rounding-minutes))
4780 (time (decode-time)))
4781 (apply 'encode-time
4782 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4783 (nthcdr 2 time))))
4784 (current-time)))
4786 ;;;; Font-Lock stuff, including the activators
4788 (defvar org-mouse-map (make-sparse-keymap))
4789 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
4790 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
4791 (when org-mouse-1-follows-link
4792 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4793 (when org-tab-follows-link
4794 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4795 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4797 (require 'font-lock)
4799 (defconst org-non-link-chars "]\t\n\r<>")
4800 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4801 "shell" "elisp" "doi" "message"))
4802 (defvar org-link-types-re nil
4803 "Matches a link that has a url-like prefix like \"http:\"")
4804 (defvar org-link-re-with-space nil
4805 "Matches a link with spaces, optional angular brackets around it.")
4806 (defvar org-link-re-with-space2 nil
4807 "Matches a link with spaces, optional angular brackets around it.")
4808 (defvar org-link-re-with-space3 nil
4809 "Matches a link with spaces, only for internal part in bracket links.")
4810 (defvar org-angle-link-re nil
4811 "Matches link with angular brackets, spaces are allowed.")
4812 (defvar org-plain-link-re nil
4813 "Matches plain link, without spaces.")
4814 (defvar org-bracket-link-regexp nil
4815 "Matches a link in double brackets.")
4816 (defvar org-bracket-link-analytic-regexp nil
4817 "Regular expression used to analyze links.
4818 Here is what the match groups contain after a match:
4819 1: http:
4820 2: http
4821 3: path
4822 4: [desc]
4823 5: desc")
4824 (defvar org-bracket-link-analytic-regexp++ nil
4825 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
4826 (defvar org-any-link-re nil
4827 "Regular expression matching any link.")
4829 (defcustom org-match-sexp-depth 3
4830 "Number of stacked braces for sub/superscript matching.
4831 This has to be set before loading org.el to be effective."
4832 :group 'org-export-translation ; ??????????????????????????/
4833 :type 'integer)
4835 (defun org-create-multibrace-regexp (left right n)
4836 "Create a regular expression which will match a balanced sexp.
4837 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
4838 as single character strings.
4839 The regexp returned will match the entire expression including the
4840 delimiters. It will also define a single group which contains the
4841 match except for the outermost delimiters. The maximum depth of
4842 stacked delimiters is N. Escaping delimiters is not possible."
4843 (let* ((nothing (concat "[^" left right "]*?"))
4844 (or "\\|")
4845 (re nothing)
4846 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
4847 (while (> n 1)
4848 (setq n (1- n)
4849 re (concat re or next)
4850 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
4851 (concat left "\\(" re "\\)" right)))
4853 (defvar org-match-substring-regexp
4854 (concat
4855 "\\([^\\]\\)\\([_^]\\)\\("
4856 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
4857 "\\|"
4858 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
4859 "\\|"
4860 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
4861 "The regular expression matching a sub- or superscript.")
4863 (defvar org-match-substring-with-braces-regexp
4864 (concat
4865 "\\([^\\]\\)\\([_^]\\)\\("
4866 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
4867 "\\)")
4868 "The regular expression matching a sub- or superscript, forcing braces.")
4870 (defun org-make-link-regexps ()
4871 "Update the link regular expressions.
4872 This should be called after the variable `org-link-types' has changed."
4873 (setq org-link-types-re
4874 (concat
4875 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
4876 org-link-re-with-space
4877 (concat
4878 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4879 "\\([^" org-non-link-chars " ]"
4880 "[^" org-non-link-chars "]*"
4881 "[^" org-non-link-chars " ]\\)>?")
4882 org-link-re-with-space2
4883 (concat
4884 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4885 "\\([^" org-non-link-chars " ]"
4886 "[^\t\n\r]*"
4887 "[^" org-non-link-chars " ]\\)>?")
4888 org-link-re-with-space3
4889 (concat
4890 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4891 "\\([^" org-non-link-chars " ]"
4892 "[^\t\n\r]*\\)")
4893 org-angle-link-re
4894 (concat
4895 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4896 "\\([^" org-non-link-chars " ]"
4897 "[^" org-non-link-chars "]*"
4898 "\\)>")
4899 org-plain-link-re
4900 (concat
4901 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4902 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4903 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4904 org-bracket-link-regexp
4905 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4906 org-bracket-link-analytic-regexp
4907 (concat
4908 "\\[\\["
4909 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
4910 "\\([^]]+\\)"
4911 "\\]"
4912 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4913 "\\]")
4914 org-bracket-link-analytic-regexp++
4915 (concat
4916 "\\[\\["
4917 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4918 "\\([^]]+\\)"
4919 "\\]"
4920 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4921 "\\]")
4922 org-any-link-re
4923 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4924 org-angle-link-re "\\)\\|\\("
4925 org-plain-link-re "\\)")))
4927 (org-make-link-regexps)
4929 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4930 "Regular expression for fast time stamp matching.")
4931 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4932 "Regular expression for fast time stamp matching.")
4933 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4934 "Regular expression matching time strings for analysis.
4935 This one does not require the space after the date, so it can be used
4936 on a string that terminates immediately after the date.")
4937 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4938 "Regular expression matching time strings for analysis.")
4939 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4940 "Regular expression matching time stamps, with groups.")
4941 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4942 "Regular expression matching time stamps (also [..]), with groups.")
4943 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4944 "Regular expression matching a time stamp range.")
4945 (defconst org-tr-regexp-both
4946 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4947 "Regular expression matching a time stamp range.")
4948 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4949 org-ts-regexp "\\)?")
4950 "Regular expression matching a time stamp or time stamp range.")
4951 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4952 org-ts-regexp-both "\\)?")
4953 "Regular expression matching a time stamp or time stamp range.
4954 The time stamps may be either active or inactive.")
4956 (defvar org-emph-face nil)
4958 (defun org-do-emphasis-faces (limit)
4959 "Run through the buffer and add overlays to links."
4960 (let (rtn a)
4961 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4962 (if (not (= (char-after (match-beginning 3))
4963 (char-after (match-beginning 4))))
4964 (progn
4965 (setq rtn t)
4966 (setq a (assoc (match-string 3) org-emphasis-alist))
4967 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4968 'face
4969 (nth 1 a))
4970 (and (nth 4 a)
4971 (org-remove-flyspell-overlays-in
4972 (match-beginning 0) (match-end 0)))
4973 (add-text-properties (match-beginning 2) (match-end 2)
4974 '(font-lock-multiline t org-emphasis t))
4975 (when org-hide-emphasis-markers
4976 (add-text-properties (match-end 4) (match-beginning 5)
4977 '(invisible org-link))
4978 (add-text-properties (match-beginning 3) (match-end 3)
4979 '(invisible org-link)))))
4980 (backward-char 1))
4981 rtn))
4983 (defun org-emphasize (&optional char)
4984 "Insert or change an emphasis, i.e. a font like bold or italic.
4985 If there is an active region, change that region to a new emphasis.
4986 If there is no region, just insert the marker characters and position
4987 the cursor between them.
4988 CHAR should be either the marker character, or the first character of the
4989 HTML tag associated with that emphasis. If CHAR is a space, the means
4990 to remove the emphasis of the selected region.
4991 If char is not given (for example in an interactive call) it
4992 will be prompted for."
4993 (interactive)
4994 (let ((eal org-emphasis-alist) e det
4995 (erc org-emphasis-regexp-components)
4996 (prompt "")
4997 (string "") beg end move tag c s)
4998 (if (org-region-active-p)
4999 (setq beg (region-beginning) end (region-end)
5000 string (buffer-substring beg end))
5001 (setq move t))
5003 (while (setq e (pop eal))
5004 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5005 c (aref tag 0))
5006 (push (cons c (string-to-char (car e))) det)
5007 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5008 (substring tag 1)))))
5009 (setq det (nreverse det))
5010 (unless char
5011 (message "%s" (concat "Emphasis marker or tag:" prompt))
5012 (setq char (read-char-exclusive)))
5013 (setq char (or (cdr (assoc char det)) char))
5014 (if (equal char ?\ )
5015 (setq s "" move nil)
5016 (unless (assoc (char-to-string char) org-emphasis-alist)
5017 (error "No such emphasis marker: \"%c\"" char))
5018 (setq s (char-to-string char)))
5019 (while (and (> (length string) 1)
5020 (equal (substring string 0 1) (substring string -1))
5021 (assoc (substring string 0 1) org-emphasis-alist))
5022 (setq string (substring string 1 -1)))
5023 (setq string (concat s string s))
5024 (if beg (delete-region beg end))
5025 (unless (or (bolp)
5026 (string-match (concat "[" (nth 0 erc) "\n]")
5027 (char-to-string (char-before (point)))))
5028 (insert " "))
5029 (unless (or (eobp)
5030 (string-match (concat "[" (nth 1 erc) "\n]")
5031 (char-to-string (char-after (point)))))
5032 (insert " ") (backward-char 1))
5033 (insert string)
5034 (and move (backward-char 1))))
5036 (defconst org-nonsticky-props
5037 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5039 (defsubst org-rear-nonsticky-at (pos)
5040 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5042 (defun org-activate-plain-links (limit)
5043 "Run through the buffer and add overlays to links."
5044 (catch 'exit
5045 (let (f)
5046 (if (re-search-forward org-plain-link-re limit t)
5047 (progn
5048 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5049 (setq f (get-text-property (match-beginning 0) 'face))
5050 (if (or (eq f 'org-tag)
5051 (and (listp f) (memq 'org-tag f)))
5053 (add-text-properties (match-beginning 0) (match-end 0)
5054 (list 'mouse-face 'highlight
5055 'face 'org-link
5056 'keymap org-mouse-map))
5057 (org-rear-nonsticky-at (match-end 0)))
5058 t)))))
5060 (defun org-activate-code (limit)
5061 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
5062 (progn
5063 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5064 (remove-text-properties (match-beginning 0) (match-end 0)
5065 '(display t invisible t intangible t))
5066 t)))
5068 (defcustom org-src-fontify-natively nil
5069 "When non-nil, fontify code in code blocks."
5070 :type 'boolean
5071 :group 'org-appearance
5072 :group 'org-babel)
5074 (defun org-fontify-meta-lines-and-blocks (limit)
5075 "Fontify #+ lines and blocks, in the correct ways."
5076 (let ((case-fold-search t))
5077 (if (re-search-forward
5078 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5079 limit t)
5080 (let ((beg (match-beginning 0))
5081 (block-start (match-end 0))
5082 (block-end nil)
5083 (lang (match-string 7))
5084 (beg1 (line-beginning-position 2))
5085 (dc1 (downcase (match-string 2)))
5086 (dc3 (downcase (match-string 3)))
5087 end end1 quoting block-type)
5088 (cond
5089 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5090 ;; a single line of backend-specific content
5091 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5092 (remove-text-properties (match-beginning 0) (match-end 0)
5093 '(display t invisible t intangible t))
5094 (add-text-properties (match-beginning 1) (match-end 3)
5095 '(font-lock-fontified t face org-meta-line))
5096 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5097 '(font-lock-fontified t face org-block))
5098 ; for backend-specific code
5100 ((and (match-end 4) (equal dc3 "begin"))
5101 ;; Truly a block
5102 (setq block-type (downcase (match-string 5))
5103 quoting (member block-type org-protecting-blocks))
5104 (when (re-search-forward
5105 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5106 nil t) ;; on purpose, we look further than LIMIT
5107 (setq end (match-end 0) end1 (1- (match-beginning 0)))
5108 (setq block-end (match-beginning 0))
5109 (when quoting
5110 (remove-text-properties beg end
5111 '(display t invisible t intangible t)))
5112 (add-text-properties
5113 beg end
5114 '(font-lock-fontified t font-lock-multiline t))
5115 (add-text-properties beg beg1 '(face org-meta-line))
5116 (add-text-properties end1 (+ end 1) '(face org-meta-line))
5117 ; for end_src
5118 (cond
5119 ((and lang org-src-fontify-natively)
5120 (org-src-font-lock-fontify-block lang block-start block-end))
5121 (quoting
5122 (add-text-properties beg1 (+ end1 1) '(face
5123 org-block)))
5124 ; end of source block
5125 ((not org-fontify-quote-and-verse-blocks))
5126 ((string= block-type "quote")
5127 (add-text-properties beg1 end1 '(face org-quote)))
5128 ((string= block-type "verse")
5129 (add-text-properties beg1 end1 '(face org-verse))))
5131 ((member dc1 '("title:" "author:" "email:" "date:"))
5132 (add-text-properties
5133 beg (match-end 3)
5134 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5135 '(font-lock-fontified t invisible t)
5136 '(font-lock-fontified t face org-document-info-keyword)))
5137 (add-text-properties
5138 (match-beginning 6) (match-end 6)
5139 (if (string-equal dc1 "title:")
5140 '(font-lock-fontified t face org-document-title)
5141 '(font-lock-fontified t face org-document-info))))
5142 ((not (member (char-after beg) '(?\ ?\t)))
5143 ;; just any other in-buffer setting, but not indented
5144 (add-text-properties
5145 beg (match-end 0)
5146 '(font-lock-fontified t face org-meta-line))
5148 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5149 "orgtbl:" "tblfm:" "tblname:" "result:"
5150 "results:" "source:" "srcname:" "call:"))
5151 (and (match-end 4) (equal dc3 "attr")))
5152 (add-text-properties
5153 beg (match-end 0)
5154 '(font-lock-fontified t face org-meta-line))
5156 ((member dc3 '(" " ""))
5157 (add-text-properties
5158 beg (match-end 0)
5159 '(font-lock-fontified t face font-lock-comment-face)))
5160 (t nil))))))
5162 (defun org-activate-angle-links (limit)
5163 "Run through the buffer and add overlays to links."
5164 (if (re-search-forward org-angle-link-re limit t)
5165 (progn
5166 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5167 (add-text-properties (match-beginning 0) (match-end 0)
5168 (list 'mouse-face 'highlight
5169 'keymap org-mouse-map))
5170 (org-rear-nonsticky-at (match-end 0))
5171 t)))
5173 (defun org-activate-footnote-links (limit)
5174 "Run through the buffer and add overlays to links."
5175 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
5176 limit t)
5177 (progn
5178 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5179 (add-text-properties (match-beginning 2) (match-end 2)
5180 (list 'mouse-face 'highlight
5181 'keymap org-mouse-map
5182 'help-echo
5183 (if (= (point-at-bol) (match-beginning 2))
5184 "Footnote definition"
5185 "Footnote reference")
5187 (org-rear-nonsticky-at (match-end 2))
5188 t)))
5190 (defun org-activate-bracket-links (limit)
5191 "Run through the buffer and add overlays to bracketed links."
5192 (if (re-search-forward org-bracket-link-regexp limit t)
5193 (let* ((help (concat "LINK: "
5194 (org-match-string-no-properties 1)))
5195 ;; FIXME: above we should remove the escapes.
5196 ;; but that requires another match, protecting match data,
5197 ;; a lot of overhead for font-lock.
5198 (ip (org-maybe-intangible
5199 (list 'invisible 'org-link
5200 'keymap org-mouse-map 'mouse-face 'highlight
5201 'font-lock-multiline t 'help-echo help)))
5202 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5203 'font-lock-multiline t 'help-echo help)))
5204 ;; We need to remove the invisible property here. Table narrowing
5205 ;; may have made some of this invisible.
5206 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5207 (remove-text-properties (match-beginning 0) (match-end 0)
5208 '(invisible nil))
5209 (if (match-end 3)
5210 (progn
5211 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5212 (org-rear-nonsticky-at (match-beginning 3))
5213 (add-text-properties (match-beginning 3) (match-end 3) vp)
5214 (org-rear-nonsticky-at (match-end 3))
5215 (add-text-properties (match-end 3) (match-end 0) ip)
5216 (org-rear-nonsticky-at (match-end 0)))
5217 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5218 (org-rear-nonsticky-at (match-beginning 1))
5219 (add-text-properties (match-beginning 1) (match-end 1) vp)
5220 (org-rear-nonsticky-at (match-end 1))
5221 (add-text-properties (match-end 1) (match-end 0) ip)
5222 (org-rear-nonsticky-at (match-end 0)))
5223 t)))
5225 (defun org-activate-dates (limit)
5226 "Run through the buffer and add overlays to dates."
5227 (if (re-search-forward org-tsr-regexp-both limit t)
5228 (progn
5229 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5230 (add-text-properties (match-beginning 0) (match-end 0)
5231 (list 'mouse-face 'highlight
5232 'keymap org-mouse-map))
5233 (org-rear-nonsticky-at (match-end 0))
5234 (when org-display-custom-times
5235 (if (match-end 3)
5236 (org-display-custom-time (match-beginning 3) (match-end 3)))
5237 (org-display-custom-time (match-beginning 1) (match-end 1)))
5238 t)))
5240 (defvar org-target-link-regexp nil
5241 "Regular expression matching radio targets in plain text.")
5242 (make-variable-buffer-local 'org-target-link-regexp)
5243 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5244 "Regular expression matching a link target.")
5245 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5246 "Regular expression matching a radio target.")
5247 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5248 "Regular expression matching any target.")
5250 (defun org-activate-target-links (limit)
5251 "Run through the buffer and add overlays to target matches."
5252 (when org-target-link-regexp
5253 (let ((case-fold-search t))
5254 (if (re-search-forward org-target-link-regexp limit t)
5255 (progn
5256 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5257 (add-text-properties (match-beginning 0) (match-end 0)
5258 (list 'mouse-face 'highlight
5259 'keymap org-mouse-map
5260 'help-echo "Radio target link"
5261 'org-linked-text t))
5262 (org-rear-nonsticky-at (match-end 0))
5263 t)))))
5265 (defun org-update-radio-target-regexp ()
5266 "Find all radio targets in this file and update the regular expression."
5267 (interactive)
5268 (when (memq 'radio org-activate-links)
5269 (setq org-target-link-regexp
5270 (org-make-target-link-regexp (org-all-targets 'radio)))
5271 (org-restart-font-lock)))
5273 (defun org-hide-wide-columns (limit)
5274 (let (s e)
5275 (setq s (text-property-any (point) (or limit (point-max))
5276 'org-cwidth t))
5277 (when s
5278 (setq e (next-single-property-change s 'org-cwidth))
5279 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5280 (goto-char e)
5281 t)))
5283 (defvar org-latex-and-specials-regexp nil
5284 "Regular expression for highlighting export special stuff.")
5285 (defvar org-match-substring-regexp)
5286 (defvar org-match-substring-with-braces-regexp)
5288 ;; This should be with the exporter code, but we also use if for font-locking
5289 (defconst org-export-html-special-string-regexps
5290 '(("\\\\-" . "&shy;")
5291 ("---\\([^-]\\)" . "&mdash;\\1")
5292 ("--\\([^-]\\)" . "&ndash;\\1")
5293 ("\\.\\.\\." . "&hellip;"))
5294 "Regular expressions for special string conversion.")
5297 (defun org-compute-latex-and-specials-regexp ()
5298 "Compute regular expression for stuff treated specially by exporters."
5299 (if (not org-highlight-latex-fragments-and-specials)
5300 (org-set-local 'org-latex-and-specials-regexp nil)
5301 (require 'org-exp)
5302 (let*
5303 ((matchers (plist-get org-format-latex-options :matchers))
5304 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5305 org-latex-regexps)))
5306 (org-export-allow-BIND nil)
5307 (options (org-combine-plists (org-default-export-plist)
5308 (org-infile-export-plist)))
5309 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5310 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5311 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5312 (org-export-html-expand (plist-get options :expand-quoted-html))
5313 (org-export-with-special-strings (plist-get options :special-strings))
5314 (re-sub
5315 (cond
5316 ((equal org-export-with-sub-superscripts '{})
5317 (list org-match-substring-with-braces-regexp))
5318 (org-export-with-sub-superscripts
5319 (list org-match-substring-regexp))
5320 (t nil)))
5321 (re-latex
5322 (if org-export-with-LaTeX-fragments
5323 (mapcar (lambda (x) (nth 1 x)) latexs)))
5324 (re-macros
5325 (if org-export-with-TeX-macros
5326 (list (concat "\\\\"
5327 (regexp-opt
5328 (append
5330 (delq nil
5331 (mapcar 'car-safe
5332 (append org-entities-user
5333 org-entities)))
5334 (if (boundp 'org-latex-entities)
5335 (mapcar (lambda (x)
5336 (or (car-safe x) x))
5337 org-latex-entities)
5338 nil))
5339 'words))) ; FIXME
5341 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5342 (re-special (if org-export-with-special-strings
5343 (mapcar (lambda (x) (car x))
5344 org-export-html-special-string-regexps)))
5345 (re-rest
5346 (delq nil
5347 (list
5348 (if org-export-html-expand "@<[^>\n]+>")
5349 ))))
5350 (org-set-local
5351 'org-latex-and-specials-regexp
5352 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5353 re-rest) "\\|")))))
5355 (defun org-do-latex-and-special-faces (limit)
5356 "Run through the buffer and add overlays to links."
5357 (when org-latex-and-specials-regexp
5358 (let (rtn d)
5359 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5360 limit t))
5361 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5362 'face))
5363 '(org-code org-verbatim underline)))
5364 (progn
5365 (setq rtn t
5366 d (cond ((member (char-after (1+ (match-beginning 0)))
5367 '(?_ ?^)) 1)
5368 (t 0)))
5369 (font-lock-prepend-text-property
5370 (+ d (match-beginning 0)) (match-end 0)
5371 'face 'org-latex-and-export-specials)
5372 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5373 '(font-lock-multiline t)))))
5374 rtn)))
5376 (defun org-restart-font-lock ()
5377 "Restart `font-lock-mode', to force refontification."
5378 (when (and (boundp 'font-lock-mode) font-lock-mode)
5379 (font-lock-mode -1)
5380 (font-lock-mode 1)))
5382 (defun org-all-targets (&optional radio)
5383 "Return a list of all targets in this file.
5384 With optional argument RADIO, only find radio targets."
5385 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5386 rtn)
5387 (save-excursion
5388 (goto-char (point-min))
5389 (while (re-search-forward re nil t)
5390 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5391 rtn)))
5393 (defun org-make-target-link-regexp (targets)
5394 "Make regular expression matching all strings in TARGETS.
5395 The regular expression finds the targets also if there is a line break
5396 between words."
5397 (and targets
5398 (concat
5399 "\\<\\("
5400 (mapconcat
5401 (lambda (x)
5402 (while (string-match " +" x)
5403 (setq x (replace-match "\\s-+" t t x)))
5405 targets
5406 "\\|")
5407 "\\)\\>")))
5409 (defun org-activate-tags (limit)
5410 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5411 (progn
5412 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5413 (add-text-properties (match-beginning 1) (match-end 1)
5414 (list 'mouse-face 'highlight
5415 'keymap org-mouse-map))
5416 (org-rear-nonsticky-at (match-end 1))
5417 t)))
5419 (defun org-outline-level ()
5420 "Compute the outline level of the heading at point.
5421 This function assumes that the cursor is at the beginning of a line matched
5422 by `outline-regexp'. Otherwise it returns garbage.
5423 If this is called at a normal headline, the level is the number of stars.
5424 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
5425 For plain list items, if they are matched by `outline-regexp', this returns
5426 1000 plus the line indentation."
5427 (save-excursion
5428 (looking-at outline-regexp)
5429 (if (match-beginning 1)
5430 (+ (org-get-string-indentation (match-string 1)) 1000)
5431 (1- (- (match-end 0) (match-beginning 0))))))
5433 (defvar org-font-lock-keywords nil)
5435 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5436 "Regular expression matching a property line.")
5438 (defvar org-font-lock-hook nil
5439 "Functions to be called for special font lock stuff.")
5441 (defvar org-font-lock-set-keywords-hook nil
5442 "Functions that can manipulate `org-font-lock-extra-keywords'.
5443 This is calles after `org-font-lock-extra-keywords' is defined, but before
5444 it is installed to be used by font lock. This can be useful if something
5445 needs to be inserted at a specific position in the font-lock sequence.")
5447 (defun org-font-lock-hook (limit)
5448 (run-hook-with-args 'org-font-lock-hook limit))
5450 (defun org-set-font-lock-defaults ()
5451 (let* ((em org-fontify-emphasized-text)
5452 (lk org-activate-links)
5453 (org-font-lock-extra-keywords
5454 (list
5455 ;; Call the hook
5456 '(org-font-lock-hook)
5457 ;; Headlines
5458 `(,(if org-fontify-whole-heading-line
5459 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5460 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5461 (1 (org-get-level-face 1))
5462 (2 (org-get-level-face 2))
5463 (3 (org-get-level-face 3)))
5464 ;; Table lines
5465 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5466 (1 'org-table t))
5467 ;; Table internals
5468 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5469 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5470 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5471 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5472 ;; Drawers
5473 (list org-drawer-regexp '(0 'org-special-keyword t))
5474 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5475 ;; Properties
5476 (list org-property-re
5477 '(1 'org-special-keyword t)
5478 '(3 'org-property-value t))
5479 ;; Links
5480 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5481 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5482 (if (memq 'plain lk) '(org-activate-plain-links))
5483 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5484 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5485 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5486 (if (memq 'footnote lk) '(org-activate-footnote-links
5487 (2 'org-footnote t)))
5488 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5489 '(org-hide-wide-columns (0 nil append))
5490 ;; TODO lines
5491 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
5492 '(1 (org-get-todo-face 1) t))
5493 ;; DONE
5494 (if org-fontify-done-headline
5495 (list (concat "^[*]+ +\\<\\("
5496 (mapconcat 'regexp-quote org-done-keywords "\\|")
5497 "\\)\\(.*\\)")
5498 '(2 'org-headline-done t))
5499 nil)
5500 ;; Priorities
5501 '(org-font-lock-add-priority-faces)
5502 ;; Tags
5503 '(org-font-lock-add-tag-faces)
5504 ;; Special keywords
5505 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5506 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5507 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5508 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5509 ;; Emphasis
5510 (if em
5511 (if (featurep 'xemacs)
5512 '(org-do-emphasis-faces (0 nil append))
5513 '(org-do-emphasis-faces)))
5514 ;; Checkboxes
5515 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5516 1 'org-checkbox prepend)
5517 (if (cdr (assq 'checkbox org-list-automatic-rules))
5518 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5519 (0 (org-get-checkbox-statistics-face) t)))
5520 ;; Description list items
5521 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\(.*? ::\\)"
5522 2 'bold prepend)
5523 ;; ARCHIVEd headings
5524 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5525 '(1 'org-archived prepend))
5526 ;; Specials
5527 '(org-do-latex-and-special-faces)
5528 '(org-fontify-entities)
5529 '(org-raise-scripts)
5530 ;; Code
5531 '(org-activate-code (1 'org-code t))
5532 ;; COMMENT
5533 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5534 "\\|" org-quote-string "\\)\\>")
5535 '(1 'org-special-keyword t))
5536 '("^#.*" (0 'font-lock-comment-face t))
5537 ;; Blocks and meta lines
5538 '(org-fontify-meta-lines-and-blocks)
5540 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5541 (run-hooks 'org-font-lock-set-keywords-hook)
5542 ;; Now set the full font-lock-keywords
5543 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5544 (org-set-local 'font-lock-defaults
5545 '(org-font-lock-keywords t nil nil backward-paragraph))
5546 (kill-local-variable 'font-lock-keywords) nil))
5548 (defun org-toggle-pretty-entities ()
5549 "Toggle the composition display of entities as UTF8 characters."
5550 (interactive)
5551 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5552 (org-restart-font-lock)
5553 (if org-pretty-entities
5554 (message "Entities are displayed as UTF8 characers")
5555 (save-restriction
5556 (widen)
5557 (org-decompose-region (point-min) (point-max))
5558 (message "Entities are displayed plain"))))
5560 (defun org-fontify-entities (limit)
5561 "Find an entity to fontify."
5562 (let (ee)
5563 (when org-pretty-entities
5564 (catch 'match
5565 (while (re-search-forward
5566 "\\\\\\([a-zA-Z][a-zA-Z0-9]*\\)\\($\\|[^[:alnum:]\n]\\)"
5567 limit t)
5568 (if (and (not (org-in-indented-comment-line))
5569 (setq ee (org-entity-get (match-string 1)))
5570 (= (length (nth 6 ee)) 1))
5571 (progn
5572 (add-text-properties
5573 (match-beginning 0) (match-end 1)
5574 (list 'font-lock-fontified t))
5575 (compose-region (match-beginning 0) (match-end 1)
5576 (nth 6 ee) nil)
5577 (backward-char 1)
5578 (throw 'match t))))
5579 nil))))
5581 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5582 "Fontify string S like in Org-mode."
5583 (with-temp-buffer
5584 (insert s)
5585 (let ((org-odd-levels-only odd-levels))
5586 (org-mode)
5587 (font-lock-fontify-buffer)
5588 (buffer-string))))
5590 (defvar org-m nil)
5591 (defvar org-l nil)
5592 (defvar org-f nil)
5593 (defun org-get-level-face (n)
5594 "Get the right face for match N in font-lock matching of headlines."
5595 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5596 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5597 (if org-cycle-level-faces
5598 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5599 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5600 (cond
5601 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5602 ((eq n 2) org-f)
5603 (t (if org-level-color-stars-only nil org-f))))
5606 (defun org-get-todo-face (kwd)
5607 "Get the right face for a TODO keyword KWD.
5608 If KWD is a number, get the corresponding match group."
5609 (if (numberp kwd) (setq kwd (match-string kwd)))
5610 (or (org-face-from-face-or-color
5611 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5612 (and (member kwd org-done-keywords) 'org-done)
5613 'org-todo))
5615 (defun org-face-from-face-or-color (context inherit face-or-color)
5616 "Create a face list that inherits INHERIT, but sets the foreground color.
5617 When FACE-OR-COLOR is not a string, just return it."
5618 (if (stringp face-or-color)
5619 (list :inherit inherit
5620 (cdr (assoc context org-faces-easy-properties))
5621 face-or-color)
5622 face-or-color))
5624 (defun org-font-lock-add-tag-faces (limit)
5625 "Add the special tag faces."
5626 (when (and org-tag-faces org-tags-special-faces-re)
5627 (while (re-search-forward org-tags-special-faces-re limit t)
5628 (add-text-properties (match-beginning 1) (match-end 1)
5629 (list 'face (org-get-tag-face 1)
5630 'font-lock-fontified t))
5631 (backward-char 1))))
5633 (defun org-font-lock-add-priority-faces (limit)
5634 "Add the special priority faces."
5635 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5636 (add-text-properties
5637 (match-beginning 0) (match-end 0)
5638 (list 'face (or (org-face-from-face-or-color
5639 'priority 'org-special-keyword
5640 (cdr (assoc (char-after (match-beginning 1))
5641 org-priority-faces)))
5642 'org-special-keyword)
5643 'font-lock-fontified t))))
5645 (defun org-get-tag-face (kwd)
5646 "Get the right face for a TODO keyword KWD.
5647 If KWD is a number, get the corresponding match group."
5648 (if (numberp kwd) (setq kwd (match-string kwd)))
5649 (or (org-face-from-face-or-color
5650 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5651 'org-tag))
5653 (defun org-unfontify-region (beg end &optional maybe_loudly)
5654 "Remove fontification and activation overlays from links."
5655 (font-lock-default-unfontify-region beg end)
5656 (let* ((buffer-undo-list t)
5657 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5658 (inhibit-modification-hooks t)
5659 deactivate-mark buffer-file-name buffer-file-truename)
5660 (org-decompose-region beg end)
5661 (remove-text-properties
5662 beg end
5663 (if org-indent-mode
5664 ;; also remove line-prefix and wrap-prefix properties
5665 '(mouse-face t keymap t org-linked-text t
5666 invisible t intangible t
5667 line-prefix t wrap-prefix t
5668 org-no-flyspell t org-emphasis t)
5669 '(mouse-face t keymap t org-linked-text t
5670 invisible t intangible t
5671 org-no-flyspell t org-emphasis t)))
5672 (org-remove-font-lock-display-properties beg end)))
5674 (defconst org-script-display '(((raise -0.3) (height 0.7))
5675 ((raise 0.3) (height 0.7))
5676 ((raise -0.5))
5677 ((raise 0.5)))
5678 "Display properties for showing superscripts and subscripts.")
5680 (defun org-remove-font-lock-display-properties (beg end)
5681 "Remove specific display properties that have been added by font lock.
5682 The will remove the raise properties that are used to show superscripts
5683 and subscripts."
5684 (let (next prop)
5685 (while (< beg end)
5686 (setq next (next-single-property-change beg 'display nil end)
5687 prop (get-text-property beg 'display))
5688 (if (member prop org-script-display)
5689 (put-text-property beg next 'display nil))
5690 (setq beg next))))
5692 (defun org-raise-scripts (limit)
5693 "Add raise properties to sub/superscripts."
5694 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
5695 (if (re-search-forward
5696 (if (eq org-use-sub-superscripts t)
5697 org-match-substring-regexp
5698 org-match-substring-with-braces-regexp)
5699 limit t)
5700 (let* ((pos (point)) table-p comment-p
5701 (mpos (match-beginning 3))
5702 (emph-p (get-text-property mpos 'org-emphasis))
5703 (link-p (get-text-property mpos 'mouse-face))
5704 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
5705 (goto-char (point-at-bol))
5706 (setq table-p (org-looking-at-p org-table-dataline-regexp)
5707 comment-p (org-looking-at-p "[ \t]*#"))
5708 (goto-char pos)
5709 ;; FIXME: Should we go back one character here, for a_b^c
5710 ;; (goto-char (1- pos)) ;????????????????????
5711 (if (or comment-p emph-p link-p keyw-p)
5713 (put-text-property (match-beginning 3) (match-end 0)
5714 'display
5715 (if (equal (char-after (match-beginning 2)) ?^)
5716 (nth (if table-p 3 1) org-script-display)
5717 (nth (if table-p 2 0) org-script-display)))
5718 (add-text-properties (match-beginning 2) (match-end 2)
5719 (list 'invisible t
5720 'org-dwidth t 'org-dwidth-n 1))
5721 (if (and (eq (char-after (match-beginning 3)) ?{)
5722 (eq (char-before (match-end 3)) ?}))
5723 (progn
5724 (add-text-properties
5725 (match-beginning 3) (1+ (match-beginning 3))
5726 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
5727 (add-text-properties
5728 (1- (match-end 3)) (match-end 3)
5729 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
5730 t)))))
5732 ;;;; Visibility cycling, including org-goto and indirect buffer
5734 ;;; Cycling
5736 (defvar org-cycle-global-status nil)
5737 (make-variable-buffer-local 'org-cycle-global-status)
5738 (defvar org-cycle-subtree-status nil)
5739 (make-variable-buffer-local 'org-cycle-subtree-status)
5741 ;;;###autoload
5743 (defvar org-inlinetask-min-level)
5745 (defun org-cycle (&optional arg)
5746 "TAB-action and visibility cycling for Org-mode.
5748 This is the command invoked in Org-mode by the TAB key. Its main purpose
5749 is outline visibility cycling, but it also invokes other actions
5750 in special contexts.
5752 - When this function is called with a prefix argument, rotate the entire
5753 buffer through 3 states (global cycling)
5754 1. OVERVIEW: Show only top-level headlines.
5755 2. CONTENTS: Show all headlines of all levels, but no body text.
5756 3. SHOW ALL: Show everything.
5757 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5758 determined by the variable `org-startup-folded', and by any VISIBILITY
5759 properties in the buffer.
5760 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5761 including any drawers.
5763 - When inside a table, re-align the table and move to the next field.
5765 - When point is at the beginning of a headline, rotate the subtree started
5766 by this line through 3 different states (local cycling)
5767 1. FOLDED: Only the main headline is shown.
5768 2. CHILDREN: The main headline and the direct children are shown.
5769 From this state, you can move to one of the children
5770 and zoom in further.
5771 3. SUBTREE: Show the entire subtree, including body text.
5772 If there is no subtree, switch directly from CHILDREN to FOLDED.
5774 - When point is at the beginning of an empty headline and the variable
5775 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5776 of the headline by demoting and promoting it to likely levels. This
5777 speeds up creation document structure by pressing TAB once or several
5778 times right after creating a new headline.
5780 - When there is a numeric prefix, go up to a heading with level ARG, do
5781 a `show-subtree' and return to the previous cursor position. If ARG
5782 is negative, go up that many levels.
5784 - When point is not at the beginning of a headline, execute the global
5785 binding for TAB, which is re-indenting the line. See the option
5786 `org-cycle-emulate-tab' for details.
5788 - Special case: if point is at the beginning of the buffer and there is
5789 no headline in line 1, this function will act as if called with prefix arg
5790 (C-u TAB, same as S-TAB) also when called without prefix arg.
5791 But only if also the variable `org-cycle-global-at-bob' is t."
5792 (interactive "P")
5793 (org-load-modules-maybe)
5794 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5795 (and org-cycle-level-after-item/entry-creation
5796 (or (org-cycle-level)
5797 (org-cycle-item-indentation))))
5798 (let* ((limit-level
5799 (or org-cycle-max-level
5800 (and (boundp 'org-inlinetask-min-level)
5801 org-inlinetask-min-level
5802 (1- org-inlinetask-min-level))))
5803 (nstars (and limit-level
5804 (if org-odd-levels-only
5805 (and limit-level (1- (* limit-level 2)))
5806 limit-level)))
5807 (outline-regexp
5808 (cond
5809 ((not (org-mode-p)) outline-regexp)
5810 ((or (eq org-cycle-include-plain-lists 'integrate)
5811 (and org-cycle-include-plain-lists (org-at-item-p)))
5812 (concat "\\(?:\\*"
5813 (if nstars (format "\\{1,%d\\}" nstars) "+")
5814 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5815 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5816 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
5817 (not (looking-at outline-regexp))))
5818 (org-cycle-hook
5819 (if bob-special
5820 (delq 'org-optimize-window-after-visibility-change
5821 (copy-sequence org-cycle-hook))
5822 org-cycle-hook))
5823 (pos (point)))
5825 (if (or bob-special (equal arg '(4)))
5826 ;; special case: use global cycling
5827 (setq arg t))
5829 (cond
5831 ((equal arg '(16))
5832 (setq last-command 'dummy)
5833 (org-set-startup-visibility)
5834 (message "Startup visibility, plus VISIBILITY properties"))
5836 ((equal arg '(64))
5837 (show-all)
5838 (message "Entire buffer visible, including drawers"))
5840 ((org-at-table-p 'any)
5841 ;; Enter the table or move to the next field in the table
5842 (if (org-at-table.el-p)
5843 (message "Use C-c ' to edit table.el tables")
5844 (if arg (org-table-edit-field t)
5845 (org-table-justify-field-maybe)
5846 (call-interactively 'org-table-next-field))))
5848 ((run-hook-with-args-until-success
5849 'org-tab-after-check-for-table-hook))
5851 ((eq arg t) ;; Global cycling
5852 (org-cycle-internal-global))
5854 ((and org-drawers org-drawer-regexp
5855 (save-excursion
5856 (beginning-of-line 1)
5857 (looking-at org-drawer-regexp)))
5858 ;; Toggle block visibility
5859 (org-flag-drawer
5860 (not (get-char-property (match-end 0) 'invisible))))
5862 ((integerp arg)
5863 ;; Show-subtree, ARG levels up from here.
5864 (save-excursion
5865 (org-back-to-heading)
5866 (outline-up-heading (if (< arg 0) (- arg)
5867 (- (funcall outline-level) arg)))
5868 (org-show-subtree)))
5870 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5871 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5873 (org-cycle-internal-local))
5875 ;; TAB emulation and template completion
5876 (buffer-read-only (org-back-to-heading))
5878 ((run-hook-with-args-until-success
5879 'org-tab-after-check-for-cycling-hook))
5881 ((org-try-structure-completion))
5883 ((org-try-cdlatex-tab))
5885 ((run-hook-with-args-until-success
5886 'org-tab-before-tab-emulation-hook))
5888 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5889 (or (not (bolp))
5890 (not (looking-at outline-regexp))))
5891 (call-interactively (global-key-binding "\t")))
5893 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5894 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5895 (or (and (eq org-cycle-emulate-tab 'white)
5896 (= (match-end 0) (point-at-eol)))
5897 (and (eq org-cycle-emulate-tab 'whitestart)
5898 (>= (match-end 0) pos))))
5900 (eq org-cycle-emulate-tab t))
5901 (call-interactively (global-key-binding "\t")))
5903 (t (save-excursion
5904 (org-back-to-heading)
5905 (org-cycle)))))))
5907 (defun org-cycle-internal-global ()
5908 "Do the global cycling action."
5909 (cond
5910 ((and (eq last-command this-command)
5911 (eq org-cycle-global-status 'overview))
5912 ;; We just created the overview - now do table of contents
5913 ;; This can be slow in very large buffers, so indicate action
5914 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5915 (message "CONTENTS...")
5916 (org-content)
5917 (message "CONTENTS...done")
5918 (setq org-cycle-global-status 'contents)
5919 (run-hook-with-args 'org-cycle-hook 'contents))
5921 ((and (eq last-command this-command)
5922 (eq org-cycle-global-status 'contents))
5923 ;; We just showed the table of contents - now show everything
5924 (run-hook-with-args 'org-pre-cycle-hook 'all)
5925 (show-all)
5926 (message "SHOW ALL")
5927 (setq org-cycle-global-status 'all)
5928 (run-hook-with-args 'org-cycle-hook 'all))
5931 ;; Default action: go to overview
5932 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5933 (org-overview)
5934 (message "OVERVIEW")
5935 (setq org-cycle-global-status 'overview)
5936 (run-hook-with-args 'org-cycle-hook 'overview))))
5938 (defun org-cycle-internal-local ()
5939 "Do the local cycling action."
5940 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5941 ;; First, some boundaries
5942 (save-excursion
5943 (org-back-to-heading)
5944 (setq level (funcall outline-level))
5945 (save-excursion
5946 (beginning-of-line 2)
5947 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5948 ; XEmacs does not have `next-single-char-property-change'
5949 ; I'm not sure about Emacs 21.
5950 (while (and (not (eobp)) ;; this is like `next-line'
5951 (get-char-property (1- (point)) 'invisible))
5952 (beginning-of-line 2))
5953 (while (and (not (eobp)) ;; this is like `next-line'
5954 (get-char-property (1- (point)) 'invisible))
5955 (goto-char (next-single-char-property-change (point) 'invisible))
5956 (and (eolp) (beginning-of-line 2))))
5957 (setq eol (point)))
5958 (outline-end-of-heading) (setq eoh (point))
5959 (save-excursion
5960 (outline-next-heading)
5961 (setq has-children (and (org-at-heading-p t)
5962 (> (funcall outline-level) level))))
5963 ;; if we're in a list, org-end-of-subtree is in fact org-end-of-item.
5964 (if (org-at-item-p)
5965 (setq eos (if (and (org-end-of-item) (bolp))
5966 (1- (point))
5967 (point)))
5968 (org-end-of-subtree t)
5969 (unless (eobp)
5970 (skip-chars-forward " \t\n"))
5971 (setq eos (if (eobp) (point) (1- (point))))))
5972 ;; Find out what to do next and set `this-command'
5973 (cond
5974 ((= eos eoh)
5975 ;; Nothing is hidden behind this heading
5976 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5977 (message "EMPTY ENTRY")
5978 (setq org-cycle-subtree-status nil)
5979 (save-excursion
5980 (goto-char eos)
5981 (outline-next-heading)
5982 (if (org-invisible-p) (org-flag-heading nil))))
5983 ((and (or (>= eol eos)
5984 (not (string-match "\\S-" (buffer-substring eol eos))))
5985 (or has-children
5986 (not (setq children-skipped
5987 org-cycle-skip-children-state-if-no-children))))
5988 ;; Entire subtree is hidden in one line: children view
5989 (run-hook-with-args 'org-pre-cycle-hook 'children)
5990 (org-show-entry)
5991 (show-children)
5992 (message "CHILDREN")
5993 (save-excursion
5994 (goto-char eos)
5995 (outline-next-heading)
5996 (if (org-invisible-p) (org-flag-heading nil)))
5997 (setq org-cycle-subtree-status 'children)
5998 (run-hook-with-args 'org-cycle-hook 'children))
5999 ((or children-skipped
6000 (and (eq last-command this-command)
6001 (eq org-cycle-subtree-status 'children)))
6002 ;; We just showed the children, or no children are there,
6003 ;; now show everything.
6004 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6005 (outline-flag-region eoh eos nil)
6006 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6007 (setq org-cycle-subtree-status 'subtree)
6008 (run-hook-with-args 'org-cycle-hook 'subtree))
6010 ;; Default action: hide the subtree.
6011 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6012 (outline-flag-region eoh eos t)
6013 (message "FOLDED")
6014 (setq org-cycle-subtree-status 'folded)
6015 (run-hook-with-args 'org-cycle-hook 'folded)))))
6017 ;;;###autoload
6018 (defun org-global-cycle (&optional arg)
6019 "Cycle the global visibility. For details see `org-cycle'.
6020 With \\[universal-argument] prefix arg, switch to startup visibility.
6021 With a numeric prefix, show all headlines up to that level."
6022 (interactive "P")
6023 (let ((org-cycle-include-plain-lists
6024 (if (org-mode-p) org-cycle-include-plain-lists nil)))
6025 (cond
6026 ((integerp arg)
6027 (show-all)
6028 (hide-sublevels arg)
6029 (setq org-cycle-global-status 'contents))
6030 ((equal arg '(4))
6031 (org-set-startup-visibility)
6032 (message "Startup visibility, plus VISIBILITY properties."))
6034 (org-cycle '(4))))))
6036 (defun org-set-startup-visibility ()
6037 "Set the visibility required by startup options and properties."
6038 (cond
6039 ((eq org-startup-folded t)
6040 (org-cycle '(4)))
6041 ((eq org-startup-folded 'content)
6042 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6043 (org-cycle '(4)) (org-cycle '(4)))))
6044 (unless (eq org-startup-folded 'showeverything)
6045 (if org-hide-block-startup (org-hide-block-all))
6046 (org-set-visibility-according-to-property 'no-cleanup)
6047 (org-cycle-hide-archived-subtrees 'all)
6048 (org-cycle-hide-drawers 'all)
6049 (org-cycle-show-empty-lines t)))
6051 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6052 "Switch subtree visibilities according to :VISIBILITY: property."
6053 (interactive)
6054 (let (org-show-entry-below state)
6055 (save-excursion
6056 (goto-char (point-max))
6057 (while (re-search-backward
6058 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6059 nil t)
6060 (setq state (match-string 1))
6061 (save-excursion
6062 (org-back-to-heading t)
6063 (hide-subtree)
6064 (org-reveal)
6065 (cond
6066 ((equal state '("fold" "folded"))
6067 (hide-subtree))
6068 ((equal state "children")
6069 (org-show-hidden-entry)
6070 (show-children))
6071 ((equal state "content")
6072 (save-excursion
6073 (save-restriction
6074 (org-narrow-to-subtree)
6075 (org-content))))
6076 ((member state '("all" "showall"))
6077 (show-subtree)))))
6078 (unless no-cleanup
6079 (org-cycle-hide-archived-subtrees 'all)
6080 (org-cycle-hide-drawers 'all)
6081 (org-cycle-show-empty-lines 'all)))))
6083 (defun org-overview ()
6084 "Switch to overview mode, showing only top-level headlines.
6085 Really, this shows all headlines with level equal or greater than the level
6086 of the first headline in the buffer. This is important, because if the
6087 first headline is not level one, then (hide-sublevels 1) gives confusing
6088 results."
6089 (interactive)
6090 (let ((level (save-excursion
6091 (goto-char (point-min))
6092 (if (re-search-forward (concat "^" outline-regexp) nil t)
6093 (progn
6094 (goto-char (match-beginning 0))
6095 (funcall outline-level))))))
6096 (and level (hide-sublevels level))))
6098 (defun org-content (&optional arg)
6099 "Show all headlines in the buffer, like a table of contents.
6100 With numerical argument N, show content up to level N."
6101 (interactive "P")
6102 (save-excursion
6103 ;; Visit all headings and show their offspring
6104 (and (integerp arg) (org-overview))
6105 (goto-char (point-max))
6106 (catch 'exit
6107 (while (and (progn (condition-case nil
6108 (outline-previous-visible-heading 1)
6109 (error (goto-char (point-min))))
6111 (looking-at outline-regexp))
6112 (if (integerp arg)
6113 (show-children (1- arg))
6114 (show-branches))
6115 (if (bobp) (throw 'exit nil))))))
6118 (defun org-optimize-window-after-visibility-change (state)
6119 "Adjust the window after a change in outline visibility.
6120 This function is the default value of the hook `org-cycle-hook'."
6121 (when (get-buffer-window (current-buffer))
6122 (cond
6123 ((eq state 'content) nil)
6124 ((eq state 'all) nil)
6125 ((eq state 'folded) nil)
6126 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6127 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6129 (defun org-remove-empty-overlays-at (pos)
6130 "Remove outline overlays that do not contain non-white stuff."
6131 (mapc
6132 (lambda (o)
6133 (and (eq 'outline (overlay-get o 'invisible))
6134 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6135 (overlay-end o))))
6136 (delete-overlay o)))
6137 (overlays-at pos)))
6139 (defun org-clean-visibility-after-subtree-move ()
6140 "Fix visibility issues after moving a subtree."
6141 ;; First, find a reasonable region to look at:
6142 ;; Start two siblings above, end three below
6143 (let* ((beg (save-excursion
6144 (and (org-get-last-sibling)
6145 (org-get-last-sibling))
6146 (point)))
6147 (end (save-excursion
6148 (and (org-get-next-sibling)
6149 (org-get-next-sibling)
6150 (org-get-next-sibling))
6151 (if (org-at-heading-p)
6152 (point-at-eol)
6153 (point))))
6154 (level (looking-at "\\*+"))
6155 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6156 (save-excursion
6157 (save-restriction
6158 (narrow-to-region beg end)
6159 (when re
6160 ;; Properly fold already folded siblings
6161 (goto-char (point-min))
6162 (while (re-search-forward re nil t)
6163 (if (and (not (org-invisible-p))
6164 (save-excursion
6165 (goto-char (point-at-eol)) (org-invisible-p)))
6166 (hide-entry))))
6167 (org-cycle-show-empty-lines 'overview)
6168 (org-cycle-hide-drawers 'overview)))))
6170 (defun org-cycle-show-empty-lines (state)
6171 "Show empty lines above all visible headlines.
6172 The region to be covered depends on STATE when called through
6173 `org-cycle-hook'. Lisp program can use t for STATE to get the
6174 entire buffer covered. Note that an empty line is only shown if there
6175 are at least `org-cycle-separator-lines' empty lines before the headline."
6176 (when (not (= org-cycle-separator-lines 0))
6177 (save-excursion
6178 (let* ((n (abs org-cycle-separator-lines))
6179 (re (cond
6180 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6181 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6182 (t (let ((ns (number-to-string (- n 2))))
6183 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6184 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6185 beg end b e)
6186 (cond
6187 ((memq state '(overview contents t))
6188 (setq beg (point-min) end (point-max)))
6189 ((memq state '(children folded))
6190 (setq beg (point) end (progn (org-end-of-subtree t t)
6191 (beginning-of-line 2)
6192 (point)))))
6193 (when beg
6194 (goto-char beg)
6195 (while (re-search-forward re end t)
6196 (unless (get-char-property (match-end 1) 'invisible)
6197 (setq e (match-end 1))
6198 (if (< org-cycle-separator-lines 0)
6199 (setq b (save-excursion
6200 (goto-char (match-beginning 0))
6201 (org-back-over-empty-lines)
6202 (if (save-excursion
6203 (goto-char (max (point-min) (1- (point))))
6204 (org-on-heading-p))
6205 (1- (point))
6206 (point))))
6207 (setq b (match-beginning 1)))
6208 (outline-flag-region b e nil)))))))
6209 ;; Never hide empty lines at the end of the file.
6210 (save-excursion
6211 (goto-char (point-max))
6212 (outline-previous-heading)
6213 (outline-end-of-heading)
6214 (if (and (looking-at "[ \t\n]+")
6215 (= (match-end 0) (point-max)))
6216 (outline-flag-region (point) (match-end 0) nil))))
6218 (defun org-show-empty-lines-in-parent ()
6219 "Move to the parent and re-show empty lines before visible headlines."
6220 (save-excursion
6221 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6222 (org-cycle-show-empty-lines context))))
6224 (defun org-files-list ()
6225 "Return `org-agenda-files' list, plus all open org-mode files.
6226 This is useful for operations that need to scan all of a user's
6227 open and agenda-wise Org files."
6228 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6229 (dolist (buf (buffer-list))
6230 (with-current-buffer buf
6231 (if (and (eq major-mode 'org-mode) (buffer-file-name))
6232 (let ((file (expand-file-name (buffer-file-name))))
6233 (unless (member file files)
6234 (push file files))))))
6235 files))
6237 (defsubst org-entry-beginning-position ()
6238 "Return the beginning position of the current entry."
6239 (save-excursion (outline-back-to-heading t) (point)))
6241 (defsubst org-entry-end-position ()
6242 "Return the end position of the current entry."
6243 (save-excursion (outline-next-heading) (point)))
6245 (defun org-cycle-hide-drawers (state)
6246 "Re-hide all drawers after a visibility state change."
6247 (when (and (org-mode-p)
6248 (not (memq state '(overview folded contents))))
6249 (save-excursion
6250 (let* ((globalp (memq state '(contents all)))
6251 (beg (if globalp (point-min) (point)))
6252 (end (if globalp (point-max)
6253 (if (eq state 'children)
6254 (save-excursion (outline-next-heading) (point))
6255 (org-end-of-subtree t)))))
6256 (goto-char beg)
6257 (while (re-search-forward org-drawer-regexp end t)
6258 (org-flag-drawer t))))))
6260 (defun org-flag-drawer (flag)
6261 (save-excursion
6262 (beginning-of-line 1)
6263 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6264 (let ((b (match-end 0))
6265 (outline-regexp org-outline-regexp))
6266 (if (re-search-forward
6267 "^[ \t]*:END:"
6268 (save-excursion (outline-next-heading) (point)) t)
6269 (outline-flag-region b (point-at-eol) flag)
6270 (error ":END: line missing at position %s" b))))))
6272 (defun org-subtree-end-visible-p ()
6273 "Is the end of the current subtree visible?"
6274 (pos-visible-in-window-p
6275 (save-excursion (org-end-of-subtree t) (point))))
6277 (defun org-first-headline-recenter (&optional N)
6278 "Move cursor to the first headline and recenter the headline.
6279 Optional argument N means put the headline into the Nth line of the window."
6280 (goto-char (point-min))
6281 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
6282 (beginning-of-line)
6283 (recenter (prefix-numeric-value N))))
6285 ;;; Saving and restoring visibility
6287 (defun org-outline-overlay-data (&optional use-markers)
6288 "Return a list of the locations of all outline overlays.
6289 These are overlays with the `invisible' property value `outline'.
6290 The return value is a list of cons cells, with start and stop
6291 positions for each overlay.
6292 If USE-MARKERS is set, return the positions as markers."
6293 (let (beg end)
6294 (save-excursion
6295 (save-restriction
6296 (widen)
6297 (delq nil
6298 (mapcar (lambda (o)
6299 (when (eq (overlay-get o 'invisible) 'outline)
6300 (setq beg (overlay-start o)
6301 end (overlay-end o))
6302 (and beg end (> end beg)
6303 (if use-markers
6304 (cons (move-marker (make-marker) beg)
6305 (move-marker (make-marker) end))
6306 (cons beg end)))))
6307 (overlays-in (point-min) (point-max))))))))
6309 (defun org-set-outline-overlay-data (data)
6310 "Create visibility overlays for all positions in DATA.
6311 DATA should have been made by `org-outline-overlay-data'."
6312 (let (o)
6313 (save-excursion
6314 (save-restriction
6315 (widen)
6316 (show-all)
6317 (mapc (lambda (c)
6318 (setq o (make-overlay (car c) (cdr c)))
6319 (overlay-put o 'invisible 'outline))
6320 data)))))
6322 ;;; Folding of blocks
6324 (defconst org-block-regexp
6326 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
6327 "Regular expression for hiding blocks.")
6329 (defvar org-hide-block-overlays nil
6330 "Overlays hiding blocks.")
6331 (make-variable-buffer-local 'org-hide-block-overlays)
6333 (defun org-block-map (function &optional start end)
6334 "Call FUNCTION at the head of all source blocks in the current buffer.
6335 Optional arguments START and END can be used to limit the range."
6336 (let ((start (or start (point-min)))
6337 (end (or end (point-max))))
6338 (save-excursion
6339 (goto-char start)
6340 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6341 (save-excursion
6342 (save-match-data
6343 (goto-char (match-beginning 0))
6344 (funcall function)))))))
6346 (defun org-hide-block-toggle-all ()
6347 "Toggle the visibility of all blocks in the current buffer."
6348 (org-block-map #'org-hide-block-toggle))
6350 (defun org-hide-block-all ()
6351 "Fold all blocks in the current buffer."
6352 (interactive)
6353 (org-show-block-all)
6354 (org-block-map #'org-hide-block-toggle-maybe))
6356 (defun org-show-block-all ()
6357 "Unfold all blocks in the current buffer."
6358 (interactive)
6359 (mapc 'delete-overlay org-hide-block-overlays)
6360 (setq org-hide-block-overlays nil))
6362 (defun org-hide-block-toggle-maybe ()
6363 "Toggle visibility of block at point."
6364 (interactive)
6365 (let ((case-fold-search t))
6366 (if (save-excursion
6367 (beginning-of-line 1)
6368 (looking-at org-block-regexp))
6369 (progn (org-hide-block-toggle)
6370 t) ;; to signal that we took action
6371 nil))) ;; to signal that we did not
6373 (defun org-hide-block-toggle (&optional force)
6374 "Toggle the visibility of the current block."
6375 (interactive)
6376 (save-excursion
6377 (beginning-of-line)
6378 (if (re-search-forward org-block-regexp nil t)
6379 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6380 (end (match-end 0)) ;; end of entire body
6382 (if (memq t (mapcar (lambda (overlay)
6383 (eq (overlay-get overlay 'invisible)
6384 'org-hide-block))
6385 (overlays-at start)))
6386 (if (or (not force) (eq force 'off))
6387 (mapc (lambda (ov)
6388 (when (member ov org-hide-block-overlays)
6389 (setq org-hide-block-overlays
6390 (delq ov org-hide-block-overlays)))
6391 (when (eq (overlay-get ov 'invisible)
6392 'org-hide-block)
6393 (delete-overlay ov)))
6394 (overlays-at start)))
6395 (setq ov (make-overlay start end))
6396 (overlay-put ov 'invisible 'org-hide-block)
6397 ;; make the block accessible to isearch
6398 (overlay-put
6399 ov 'isearch-open-invisible
6400 (lambda (ov)
6401 (when (member ov org-hide-block-overlays)
6402 (setq org-hide-block-overlays
6403 (delq ov org-hide-block-overlays)))
6404 (when (eq (overlay-get ov 'invisible)
6405 'org-hide-block)
6406 (delete-overlay ov))))
6407 (push ov org-hide-block-overlays)))
6408 (error "Not looking at a source block"))))
6410 ;; org-tab-after-check-for-cycling-hook
6411 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6412 ;; Remove overlays when changing major mode
6413 (add-hook 'org-mode-hook
6414 (lambda () (org-add-hook 'change-major-mode-hook
6415 'org-show-block-all 'append 'local)))
6417 ;;; Org-goto
6419 (defvar org-goto-window-configuration nil)
6420 (defvar org-goto-marker nil)
6421 (defvar org-goto-map
6422 (let ((map (make-sparse-keymap)))
6423 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6424 (while (setq cmd (pop cmds))
6425 (substitute-key-definition cmd cmd map global-map)))
6426 (suppress-keymap map)
6427 (org-defkey map "\C-m" 'org-goto-ret)
6428 (org-defkey map [(return)] 'org-goto-ret)
6429 (org-defkey map [(left)] 'org-goto-left)
6430 (org-defkey map [(right)] 'org-goto-right)
6431 (org-defkey map [(control ?g)] 'org-goto-quit)
6432 (org-defkey map "\C-i" 'org-cycle)
6433 (org-defkey map [(tab)] 'org-cycle)
6434 (org-defkey map [(down)] 'outline-next-visible-heading)
6435 (org-defkey map [(up)] 'outline-previous-visible-heading)
6436 (if org-goto-auto-isearch
6437 (if (fboundp 'define-key-after)
6438 (define-key-after map [t] 'org-goto-local-auto-isearch)
6439 nil)
6440 (org-defkey map "q" 'org-goto-quit)
6441 (org-defkey map "n" 'outline-next-visible-heading)
6442 (org-defkey map "p" 'outline-previous-visible-heading)
6443 (org-defkey map "f" 'outline-forward-same-level)
6444 (org-defkey map "b" 'outline-backward-same-level)
6445 (org-defkey map "u" 'outline-up-heading))
6446 (org-defkey map "/" 'org-occur)
6447 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6448 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6449 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6450 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6451 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6452 map))
6454 (defconst org-goto-help
6455 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6456 RET=jump to location [Q]uit and return to previous location
6457 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6459 (defvar org-goto-start-pos) ; dynamically scoped parameter
6461 ;; FIXME: Docstring does not mention both interfaces
6462 (defun org-goto (&optional alternative-interface)
6463 "Look up a different location in the current file, keeping current visibility.
6465 When you want look-up or go to a different location in a document, the
6466 fastest way is often to fold the entire buffer and then dive into the tree.
6467 This method has the disadvantage, that the previous location will be folded,
6468 which may not be what you want.
6470 This command works around this by showing a copy of the current buffer
6471 in an indirect buffer, in overview mode. You can dive into the tree in
6472 that copy, use org-occur and incremental search to find a location.
6473 When pressing RET or `Q', the command returns to the original buffer in
6474 which the visibility is still unchanged. After RET is will also jump to
6475 the location selected in the indirect buffer and expose the
6476 the headline hierarchy above."
6477 (interactive "P")
6478 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6479 (org-refile-use-outline-path t)
6480 (org-refile-target-verify-function nil)
6481 (interface
6482 (if (not alternative-interface)
6483 org-goto-interface
6484 (if (eq org-goto-interface 'outline)
6485 'outline-path-completion
6486 'outline)))
6487 (org-goto-start-pos (point))
6488 (selected-point
6489 (if (eq interface 'outline)
6490 (car (org-get-location (current-buffer) org-goto-help))
6491 (let ((pa (org-refile-get-location "Goto: ")))
6492 (org-refile-check-position pa)
6493 (nth 3 pa)))))
6494 (if selected-point
6495 (progn
6496 (org-mark-ring-push org-goto-start-pos)
6497 (goto-char selected-point)
6498 (if (or (org-invisible-p) (org-invisible-p2))
6499 (org-show-context 'org-goto)))
6500 (message "Quit"))))
6502 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6503 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6504 (defvar org-goto-local-auto-isearch-map) ; defined below
6506 (defun org-get-location (buf help)
6507 "Let the user select a location in the Org-mode buffer BUF.
6508 This function uses a recursive edit. It returns the selected position
6509 or nil."
6510 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6511 (isearch-hide-immediately nil)
6512 (isearch-search-fun-function
6513 (lambda () 'org-goto-local-search-headings))
6514 (org-goto-selected-point org-goto-exit-command)
6515 (pop-up-frames nil)
6516 (special-display-buffer-names nil)
6517 (special-display-regexps nil)
6518 (special-display-function nil))
6519 (save-excursion
6520 (save-window-excursion
6521 (delete-other-windows)
6522 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6523 (switch-to-buffer
6524 (condition-case nil
6525 (make-indirect-buffer (current-buffer) "*org-goto*")
6526 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6527 (with-output-to-temp-buffer "*Help*"
6528 (princ help))
6529 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6530 (setq buffer-read-only nil)
6531 (let ((org-startup-truncated t)
6532 (org-startup-folded nil)
6533 (org-startup-align-all-tables nil))
6534 (org-mode)
6535 (org-overview))
6536 (setq buffer-read-only t)
6537 (if (and (boundp 'org-goto-start-pos)
6538 (integer-or-marker-p org-goto-start-pos))
6539 (let ((org-show-hierarchy-above t)
6540 (org-show-siblings t)
6541 (org-show-following-heading t))
6542 (goto-char org-goto-start-pos)
6543 (and (org-invisible-p) (org-show-context)))
6544 (goto-char (point-min)))
6545 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6546 (message "Select location and press RET")
6547 (use-local-map org-goto-map)
6548 (recursive-edit)
6550 (kill-buffer "*org-goto*")
6551 (cons org-goto-selected-point org-goto-exit-command)))
6553 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6554 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6555 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6556 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6558 (defun org-goto-local-search-headings (string bound noerror)
6559 "Search and make sure that any matches are in headlines."
6560 (catch 'return
6561 (while (if isearch-forward
6562 (search-forward string bound noerror)
6563 (search-backward string bound noerror))
6564 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6565 (and (member :headline context)
6566 (not (member :tags context))))
6567 (throw 'return (point))))))
6569 (defun org-goto-local-auto-isearch ()
6570 "Start isearch."
6571 (interactive)
6572 (goto-char (point-min))
6573 (let ((keys (this-command-keys)))
6574 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6575 (isearch-mode t)
6576 (isearch-process-search-char (string-to-char keys)))))
6578 (defun org-goto-ret (&optional arg)
6579 "Finish `org-goto' by going to the new location."
6580 (interactive "P")
6581 (setq org-goto-selected-point (point)
6582 org-goto-exit-command 'return)
6583 (throw 'exit nil))
6585 (defun org-goto-left ()
6586 "Finish `org-goto' by going to the new location."
6587 (interactive)
6588 (if (org-on-heading-p)
6589 (progn
6590 (beginning-of-line 1)
6591 (setq org-goto-selected-point (point)
6592 org-goto-exit-command 'left)
6593 (throw 'exit nil))
6594 (error "Not on a heading")))
6596 (defun org-goto-right ()
6597 "Finish `org-goto' by going to the new location."
6598 (interactive)
6599 (if (org-on-heading-p)
6600 (progn
6601 (setq org-goto-selected-point (point)
6602 org-goto-exit-command 'right)
6603 (throw 'exit nil))
6604 (error "Not on a heading")))
6606 (defun org-goto-quit ()
6607 "Finish `org-goto' without cursor motion."
6608 (interactive)
6609 (setq org-goto-selected-point nil)
6610 (setq org-goto-exit-command 'quit)
6611 (throw 'exit nil))
6613 ;;; Indirect buffer display of subtrees
6615 (defvar org-indirect-dedicated-frame nil
6616 "This is the frame being used for indirect tree display.")
6617 (defvar org-last-indirect-buffer nil)
6619 (defun org-tree-to-indirect-buffer (&optional arg)
6620 "Create indirect buffer and narrow it to current subtree.
6621 With numerical prefix ARG, go up to this level and then take that tree.
6622 If ARG is negative, go up that many levels.
6623 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6624 indirect buffer previously made with this command, to avoid proliferation of
6625 indirect buffers. However, when you call the command with a \
6626 \\[universal-argument] prefix, or
6627 when `org-indirect-buffer-display' is `new-frame', the last buffer
6628 is kept so that you can work with several indirect buffers at the same time.
6629 If `org-indirect-buffer-display' is `dedicated-frame', the \
6630 \\[universal-argument] prefix also
6631 requests that a new frame be made for the new buffer, so that the dedicated
6632 frame is not changed."
6633 (interactive "P")
6634 (let ((cbuf (current-buffer))
6635 (cwin (selected-window))
6636 (pos (point))
6637 beg end level heading ibuf)
6638 (save-excursion
6639 (org-back-to-heading t)
6640 (when (numberp arg)
6641 (setq level (org-outline-level))
6642 (if (< arg 0) (setq arg (+ level arg)))
6643 (while (> (setq level (org-outline-level)) arg)
6644 (outline-up-heading 1 t)))
6645 (setq beg (point)
6646 heading (org-get-heading))
6647 (org-end-of-subtree t t)
6648 (if (org-on-heading-p) (backward-char 1))
6649 (setq end (point)))
6650 (if (and (buffer-live-p org-last-indirect-buffer)
6651 (not (eq org-indirect-buffer-display 'new-frame))
6652 (not arg))
6653 (kill-buffer org-last-indirect-buffer))
6654 (setq ibuf (org-get-indirect-buffer cbuf)
6655 org-last-indirect-buffer ibuf)
6656 (cond
6657 ((or (eq org-indirect-buffer-display 'new-frame)
6658 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6659 (select-frame (make-frame))
6660 (delete-other-windows)
6661 (switch-to-buffer ibuf)
6662 (org-set-frame-title heading))
6663 ((eq org-indirect-buffer-display 'dedicated-frame)
6664 (raise-frame
6665 (select-frame (or (and org-indirect-dedicated-frame
6666 (frame-live-p org-indirect-dedicated-frame)
6667 org-indirect-dedicated-frame)
6668 (setq org-indirect-dedicated-frame (make-frame)))))
6669 (delete-other-windows)
6670 (switch-to-buffer ibuf)
6671 (org-set-frame-title (concat "Indirect: " heading)))
6672 ((eq org-indirect-buffer-display 'current-window)
6673 (switch-to-buffer ibuf))
6674 ((eq org-indirect-buffer-display 'other-window)
6675 (pop-to-buffer ibuf))
6676 (t (error "Invalid value")))
6677 (if (featurep 'xemacs)
6678 (save-excursion (org-mode) (turn-on-font-lock)))
6679 (narrow-to-region beg end)
6680 (show-all)
6681 (goto-char pos)
6682 (and (window-live-p cwin) (select-window cwin))))
6684 (defun org-get-indirect-buffer (&optional buffer)
6685 (setq buffer (or buffer (current-buffer)))
6686 (let ((n 1) (base (buffer-name buffer)) bname)
6687 (while (buffer-live-p
6688 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6689 (setq n (1+ n)))
6690 (condition-case nil
6691 (make-indirect-buffer buffer bname 'clone)
6692 (error (make-indirect-buffer buffer bname)))))
6694 (defun org-set-frame-title (title)
6695 "Set the title of the current frame to the string TITLE."
6696 ;; FIXME: how to name a single frame in XEmacs???
6697 (unless (featurep 'xemacs)
6698 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6700 ;;;; Structure editing
6702 ;;; Inserting headlines
6704 (defun org-previous-line-empty-p ()
6705 (save-excursion
6706 (and (not (bobp))
6707 (or (beginning-of-line 0) t)
6708 (save-match-data
6709 (looking-at "[ \t]*$")))))
6711 (defun org-insert-heading (&optional force-heading invisible-ok)
6712 "Insert a new heading or item with same depth at point.
6713 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6714 If point is at the beginning of a headline, insert a sibling before the
6715 current headline. If point is not at the beginning, split the line,
6716 create the new headline with the text in the current line after point
6717 \(but see also the variable `org-M-RET-may-split-line').
6719 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6720 This is important for non-interactive uses of the command."
6721 (interactive "P")
6722 (if (or (= (buffer-size) 0)
6723 (and (not (save-excursion
6724 (and (ignore-errors (org-back-to-heading invisible-ok))
6725 (org-on-heading-p))))
6726 (not (org-in-item-p))))
6727 (progn
6728 (insert "\n* ")
6729 (run-hooks 'org-insert-heading-hook))
6730 (when (or force-heading (not (org-insert-item)))
6731 (let* ((empty-line-p nil)
6732 (level nil)
6733 (on-heading (org-on-heading-p))
6734 (head (save-excursion
6735 (condition-case nil
6736 (progn
6737 (org-back-to-heading invisible-ok)
6738 (when (and (not on-heading)
6739 (featurep 'org-inlinetask)
6740 (integerp org-inlinetask-min-level)
6741 (>= (length (match-string 0))
6742 org-inlinetask-min-level))
6743 ;; Find a heading level before the inline task
6744 (while (and (setq level (org-up-heading-safe))
6745 (>= level org-inlinetask-min-level)))
6746 (if (org-on-heading-p)
6747 (org-back-to-heading invisible-ok)
6748 (error "This should not happen")))
6749 (setq empty-line-p (org-previous-line-empty-p))
6750 (match-string 0))
6751 (error "*"))))
6752 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6753 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6754 pos hide-previous previous-pos)
6755 (cond
6756 ((and (org-on-heading-p) (bolp)
6757 (or (bobp)
6758 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6759 ;; insert before the current line
6760 (open-line (if blank 2 1)))
6761 ((and (bolp)
6762 (not org-insert-heading-respect-content)
6763 (or (bobp)
6764 (save-excursion
6765 (backward-char 1) (not (org-invisible-p)))))
6766 ;; insert right here
6767 nil)
6769 ;; somewhere in the line
6770 (save-excursion
6771 (setq previous-pos (point-at-bol))
6772 (end-of-line)
6773 (setq hide-previous (org-invisible-p)))
6774 (and org-insert-heading-respect-content (org-show-subtree))
6775 (let ((split
6776 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6777 (save-excursion
6778 (let ((p (point)))
6779 (goto-char (point-at-bol))
6780 (and (looking-at org-complex-heading-regexp)
6781 (> p (match-beginning 4)))))))
6782 tags pos)
6783 (cond
6784 (org-insert-heading-respect-content
6785 (org-end-of-subtree nil t)
6786 (when (featurep 'org-inlinetask)
6787 (while (and (not (eobp))
6788 (looking-at "\\(\\*+\\)[ \t]+")
6789 (>= (length (match-string 1))
6790 org-inlinetask-min-level))
6791 (org-end-of-subtree nil t)))
6792 (or (bolp) (newline))
6793 (or (org-previous-line-empty-p)
6794 (and blank (newline)))
6795 (open-line 1))
6796 ((org-on-heading-p)
6797 (when hide-previous
6798 (show-children)
6799 (org-show-entry))
6800 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
6801 (setq tags (and (match-end 2) (match-string 2)))
6802 (and (match-end 1)
6803 (delete-region (match-beginning 1) (match-end 1)))
6804 (setq pos (point-at-bol))
6805 (or split (end-of-line 1))
6806 (delete-horizontal-space)
6807 (if (string-match "\\`\\*+\\'"
6808 (buffer-substring (point-at-bol) (point)))
6809 (insert " "))
6810 (newline (if blank 2 1))
6811 (when tags
6812 (save-excursion
6813 (goto-char pos)
6814 (end-of-line 1)
6815 (insert " " tags)
6816 (org-set-tags nil 'align))))
6818 (or split (end-of-line 1))
6819 (newline (if blank 2 1)))))))
6820 (insert head) (just-one-space)
6821 (setq pos (point))
6822 (end-of-line 1)
6823 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6824 (when (and org-insert-heading-respect-content hide-previous)
6825 (save-excursion
6826 (goto-char previous-pos)
6827 (hide-subtree)))
6828 (run-hooks 'org-insert-heading-hook)))))
6830 (defun org-get-heading (&optional no-tags)
6831 "Return the heading of the current entry, without the stars."
6832 (save-excursion
6833 (org-back-to-heading t)
6834 (if (looking-at
6835 (if no-tags
6836 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@#%]+:[ \t]*\\)?$")
6837 "\\*+[ \t]+\\([^\r\n]*\\)"))
6838 (match-string 1) "")))
6840 (defun org-heading-components ()
6841 "Return the components of the current heading.
6842 This is a list with the following elements:
6843 - the level as an integer
6844 - the reduced level, different if `org-odd-levels-only' is set.
6845 - the TODO keyword, or nil
6846 - the priority character, like ?A, or nil if no priority is given
6847 - the headline text itself, or the tags string if no headline text
6848 - the tags string, or nil."
6849 (save-excursion
6850 (org-back-to-heading t)
6851 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6852 (list (length (match-string 1))
6853 (org-reduced-level (length (match-string 1)))
6854 (org-match-string-no-properties 2)
6855 (and (match-end 3) (aref (match-string 3) 2))
6856 (org-match-string-no-properties 4)
6857 (org-match-string-no-properties 5)))))
6859 (defun org-get-entry ()
6860 "Get the entry text, after heading, entire subtree."
6861 (save-excursion
6862 (org-back-to-heading t)
6863 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6865 (defun org-insert-heading-after-current ()
6866 "Insert a new heading with same level as current, after current subtree."
6867 (interactive)
6868 (org-back-to-heading)
6869 (org-insert-heading)
6870 (org-move-subtree-down)
6871 (end-of-line 1))
6873 (defun org-insert-heading-respect-content ()
6874 (interactive)
6875 (let ((org-insert-heading-respect-content t))
6876 (org-insert-heading t)))
6878 (defun org-insert-todo-heading-respect-content (&optional force-state)
6879 (interactive "P")
6880 (let ((org-insert-heading-respect-content t))
6881 (org-insert-todo-heading force-state t)))
6883 (defun org-insert-todo-heading (arg &optional force-heading)
6884 "Insert a new heading with the same level and TODO state as current heading.
6885 If the heading has no TODO state, or if the state is DONE, use the first
6886 state (TODO by default). Also with prefix arg, force first state."
6887 (interactive "P")
6888 (when (or force-heading (not (org-insert-item 'checkbox)))
6889 (org-insert-heading force-heading)
6890 (save-excursion
6891 (org-back-to-heading)
6892 (outline-previous-heading)
6893 (looking-at org-todo-line-regexp))
6894 (let*
6895 ((new-mark-x
6896 (if (or arg
6897 (not (match-beginning 2))
6898 (member (match-string 2) org-done-keywords))
6899 (car org-todo-keywords-1)
6900 (match-string 2)))
6901 (new-mark
6903 (run-hook-with-args-until-success
6904 'org-todo-get-default-hook new-mark-x nil)
6905 new-mark-x)))
6906 (beginning-of-line 1)
6907 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6908 (if org-treat-insert-todo-heading-as-state-change
6909 (org-todo new-mark)
6910 (insert new-mark " "))))
6911 (when org-provide-todo-statistics
6912 (org-update-parent-todo-statistics))))
6914 (defun org-insert-subheading (arg)
6915 "Insert a new subheading and demote it.
6916 Works for outline headings and for plain lists alike."
6917 (interactive "P")
6918 (org-insert-heading arg)
6919 (cond
6920 ((org-on-heading-p) (org-do-demote))
6921 ((org-at-item-p) (org-indent-item))))
6923 (defun org-insert-todo-subheading (arg)
6924 "Insert a new subheading with TODO keyword or checkbox and demote it.
6925 Works for outline headings and for plain lists alike."
6926 (interactive "P")
6927 (org-insert-todo-heading arg)
6928 (cond
6929 ((org-on-heading-p) (org-do-demote))
6930 ((org-at-item-p) (org-indent-item))))
6932 ;;; Promotion and Demotion
6934 (defvar org-after-demote-entry-hook nil
6935 "Hook run after an entry has been demoted.
6936 The cursor will be at the beginning of the entry.
6937 When a subtree is being demoted, the hook will be called for each node.")
6939 (defvar org-after-promote-entry-hook nil
6940 "Hook run after an entry has been promoted.
6941 The cursor will be at the beginning of the entry.
6942 When a subtree is being promoted, the hook will be called for each node.")
6944 (defun org-promote-subtree ()
6945 "Promote the entire subtree.
6946 See also `org-promote'."
6947 (interactive)
6948 (save-excursion
6949 (org-map-tree 'org-promote))
6950 (org-fix-position-after-promote))
6952 (defun org-demote-subtree ()
6953 "Demote the entire subtree. See `org-demote'.
6954 See also `org-promote'."
6955 (interactive)
6956 (save-excursion
6957 (org-map-tree 'org-demote))
6958 (org-fix-position-after-promote))
6961 (defun org-do-promote ()
6962 "Promote the current heading higher up the tree.
6963 If the region is active in `transient-mark-mode', promote all headings
6964 in the region."
6965 (interactive)
6966 (save-excursion
6967 (if (org-region-active-p)
6968 (org-map-region 'org-promote (region-beginning) (region-end))
6969 (org-promote)))
6970 (org-fix-position-after-promote))
6972 (defun org-do-demote ()
6973 "Demote the current heading lower down the tree.
6974 If the region is active in `transient-mark-mode', demote all headings
6975 in the region."
6976 (interactive)
6977 (save-excursion
6978 (if (org-region-active-p)
6979 (org-map-region 'org-demote (region-beginning) (region-end))
6980 (org-demote)))
6981 (org-fix-position-after-promote))
6983 (defun org-fix-position-after-promote ()
6984 "Make sure that after pro/demotion cursor position is right."
6985 (let ((pos (point)))
6986 (when (save-excursion
6987 (beginning-of-line 1)
6988 (looking-at org-todo-line-regexp)
6989 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6990 (cond ((eobp) (insert " "))
6991 ((eolp) (insert " "))
6992 ((equal (char-after) ?\ ) (forward-char 1))))))
6994 (defun org-current-level ()
6995 "Return the level of the current entry, or nil if before the first headline.
6996 The level is the number of stars at the beginning of the headline."
6997 (save-excursion
6998 (condition-case nil
6999 (progn
7000 (org-back-to-heading t)
7001 (funcall outline-level))
7002 (error nil))))
7004 (defun org-get-previous-line-level ()
7005 "Return the outline depth of the last headline before the current line.
7006 Returns 0 for the first headline in the buffer, and nil if before the
7007 first headline."
7008 (let ((current-level (org-current-level))
7009 (prev-level (when (> (line-number-at-pos) 1)
7010 (save-excursion
7011 (beginning-of-line 0)
7012 (org-current-level)))))
7013 (cond ((null current-level) nil) ; Before first headline
7014 ((null prev-level) 0) ; At first headline
7015 (prev-level))))
7017 (defun org-reduced-level (l)
7018 "Compute the effective level of a heading.
7019 This takes into account the setting of `org-odd-levels-only'."
7020 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
7022 (defun org-level-increment ()
7023 "Return the number of stars that will be added or removed at a
7024 time to headlines when structure editing, based on the value of
7025 `org-odd-levels-only'."
7026 (if org-odd-levels-only 2 1))
7028 (defun org-get-valid-level (level &optional change)
7029 "Rectify a level change under the influence of `org-odd-levels-only'
7030 LEVEL is a current level, CHANGE is by how much the level should be
7031 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7032 even level numbers will become the next higher odd number."
7033 (if org-odd-levels-only
7034 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7035 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7036 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7037 (max 1 (+ level (or change 0)))))
7039 (if (boundp 'define-obsolete-function-alias)
7040 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7041 (define-obsolete-function-alias 'org-get-legal-level
7042 'org-get-valid-level)
7043 (define-obsolete-function-alias 'org-get-legal-level
7044 'org-get-valid-level "23.1")))
7046 (defun org-promote ()
7047 "Promote the current heading higher up the tree.
7048 If the region is active in `transient-mark-mode', promote all headings
7049 in the region."
7050 (org-back-to-heading t)
7051 (let* ((level (save-match-data (funcall outline-level)))
7052 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7053 (diff (abs (- level (length up-head) -1))))
7054 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7055 (replace-match up-head nil t)
7056 ;; Fixup tag positioning
7057 (and org-auto-align-tags (org-set-tags nil t))
7058 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7059 (run-hooks 'org-after-promote-entry-hook)))
7061 (defun org-demote ()
7062 "Demote the current heading lower down the tree.
7063 If the region is active in `transient-mark-mode', demote all headings
7064 in the region."
7065 (org-back-to-heading t)
7066 (let* ((level (save-match-data (funcall outline-level)))
7067 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7068 (diff (abs (- level (length down-head) -1))))
7069 (replace-match down-head nil t)
7070 ;; Fixup tag positioning
7071 (and org-auto-align-tags (org-set-tags nil t))
7072 (if org-adapt-indentation (org-fixup-indentation diff))
7073 (run-hooks 'org-after-demote-entry-hook)))
7075 (defun org-cycle-level ()
7076 "Cycle the level of an empty headline through possible states.
7077 This goes first to child, then to parent, level, then up the hierarchy.
7078 After top level, it switches back to sibling level."
7079 (interactive)
7080 (let ((org-adapt-indentation nil))
7081 (when (org-point-at-end-of-empty-headline)
7082 (setq this-command 'org-cycle-level) ; Only needed for caching
7083 (let ((cur-level (org-current-level))
7084 (prev-level (org-get-previous-line-level)))
7085 (cond
7086 ;; If first headline in file, promote to top-level.
7087 ((= prev-level 0)
7088 (loop repeat (/ (- cur-level 1) (org-level-increment))
7089 do (org-do-promote)))
7090 ;; If same level as prev, demote one.
7091 ((= prev-level cur-level)
7092 (org-do-demote))
7093 ;; If parent is top-level, promote to top level if not already.
7094 ((= prev-level 1)
7095 (loop repeat (/ (- cur-level 1) (org-level-increment))
7096 do (org-do-promote)))
7097 ;; If top-level, return to prev-level.
7098 ((= cur-level 1)
7099 (loop repeat (/ (- prev-level 1) (org-level-increment))
7100 do (org-do-demote)))
7101 ;; If less than prev-level, promote one.
7102 ((< cur-level prev-level)
7103 (org-do-promote))
7104 ;; If deeper than prev-level, promote until higher than
7105 ;; prev-level.
7106 ((> cur-level prev-level)
7107 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7108 do (org-do-promote))))
7109 t))))
7111 (defun org-map-tree (fun)
7112 "Call FUN for every heading underneath the current one."
7113 (org-back-to-heading)
7114 (let ((level (funcall outline-level)))
7115 (save-excursion
7116 (funcall fun)
7117 (while (and (progn
7118 (outline-next-heading)
7119 (> (funcall outline-level) level))
7120 (not (eobp)))
7121 (funcall fun)))))
7123 (defun org-map-region (fun beg end)
7124 "Call FUN for every heading between BEG and END."
7125 (let ((org-ignore-region t))
7126 (save-excursion
7127 (setq end (copy-marker end))
7128 (goto-char beg)
7129 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
7130 (< (point) end))
7131 (funcall fun))
7132 (while (and (progn
7133 (outline-next-heading)
7134 (< (point) end))
7135 (not (eobp)))
7136 (funcall fun)))))
7138 (defun org-fixup-indentation (diff)
7139 "Change the indentation in the current entry by DIFF.
7140 However, if any line in the current entry has no indentation, or if it
7141 would end up with no indentation after the change, nothing at all is done."
7142 (save-excursion
7143 (let ((end (save-excursion (outline-next-heading)
7144 (point-marker)))
7145 (prohibit (if (> diff 0)
7146 "^\\S-"
7147 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7148 col)
7149 (unless (save-excursion (end-of-line 1)
7150 (re-search-forward prohibit end t))
7151 (while (and (< (point) end)
7152 (re-search-forward "^[ \t]+" end t))
7153 (goto-char (match-end 0))
7154 (setq col (current-column))
7155 (if (< diff 0) (replace-match ""))
7156 (org-indent-to-column (+ diff col))))
7157 (move-marker end nil))))
7159 (defun org-convert-to-odd-levels ()
7160 "Convert an org-mode file with all levels allowed to one with odd levels.
7161 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7162 level 5 etc."
7163 (interactive)
7164 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7165 (let ((outline-regexp org-outline-regexp)
7166 (outline-level 'org-outline-level)
7167 (org-odd-levels-only nil) n)
7168 (save-excursion
7169 (goto-char (point-min))
7170 (while (re-search-forward "^\\*\\*+ " nil t)
7171 (setq n (- (length (match-string 0)) 2))
7172 (while (>= (setq n (1- n)) 0)
7173 (org-demote))
7174 (end-of-line 1))))))
7176 (defun org-convert-to-oddeven-levels ()
7177 "Convert an org-mode file with only odd levels to one with odd/even levels.
7178 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7179 file contains a section with an even level, conversion would
7180 destroy the structure of the file. An error is signaled in this
7181 case."
7182 (interactive)
7183 (goto-char (point-min))
7184 ;; First check if there are no even levels
7185 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7186 (org-show-context t)
7187 (error "Not all levels are odd in this file. Conversion not possible"))
7188 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7189 (let ((outline-regexp org-outline-regexp)
7190 (outline-level 'org-outline-level)
7191 (org-odd-levels-only nil) n)
7192 (save-excursion
7193 (goto-char (point-min))
7194 (while (re-search-forward "^\\*\\*+ " nil t)
7195 (setq n (/ (1- (length (match-string 0))) 2))
7196 (while (>= (setq n (1- n)) 0)
7197 (org-promote))
7198 (end-of-line 1))))))
7200 (defun org-tr-level (n)
7201 "Make N odd if required."
7202 (if org-odd-levels-only (1+ (/ n 2)) n))
7204 ;;; Vertical tree motion, cutting and pasting of subtrees
7206 (defun org-move-subtree-up (&optional arg)
7207 "Move the current subtree up past ARG headlines of the same level."
7208 (interactive "p")
7209 (org-move-subtree-down (- (prefix-numeric-value arg))))
7211 (defun org-move-subtree-down (&optional arg)
7212 "Move the current subtree down past ARG headlines of the same level."
7213 (interactive "p")
7214 (setq arg (prefix-numeric-value arg))
7215 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7216 'org-get-last-sibling))
7217 (ins-point (make-marker))
7218 (cnt (abs arg))
7219 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7220 ;; Select the tree
7221 (org-back-to-heading)
7222 (setq beg0 (point))
7223 (save-excursion
7224 (setq ne-beg (org-back-over-empty-lines))
7225 (setq beg (point)))
7226 (save-match-data
7227 (save-excursion (outline-end-of-heading)
7228 (setq folded (org-invisible-p)))
7229 (outline-end-of-subtree))
7230 (outline-next-heading)
7231 (setq ne-end (org-back-over-empty-lines))
7232 (setq end (point))
7233 (goto-char beg0)
7234 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7235 ;; include less whitespace
7236 (save-excursion
7237 (goto-char beg)
7238 (forward-line (- ne-beg ne-end))
7239 (setq beg (point))))
7240 ;; Find insertion point, with error handling
7241 (while (> cnt 0)
7242 (or (and (funcall movfunc) (looking-at outline-regexp))
7243 (progn (goto-char beg0)
7244 (error "Cannot move past superior level or buffer limit")))
7245 (setq cnt (1- cnt)))
7246 (if (> arg 0)
7247 ;; Moving forward - still need to move over subtree
7248 (progn (org-end-of-subtree t t)
7249 (save-excursion
7250 (org-back-over-empty-lines)
7251 (or (bolp) (newline)))))
7252 (setq ne-ins (org-back-over-empty-lines))
7253 (move-marker ins-point (point))
7254 (setq txt (buffer-substring beg end))
7255 (org-save-markers-in-region beg end)
7256 (delete-region beg end)
7257 (org-remove-empty-overlays-at beg)
7258 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7259 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7260 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7261 (let ((bbb (point)))
7262 (insert-before-markers txt)
7263 (org-reinstall-markers-in-region bbb)
7264 (move-marker ins-point bbb))
7265 (or (bolp) (insert "\n"))
7266 (setq ins-end (point))
7267 (goto-char ins-point)
7268 (org-skip-whitespace)
7269 (when (and (< arg 0)
7270 (org-first-sibling-p)
7271 (> ne-ins ne-beg))
7272 ;; Move whitespace back to beginning
7273 (save-excursion
7274 (goto-char ins-end)
7275 (let ((kill-whole-line t))
7276 (kill-line (- ne-ins ne-beg)) (point)))
7277 (insert (make-string (- ne-ins ne-beg) ?\n)))
7278 (move-marker ins-point nil)
7279 (if folded
7280 (hide-subtree)
7281 (org-show-entry)
7282 (show-children)
7283 (org-cycle-hide-drawers 'children))
7284 (org-clean-visibility-after-subtree-move)))
7286 (defvar org-subtree-clip ""
7287 "Clipboard for cut and paste of subtrees.
7288 This is actually only a copy of the kill, because we use the normal kill
7289 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7291 (defvar org-subtree-clip-folded nil
7292 "Was the last copied subtree folded?
7293 This is used to fold the tree back after pasting.")
7295 (defun org-cut-subtree (&optional n)
7296 "Cut the current subtree into the clipboard.
7297 With prefix arg N, cut this many sequential subtrees.
7298 This is a short-hand for marking the subtree and then cutting it."
7299 (interactive "p")
7300 (org-copy-subtree n 'cut))
7302 (defun org-copy-subtree (&optional n cut force-store-markers)
7303 "Cut the current subtree into the clipboard.
7304 With prefix arg N, cut this many sequential subtrees.
7305 This is a short-hand for marking the subtree and then copying it.
7306 If CUT is non-nil, actually cut the subtree.
7307 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7308 of some markers in the region, even if CUT is non-nil. This is
7309 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7310 (interactive "p")
7311 (let (beg end folded (beg0 (point)))
7312 (if (interactive-p)
7313 (org-back-to-heading nil) ; take what looks like a subtree
7314 (org-back-to-heading t)) ; take what is really there
7315 (org-back-over-empty-lines)
7316 (setq beg (point))
7317 (skip-chars-forward " \t\r\n")
7318 (save-match-data
7319 (save-excursion (outline-end-of-heading)
7320 (setq folded (org-invisible-p)))
7321 (condition-case nil
7322 (org-forward-same-level (1- n) t)
7323 (error nil))
7324 (org-end-of-subtree t t))
7325 (org-back-over-empty-lines)
7326 (setq end (point))
7327 (goto-char beg0)
7328 (when (> end beg)
7329 (setq org-subtree-clip-folded folded)
7330 (when (or cut force-store-markers)
7331 (org-save-markers-in-region beg end))
7332 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7333 (setq org-subtree-clip (current-kill 0))
7334 (message "%s: Subtree(s) with %d characters"
7335 (if cut "Cut" "Copied")
7336 (length org-subtree-clip)))))
7338 (defun org-paste-subtree (&optional level tree for-yank)
7339 "Paste the clipboard as a subtree, with modification of headline level.
7340 The entire subtree is promoted or demoted in order to match a new headline
7341 level.
7343 If the cursor is at the beginning of a headline, the same level as
7344 that headline is used to paste the tree
7346 If not, the new level is derived from the *visible* headings
7347 before and after the insertion point, and taken to be the inferior headline
7348 level of the two. So if the previous visible heading is level 3 and the
7349 next is level 4 (or vice versa), level 4 will be used for insertion.
7350 This makes sure that the subtree remains an independent subtree and does
7351 not swallow low level entries.
7353 You can also force a different level, either by using a numeric prefix
7354 argument, or by inserting the heading marker by hand. For example, if the
7355 cursor is after \"*****\", then the tree will be shifted to level 5.
7357 If optional TREE is given, use this text instead of the kill ring.
7359 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7360 move back over whitespace before inserting, and move point to the end of
7361 the inserted text when done."
7362 (interactive "P")
7363 (setq tree (or tree (and kill-ring (current-kill 0))))
7364 (unless (org-kill-is-subtree-p tree)
7365 (error "%s"
7366 (substitute-command-keys
7367 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7368 (let* ((visp (not (org-invisible-p)))
7369 (txt tree)
7370 (^re (concat "^\\(" outline-regexp "\\)"))
7371 (re (concat "\\(" outline-regexp "\\)"))
7372 (^re_ (concat "\\(\\*+\\)[ \t]*"))
7374 (old-level (if (string-match ^re txt)
7375 (- (match-end 0) (match-beginning 0) 1)
7376 -1))
7377 (force-level (cond (level (prefix-numeric-value level))
7378 ((and (looking-at "[ \t]*$")
7379 (string-match
7380 ^re_ (buffer-substring
7381 (point-at-bol) (point))))
7382 (- (match-end 1) (match-beginning 1)))
7383 ((and (bolp)
7384 (looking-at org-outline-regexp))
7385 (- (match-end 0) (point) 1))
7386 (t nil)))
7387 (previous-level (save-excursion
7388 (condition-case nil
7389 (progn
7390 (outline-previous-visible-heading 1)
7391 (if (looking-at re)
7392 (- (match-end 0) (match-beginning 0) 1)
7394 (error 1))))
7395 (next-level (save-excursion
7396 (condition-case nil
7397 (progn
7398 (or (looking-at outline-regexp)
7399 (outline-next-visible-heading 1))
7400 (if (looking-at re)
7401 (- (match-end 0) (match-beginning 0) 1)
7403 (error 1))))
7404 (new-level (or force-level (max previous-level next-level)))
7405 (shift (if (or (= old-level -1)
7406 (= new-level -1)
7407 (= old-level new-level))
7409 (- new-level old-level)))
7410 (delta (if (> shift 0) -1 1))
7411 (func (if (> shift 0) 'org-demote 'org-promote))
7412 (org-odd-levels-only nil)
7413 beg end newend)
7414 ;; Remove the forced level indicator
7415 (if force-level
7416 (delete-region (point-at-bol) (point)))
7417 ;; Paste
7418 (beginning-of-line 1)
7419 (unless for-yank (org-back-over-empty-lines))
7420 (setq beg (point))
7421 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7422 (insert-before-markers txt)
7423 (unless (string-match "\n\\'" txt) (insert "\n"))
7424 (setq newend (point))
7425 (org-reinstall-markers-in-region beg)
7426 (setq end (point))
7427 (goto-char beg)
7428 (skip-chars-forward " \t\n\r")
7429 (setq beg (point))
7430 (if (and (org-invisible-p) visp)
7431 (save-excursion (outline-show-heading)))
7432 ;; Shift if necessary
7433 (unless (= shift 0)
7434 (save-restriction
7435 (narrow-to-region beg end)
7436 (while (not (= shift 0))
7437 (org-map-region func (point-min) (point-max))
7438 (setq shift (+ delta shift)))
7439 (goto-char (point-min))
7440 (setq newend (point-max))))
7441 (when (or (interactive-p) for-yank)
7442 (message "Clipboard pasted as level %d subtree" new-level))
7443 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7444 kill-ring
7445 (eq org-subtree-clip (current-kill 0))
7446 org-subtree-clip-folded)
7447 ;; The tree was folded before it was killed/copied
7448 (hide-subtree))
7449 (and for-yank (goto-char newend))))
7451 (defun org-kill-is-subtree-p (&optional txt)
7452 "Check if the current kill is an outline subtree, or a set of trees.
7453 Returns nil if kill does not start with a headline, or if the first
7454 headline level is not the largest headline level in the tree.
7455 So this will actually accept several entries of equal levels as well,
7456 which is OK for `org-paste-subtree'.
7457 If optional TXT is given, check this string instead of the current kill."
7458 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7459 (start-level (and kill
7460 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
7461 org-outline-regexp "\\)")
7462 kill)
7463 (- (match-end 2) (match-beginning 2) 1)))
7464 (re (concat "^" org-outline-regexp))
7465 (start (1+ (or (match-beginning 2) -1))))
7466 (if (not start-level)
7467 (progn
7468 nil) ;; does not even start with a heading
7469 (catch 'exit
7470 (while (setq start (string-match re kill (1+ start)))
7471 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7472 (throw 'exit nil)))
7473 t))))
7475 (defvar org-markers-to-move nil
7476 "Markers that should be moved with a cut-and-paste operation.
7477 Those markers are stored together with their positions relative to
7478 the start of the region.")
7480 (defun org-save-markers-in-region (beg end)
7481 "Check markers in region.
7482 If these markers are between BEG and END, record their position relative
7483 to BEG, so that after moving the block of text, we can put the markers back
7484 into place.
7485 This function gets called just before an entry or tree gets cut from the
7486 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7487 called immediately, to move the markers with the entries."
7488 (setq org-markers-to-move nil)
7489 (when (featurep 'org-clock)
7490 (org-clock-save-markers-for-cut-and-paste beg end))
7491 (when (featurep 'org-agenda)
7492 (org-agenda-save-markers-for-cut-and-paste beg end)))
7494 (defun org-check-and-save-marker (marker beg end)
7495 "Check if MARKER is between BEG and END.
7496 If yes, remember the marker and the distance to BEG."
7497 (when (and (marker-buffer marker)
7498 (equal (marker-buffer marker) (current-buffer)))
7499 (if (and (>= marker beg) (< marker end))
7500 (push (cons marker (- marker beg)) org-markers-to-move))))
7502 (defun org-reinstall-markers-in-region (beg)
7503 "Move all remembered markers to their position relative to BEG."
7504 (mapc (lambda (x)
7505 (move-marker (car x) (+ beg (cdr x))))
7506 org-markers-to-move)
7507 (setq org-markers-to-move nil))
7509 (defun org-narrow-to-subtree ()
7510 "Narrow buffer to the current subtree."
7511 (interactive)
7512 (save-excursion
7513 (save-match-data
7514 (narrow-to-region
7515 (progn (org-back-to-heading t) (point))
7516 (progn (org-end-of-subtree t t)
7517 (if (and (org-on-heading-p) (not (eobp))) (backward-char 1))
7518 (point))))))
7520 (eval-when-compile
7521 (defvar org-property-drawer-re))
7523 (defun org-clone-subtree-with-time-shift (n &optional shift)
7524 "Clone the task (subtree) at point N times.
7525 The clones will be inserted as siblings.
7527 In interactive use, the user will be prompted for the number of
7528 clones to be produced, and for a time SHIFT, which may be a
7529 repeater as used in time stamps, for example `+3d'.
7531 When a valid repeater is given and the entry contains any time
7532 stamps, the clones will become a sequence in time, with time
7533 stamps in the subtree shifted for each clone produced. If SHIFT
7534 is nil or the empty string, time stamps will be left alone. The
7535 ID property of the original subtree is removed.
7537 If the original subtree did contain time stamps with a repeater,
7538 the following will happen:
7539 - the repeater will be removed in each clone
7540 - an additional clone will be produced, with the current, unshifted
7541 date(s) in the entry.
7542 - the original entry will be placed *after* all the clones, with
7543 repeater intact.
7544 - the start days in the repeater in the original entry will be shifted
7545 to past the last clone.
7546 I this way you can spell out a number of instances of a repeating task,
7547 and still retain the repeater to cover future instances of the task."
7548 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7549 (let (beg end template task idprop
7550 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7551 (if (not (and (integerp n) (> n 0)))
7552 (error "Invalid number of replications %s" n))
7553 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7554 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7555 shift)))
7556 (error "Invalid shift specification %s" shift))
7557 (when doshift
7558 (setq shift-n (string-to-number (match-string 1 shift))
7559 shift-what (cdr (assoc (match-string 2 shift)
7560 '(("d" . day) ("w" . week)
7561 ("m" . month) ("y" . year))))))
7562 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7563 (setq nmin 1 nmax n)
7564 (org-back-to-heading t)
7565 (setq beg (point))
7566 (setq idprop (org-entry-get nil "ID"))
7567 (org-end-of-subtree t t)
7568 (or (bolp) (insert "\n"))
7569 (setq end (point))
7570 (setq template (buffer-substring beg end))
7571 (when (and doshift
7572 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7573 (delete-region beg end)
7574 (setq end beg)
7575 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7576 (goto-char end)
7577 (loop for n from nmin to nmax do
7578 ;; prepare clone
7579 (with-temp-buffer
7580 (insert template)
7581 (org-mode)
7582 (goto-char (point-min))
7583 (and idprop (if org-clone-delete-id
7584 (org-entry-delete nil "ID")
7585 (org-id-get-create t)))
7586 (while (re-search-forward org-property-drawer-re nil t)
7587 (org-remove-empty-drawer-at "PROPERTIES" (point)))
7588 (goto-char (point-min))
7589 (when doshift
7590 (while (re-search-forward org-ts-regexp-both nil t)
7591 (org-timestamp-change (* n shift-n) shift-what))
7592 (unless (= n n-no-remove)
7593 (goto-char (point-min))
7594 (while (re-search-forward org-ts-regexp nil t)
7595 (save-excursion
7596 (goto-char (match-beginning 0))
7597 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7598 (delete-region (match-beginning 1) (match-end 1)))))))
7599 (setq task (buffer-string)))
7600 (insert task))
7601 (goto-char beg)))
7603 ;;; Outline Sorting
7605 (defun org-sort (with-case)
7606 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
7607 Optional argument WITH-CASE means sort case-sensitively.
7608 With a double prefix argument, also remove duplicate entries."
7609 (interactive "P")
7610 (cond
7611 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
7612 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
7614 (org-call-with-arg 'org-sort-entries with-case))))
7616 (defun org-sort-remove-invisible (s)
7617 (remove-text-properties 0 (length s) org-rm-props s)
7618 (while (string-match org-bracket-link-regexp s)
7619 (setq s (replace-match (if (match-end 2)
7620 (match-string 3 s)
7621 (match-string 1 s)) t t s)))
7624 (defvar org-priority-regexp) ; defined later in the file
7626 (defvar org-after-sorting-entries-or-items-hook nil
7627 "Hook that is run after a bunch of entries or items have been sorted.
7628 When children are sorted, the cursor is in the parent line when this
7629 hook gets called. When a region or a plain list is sorted, the cursor
7630 will be in the first entry of the sorted region/list.")
7632 (defun org-sort-entries
7633 (&optional with-case sorting-type getkey-func compare-func property)
7634 "Sort entries on a certain level of an outline tree.
7635 If there is an active region, the entries in the region are sorted.
7636 Else, if the cursor is before the first entry, sort the top-level items.
7637 Else, the children of the entry at point are sorted.
7639 Sorting can be alphabetically, numerically, by date/time as given by
7640 a time stamp, by a property or by priority.
7642 The command prompts for the sorting type unless it has been given to the
7643 function through the SORTING-TYPE argument, which needs to be a character,
7644 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7645 precise meaning of each character:
7647 n Numerically, by converting the beginning of the entry/item to a number.
7648 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7649 t By date/time, either the first active time stamp in the entry, or, if
7650 none exist, by the first inactive one.
7651 s By the scheduled date/time.
7652 d By deadline date/time.
7653 c By creation time, which is assumed to be the first inactive time stamp
7654 at the beginning of a line.
7655 p By priority according to the cookie.
7656 r By the value of a property.
7658 Capital letters will reverse the sort order.
7660 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7661 called with point at the beginning of the record. It must return either
7662 a string or a number that should serve as the sorting key for that record.
7664 Comparing entries ignores case by default. However, with an optional argument
7665 WITH-CASE, the sorting considers case as well."
7666 (interactive "P")
7667 (let ((case-func (if with-case 'identity 'downcase))
7668 start beg end stars re re2
7669 txt what tmp)
7670 ;; Find beginning and end of region to sort
7671 (cond
7672 ((org-region-active-p)
7673 ;; we will sort the region
7674 (setq end (region-end)
7675 what "region")
7676 (goto-char (region-beginning))
7677 (if (not (org-on-heading-p)) (outline-next-heading))
7678 (setq start (point)))
7679 ((or (org-on-heading-p)
7680 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7681 ;; we will sort the children of the current headline
7682 (org-back-to-heading)
7683 (setq start (point)
7684 end (progn (org-end-of-subtree t t)
7685 (or (bolp) (insert "\n"))
7686 (org-back-over-empty-lines)
7687 (point))
7688 what "children")
7689 (goto-char start)
7690 (show-subtree)
7691 (outline-next-heading))
7693 ;; we will sort the top-level entries in this file
7694 (goto-char (point-min))
7695 (or (org-on-heading-p) (outline-next-heading))
7696 (setq start (point))
7697 (goto-char (point-max))
7698 (beginning-of-line 1)
7699 (when (looking-at ".*?\\S-")
7700 ;; File ends in a non-white line
7701 (end-of-line 1)
7702 (insert "\n"))
7703 (setq end (point-max))
7704 (setq what "top-level")
7705 (goto-char start)
7706 (show-all)))
7708 (setq beg (point))
7709 (if (>= beg end) (error "Nothing to sort"))
7711 (looking-at "\\(\\*+\\)")
7712 (setq stars (match-string 1)
7713 re (concat "^" (regexp-quote stars) " +")
7714 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7715 txt (buffer-substring beg end))
7716 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7717 (if (and (not (equal stars "*")) (string-match re2 txt))
7718 (error "Region to sort contains a level above the first entry"))
7720 (unless sorting-type
7721 (message
7722 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7723 [t]ime [s]cheduled [d]eadline [c]reated
7724 A/N/T/S/D/C/P/O/F means reversed:"
7725 what)
7726 (setq sorting-type (read-char-exclusive))
7728 (and (= (downcase sorting-type) ?f)
7729 (setq getkey-func
7730 (org-icompleting-read "Sort using function: "
7731 obarray 'fboundp t nil nil))
7732 (setq getkey-func (intern getkey-func)))
7734 (and (= (downcase sorting-type) ?r)
7735 (setq property
7736 (org-icompleting-read "Property: "
7737 (mapcar 'list (org-buffer-property-keys t))
7738 nil t))))
7740 (message "Sorting entries...")
7742 (save-restriction
7743 (narrow-to-region start end)
7744 (let ((dcst (downcase sorting-type))
7745 (case-fold-search nil)
7746 (now (current-time)))
7747 (sort-subr
7748 (/= dcst sorting-type)
7749 ;; This function moves to the beginning character of the "record" to
7750 ;; be sorted.
7751 (lambda nil
7752 (if (re-search-forward re nil t)
7753 (goto-char (match-beginning 0))
7754 (goto-char (point-max))))
7755 ;; This function moves to the last character of the "record" being
7756 ;; sorted.
7757 (lambda nil
7758 (save-match-data
7759 (condition-case nil
7760 (outline-forward-same-level 1)
7761 (error
7762 (goto-char (point-max))))))
7763 ;; This function returns the value that gets sorted against.
7764 (lambda nil
7765 (cond
7766 ((= dcst ?n)
7767 (if (looking-at org-complex-heading-regexp)
7768 (string-to-number (match-string 4))
7769 nil))
7770 ((= dcst ?a)
7771 (if (looking-at org-complex-heading-regexp)
7772 (funcall case-func (match-string 4))
7773 nil))
7774 ((= dcst ?t)
7775 (let ((end (save-excursion (outline-next-heading) (point))))
7776 (if (or (re-search-forward org-ts-regexp end t)
7777 (re-search-forward org-ts-regexp-both end t))
7778 (org-time-string-to-seconds (match-string 0))
7779 (org-float-time now))))
7780 ((= dcst ?c)
7781 (let ((end (save-excursion (outline-next-heading) (point))))
7782 (if (re-search-forward
7783 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7784 end t)
7785 (org-time-string-to-seconds (match-string 0))
7786 (org-float-time now))))
7787 ((= dcst ?s)
7788 (let ((end (save-excursion (outline-next-heading) (point))))
7789 (if (re-search-forward org-scheduled-time-regexp end t)
7790 (org-time-string-to-seconds (match-string 1))
7791 (org-float-time now))))
7792 ((= dcst ?d)
7793 (let ((end (save-excursion (outline-next-heading) (point))))
7794 (if (re-search-forward org-deadline-time-regexp end t)
7795 (org-time-string-to-seconds (match-string 1))
7796 (org-float-time now))))
7797 ((= dcst ?p)
7798 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7799 (string-to-char (match-string 2))
7800 org-default-priority))
7801 ((= dcst ?r)
7802 (or (org-entry-get nil property) ""))
7803 ((= dcst ?o)
7804 (if (looking-at org-complex-heading-regexp)
7805 (- 9999 (length (member (match-string 2)
7806 org-todo-keywords-1)))))
7807 ((= dcst ?f)
7808 (if getkey-func
7809 (progn
7810 (setq tmp (funcall getkey-func))
7811 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7812 tmp)
7813 (error "Invalid key function `%s'" getkey-func)))
7814 (t (error "Invalid sorting type `%c'" sorting-type))))
7816 (cond
7817 ((= dcst ?a) 'string<)
7818 ((= dcst ?f) compare-func)
7819 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7820 (t nil)))))
7821 (run-hooks 'org-after-sorting-entries-or-items-hook)
7822 (message "Sorting entries...done")))
7824 (defun org-do-sort (table what &optional with-case sorting-type)
7825 "Sort TABLE of WHAT according to SORTING-TYPE.
7826 The user will be prompted for the SORTING-TYPE if the call to this
7827 function does not specify it. WHAT is only for the prompt, to indicate
7828 what is being sorted. The sorting key will be extracted from
7829 the car of the elements of the table.
7830 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7831 (unless sorting-type
7832 (message
7833 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7834 what)
7835 (setq sorting-type (read-char-exclusive)))
7836 (let ((dcst (downcase sorting-type))
7837 extractfun comparefun)
7838 ;; Define the appropriate functions
7839 (cond
7840 ((= dcst ?n)
7841 (setq extractfun 'string-to-number
7842 comparefun (if (= dcst sorting-type) '< '>)))
7843 ((= dcst ?a)
7844 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7845 (lambda(x) (downcase (org-sort-remove-invisible x))))
7846 comparefun (if (= dcst sorting-type)
7847 'string<
7848 (lambda (a b) (and (not (string< a b))
7849 (not (string= a b)))))))
7850 ((= dcst ?t)
7851 (setq extractfun
7852 (lambda (x)
7853 (if (or (string-match org-ts-regexp x)
7854 (string-match org-ts-regexp-both x))
7855 (org-float-time
7856 (org-time-string-to-time (match-string 0 x)))
7858 comparefun (if (= dcst sorting-type) '< '>)))
7859 (t (error "Invalid sorting type `%c'" sorting-type)))
7861 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7862 table)
7863 (lambda (a b) (funcall comparefun (car a) (car b))))))
7866 ;;; The orgstruct minor mode
7868 ;; Define a minor mode which can be used in other modes in order to
7869 ;; integrate the org-mode structure editing commands.
7871 ;; This is really a hack, because the org-mode structure commands use
7872 ;; keys which normally belong to the major mode. Here is how it
7873 ;; works: The minor mode defines all the keys necessary to operate the
7874 ;; structure commands, but wraps the commands into a function which
7875 ;; tests if the cursor is currently at a headline or a plain list
7876 ;; item. If that is the case, the structure command is used,
7877 ;; temporarily setting many Org-mode variables like regular
7878 ;; expressions for filling etc. However, when any of those keys is
7879 ;; used at a different location, function uses `key-binding' to look
7880 ;; up if the key has an associated command in another currently active
7881 ;; keymap (minor modes, major mode, global), and executes that
7882 ;; command. There might be problems if any of the keys is otherwise
7883 ;; used as a prefix key.
7885 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7886 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7887 ;; addresses this by checking explicitly for both bindings.
7889 (defvar orgstruct-mode-map (make-sparse-keymap)
7890 "Keymap for the minor `orgstruct-mode'.")
7892 (defvar org-local-vars nil
7893 "List of local variables, for use by `orgstruct-mode'.")
7895 ;;;###autoload
7896 (define-minor-mode orgstruct-mode
7897 "Toggle the minor mode `orgstruct-mode'.
7898 This mode is for using Org-mode structure commands in other
7899 modes. The following keys behave as if Org-mode were active, if
7900 the cursor is on a headline, or on a plain list item (both as
7901 defined by Org-mode).
7903 M-up Move entry/item up
7904 M-down Move entry/item down
7905 M-left Promote
7906 M-right Demote
7907 M-S-up Move entry/item up
7908 M-S-down Move entry/item down
7909 M-S-left Promote subtree
7910 M-S-right Demote subtree
7911 M-q Fill paragraph and items like in Org-mode
7912 C-c ^ Sort entries
7913 C-c - Cycle list bullet
7914 TAB Cycle item visibility
7915 M-RET Insert new heading/item
7916 S-M-RET Insert new TODO heading / Checkbox item
7917 C-c C-c Set tags / toggle checkbox"
7918 nil " OrgStruct" nil
7919 (org-load-modules-maybe)
7920 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7922 ;;;###autoload
7923 (defun turn-on-orgstruct ()
7924 "Unconditionally turn on `orgstruct-mode'."
7925 (orgstruct-mode 1))
7927 (defun orgstruct++-mode (&optional arg)
7928 "Toggle `orgstruct-mode', the enhanced version of it.
7929 In addition to setting orgstruct-mode, this also exports all indentation
7930 and autofilling variables from org-mode into the buffer. It will also
7931 recognize item context in multiline items.
7932 Note that turning off orgstruct-mode will *not* remove the
7933 indentation/paragraph settings. This can only be done by refreshing the
7934 major mode, for example with \\[normal-mode]."
7935 (interactive "P")
7936 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7937 (if (< arg 1)
7938 (orgstruct-mode -1)
7939 (orgstruct-mode 1)
7940 (let (var val)
7941 (mapc
7942 (lambda (x)
7943 (when (string-match
7944 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7945 (symbol-name (car x)))
7946 (setq var (car x) val (nth 1 x))
7947 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7948 org-local-vars)
7949 (org-set-local 'orgstruct-is-++ t))))
7951 (defvar orgstruct-is-++ nil
7952 "Is `orgstruct-mode' in ++ version in the current-buffer?")
7953 (make-variable-buffer-local 'orgstruct-is-++)
7955 ;;;###autoload
7956 (defun turn-on-orgstruct++ ()
7957 "Unconditionally turn on `orgstruct++-mode'."
7958 (orgstruct++-mode 1))
7960 (defun orgstruct-error ()
7961 "Error when there is no default binding for a structure key."
7962 (interactive)
7963 (error "This key has no function outside structure elements"))
7965 (defun orgstruct-setup ()
7966 "Setup orgstruct keymaps."
7967 (let ((nfunc 0)
7968 (bindings
7969 (list
7970 '([(meta up)] org-metaup)
7971 '([(meta down)] org-metadown)
7972 '([(meta left)] org-metaleft)
7973 '([(meta right)] org-metaright)
7974 '([(meta shift up)] org-shiftmetaup)
7975 '([(meta shift down)] org-shiftmetadown)
7976 '([(meta shift left)] org-shiftmetaleft)
7977 '([(meta shift right)] org-shiftmetaright)
7978 '([?\e (up)] org-metaup)
7979 '([?\e (down)] org-metadown)
7980 '([?\e (left)] org-metaleft)
7981 '([?\e (right)] org-metaright)
7982 '([?\e (shift up)] org-shiftmetaup)
7983 '([?\e (shift down)] org-shiftmetadown)
7984 '([?\e (shift left)] org-shiftmetaleft)
7985 '([?\e (shift right)] org-shiftmetaright)
7986 '([(shift up)] org-shiftup)
7987 '([(shift down)] org-shiftdown)
7988 '([(shift left)] org-shiftleft)
7989 '([(shift right)] org-shiftright)
7990 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7991 '("\M-q" fill-paragraph)
7992 '("\C-c^" org-sort)
7993 '("\C-c-" org-cycle-list-bullet)))
7994 elt key fun cmd)
7995 (while (setq elt (pop bindings))
7996 (setq nfunc (1+ nfunc))
7997 (setq key (org-key (car elt))
7998 fun (nth 1 elt)
7999 cmd (orgstruct-make-binding fun nfunc key))
8000 (org-defkey orgstruct-mode-map key cmd))
8002 ;; Special treatment needed for TAB and RET
8003 (org-defkey orgstruct-mode-map [(tab)]
8004 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8005 (org-defkey orgstruct-mode-map "\C-i"
8006 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8008 (org-defkey orgstruct-mode-map "\M-\C-m"
8009 (orgstruct-make-binding 'org-insert-heading 105
8010 "\M-\C-m" [(meta return)]))
8011 (org-defkey orgstruct-mode-map [(meta return)]
8012 (orgstruct-make-binding 'org-insert-heading 106
8013 [(meta return)] "\M-\C-m"))
8015 (org-defkey orgstruct-mode-map [(shift meta return)]
8016 (orgstruct-make-binding 'org-insert-todo-heading 107
8017 [(meta return)] "\M-\C-m"))
8019 (org-defkey orgstruct-mode-map "\e\C-m"
8020 (orgstruct-make-binding 'org-insert-heading 108
8021 "\e\C-m" [?\e (return)]))
8022 (org-defkey orgstruct-mode-map [?\e (return)]
8023 (orgstruct-make-binding 'org-insert-heading 109
8024 [?\e (return)] "\e\C-m"))
8025 (org-defkey orgstruct-mode-map [?\e (shift return)]
8026 (orgstruct-make-binding 'org-insert-todo-heading 110
8027 [?\e (return)] "\e\C-m"))
8029 (unless org-local-vars
8030 (setq org-local-vars (org-get-local-variables)))
8034 (defun orgstruct-make-binding (fun n &rest keys)
8035 "Create a function for binding in the structure minor mode.
8036 FUN is the command to call inside a table. N is used to create a unique
8037 command name. KEYS are keys that should be checked in for a command
8038 to execute outside of tables."
8039 (eval
8040 (list 'defun
8041 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8042 '(arg)
8043 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8044 "Outside of structure, run the binding of `"
8045 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8046 "'.")
8047 '(interactive "p")
8048 (list 'if
8049 `(org-context-p 'headline 'item
8050 (and orgstruct-is-++
8051 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8052 'item-body))
8053 (list 'org-run-like-in-org-mode (list 'quote fun))
8054 (list 'let '(orgstruct-mode)
8055 (list 'call-interactively
8056 (append '(or)
8057 (mapcar (lambda (k)
8058 (list 'key-binding k))
8059 keys)
8060 '('orgstruct-error))))))))
8062 (defun org-context-p (&rest contexts)
8063 "Check if local context is any of CONTEXTS.
8064 Possible values in the list of contexts are `table', `headline', and `item'."
8065 (let ((pos (point)))
8066 (goto-char (point-at-bol))
8067 (prog1 (or (and (memq 'table contexts)
8068 (looking-at "[ \t]*|"))
8069 (and (memq 'headline contexts)
8070 ;;????????? (looking-at "\\*+"))
8071 (looking-at outline-regexp))
8072 (and (memq 'item contexts)
8073 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8074 (and (memq 'item-body contexts)
8075 (org-in-item-p)))
8076 (goto-char pos))))
8078 (defun org-get-local-variables ()
8079 "Return a list of all local variables in an org-mode buffer."
8080 (let (varlist)
8081 (with-current-buffer (get-buffer-create "*Org tmp*")
8082 (erase-buffer)
8083 (org-mode)
8084 (setq varlist (buffer-local-variables)))
8085 (kill-buffer "*Org tmp*")
8086 (delq nil
8087 (mapcar
8088 (lambda (x)
8089 (setq x
8090 (if (symbolp x)
8091 (list x)
8092 (list (car x) (list 'quote (cdr x)))))
8093 (if (string-match
8094 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8095 (symbol-name (car x)))
8096 x nil))
8097 varlist))))
8099 ;;;###autoload
8100 (defun org-run-like-in-org-mode (cmd)
8101 "Run a command, pretending that the current buffer is in Org-mode.
8102 This will temporarily bind local variables that are typically bound in
8103 Org-mode to the values they have in Org-mode, and then interactively
8104 call CMD."
8105 (org-load-modules-maybe)
8106 (unless org-local-vars
8107 (setq org-local-vars (org-get-local-variables)))
8108 (eval (list 'let org-local-vars
8109 (list 'call-interactively (list 'quote cmd)))))
8111 ;;;; Archiving
8113 (defun org-get-category (&optional pos)
8114 "Get the category applying to position POS."
8115 (get-text-property (or pos (point)) 'org-category))
8117 (defun org-refresh-category-properties ()
8118 "Refresh category text properties in the buffer."
8119 (let ((def-cat (cond
8120 ((null org-category)
8121 (if buffer-file-name
8122 (file-name-sans-extension
8123 (file-name-nondirectory buffer-file-name))
8124 "???"))
8125 ((symbolp org-category) (symbol-name org-category))
8126 (t org-category)))
8127 beg end cat pos optionp)
8128 (org-unmodified
8129 (save-excursion
8130 (save-restriction
8131 (widen)
8132 (goto-char (point-min))
8133 (put-text-property (point) (point-max) 'org-category def-cat)
8134 (while (re-search-forward
8135 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8136 (setq pos (match-end 0)
8137 optionp (equal (char-after (match-beginning 0)) ?#)
8138 cat (org-trim (match-string 2)))
8139 (if optionp
8140 (setq beg (point-at-bol) end (point-max))
8141 (org-back-to-heading t)
8142 (setq beg (point) end (org-end-of-subtree t t)))
8143 (put-text-property beg end 'org-category cat)
8144 (goto-char pos)))))))
8147 ;;;; Link Stuff
8149 ;;; Link abbreviations
8151 (defun org-link-expand-abbrev (link)
8152 "Apply replacements as defined in `org-link-abbrev-alist."
8153 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
8154 (let* ((key (match-string 1 link))
8155 (as (or (assoc key org-link-abbrev-alist-local)
8156 (assoc key org-link-abbrev-alist)))
8157 (tag (and (match-end 2) (match-string 3 link)))
8158 rpl)
8159 (if (not as)
8160 link
8161 (setq rpl (cdr as))
8162 (cond
8163 ((symbolp rpl) (funcall rpl tag))
8164 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8165 ((string-match "%h" rpl)
8166 (replace-match (url-hexify-string (or tag "")) t t rpl))
8167 (t (concat rpl tag)))))
8168 link))
8170 ;;; Storing and inserting links
8172 (defvar org-insert-link-history nil
8173 "Minibuffer history for links inserted with `org-insert-link'.")
8175 (defvar org-stored-links nil
8176 "Contains the links stored with `org-store-link'.")
8178 (defvar org-store-link-plist nil
8179 "Plist with info about the most recently link created with `org-store-link'.")
8181 (defvar org-link-protocols nil
8182 "Link protocols added to Org-mode using `org-add-link-type'.")
8184 (defvar org-store-link-functions nil
8185 "List of functions that are called to create and store a link.
8186 Each function will be called in turn until one returns a non-nil
8187 value. Each function should check if it is responsible for creating
8188 this link (for example by looking at the major mode).
8189 If not, it must exit and return nil.
8190 If yes, it should return a non-nil value after a calling
8191 `org-store-link-props' with a list of properties and values.
8192 Special properties are:
8194 :type The link prefix, like \"http\". This must be given.
8195 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8196 This is obligatory as well.
8197 :description Optional default description for the second pair
8198 of brackets in an Org-mode link. The user can still change
8199 this when inserting this link into an Org-mode buffer.
8201 In addition to these, any additional properties can be specified
8202 and then used in remember templates.")
8204 (defun org-add-link-type (type &optional follow export)
8205 "Add TYPE to the list of `org-link-types'.
8206 Re-compute all regular expressions depending on `org-link-types'
8208 FOLLOW and EXPORT are two functions.
8210 FOLLOW should take the link path as the single argument and do whatever
8211 is necessary to follow the link, for example find a file or display
8212 a mail message.
8214 EXPORT should format the link path for export to one of the export formats.
8215 It should be a function accepting three arguments:
8217 path the path of the link, the text after the prefix (like \"http:\")
8218 desc the description of the link, if any, nil if there was no description
8219 format the export format, a symbol like `html' or `latex' or `ascii'..
8221 The function may use the FORMAT information to return different values
8222 depending on the format. The return value will be put literally into
8223 the exported file. If the return value is nil, this means Org should
8224 do what it normally does with links which do not have EXPORT defined.
8226 Org-mode has a built-in default for exporting links. If you are happy with
8227 this default, there is no need to define an export function for the link
8228 type. For a simple example of an export function, see `org-bbdb.el'."
8229 (add-to-list 'org-link-types type t)
8230 (org-make-link-regexps)
8231 (if (assoc type org-link-protocols)
8232 (setcdr (assoc type org-link-protocols) (list follow export))
8233 (push (list type follow export) org-link-protocols)))
8235 (defvar org-agenda-buffer-name)
8237 ;;;###autoload
8238 (defun org-store-link (arg)
8239 "\\<org-mode-map>Store an org-link to the current location.
8240 This link is added to `org-stored-links' and can later be inserted
8241 into an org-buffer with \\[org-insert-link].
8243 For some link types, a prefix arg is interpreted:
8244 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8245 For file links, arg negates `org-context-in-file-links'."
8246 (interactive "P")
8247 (org-load-modules-maybe)
8248 (setq org-store-link-plist nil) ; reset
8249 (let ((outline-regexp (org-get-limited-outline-regexp))
8250 link cpltxt desc description search txt custom-id agenda-link)
8251 (cond
8253 ((run-hook-with-args-until-success 'org-store-link-functions)
8254 (setq link (plist-get org-store-link-plist :link)
8255 desc (or (plist-get org-store-link-plist :description) link)))
8257 ((equal (buffer-name) "*Org Edit Src Example*")
8258 (let (label gc)
8259 (while (or (not label)
8260 (save-excursion
8261 (save-restriction
8262 (widen)
8263 (goto-char (point-min))
8264 (re-search-forward
8265 (regexp-quote (format org-coderef-label-format label))
8266 nil t))))
8267 (when label (message "Label exists already") (sit-for 2))
8268 (setq label (read-string "Code line label: " label)))
8269 (end-of-line 1)
8270 (setq link (format org-coderef-label-format label))
8271 (setq gc (- 79 (length link)))
8272 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8273 (insert link)
8274 (setq link (concat "(" label ")") desc nil)))
8276 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8277 ;; We are in the agenda, link to referenced location
8278 (let ((m (or (get-text-property (point) 'org-hd-marker)
8279 (get-text-property (point) 'org-marker))))
8280 (when m
8281 (org-with-point-at m
8282 (setq agenda-link
8283 (if (interactive-p)
8284 (call-interactively 'org-store-link)
8285 (org-store-link nil)))))))
8287 ((eq major-mode 'calendar-mode)
8288 (let ((cd (calendar-cursor-to-date)))
8289 (setq link
8290 (format-time-string
8291 (car org-time-stamp-formats)
8292 (apply 'encode-time
8293 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8294 nil nil nil))))
8295 (org-store-link-props :type "calendar" :date cd)))
8297 ((eq major-mode 'w3-mode)
8298 (setq cpltxt (if (and (buffer-name)
8299 (not (string-match "Untitled" (buffer-name))))
8300 (buffer-name)
8301 (url-view-url t))
8302 link (org-make-link (url-view-url t)))
8303 (org-store-link-props :type "w3" :url (url-view-url t)))
8305 ((eq major-mode 'w3m-mode)
8306 (setq cpltxt (or w3m-current-title w3m-current-url)
8307 link (org-make-link w3m-current-url))
8308 (org-store-link-props :type "w3m" :url (url-view-url t)))
8310 ((setq search (run-hook-with-args-until-success
8311 'org-create-file-search-functions))
8312 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8313 "::" search))
8314 (setq cpltxt (or description link)))
8316 ((eq major-mode 'image-mode)
8317 (setq cpltxt (concat "file:"
8318 (abbreviate-file-name buffer-file-name))
8319 link (org-make-link cpltxt))
8320 (org-store-link-props :type "image" :file buffer-file-name))
8322 ((eq major-mode 'dired-mode)
8323 ;; link to the file in the current line
8324 (let ((file (dired-get-filename nil t)))
8325 (setq file (if file
8326 (abbreviate-file-name
8327 (expand-file-name (dired-get-filename nil t)))
8328 ;; otherwise, no file so use current directory.
8329 default-directory))
8330 (setq cpltxt (concat "file:" file)
8331 link (org-make-link cpltxt))))
8333 ((and (buffer-file-name (buffer-base-buffer)) (org-mode-p))
8334 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
8335 (cond
8336 ((org-in-regexp "<<\\(.*?\\)>>")
8337 (setq cpltxt
8338 (concat "file:"
8339 (abbreviate-file-name
8340 (buffer-file-name (buffer-base-buffer)))
8341 "::" (match-string 1))
8342 link (org-make-link cpltxt)))
8343 ((and (featurep 'org-id)
8344 (or (eq org-link-to-org-use-id t)
8345 (and (eq org-link-to-org-use-id 'create-if-interactive)
8346 (interactive-p))
8347 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
8348 (interactive-p)
8349 (not custom-id))
8350 (and org-link-to-org-use-id
8351 (condition-case nil
8352 (org-entry-get nil "ID")
8353 (error nil)))))
8354 ;; We can make a link using the ID.
8355 (setq link (condition-case nil
8356 (prog1 (org-id-store-link)
8357 (setq desc (plist-get org-store-link-plist
8358 :description)))
8359 (error
8360 ;; probably before first headline, link to file only
8361 (concat "file:"
8362 (abbreviate-file-name
8363 (buffer-file-name (buffer-base-buffer))))))))
8365 ;; Just link to current headline
8366 (setq cpltxt (concat "file:"
8367 (abbreviate-file-name
8368 (buffer-file-name (buffer-base-buffer)))))
8369 ;; Add a context search string
8370 (when (org-xor org-context-in-file-links arg)
8371 (setq txt (cond
8372 ((org-on-heading-p) nil)
8373 ((org-region-active-p)
8374 (buffer-substring (region-beginning) (region-end)))
8375 (t nil)))
8376 (when (or (null txt) (string-match "\\S-" txt))
8377 (setq cpltxt
8378 (concat cpltxt "::"
8379 (condition-case nil
8380 (org-make-org-heading-search-string txt)
8381 (error "")))
8382 desc (or (nth 4 (ignore-errors
8383 (org-heading-components))) "NONE"))))
8384 (if (string-match "::\\'" cpltxt)
8385 (setq cpltxt (substring cpltxt 0 -2)))
8386 (setq link (org-make-link cpltxt)))))
8388 ((buffer-file-name (buffer-base-buffer))
8389 ;; Just link to this file here.
8390 (setq cpltxt (concat "file:"
8391 (abbreviate-file-name
8392 (buffer-file-name (buffer-base-buffer)))))
8393 ;; Add a context string
8394 (when (org-xor org-context-in-file-links arg)
8395 (setq txt (if (org-region-active-p)
8396 (buffer-substring (region-beginning) (region-end))
8397 (buffer-substring (point-at-bol) (point-at-eol))))
8398 ;; Only use search option if there is some text.
8399 (when (string-match "\\S-" txt)
8400 (setq cpltxt
8401 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8402 desc "NONE")))
8403 (setq link (org-make-link cpltxt)))
8405 ((interactive-p)
8406 (error "Cannot link to a buffer which is not visiting a file"))
8408 (t (setq link nil)))
8410 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8411 (setq link (or link cpltxt)
8412 desc (or desc cpltxt))
8413 (if (equal desc "NONE") (setq desc nil))
8415 (if (and (or (interactive-p) executing-kbd-macro) link)
8416 (progn
8417 (setq org-stored-links
8418 (cons (list link desc) org-stored-links))
8419 (message "Stored: %s" (or desc link))
8420 (when custom-id
8421 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8422 "::#" custom-id))
8423 (setq org-stored-links
8424 (cons (list link desc) org-stored-links))))
8425 (or agenda-link (and link (org-make-link-string link desc))))))
8427 (defun org-store-link-props (&rest plist)
8428 "Store link properties, extract names and addresses."
8429 (let (x adr)
8430 (when (setq x (plist-get plist :from))
8431 (setq adr (mail-extract-address-components x))
8432 (setq plist (plist-put plist :fromname (car adr)))
8433 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8434 (when (setq x (plist-get plist :to))
8435 (setq adr (mail-extract-address-components x))
8436 (setq plist (plist-put plist :toname (car adr)))
8437 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8438 (let ((from (plist-get plist :from))
8439 (to (plist-get plist :to)))
8440 (when (and from to org-from-is-user-regexp)
8441 (setq plist
8442 (plist-put plist :fromto
8443 (if (string-match org-from-is-user-regexp from)
8444 (concat "to %t")
8445 (concat "from %f"))))))
8446 (setq org-store-link-plist plist))
8448 (defun org-add-link-props (&rest plist)
8449 "Add these properties to the link property list."
8450 (let (key value)
8451 (while plist
8452 (setq key (pop plist) value (pop plist))
8453 (setq org-store-link-plist
8454 (plist-put org-store-link-plist key value)))))
8456 (defun org-email-link-description (&optional fmt)
8457 "Return the description part of an email link.
8458 This takes information from `org-store-link-plist' and formats it
8459 according to FMT (default from `org-email-link-description-format')."
8460 (setq fmt (or fmt org-email-link-description-format))
8461 (let* ((p org-store-link-plist)
8462 (to (plist-get p :toaddress))
8463 (from (plist-get p :fromaddress))
8464 (table
8465 (list
8466 (cons "%c" (plist-get p :fromto))
8467 (cons "%F" (plist-get p :from))
8468 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8469 (cons "%T" (plist-get p :to))
8470 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8471 (cons "%s" (plist-get p :subject))
8472 (cons "%m" (plist-get p :message-id)))))
8473 (when (string-match "%c" fmt)
8474 ;; Check if the user wrote this message
8475 (if (and org-from-is-user-regexp from to
8476 (save-match-data (string-match org-from-is-user-regexp from)))
8477 (setq fmt (replace-match "to %t" t t fmt))
8478 (setq fmt (replace-match "from %f" t t fmt))))
8479 (org-replace-escapes fmt table)))
8481 (defun org-make-org-heading-search-string (&optional string heading)
8482 "Make search string for STRING or current headline."
8483 (interactive)
8484 (let ((s (or string (org-get-heading))))
8485 (unless (and string (not heading))
8486 ;; We are using a headline, clean up garbage in there.
8487 (if (string-match org-todo-regexp s)
8488 (setq s (replace-match "" t t s)))
8489 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8490 (setq s (replace-match "" t t s)))
8491 (setq s (org-trim s))
8492 (if (string-match (concat "^\\(" org-quote-string "\\|"
8493 org-comment-string "\\)") s)
8494 (setq s (replace-match "" t t s)))
8495 (while (string-match org-ts-regexp s)
8496 (setq s (replace-match "" t t s))))
8497 (or string (setq s (concat "*" s))) ; Add * for headlines
8498 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8500 (defun org-make-link (&rest strings)
8501 "Concatenate STRINGS."
8502 (apply 'concat strings))
8504 (defun org-make-link-string (link &optional description)
8505 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8506 (unless (string-match "\\S-" link)
8507 (error "Empty link"))
8508 (when (and description
8509 (stringp description)
8510 (not (string-match "\\S-" description)))
8511 (setq description nil))
8512 (when (stringp description)
8513 ;; Remove brackets from the description, they are fatal.
8514 (while (string-match "\\[" description)
8515 (setq description (replace-match "{" t t description)))
8516 (while (string-match "\\]" description)
8517 (setq description (replace-match "}" t t description))))
8518 (when (equal (org-link-escape link) description)
8519 ;; No description needed, it is identical
8520 (setq description nil))
8521 (when (and (not description)
8522 (not (equal link (org-link-escape link))))
8523 (setq description (org-extract-attributes link)))
8524 (setq link (if (string-match org-link-types-re link)
8525 (concat (match-string 1 link)
8526 (org-link-escape (substring link (match-end 1))))
8527 (org-link-escape link)))
8528 (concat "[[" link "]"
8529 (if description (concat "[" description "]") "")
8530 "]"))
8532 (defconst org-link-escape-chars
8533 '((?\ . "%20")
8534 (?\[ . "%5B")
8535 (?\] . "%5D")
8536 (?\340 . "%E0") ; `a
8537 (?\342 . "%E2") ; ^a
8538 (?\347 . "%E7") ; ,c
8539 (?\350 . "%E8") ; `e
8540 (?\351 . "%E9") ; 'e
8541 (?\352 . "%EA") ; ^e
8542 (?\356 . "%EE") ; ^i
8543 (?\364 . "%F4") ; ^o
8544 (?\371 . "%F9") ; `u
8545 (?\373 . "%FB") ; ^u
8546 (?\; . "%3B")
8547 ;; (?? . "%3F")
8548 (?= . "%3D")
8549 (?+ . "%2B")
8551 "Association list of escapes for some characters problematic in links.
8552 This is the list that is used for internal purposes.")
8554 (defvar org-url-encoding-use-url-hexify nil)
8556 (defconst org-link-escape-chars-browser
8557 '((?\ . "%20")) ; 32 for the SPC char
8558 "Association list of escapes for some characters problematic in links.
8559 This is the list that is used before handing over to the browser.")
8561 (defun org-link-escape (text &optional table)
8562 "Escape characters in TEXT that are problematic for links."
8563 (if (and org-url-encoding-use-url-hexify (not table))
8564 (url-hexify-string text)
8565 (setq table (or table org-link-escape-chars))
8566 (when text
8567 (let ((re (mapconcat (lambda (x) (regexp-quote
8568 (char-to-string (car x))))
8569 table "\\|")))
8570 (while (string-match re text)
8571 (setq text
8572 (replace-match
8573 (cdr (assoc (string-to-char (match-string 0 text))
8574 table))
8575 t t text)))
8576 text))))
8578 (defun org-link-unescape (text &optional table)
8579 "Reverse the action of `org-link-escape'."
8580 (if (and org-url-encoding-use-url-hexify (not table))
8581 (url-unhex-string text)
8582 (setq table (or table org-link-escape-chars))
8583 (when text
8584 (let ((case-fold-search t)
8585 (re (mapconcat (lambda (x) (regexp-quote (downcase (cdr x))))
8586 table "\\|")))
8587 (while (string-match re text)
8588 (setq text
8589 (replace-match
8590 (char-to-string (car (rassoc (upcase (match-string 0 text))
8591 table)))
8592 t t text)))
8593 text))))
8595 (defun org-xor (a b)
8596 "Exclusive or."
8597 (if a (not b) b))
8599 (defun org-fixup-message-id-for-http (s)
8600 "Replace special characters in a message id, so it can be used in an http query."
8601 (when (string-match "%" s)
8602 (setq s (mapconcat (lambda (c)
8603 (if (eq c ?%)
8604 "%25"
8605 (char-to-string c)))
8606 s "")))
8607 (while (string-match "<" s)
8608 (setq s (replace-match "%3C" t t s)))
8609 (while (string-match ">" s)
8610 (setq s (replace-match "%3E" t t s)))
8611 (while (string-match "@" s)
8612 (setq s (replace-match "%40" t t s)))
8615 ;;;###autoload
8616 (defun org-insert-link-global ()
8617 "Insert a link like Org-mode does.
8618 This command can be called in any mode to insert a link in Org-mode syntax."
8619 (interactive)
8620 (org-load-modules-maybe)
8621 (org-run-like-in-org-mode 'org-insert-link))
8623 (defun org-insert-link (&optional complete-file link-location)
8624 "Insert a link. At the prompt, enter the link.
8626 Completion can be used to insert any of the link protocol prefixes like
8627 http or ftp in use.
8629 The history can be used to select a link previously stored with
8630 `org-store-link'. When the empty string is entered (i.e. if you just
8631 press RET at the prompt), the link defaults to the most recently
8632 stored link. As SPC triggers completion in the minibuffer, you need to
8633 use M-SPC or C-q SPC to force the insertion of a space character.
8635 You will also be prompted for a description, and if one is given, it will
8636 be displayed in the buffer instead of the link.
8638 If there is already a link at point, this command will allow you to edit link
8639 and description parts.
8641 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
8642 be selected using completion. The path to the file will be relative to the
8643 current directory if the file is in the current directory or a subdirectory.
8644 Otherwise, the link will be the absolute path as completed in the minibuffer
8645 \(i.e. normally ~/path/to/file). You can configure this behavior using the
8646 option `org-link-file-path-type'.
8648 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
8649 the current directory or below.
8651 With three \\[universal-argument] prefixes, negate the meaning of
8652 `org-keep-stored-link-after-insertion'.
8654 If `org-make-link-description-function' is non-nil, this function will be
8655 called with the link target, and the result will be the default
8656 link description.
8658 If the LINK-LOCATION parameter is non-nil, this value will be
8659 used as the link location instead of reading one interactively."
8660 (interactive "P")
8661 (let* ((wcf (current-window-configuration))
8662 (region (if (org-region-active-p)
8663 (buffer-substring (region-beginning) (region-end))))
8664 (remove (and region (list (region-beginning) (region-end))))
8665 (desc region)
8666 tmphist ; byte-compile incorrectly complains about this
8667 (link link-location)
8668 entry file all-prefixes)
8669 (cond
8670 (link-location) ; specified by arg, just use it.
8671 ((org-in-regexp org-bracket-link-regexp 1)
8672 ;; We do have a link at point, and we are going to edit it.
8673 (setq remove (list (match-beginning 0) (match-end 0)))
8674 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8675 (setq link (read-string "Link: "
8676 (org-link-unescape
8677 (org-match-string-no-properties 1)))))
8678 ((or (org-in-regexp org-angle-link-re)
8679 (org-in-regexp org-plain-link-re))
8680 ;; Convert to bracket link
8681 (setq remove (list (match-beginning 0) (match-end 0))
8682 link (read-string "Link: "
8683 (org-remove-angle-brackets (match-string 0)))))
8684 ((member complete-file '((4) (16)))
8685 ;; Completing read for file names.
8686 (setq link (org-file-complete-link complete-file)))
8688 ;; Read link, with completion for stored links.
8689 (with-output-to-temp-buffer "*Org Links*"
8690 (princ "Insert a link.
8691 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8692 (when org-stored-links
8693 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8694 (princ (mapconcat
8695 (lambda (x)
8696 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8697 (reverse org-stored-links) "\n"))))
8698 (let ((cw (selected-window)))
8699 (select-window (get-buffer-window "*Org Links*" 'visible))
8700 (setq truncate-lines t)
8701 (unless (pos-visible-in-window-p (point-max))
8702 (org-fit-window-to-buffer))
8703 (and (window-live-p cw) (select-window cw)))
8704 ;; Fake a link history, containing the stored links.
8705 (setq tmphist (append (mapcar 'car org-stored-links)
8706 org-insert-link-history))
8707 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8708 (mapcar 'car org-link-abbrev-alist)
8709 org-link-types))
8710 (unwind-protect
8711 (progn
8712 (setq link
8713 (let ((org-completion-use-ido nil)
8714 (org-completion-use-iswitchb nil))
8715 (org-completing-read
8716 "Link: "
8717 (append
8718 (mapcar (lambda (x) (list (concat x ":")))
8719 all-prefixes)
8720 (mapcar 'car org-stored-links))
8721 nil nil nil
8722 'tmphist
8723 (car (car org-stored-links)))))
8724 (if (not (string-match "\\S-" link))
8725 (error "No link selected"))
8726 (if (or (member link all-prefixes)
8727 (and (equal ":" (substring link -1))
8728 (member (substring link 0 -1) all-prefixes)
8729 (setq link (substring link 0 -1))))
8730 (setq link (org-link-try-special-completion link))))
8731 (set-window-configuration wcf)
8732 (kill-buffer "*Org Links*"))
8733 (setq entry (assoc link org-stored-links))
8734 (or entry (push link org-insert-link-history))
8735 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8736 (not org-keep-stored-link-after-insertion))
8737 (setq org-stored-links (delq (assoc link org-stored-links)
8738 org-stored-links)))
8739 (setq desc (or desc (nth 1 entry)))))
8741 (if (string-match org-plain-link-re link)
8742 ;; URL-like link, normalize the use of angular brackets.
8743 (setq link (org-make-link (org-remove-angle-brackets link))))
8745 ;; Check if we are linking to the current file with a search option
8746 ;; If yes, simplify the link by using only the search option.
8747 (when (and buffer-file-name
8748 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8749 (let* ((path (match-string 1 link))
8750 (case-fold-search nil)
8751 (search (match-string 2 link)))
8752 (save-match-data
8753 (if (equal (file-truename buffer-file-name) (file-truename path))
8754 ;; We are linking to this same file, with a search option
8755 (setq link search)))))
8757 ;; Check if we can/should use a relative path. If yes, simplify the link
8758 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8759 (let* ((type (match-string 1 link))
8760 (path (match-string 2 link))
8761 (origpath path)
8762 (case-fold-search nil))
8763 (cond
8764 ((or (eq org-link-file-path-type 'absolute)
8765 (equal complete-file '(16)))
8766 (setq path (abbreviate-file-name (expand-file-name path))))
8767 ((eq org-link-file-path-type 'noabbrev)
8768 (setq path (expand-file-name path)))
8769 ((eq org-link-file-path-type 'relative)
8770 (setq path (file-relative-name path)))
8772 (save-match-data
8773 (if (string-match (concat "^" (regexp-quote
8774 (expand-file-name
8775 (file-name-as-directory
8776 default-directory))))
8777 (expand-file-name path))
8778 ;; We are linking a file with relative path name.
8779 (setq path (substring (expand-file-name path)
8780 (match-end 0)))
8781 (setq path (abbreviate-file-name (expand-file-name path)))))))
8782 (setq link (concat type path))
8783 (if (equal desc origpath)
8784 (setq desc path))))
8786 (if org-make-link-description-function
8787 (setq desc (funcall org-make-link-description-function link desc)))
8789 (setq desc (read-string "Description: " desc))
8790 (unless (string-match "\\S-" desc) (setq desc nil))
8791 (if remove (apply 'delete-region remove))
8792 (insert (org-make-link-string link desc))))
8794 (defun org-link-try-special-completion (type)
8795 "If there is completion support for link type TYPE, offer it."
8796 (let ((fun (intern (concat "org-" type "-complete-link"))))
8797 (if (functionp fun)
8798 (funcall fun)
8799 (read-string "Link (no completion support): " (concat type ":")))))
8801 (defun org-file-complete-link (&optional arg)
8802 "Create a file link using completion."
8803 (let (file link)
8804 (setq file (read-file-name "File: "))
8805 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8806 (pwd1 (file-name-as-directory (abbreviate-file-name
8807 (expand-file-name ".")))))
8808 (cond
8809 ((equal arg '(16))
8810 (setq link (org-make-link
8811 "file:"
8812 (abbreviate-file-name (expand-file-name file)))))
8813 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8814 (setq link (org-make-link "file:" (match-string 1 file))))
8815 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8816 (expand-file-name file))
8817 (setq link (org-make-link
8818 "file:" (match-string 1 (expand-file-name file)))))
8819 (t (setq link (org-make-link "file:" file)))))
8820 link))
8822 (defun org-completing-read (&rest args)
8823 "Completing-read with SPACE being a normal character."
8824 (let ((minibuffer-local-completion-map
8825 (copy-keymap minibuffer-local-completion-map)))
8826 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8827 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8828 (apply 'org-icompleting-read args)))
8830 (defun org-completing-read-no-i (&rest args)
8831 (let (org-completion-use-ido org-completion-use-iswitchb)
8832 (apply 'org-completing-read args)))
8834 (defun org-iswitchb-completing-read (prompt choices &rest args)
8835 "Use iswitch as a completing-read replacement to choose from choices.
8836 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8837 from."
8838 (let* ((iswitchb-use-virtual-buffers nil)
8839 (iswitchb-make-buflist-hook
8840 (lambda ()
8841 (setq iswitchb-temp-buflist choices))))
8842 (iswitchb-read-buffer prompt)))
8844 (defun org-icompleting-read (&rest args)
8845 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8846 (org-without-partial-completion
8847 (if (and org-completion-use-ido
8848 (fboundp 'ido-completing-read)
8849 (boundp 'ido-mode) ido-mode
8850 (listp (second args)))
8851 (let ((ido-enter-matching-directory nil))
8852 (apply 'ido-completing-read (concat (car args))
8853 (if (consp (car (nth 1 args)))
8854 (mapcar (lambda (x) (car x)) (nth 1 args))
8855 (nth 1 args))
8856 (cddr args)))
8857 (if (and org-completion-use-iswitchb
8858 (boundp 'iswitchb-mode) iswitchb-mode
8859 (listp (second args)))
8860 (apply 'org-iswitchb-completing-read (concat (car args))
8861 (if (consp (car (nth 1 args)))
8862 (mapcar (lambda (x) (car x)) (nth 1 args))
8863 (nth 1 args))
8864 (cddr args))
8865 (apply 'completing-read args)))))
8867 (defun org-extract-attributes (s)
8868 "Extract the attributes cookie from a string and set as text property."
8869 (let (a attr (start 0) key value)
8870 (save-match-data
8871 (when (string-match "{{\\([^}]+\\)}}$" s)
8872 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8873 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8874 (setq key (match-string 1 a) value (match-string 2 a)
8875 start (match-end 0)
8876 attr (plist-put attr (intern key) value))))
8877 (org-add-props s nil 'org-attr attr))
8880 (defun org-extract-attributes-from-string (tag)
8881 (let (key value attr)
8882 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8883 (setq key (match-string 1 tag) value (match-string 2 tag)
8884 tag (replace-match "" t t tag)
8885 attr (plist-put attr (intern key) value)))
8886 (cons tag attr)))
8888 (defun org-attributes-to-string (plist)
8889 "Format a property list into an HTML attribute list."
8890 (let ((s "") key value)
8891 (while plist
8892 (setq key (pop plist) value (pop plist))
8893 (and value
8894 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8897 ;;; Opening/following a link
8899 (defvar org-link-search-failed nil)
8901 (defvar org-open-link-functions nil
8902 "Hook for functions finding a plain text link.
8903 These functions must take a single argument, the link content.
8904 They will be called for links that look like [[link text][description]]
8905 when LINK TEXT does not have a protocol like \"http:\" and does not look
8906 like a filename (e.g. \"./blue.png\").
8908 These functions will be called *before* Org attempts to resolve the
8909 link by doing text searches in the current buffer - so if you want a
8910 link \"[[target]]\" to still find \"<<target>>\", your function should
8911 handle this as a special case.
8913 When the function does handle the link, it must return a non-nil value.
8914 If it decides that it is not responsible for this link, it must return
8915 nil to indicate that that Org-mode can continue with other options
8916 like exact and fuzzy text search.")
8918 (defun org-next-link ()
8919 "Move forward to the next link.
8920 If the link is in hidden text, expose it."
8921 (interactive)
8922 (when (and org-link-search-failed (eq this-command last-command))
8923 (goto-char (point-min))
8924 (message "Link search wrapped back to beginning of buffer"))
8925 (setq org-link-search-failed nil)
8926 (let* ((pos (point))
8927 (ct (org-context))
8928 (a (assoc :link ct)))
8929 (if a (goto-char (nth 2 a)))
8930 (if (re-search-forward org-any-link-re nil t)
8931 (progn
8932 (goto-char (match-beginning 0))
8933 (if (org-invisible-p) (org-show-context)))
8934 (goto-char pos)
8935 (setq org-link-search-failed t)
8936 (error "No further link found"))))
8938 (defun org-previous-link ()
8939 "Move backward to the previous link.
8940 If the link is in hidden text, expose it."
8941 (interactive)
8942 (when (and org-link-search-failed (eq this-command last-command))
8943 (goto-char (point-max))
8944 (message "Link search wrapped back to end of buffer"))
8945 (setq org-link-search-failed nil)
8946 (let* ((pos (point))
8947 (ct (org-context))
8948 (a (assoc :link ct)))
8949 (if a (goto-char (nth 1 a)))
8950 (if (re-search-backward org-any-link-re nil t)
8951 (progn
8952 (goto-char (match-beginning 0))
8953 (if (org-invisible-p) (org-show-context)))
8954 (goto-char pos)
8955 (setq org-link-search-failed t)
8956 (error "No further link found"))))
8958 (defun org-translate-link (s)
8959 "Translate a link string if a translation function has been defined."
8960 (if (and org-link-translation-function
8961 (fboundp org-link-translation-function)
8962 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8963 (progn
8964 (setq s (funcall org-link-translation-function
8965 (match-string 1) (match-string 2)))
8966 (concat (car s) ":" (cdr s)))
8969 (defun org-translate-link-from-planner (type path)
8970 "Translate a link from Emacs Planner syntax so that Org can follow it.
8971 This is still an experimental function, your mileage may vary."
8972 (cond
8973 ((member type '("http" "https" "news" "ftp"))
8974 ;; standard Internet links are the same.
8975 nil)
8976 ((and (equal type "irc") (string-match "^//" path))
8977 ;; Planner has two / at the beginning of an irc link, we have 1.
8978 ;; We should have zero, actually....
8979 (setq path (substring path 1)))
8980 ((and (equal type "lisp") (string-match "^/" path))
8981 ;; Planner has a slash, we do not.
8982 (setq type "elisp" path (substring path 1)))
8983 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8984 ;; A typical message link. Planner has the id after the final slash,
8985 ;; we separate it with a hash mark
8986 (setq path (concat (match-string 1 path) "#"
8987 (org-remove-angle-brackets (match-string 2 path)))))
8989 (cons type path))
8991 (defun org-find-file-at-mouse (ev)
8992 "Open file link or URL at mouse."
8993 (interactive "e")
8994 (mouse-set-point ev)
8995 (org-open-at-point 'in-emacs))
8997 (defun org-open-at-mouse (ev)
8998 "Open file link or URL at mouse."
8999 (interactive "e")
9000 (mouse-set-point ev)
9001 (if (eq major-mode 'org-agenda-mode)
9002 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9003 (org-open-at-point))
9005 (defvar org-window-config-before-follow-link nil
9006 "The window configuration before following a link.
9007 This is saved in case the need arises to restore it.")
9009 (defvar org-open-link-marker (make-marker)
9010 "Marker pointing to the location where `org-open-at-point; was called.")
9012 ;;;###autoload
9013 (defun org-open-at-point-global ()
9014 "Follow a link like Org-mode does.
9015 This command can be called in any mode to follow a link that has
9016 Org-mode syntax."
9017 (interactive)
9018 (org-run-like-in-org-mode 'org-open-at-point))
9020 ;;;###autoload
9021 (defun org-open-link-from-string (s &optional arg reference-buffer)
9022 "Open a link in the string S, as if it was in Org-mode."
9023 (interactive "sLink: \nP")
9024 (let ((reference-buffer (or reference-buffer (current-buffer))))
9025 (with-temp-buffer
9026 (let ((org-inhibit-startup t))
9027 (org-mode)
9028 (insert s)
9029 (goto-char (point-min))
9030 (when reference-buffer
9031 (setq org-link-abbrev-alist-local
9032 (with-current-buffer reference-buffer
9033 org-link-abbrev-alist-local)))
9034 (org-open-at-point arg reference-buffer)))))
9036 (defvar org-open-at-point-functions nil
9037 "Hook that is run when following a link at point.
9039 Functions in this hook must return t if they identify and follow
9040 a link at point. If they don't find anything interesting at point,
9041 they must return nil.")
9043 (defun org-open-at-point (&optional in-emacs reference-buffer)
9044 "Open link at or after point.
9045 If there is no link at point, this function will search forward up to
9046 the end of the current line.
9047 Normally, files will be opened by an appropriate application. If the
9048 optional argument IN-EMACS is non-nil, Emacs will visit the file.
9049 With a double prefix argument, try to open outside of Emacs, in the
9050 application the system uses for this file type."
9051 (interactive "P")
9052 ;; if in a code block, then open the block's results
9053 (unless (call-interactively #'org-babel-open-src-block-result)
9054 (org-load-modules-maybe)
9055 (move-marker org-open-link-marker (point))
9056 (setq org-window-config-before-follow-link (current-window-configuration))
9057 (org-remove-occur-highlights nil nil t)
9058 (cond
9059 ((and (org-on-heading-p)
9060 (not (org-in-regexp
9061 (concat org-plain-link-re "\\|"
9062 org-bracket-link-regexp "\\|"
9063 org-angle-link-re "\\|"
9064 "[ \t]:[^ \t\n]+:[ \t]*$")))
9065 (not (get-text-property (point) 'org-linked-text)))
9066 (or (org-offer-links-in-entry in-emacs)
9067 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9068 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9069 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9070 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9071 (org-footnote-action))
9073 (let (type path link line search (pos (point)))
9074 (catch 'match
9075 (save-excursion
9076 (skip-chars-forward "^]\n\r")
9077 (when (org-in-regexp org-bracket-link-regexp 1)
9078 (setq link (org-extract-attributes
9079 (org-link-unescape (org-match-string-no-properties 1))))
9080 (while (string-match " *\n *" link)
9081 (setq link (replace-match " " t t link)))
9082 (setq link (org-link-expand-abbrev link))
9083 (cond
9084 ((or (file-name-absolute-p link)
9085 (string-match "^\\.\\.?/" link))
9086 (setq type "file" path link))
9087 ((string-match org-link-re-with-space3 link)
9088 (setq type (match-string 1 link) path (match-string 2 link)))
9089 (t (setq type "thisfile" path link)))
9090 (throw 'match t)))
9092 (when (get-text-property (point) 'org-linked-text)
9093 (setq type "thisfile"
9094 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9095 (1+ (point)) (point))
9096 path (buffer-substring
9097 (previous-single-property-change pos 'org-linked-text)
9098 (next-single-property-change pos 'org-linked-text)))
9099 (throw 'match t))
9101 (save-excursion
9102 (when (or (org-in-regexp org-angle-link-re)
9103 (org-in-regexp org-plain-link-re))
9104 (setq type (match-string 1) path (match-string 2))
9105 (throw 'match t)))
9106 (save-excursion
9107 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9108 (setq type "tags"
9109 path (match-string 1))
9110 (while (string-match ":" path)
9111 (setq path (replace-match "+" t t path)))
9112 (throw 'match t)))
9113 (when (org-in-regexp "<\\([^><\n]+\\)>")
9114 (setq type "tree-match"
9115 path (match-string 1))
9116 (throw 'match t)))
9117 (unless path
9118 (error "No link found"))
9120 ;; switch back to reference buffer
9121 ;; needed when if called in a temporary buffer through
9122 ;; org-open-link-from-string
9123 (with-current-buffer (or reference-buffer (current-buffer))
9125 ;; Remove any trailing spaces in path
9126 (if (string-match " +\\'" path)
9127 (setq path (replace-match "" t t path)))
9128 (if (and org-link-translation-function
9129 (fboundp org-link-translation-function))
9130 ;; Check if we need to translate the link
9131 (let ((tmp (funcall org-link-translation-function type path)))
9132 (setq type (car tmp) path (cdr tmp))))
9134 (cond
9136 ((assoc type org-link-protocols)
9137 (funcall (nth 1 (assoc type org-link-protocols)) path))
9139 ((equal type "mailto")
9140 (let ((cmd (car org-link-mailto-program))
9141 (args (cdr org-link-mailto-program)) args1
9142 (address path) (subject "") a)
9143 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9144 (setq address (match-string 1 path)
9145 subject (org-link-escape (match-string 2 path))))
9146 (while args
9147 (cond
9148 ((not (stringp (car args))) (push (pop args) args1))
9149 (t (setq a (pop args))
9150 (if (string-match "%a" a)
9151 (setq a (replace-match address t t a)))
9152 (if (string-match "%s" a)
9153 (setq a (replace-match subject t t a)))
9154 (push a args1))))
9155 (apply cmd (nreverse args1))))
9157 ((member type '("http" "https" "ftp" "news"))
9158 (browse-url (concat type ":" (org-link-escape
9159 path org-link-escape-chars-browser))))
9161 ((string= type "doi")
9162 (browse-url (concat "http://dx.doi.org/"
9163 (org-link-escape
9164 path org-link-escape-chars-browser))))
9166 ((member type '("message"))
9167 (browse-url (concat type ":" path)))
9169 ((string= type "tags")
9170 (org-tags-view in-emacs path))
9172 ((string= type "tree-match")
9173 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9175 ((string= type "file")
9176 (if (string-match "::\\([0-9]+\\)\\'" path)
9177 (setq line (string-to-number (match-string 1 path))
9178 path (substring path 0 (match-beginning 0)))
9179 (if (string-match "::\\(.+\\)\\'" path)
9180 (setq search (match-string 1 path)
9181 path (substring path 0 (match-beginning 0)))))
9182 (if (string-match "[*?{]" (file-name-nondirectory path))
9183 (dired path)
9184 (org-open-file path in-emacs line search)))
9186 ((string= type "shell")
9187 (let ((cmd path))
9188 (if (or (not org-confirm-shell-link-function)
9189 (funcall org-confirm-shell-link-function
9190 (format "Execute \"%s\" in shell? "
9191 (org-add-props cmd nil
9192 'face 'org-warning))))
9193 (progn
9194 (message "Executing %s" cmd)
9195 (shell-command cmd))
9196 (error "Abort"))))
9198 ((string= type "elisp")
9199 (let ((cmd path))
9200 (if (or (not org-confirm-elisp-link-function)
9201 (funcall org-confirm-elisp-link-function
9202 (format "Execute \"%s\" as elisp? "
9203 (org-add-props cmd nil
9204 'face 'org-warning))))
9205 (message "%s => %s" cmd
9206 (if (equal (string-to-char cmd) ?\()
9207 (eval (read cmd))
9208 (call-interactively (read cmd))))
9209 (error "Abort"))))
9211 ((and (string= type "thisfile")
9212 (run-hook-with-args-until-success
9213 'org-open-link-functions path)))
9215 ((string= type "thisfile")
9216 (if in-emacs
9217 (switch-to-buffer-other-window
9218 (org-get-buffer-for-internal-link (current-buffer)))
9219 (org-mark-ring-push))
9220 (let ((cmd `(org-link-search
9221 ,path
9222 ,(cond ((equal in-emacs '(4)) 'occur)
9223 ((equal in-emacs '(16)) 'org-occur)
9224 (t nil))
9225 ,pos)))
9226 (condition-case nil (eval cmd)
9227 (error (progn (widen) (eval cmd))))))
9230 (browse-url-at-point)))))))
9231 (move-marker org-open-link-marker nil)
9232 (run-hook-with-args 'org-follow-link-hook)))
9234 (defun org-offer-links-in-entry (&optional nth zero)
9235 "Offer links in the current entry and follow the selected link.
9236 If there is only one link, follow it immediately as well.
9237 If NTH is an integer, immediately pick the NTH link found.
9238 If ZERO is a string, check also this string for a link, and if
9239 there is one, offer it as link number zero."
9240 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9241 "\\(" org-angle-link-re "\\)\\|"
9242 "\\(" org-plain-link-re "\\)"))
9243 (cnt ?0)
9244 (in-emacs (if (integerp nth) nil nth))
9245 have-zero end links link c)
9246 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9247 (push (match-string 0 zero) links)
9248 (setq cnt (1- cnt) have-zero t))
9249 (save-excursion
9250 (org-back-to-heading t)
9251 (setq end (save-excursion (outline-next-heading) (point)))
9252 (while (re-search-forward re end t)
9253 (push (match-string 0) links))
9254 (setq links (org-uniquify (reverse links))))
9256 (cond
9257 ((null links)
9258 (message "No links"))
9259 ((equal (length links) 1)
9260 (setq link (list (car links))))
9261 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9262 (setq link (nth (if have-zero nth (1- nth)) links)))
9263 (t ; we have to select a link
9264 (save-excursion
9265 (save-window-excursion
9266 (delete-other-windows)
9267 (with-output-to-temp-buffer "*Select Link*"
9268 (mapc (lambda (l)
9269 (if (not (string-match org-bracket-link-regexp l))
9270 (princ (format "[%c] %s\n" (incf cnt)
9271 (org-remove-angle-brackets l)))
9272 (if (match-end 3)
9273 (princ (format "[%c] %s (%s)\n" (incf cnt)
9274 (match-string 3 l) (match-string 1 l)))
9275 (princ (format "[%c] %s\n" (incf cnt)
9276 (match-string 1 l))))))
9277 links))
9278 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9279 (message "Select link to open, RET to open all:")
9280 (setq c (read-char-exclusive))
9281 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9282 (when (equal c ?q) (error "Abort"))
9283 (if (equal c ?\C-m)
9284 (setq link links)
9285 (setq nth (- c ?0))
9286 (if have-zero (setq nth (1+ nth)))
9287 (unless (and (integerp nth) (>= (length links) nth))
9288 (error "Invalid link selection"))
9289 (setq link (list (nth (1- nth) links))))))
9290 (if link
9291 (let ((buf (current-buffer)))
9292 (dolist (l link)
9293 (org-open-link-from-string l in-emacs buf))
9295 nil)))
9297 ;; Add special file links that specify the way of opening
9299 (org-add-link-type "file+sys" 'org-open-file-with-system)
9300 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9301 (defun org-open-file-with-system (path)
9302 "Open file at PATH using the system way of opening it."
9303 (org-open-file path 'system))
9304 (defun org-open-file-with-emacs (path)
9305 "Open file at PATH in Emacs."
9306 (org-open-file path 'emacs))
9307 (defun org-remove-file-link-modifiers ()
9308 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9309 (goto-char (point-min))
9310 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9311 (org-if-unprotected
9312 (replace-match "file:" t t))))
9313 (eval-after-load "org-exp"
9314 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9315 'org-remove-file-link-modifiers))
9317 ;;;; Time estimates
9319 (defun org-get-effort (&optional pom)
9320 "Get the effort estimate for the current entry."
9321 (org-entry-get pom org-effort-property))
9323 ;;; File search
9325 (defvar org-create-file-search-functions nil
9326 "List of functions to construct the right search string for a file link.
9327 These functions are called in turn with point at the location to
9328 which the link should point.
9330 A function in the hook should first test if it would like to
9331 handle this file type, for example by checking the `major-mode'
9332 or the file extension. If it decides not to handle this file, it
9333 should just return nil to give other functions a chance. If it
9334 does handle the file, it must return the search string to be used
9335 when following the link. The search string will be part of the
9336 file link, given after a double colon, and `org-open-at-point'
9337 will automatically search for it. If special measures must be
9338 taken to make the search successful, another function should be
9339 added to the companion hook `org-execute-file-search-functions',
9340 which see.
9342 A function in this hook may also use `setq' to set the variable
9343 `description' to provide a suggestion for the descriptive text to
9344 be used for this link when it gets inserted into an Org-mode
9345 buffer with \\[org-insert-link].")
9347 (defvar org-execute-file-search-functions nil
9348 "List of functions to execute a file search triggered by a link.
9350 Functions added to this hook must accept a single argument, the
9351 search string that was part of the file link, the part after the
9352 double colon. The function must first check if it would like to
9353 handle this search, for example by checking the `major-mode' or
9354 the file extension. If it decides not to handle this search, it
9355 should just return nil to give other functions a chance. If it
9356 does handle the search, it must return a non-nil value to keep
9357 other functions from trying.
9359 Each function can access the current prefix argument through the
9360 variable `current-prefix-argument'. Note that a single prefix is
9361 used to force opening a link in Emacs, so it may be good to only
9362 use a numeric or double prefix to guide the search function.
9364 In case this is needed, a function in this hook can also restore
9365 the window configuration before `org-open-at-point' was called using:
9367 (set-window-configuration org-window-config-before-follow-link)")
9369 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9370 (defun org-link-search (s &optional type avoid-pos)
9371 "Search for a link search option.
9372 If S is surrounded by forward slashes, it is interpreted as a
9373 regular expression. In org-mode files, this will create an `org-occur'
9374 sparse tree. In ordinary files, `occur' will be used to list matches.
9375 If the current buffer is in `dired-mode', grep will be used to search
9376 in all files. If AVOID-POS is given, ignore matches near that position."
9377 (let ((case-fold-search t)
9378 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9379 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9380 (append '(("") (" ") ("\t") ("\n"))
9381 org-emphasis-alist)
9382 "\\|") "\\)"))
9383 (pos (point))
9384 (pre nil) (post nil)
9385 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9386 (cond
9387 ;; First check if there are any special search functions
9388 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9389 ;; Now try the builtin stuff
9390 ((and (equal (string-to-char s0) ?#)
9391 (> (length s0) 1)
9392 (save-excursion
9393 (goto-char (point-min))
9394 (and
9395 (re-search-forward
9396 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9397 (setq type 'dedicated
9398 pos (match-beginning 0))))
9399 ;; There is an exact target for this
9400 (goto-char pos)
9401 (org-back-to-heading t)))
9402 ((save-excursion
9403 (goto-char (point-min))
9404 (and
9405 (re-search-forward
9406 (concat "<<" (regexp-quote s0) ">>") nil t)
9407 (setq type 'dedicated
9408 pos (match-beginning 0))))
9409 ;; There is an exact target for this
9410 (goto-char pos))
9411 ((and (string-match "^(\\(.*\\))$" s0)
9412 (save-excursion
9413 (goto-char (point-min))
9414 (and
9415 (re-search-forward
9416 (concat "[^[]" (regexp-quote
9417 (format org-coderef-label-format
9418 (match-string 1 s0))))
9419 nil t)
9420 (setq type 'dedicated
9421 pos (1+ (match-beginning 0))))))
9422 ;; There is a coderef target for this
9423 (goto-char pos))
9424 ((string-match "^/\\(.*\\)/$" s)
9425 ;; A regular expression
9426 (cond
9427 ((org-mode-p)
9428 (org-occur (match-string 1 s)))
9429 ;;((eq major-mode 'dired-mode)
9430 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9431 (t (org-do-occur (match-string 1 s)))))
9432 ((and (org-mode-p) org-link-search-must-match-exact-headline)
9433 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9434 (goto-char (point-min))
9435 (cond
9436 ((let (case-fold-search)
9437 (re-search-forward (format org-complex-heading-regexp-format
9438 (regexp-quote s))
9439 nil t))
9440 ;; OK, found a match
9441 (setq type 'dedicated)
9442 (goto-char (match-beginning 0)))
9443 ((and (not org-link-search-inhibit-query)
9444 (eq org-link-search-must-match-exact-headline 'query-to-create)
9445 (y-or-n-p "No match - create this as a new heading? "))
9446 (goto-char (point-max))
9447 (or (bolp) (newline))
9448 (insert "* " s "\n")
9449 (beginning-of-line 0))
9451 (goto-char pos)
9452 (error "No match"))))
9454 ;; A normal search string
9455 (when (equal (string-to-char s) ?*)
9456 ;; Anchor on headlines, post may include tags.
9457 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9458 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9459 s (substring s 1)))
9460 (remove-text-properties
9461 0 (length s)
9462 '(face nil mouse-face nil keymap nil fontified nil) s)
9463 ;; Make a series of regular expressions to find a match
9464 (setq words (org-split-string s "[ \n\r\t]+")
9466 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9467 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9468 "\\)" markers)
9469 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9470 re2a (concat "[ \t\r\n]" re2a_)
9471 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9472 re4 (concat "[^a-zA-Z_]" re4_)
9474 re1 (concat pre re2 post)
9475 re3 (concat pre (if pre re4_ re4) post)
9476 re5 (concat pre ".*" re4)
9477 re2 (concat pre re2)
9478 re2a (concat pre (if pre re2a_ re2a))
9479 re4 (concat pre (if pre re4_ re4))
9480 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9481 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9482 re5 "\\)"
9484 (cond
9485 ((eq type 'org-occur) (org-occur reall))
9486 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9487 (t (goto-char (point-min))
9488 (setq type 'fuzzy)
9489 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9490 (org-search-not-self 1 re1 nil t)
9491 (org-search-not-self 1 re2 nil t)
9492 (org-search-not-self 1 re2a nil t)
9493 (org-search-not-self 1 re3 nil t)
9494 (org-search-not-self 1 re4 nil t)
9495 (org-search-not-self 1 re5 nil t)
9497 (goto-char (match-beginning 1))
9498 (goto-char pos)
9499 (error "No match"))))))
9500 (and (org-mode-p) (org-show-context 'link-search))
9501 type))
9503 (defun org-search-not-self (group &rest args)
9504 "Execute `re-search-forward', but only accept matches that do not
9505 enclose the position of `org-open-link-marker'."
9506 (let ((m org-open-link-marker))
9507 (catch 'exit
9508 (while (apply 're-search-forward args)
9509 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9510 (goto-char (match-end group))
9511 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9512 (> (match-beginning 0) (marker-position m))
9513 (< (match-end 0) (marker-position m)))
9514 (save-match-data
9515 (or (not (org-in-regexp
9516 org-bracket-link-analytic-regexp 1))
9517 (not (match-end 4)) ; no description
9518 (and (<= (match-beginning 4) (point))
9519 (>= (match-end 4) (point))))))
9520 (throw 'exit (point))))))))
9522 (defun org-get-buffer-for-internal-link (buffer)
9523 "Return a buffer to be used for displaying the link target of internal links."
9524 (cond
9525 ((not org-display-internal-link-with-indirect-buffer)
9526 buffer)
9527 ((string-match "(Clone)$" (buffer-name buffer))
9528 (message "Buffer is already a clone, not making another one")
9529 ;; we also do not modify visibility in this case
9530 buffer)
9531 (t ; make a new indirect buffer for displaying the link
9532 (let* ((bn (buffer-name buffer))
9533 (ibn (concat bn "(Clone)"))
9534 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9535 (with-current-buffer ib (org-overview))
9536 ib))))
9538 (defun org-do-occur (regexp &optional cleanup)
9539 "Call the Emacs command `occur'.
9540 If CLEANUP is non-nil, remove the printout of the regular expression
9541 in the *Occur* buffer. This is useful if the regex is long and not useful
9542 to read."
9543 (occur regexp)
9544 (when cleanup
9545 (let ((cwin (selected-window)) win beg end)
9546 (when (setq win (get-buffer-window "*Occur*"))
9547 (select-window win))
9548 (goto-char (point-min))
9549 (when (re-search-forward "match[a-z]+" nil t)
9550 (setq beg (match-end 0))
9551 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9552 (setq end (1- (match-beginning 0)))))
9553 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9554 (goto-char (point-min))
9555 (select-window cwin))))
9557 ;;; The mark ring for links jumps
9559 (defvar org-mark-ring nil
9560 "Mark ring for positions before jumps in Org-mode.")
9561 (defvar org-mark-ring-last-goto nil
9562 "Last position in the mark ring used to go back.")
9563 ;; Fill and close the ring
9564 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9565 (loop for i from 1 to org-mark-ring-length do
9566 (push (make-marker) org-mark-ring))
9567 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9568 org-mark-ring)
9570 (defun org-mark-ring-push (&optional pos buffer)
9571 "Put the current position or POS into the mark ring and rotate it."
9572 (interactive)
9573 (setq pos (or pos (point)))
9574 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9575 (move-marker (car org-mark-ring)
9576 (or pos (point))
9577 (or buffer (current-buffer)))
9578 (message "%s"
9579 (substitute-command-keys
9580 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9582 (defun org-mark-ring-goto (&optional n)
9583 "Jump to the previous position in the mark ring.
9584 With prefix arg N, jump back that many stored positions. When
9585 called several times in succession, walk through the entire ring.
9586 Org-mode commands jumping to a different position in the current file,
9587 or to another Org-mode file, automatically push the old position
9588 onto the ring."
9589 (interactive "p")
9590 (let (p m)
9591 (if (eq last-command this-command)
9592 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9593 (setq p org-mark-ring))
9594 (setq org-mark-ring-last-goto p)
9595 (setq m (car p))
9596 (switch-to-buffer (marker-buffer m))
9597 (goto-char m)
9598 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9600 (defun org-remove-angle-brackets (s)
9601 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9602 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9604 (defun org-add-angle-brackets (s)
9605 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9606 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9608 (defun org-remove-double-quotes (s)
9609 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9610 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
9613 ;;; Following specific links
9615 (defun org-follow-timestamp-link ()
9616 (cond
9617 ((org-at-date-range-p t)
9618 (let ((org-agenda-start-on-weekday)
9619 (t1 (match-string 1))
9620 (t2 (match-string 2)))
9621 (setq t1 (time-to-days (org-time-string-to-time t1))
9622 t2 (time-to-days (org-time-string-to-time t2)))
9623 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9624 ((org-at-timestamp-p t)
9625 (org-agenda-list nil (time-to-days (org-time-string-to-time
9626 (substring (match-string 1) 0 10)))
9628 (t (error "This should not happen"))))
9631 ;;; Following file links
9632 (defvar org-wait nil)
9633 (defun org-open-file (path &optional in-emacs line search)
9634 "Open the file at PATH.
9635 First, this expands any special file name abbreviations. Then the
9636 configuration variable `org-file-apps' is checked if it contains an
9637 entry for this file type, and if yes, the corresponding command is launched.
9639 If no application is found, Emacs simply visits the file.
9641 With optional prefix argument IN-EMACS, Emacs will visit the file.
9642 With a double \\[universal-argument] \\[universal-argument] \
9643 prefix arg, Org tries to avoid opening in Emacs
9644 and to use an external application to visit the file.
9646 Optional LINE specifies a line to go to, optional SEARCH a string
9647 to search for. If LINE or SEARCH is given, the file will be
9648 opened in Emacs, unless an entry from org-file-apps that makes
9649 use of groups in a regexp matches.
9650 If the file does not exist, an error is thrown."
9651 (let* ((file (if (equal path "")
9652 buffer-file-name
9653 (substitute-in-file-name (expand-file-name path))))
9654 (file-apps (append org-file-apps (org-default-apps)))
9655 (apps (org-remove-if
9656 'org-file-apps-entry-match-against-dlink-p file-apps))
9657 (apps-dlink (org-remove-if-not
9658 'org-file-apps-entry-match-against-dlink-p file-apps))
9659 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9660 (dirp (if remp nil (file-directory-p file)))
9661 (file (if (and dirp org-open-directory-means-index-dot-org)
9662 (concat (file-name-as-directory file) "index.org")
9663 file))
9664 (a-m-a-p (assq 'auto-mode apps))
9665 (dfile (downcase file))
9666 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
9667 (link (cond ((and (eq line nil)
9668 (eq search nil))
9669 file)
9670 (line
9671 (concat file "::" (number-to-string line)))
9672 (search
9673 (concat file "::" search))))
9674 (dlink (downcase link))
9675 (old-buffer (current-buffer))
9676 (old-pos (point))
9677 (old-mode major-mode)
9678 ext cmd link-match-data)
9679 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9680 (setq ext (match-string 1 dfile))
9681 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9682 (setq ext (match-string 1 dfile))))
9683 (cond
9684 ((member in-emacs '((16) system))
9685 (setq cmd (cdr (assoc 'system apps))))
9686 (in-emacs (setq cmd 'emacs))
9688 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9689 (and dirp (cdr (assoc 'directory apps)))
9690 ; first, try matching against apps-dlink
9691 ; if we get a match here, store the match data for later
9692 (let ((match (assoc-default dlink apps-dlink
9693 'string-match)))
9694 (if match
9695 (progn (setq link-match-data (match-data))
9696 match)
9697 (progn (setq in-emacs (or in-emacs line search))
9698 nil))) ; if we have no match in apps-dlink,
9699 ; always open the file in emacs if line or search
9700 ; is given (for backwards compatibility)
9701 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
9702 'string-match)
9703 (cdr (assoc ext apps))
9704 (cdr (assoc t apps))))))
9705 (when (eq cmd 'system)
9706 (setq cmd (cdr (assoc 'system apps))))
9707 (when (eq cmd 'default)
9708 (setq cmd (cdr (assoc t apps))))
9709 (when (eq cmd 'mailcap)
9710 (require 'mailcap)
9711 (mailcap-parse-mailcaps)
9712 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9713 (command (mailcap-mime-info mime-type)))
9714 (if (stringp command)
9715 (setq cmd command)
9716 (setq cmd 'emacs))))
9717 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
9718 (not (file-exists-p file))
9719 (not org-open-non-existing-files))
9720 (error "No such file: %s" file))
9721 (cond
9722 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9723 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9724 (while (string-match "['\"]%s['\"]" cmd)
9725 (setq cmd (replace-match "%s" t t cmd)))
9726 (while (string-match "%s" cmd)
9727 (setq cmd (replace-match
9728 (save-match-data
9729 (shell-quote-argument
9730 (convert-standard-filename file)))
9731 t t cmd)))
9733 ;; Replace "%1", "%2" etc. in command with group matches from regex
9734 (save-match-data
9735 (let ((match-index 1)
9736 (number-of-groups (- (/ (length link-match-data) 2) 1)))
9737 (set-match-data link-match-data)
9738 (while (<= match-index number-of-groups)
9739 (let ((regex (concat "%" (number-to-string match-index)))
9740 (replace-with (match-string match-index dlink)))
9741 (while (string-match regex cmd)
9742 (setq cmd (replace-match replace-with t t cmd))))
9743 (setq match-index (+ match-index 1)))))
9745 (save-window-excursion
9746 (start-process-shell-command cmd nil cmd)
9747 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9749 ((or (stringp cmd)
9750 (eq cmd 'emacs))
9751 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9752 (widen)
9753 (if line (org-goto-line line)
9754 (if search (org-link-search search))))
9755 ((consp cmd)
9756 (let ((file (convert-standard-filename file)))
9757 (save-match-data
9758 (set-match-data link-match-data)
9759 (eval cmd))))
9760 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9761 (and (org-mode-p) (eq old-mode 'org-mode)
9762 (or (not (equal old-buffer (current-buffer)))
9763 (not (equal old-pos (point))))
9764 (org-mark-ring-push old-pos old-buffer))))
9766 (defun org-file-apps-entry-match-against-dlink-p (entry)
9767 "This function returns non-nil if `entry' uses a regular
9768 expression which should be matched against the whole link by
9769 org-open-file.
9771 It assumes that is the case when the entry uses a regular
9772 expression which has at least one grouping construct and the
9773 action is either a lisp form or a command string containing
9774 '%1', i.e. using at least one subexpression match as a
9775 parameter."
9776 (let ((selector (car entry))
9777 (action (cdr entry)))
9778 (if (stringp selector)
9779 (and (> (regexp-opt-depth selector) 0)
9780 (or (and (stringp action)
9781 (string-match "%[0-9]" action))
9782 (consp action)))
9783 nil)))
9785 (defun org-default-apps ()
9786 "Return the default applications for this operating system."
9787 (cond
9788 ((eq system-type 'darwin)
9789 org-file-apps-defaults-macosx)
9790 ((eq system-type 'windows-nt)
9791 org-file-apps-defaults-windowsnt)
9792 (t org-file-apps-defaults-gnu)))
9794 (defun org-apps-regexp-alist (list &optional add-auto-mode)
9795 "Convert extensions to regular expressions in the cars of LIST.
9796 Also, weed out any non-string entries, because the return value is used
9797 only for regexp matching.
9798 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
9799 point to the symbol `emacs', indicating that the file should
9800 be opened in Emacs."
9801 (append
9802 (delq nil
9803 (mapcar (lambda (x)
9804 (if (not (stringp (car x)))
9806 (if (string-match "\\W" (car x))
9808 (cons (concat "\\." (car x) "\\'") (cdr x)))))
9809 list))
9810 (if add-auto-mode
9811 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
9813 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
9814 (defun org-file-remote-p (file)
9815 "Test whether FILE specifies a location on a remote system.
9816 Return non-nil if the location is indeed remote.
9818 For example, the filename \"/user@host:/foo\" specifies a location
9819 on the system \"/user@host:\"."
9820 (cond ((fboundp 'file-remote-p)
9821 (file-remote-p file))
9822 ((fboundp 'tramp-handle-file-remote-p)
9823 (tramp-handle-file-remote-p file))
9824 ((and (boundp 'ange-ftp-name-format)
9825 (string-match (car ange-ftp-name-format) file))
9827 (t nil)))
9830 ;;;; Refiling
9832 (defun org-get-org-file ()
9833 "Read a filename, with default directory `org-directory'."
9834 (let ((default (or org-default-notes-file remember-data-file)))
9835 (read-file-name (format "File name [%s]: " default)
9836 (file-name-as-directory org-directory)
9837 default)))
9839 (defun org-notes-order-reversed-p ()
9840 "Check if the current file should receive notes in reversed order."
9841 (cond
9842 ((not org-reverse-note-order) nil)
9843 ((eq t org-reverse-note-order) t)
9844 ((not (listp org-reverse-note-order)) nil)
9845 (t (catch 'exit
9846 (let ((all org-reverse-note-order)
9847 entry)
9848 (while (setq entry (pop all))
9849 (if (string-match (car entry) buffer-file-name)
9850 (throw 'exit (cdr entry))))
9851 nil)))))
9853 (defvar org-refile-target-table nil
9854 "The list of refile targets, created by `org-refile'.")
9856 (defvar org-agenda-new-buffers nil
9857 "Buffers created to visit agenda files.")
9859 (defvar org-refile-cache nil
9860 "Cache for refile targets.")
9863 (defvar org-refile-markers nil
9864 "All the markers used for caching refile locations.")
9866 (defun org-refile-marker (pos)
9867 "Get a new refile marker, but only if caching is in use."
9868 (if (not org-refile-use-cache)
9870 (let ((m (make-marker)))
9871 (move-marker m pos)
9872 (push m org-refile-markers)
9873 m)))
9875 (defun org-refile-cache-clear ()
9876 "Clear the refile cache and disable all the markers."
9877 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
9878 (setq org-refile-markers nil)
9879 (setq org-refile-cache nil)
9880 (message "Refile cache has been cleared"))
9882 (defun org-refile-cache-check-set (set)
9883 "Check if all the markers in the cache still have live buffers."
9884 (let (marker)
9885 (catch 'exit
9886 (while (and set (setq marker (nth 3 (pop set))))
9887 ;; if org-refile-use-outline-path is 'file, marker may be nil
9888 (when (and marker (null (marker-buffer marker)))
9889 (message "not found") (sit-for 3)
9890 (throw 'exit nil)))
9891 t)))
9893 (defun org-refile-cache-put (set &rest identifiers)
9894 "Push the refile targets SET into the cache, under IDENTIFIERS."
9895 (let* ((key (sha1 (prin1-to-string identifiers)))
9896 (entry (assoc key org-refile-cache)))
9897 (if entry
9898 (setcdr entry set)
9899 (push (cons key set) org-refile-cache))))
9901 (defun org-refile-cache-get (&rest identifiers)
9902 "Retrieve the cached value for refile targets given by IDENTIFIERS."
9903 (cond
9904 ((not org-refile-cache) nil)
9905 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
9907 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
9908 org-refile-cache))))
9909 (and set (org-refile-cache-check-set set) set)))))
9911 (defun org-get-refile-targets (&optional default-buffer)
9912 "Produce a table with refile targets."
9913 (let ((case-fold-search nil)
9914 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
9915 (entries (or org-refile-targets '((nil . (:level . 1)))))
9916 targets tgs txt re files f desc descre fast-path-p level pos0)
9917 (message "Getting targets...")
9918 (with-current-buffer (or default-buffer (current-buffer))
9919 (while (setq entry (pop entries))
9920 (setq files (car entry) desc (cdr entry))
9921 (setq fast-path-p nil)
9922 (cond
9923 ((null files) (setq files (list (current-buffer))))
9924 ((eq files 'org-agenda-files)
9925 (setq files (org-agenda-files 'unrestricted)))
9926 ((and (symbolp files) (fboundp files))
9927 (setq files (funcall files)))
9928 ((and (symbolp files) (boundp files))
9929 (setq files (symbol-value files))))
9930 (if (stringp files) (setq files (list files)))
9931 (cond
9932 ((eq (car desc) :tag)
9933 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
9934 ((eq (car desc) :todo)
9935 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
9936 ((eq (car desc) :regexp)
9937 (setq descre (cdr desc)))
9938 ((eq (car desc) :level)
9939 (setq descre (concat "^\\*\\{" (number-to-string
9940 (if org-odd-levels-only
9941 (1- (* 2 (cdr desc)))
9942 (cdr desc)))
9943 "\\}[ \t]")))
9944 ((eq (car desc) :maxlevel)
9945 (setq fast-path-p t)
9946 (setq descre (concat "^\\*\\{1," (number-to-string
9947 (if org-odd-levels-only
9948 (1- (* 2 (cdr desc)))
9949 (cdr desc)))
9950 "\\}[ \t]")))
9951 (t (error "Bad refiling target description %s" desc)))
9952 (while (setq f (pop files))
9953 (with-current-buffer
9954 (if (bufferp f) f (org-get-agenda-file-buffer f))
9956 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
9957 (progn
9958 (if (bufferp f) (setq f (buffer-file-name
9959 (buffer-base-buffer f))))
9960 (setq f (and f (expand-file-name f)))
9961 (if (eq org-refile-use-outline-path 'file)
9962 (push (list (file-name-nondirectory f) f nil nil) tgs))
9963 (save-excursion
9964 (save-restriction
9965 (widen)
9966 (goto-char (point-min))
9967 (while (re-search-forward descre nil t)
9968 (goto-char (setq pos0 (point-at-bol)))
9969 (catch 'next
9970 (when org-refile-target-verify-function
9971 (save-match-data
9972 (or (funcall org-refile-target-verify-function)
9973 (throw 'next t))))
9974 (when (looking-at org-complex-heading-regexp)
9975 (setq level (org-reduced-level
9976 (- (match-end 1) (match-beginning 1)))
9977 txt (org-link-display-format (match-string 4))
9978 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
9979 re (format org-complex-heading-regexp-format
9980 (regexp-quote (match-string 4))))
9981 (when org-refile-use-outline-path
9982 (setq txt (mapconcat
9983 'org-protect-slash
9984 (append
9985 (if (eq org-refile-use-outline-path
9986 'file)
9987 (list (file-name-nondirectory
9988 (buffer-file-name
9989 (buffer-base-buffer))))
9990 (if (eq org-refile-use-outline-path
9991 'full-file-path)
9992 (list (buffer-file-name
9993 (buffer-base-buffer)))))
9994 (org-get-outline-path fast-path-p
9995 level txt)
9996 (list txt))
9997 "/")))
9998 (push (list txt f re (org-refile-marker (point)))
9999 tgs)))
10000 (when (= (point) pos0)
10001 ;; verification function has not moved point
10002 (goto-char (point-at-eol))))))))
10003 (when org-refile-use-cache
10004 (org-refile-cache-put tgs (buffer-file-name) descre))
10005 (setq targets (append tgs targets))
10006 ))))
10007 (message "Getting targets...done")
10008 (nreverse targets)))
10010 (defun org-protect-slash (s)
10011 (while (string-match "/" s)
10012 (setq s (replace-match "\\" t t s)))
10015 (defvar org-olpa (make-vector 20 nil))
10017 (defun org-get-outline-path (&optional fastp level heading)
10018 "Return the outline path to the current entry, as a list.
10020 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10021 routine which makes outline path derivations for an entire file,
10022 avoiding backtracing. Refile target collection makes use of that."
10023 (if fastp
10024 (progn
10025 (if (> level 19)
10026 (error "Outline path failure, more than 19 levels"))
10027 (loop for i from level upto 19 do
10028 (aset org-olpa i nil))
10029 (prog1
10030 (delq nil (append org-olpa nil))
10031 (aset org-olpa level heading)))
10032 (let (rtn case-fold-search)
10033 (save-excursion
10034 (save-restriction
10035 (widen)
10036 (while (org-up-heading-safe)
10037 (when (looking-at org-complex-heading-regexp)
10038 (push (org-match-string-no-properties 4) rtn)))
10039 rtn)))))
10041 (defun org-format-outline-path (path &optional width prefix)
10042 "Format the outline path PATH for display.
10043 Width is the maximum number of characters that is available.
10044 Prefix is a prefix to be included in the returned string,
10045 such as the file name."
10046 (setq width (or width 79))
10047 (if prefix (setq width (- width (length prefix))))
10048 (if (not path)
10049 (or prefix "")
10050 (let* ((nsteps (length path))
10051 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10052 (maxwidth (if (<= total-width width)
10053 10000 ;; everything fits
10054 ;; we need to shorten the level headings
10055 (/ (- width nsteps) nsteps)))
10056 (org-odd-levels-only nil)
10057 (n 0)
10058 (total (1+ (length prefix))))
10059 (setq maxwidth (max maxwidth 10))
10060 (concat prefix
10061 (mapconcat
10062 (lambda (h)
10063 (setq n (1+ n))
10064 (if (and (= n nsteps) (< maxwidth 10000))
10065 (setq maxwidth (- total-width total)))
10066 (if (< (length h) maxwidth)
10067 (progn (setq total (+ total (length h) 1)) h)
10068 (setq h (substring h 0 (- maxwidth 2))
10069 total (+ total maxwidth 1))
10070 (if (string-match "[ \t]+\\'" h)
10071 (setq h (substring h 0 (match-beginning 0))))
10072 (setq h (concat h "..")))
10073 (org-add-props h nil 'face
10074 (nth (% (1- n) org-n-level-faces)
10075 org-level-faces))
10077 path "/")))))
10079 (defun org-display-outline-path (&optional file current)
10080 "Display the current outline path in the echo area."
10081 (interactive "P")
10082 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10083 (case-fold-search nil)
10084 (path (and (org-mode-p) (org-get-outline-path))))
10085 (if current (setq path (append path
10086 (save-excursion
10087 (org-back-to-heading t)
10088 (if (looking-at org-complex-heading-regexp)
10089 (list (match-string 4)))))))
10090 (message "%s"
10091 (org-format-outline-path
10092 path
10093 (1- (frame-width))
10094 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10096 (defvar org-refile-history nil
10097 "History for refiling operations.")
10099 (defvar org-after-refile-insert-hook nil
10100 "Hook run after `org-refile' has inserted its stuff at the new location.
10101 Note that this is still *before* the stuff will be removed from
10102 the *old* location.")
10104 (defvar org-capture-last-stored-marker)
10105 (defun org-refile (&optional goto default-buffer rfloc)
10106 "Move the entry at point to another heading.
10107 The list of target headings is compiled using the information in
10108 `org-refile-targets', which see. This list is created before each use
10109 and will therefore always be up-to-date.
10111 At the target location, the entry is filed as a subitem of the target heading.
10112 Depending on `org-reverse-note-order', the new subitem will either be the
10113 first or the last subitem.
10115 If there is an active region, all entries in that region will be moved.
10116 However, the region must fulfill the requirement that the first heading
10117 is the first one sets the top-level of the moved text - at most siblings
10118 below it are allowed.
10120 With prefix arg GOTO, the command will only visit the target location,
10121 not actually move anything.
10122 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10123 go to the location where the last refiling
10124 operation has put the subtree.
10125 With a prefix argument of `2', refile to the running clock.
10127 RFLOC can be a refile location obtained in a different way.
10129 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10131 If you are using target caching (see `org-refile-use-cache'),
10132 You have to clear the target cache in order to find new targets.
10133 This can be done with a 0 prefix: `C-0 C-c C-w'"
10134 (interactive "P")
10135 (if (member goto '(0 (64)))
10136 (org-refile-cache-clear)
10137 (let* ((cbuf (current-buffer))
10138 (regionp (org-region-active-p))
10139 (region-start (and regionp (region-beginning)))
10140 (region-end (and regionp (region-end)))
10141 (region-length (and regionp (- region-end region-start)))
10142 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10143 pos it nbuf file re level reversed)
10144 (setq last-command nil)
10145 (when regionp
10146 (goto-char region-start)
10147 (or (bolp) (goto-char (point-at-bol)))
10148 (setq region-start (point))
10149 (unless (org-kill-is-subtree-p
10150 (buffer-substring region-start region-end))
10151 (error "The region is not a (sequence of) subtree(s)")))
10152 (if (equal goto '(16))
10153 (org-refile-goto-last-stored)
10154 (when (or
10155 (and (equal goto 2)
10156 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10157 (prog1
10158 (setq it (list (or org-clock-heading "running clock")
10159 (buffer-file-name
10160 (marker-buffer org-clock-hd-marker))
10162 (marker-position org-clock-hd-marker)))
10163 (setq goto nil)))
10164 (setq it (or rfloc
10165 (save-excursion
10166 (org-refile-get-location
10167 (if goto "Goto: " "Refile to: ") default-buffer
10168 org-refile-allow-creating-parent-nodes)))))
10169 (setq file (nth 1 it)
10170 re (nth 2 it)
10171 pos (nth 3 it))
10172 (if (and (not goto)
10174 (equal (buffer-file-name) file)
10175 (if regionp
10176 (and (>= pos region-start)
10177 (<= pos region-end))
10178 (and (>= pos (point))
10179 (< pos (save-excursion
10180 (org-end-of-subtree t t))))))
10181 (error "Cannot refile to position inside the tree or region"))
10183 (setq nbuf (or (find-buffer-visiting file)
10184 (find-file-noselect file)))
10185 (if goto
10186 (progn
10187 (switch-to-buffer nbuf)
10188 (goto-char pos)
10189 (org-show-context 'org-goto))
10190 (if regionp
10191 (progn
10192 (org-kill-new (buffer-substring region-start region-end))
10193 (org-save-markers-in-region region-start region-end))
10194 (org-copy-subtree 1 nil t))
10195 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10196 (find-file-noselect file)))
10197 (setq reversed (org-notes-order-reversed-p))
10198 (save-excursion
10199 (save-restriction
10200 (widen)
10201 (if pos
10202 (progn
10203 (goto-char pos)
10204 (looking-at outline-regexp)
10205 (setq level (org-get-valid-level (funcall outline-level) 1))
10206 (goto-char
10207 (if reversed
10208 (or (outline-next-heading) (point-max))
10209 (or (save-excursion (org-get-next-sibling))
10210 (org-end-of-subtree t t)
10211 (point-max)))))
10212 (setq level 1)
10213 (if (not reversed)
10214 (goto-char (point-max))
10215 (goto-char (point-min))
10216 (or (outline-next-heading) (goto-char (point-max)))))
10217 (if (not (bolp)) (newline))
10218 (org-paste-subtree level)
10219 (when org-log-refile
10220 (org-add-log-setup 'refile nil nil 'findpos
10221 org-log-refile)
10222 (unless (eq org-log-refile 'note)
10223 (save-excursion (org-add-log-note))))
10224 (and org-auto-align-tags (org-set-tags nil t))
10225 (bookmark-set "org-refile-last-stored")
10226 ;; If we are refiling for capture, make sure that the
10227 ;; last-capture pointers point here
10228 (when (org-bound-and-true-p org-refile-for-capture)
10229 (bookmark-set "org-capture-last-stored-marker")
10230 (move-marker org-capture-last-stored-marker (point)))
10231 (if (fboundp 'deactivate-mark) (deactivate-mark))
10232 (run-hooks 'org-after-refile-insert-hook))))
10233 (if regionp
10234 (delete-region (point) (+ (point) region-length))
10235 (org-cut-subtree))
10236 (when (featurep 'org-inlinetask)
10237 (org-inlinetask-remove-END-maybe))
10238 (setq org-markers-to-move nil)
10239 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10241 (defun org-refile-goto-last-stored ()
10242 "Go to the location where the last refile was stored."
10243 (interactive)
10244 (bookmark-jump "org-refile-last-stored")
10245 (message "This is the location of the last refile"))
10247 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
10248 "Prompt the user for a refile location, using PROMPT."
10249 (let ((org-refile-targets org-refile-targets)
10250 (org-refile-use-outline-path org-refile-use-outline-path))
10251 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
10252 (unless org-refile-target-table
10253 (error "No refile targets"))
10254 (let* ((cbuf (current-buffer))
10255 (partial-completion-mode nil)
10256 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10257 (cfunc (if (and org-refile-use-outline-path
10258 org-outline-path-complete-in-steps)
10259 'org-olpath-completing-read
10260 'org-icompleting-read))
10261 (extra (if org-refile-use-outline-path "/" ""))
10262 (filename (and cfn (expand-file-name cfn)))
10263 (tbl (mapcar
10264 (lambda (x)
10265 (if (and (not (member org-refile-use-outline-path
10266 '(file full-file-path)))
10267 (not (equal filename (nth 1 x))))
10268 (cons (concat (car x) extra " ("
10269 (file-name-nondirectory (nth 1 x)) ")")
10270 (cdr x))
10271 (cons (concat (car x) extra) (cdr x))))
10272 org-refile-target-table))
10273 (completion-ignore-case t)
10274 pa answ parent-target child parent old-hist)
10275 (setq old-hist org-refile-history)
10276 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10277 nil 'org-refile-history))
10278 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10279 (org-refile-check-position pa)
10280 (if pa
10281 (progn
10282 (when (or (not org-refile-history)
10283 (not (eq old-hist org-refile-history))
10284 (not (equal (car pa) (car org-refile-history))))
10285 (setq org-refile-history
10286 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10287 org-refile-history
10288 (cdr org-refile-history))))
10289 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10290 (pop org-refile-history)))
10292 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10293 (progn
10294 (setq parent (match-string 1 answ)
10295 child (match-string 2 answ))
10296 (setq parent-target (or (assoc parent tbl)
10297 (assoc (concat parent "/") tbl)))
10298 (when (and parent-target
10299 (or (eq new-nodes t)
10300 (and (eq new-nodes 'confirm)
10301 (y-or-n-p (format "Create new node \"%s\"? "
10302 child)))))
10303 (org-refile-new-child parent-target child)))
10304 (error "Invalid target location")))))
10306 (defun org-refile-check-position (refile-pointer)
10307 "Check if the refile pointer matches the readline to which it points."
10308 (let* ((file (nth 1 refile-pointer))
10309 (re (nth 2 refile-pointer))
10310 (pos (nth 3 refile-pointer))
10311 buffer)
10312 (when (org-string-nw-p re)
10313 (setq buffer (if (markerp pos)
10314 (marker-buffer pos)
10315 (or (find-buffer-visiting file)
10316 (find-file-noselect file))))
10317 (with-current-buffer buffer
10318 (save-excursion
10319 (save-restriction
10320 (widen)
10321 (goto-char pos)
10322 (beginning-of-line 1)
10323 (unless (org-looking-at-p re)
10324 (error "Invalid refile position, please rebuild the cache"))))))))
10326 (defun org-refile-new-child (parent-target child)
10327 "Use refile target PARENT-TARGET to add new CHILD below it."
10328 (unless parent-target
10329 (error "Cannot find parent for new node"))
10330 (let ((file (nth 1 parent-target))
10331 (pos (nth 3 parent-target))
10332 level)
10333 (with-current-buffer (or (find-buffer-visiting file)
10334 (find-file-noselect file))
10335 (save-excursion
10336 (save-restriction
10337 (widen)
10338 (if pos
10339 (goto-char pos)
10340 (goto-char (point-max))
10341 (if (not (bolp)) (newline)))
10342 (when (looking-at outline-regexp)
10343 (setq level (funcall outline-level))
10344 (org-end-of-subtree t t))
10345 (org-back-over-empty-lines)
10346 (insert "\n" (make-string
10347 (if pos (org-get-valid-level level 1) 1) ?*)
10348 " " child "\n")
10349 (beginning-of-line 0)
10350 (list (concat (car parent-target) "/" child) file "" (point)))))))
10352 (defun org-olpath-completing-read (prompt collection &rest args)
10353 "Read an outline path like a file name."
10354 (let ((thetable collection)
10355 (org-completion-use-ido nil) ; does not work with ido.
10356 (org-completion-use-iswitchb nil)) ; or iswitchb
10357 (apply
10358 'org-icompleting-read prompt
10359 (lambda (string predicate &optional flag)
10360 (let (rtn r f (l (length string)))
10361 (cond
10362 ((eq flag nil)
10363 ;; try completion
10364 (try-completion string thetable))
10365 ((eq flag t)
10366 ;; all-completions
10367 (setq rtn (all-completions string thetable predicate))
10368 (mapcar
10369 (lambda (x)
10370 (setq r (substring x l))
10371 (if (string-match " ([^)]*)$" x)
10372 (setq f (match-string 0 x))
10373 (setq f ""))
10374 (if (string-match "/" r)
10375 (concat string (substring r 0 (match-end 0)) f)
10377 rtn))
10378 ((eq flag 'lambda)
10379 ;; exact match?
10380 (assoc string thetable)))
10382 args)))
10384 ;;;; Dynamic blocks
10386 (defun org-find-dblock (name)
10387 "Find the first dynamic block with name NAME in the buffer.
10388 If not found, stay at current position and return nil."
10389 (let (pos)
10390 (save-excursion
10391 (goto-char (point-min))
10392 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
10393 nil t)
10394 (match-beginning 0))))
10395 (if pos (goto-char pos))
10396 pos))
10398 (defconst org-dblock-start-re
10399 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10400 "Matches the start line of a dynamic block, with parameters.")
10402 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10403 "Matches the end of a dynamic block.")
10405 (defun org-create-dblock (plist)
10406 "Create a dynamic block section, with parameters taken from PLIST.
10407 PLIST must contain a :name entry which is used as name of the block."
10408 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10409 (end-of-line 1)
10410 (newline))
10411 (let ((col (current-column))
10412 (name (plist-get plist :name)))
10413 (insert "#+BEGIN: " name)
10414 (while plist
10415 (if (eq (car plist) :name)
10416 (setq plist (cddr plist))
10417 (insert " " (prin1-to-string (pop plist)))))
10418 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10419 (beginning-of-line -2)))
10421 (defun org-prepare-dblock ()
10422 "Prepare dynamic block for refresh.
10423 This empties the block, puts the cursor at the insert position and returns
10424 the property list including an extra property :name with the block name."
10425 (unless (looking-at org-dblock-start-re)
10426 (error "Not at a dynamic block"))
10427 (let* ((begdel (1+ (match-end 0)))
10428 (name (org-no-properties (match-string 1)))
10429 (params (append (list :name name)
10430 (read (concat "(" (match-string 3) ")")))))
10431 (save-excursion
10432 (beginning-of-line 1)
10433 (skip-chars-forward " \t")
10434 (setq params (plist-put params :indentation-column (current-column))))
10435 (unless (re-search-forward org-dblock-end-re nil t)
10436 (error "Dynamic block not terminated"))
10437 (setq params
10438 (append params
10439 (list :content (buffer-substring
10440 begdel (match-beginning 0)))))
10441 (delete-region begdel (match-beginning 0))
10442 (goto-char begdel)
10443 (open-line 1)
10444 params))
10446 (defun org-map-dblocks (&optional command)
10447 "Apply COMMAND to all dynamic blocks in the current buffer.
10448 If COMMAND is not given, use `org-update-dblock'."
10449 (let ((cmd (or command 'org-update-dblock)))
10450 (save-excursion
10451 (goto-char (point-min))
10452 (while (re-search-forward org-dblock-start-re nil t)
10453 (goto-char (match-beginning 0))
10454 (save-excursion
10455 (condition-case nil
10456 (funcall cmd)
10457 (error (message "Error during update of dynamic block"))))
10458 (unless (re-search-forward org-dblock-end-re nil t)
10459 (error "Dynamic block not terminated"))))))
10461 (defun org-dblock-update (&optional arg)
10462 "User command for updating dynamic blocks.
10463 Update the dynamic block at point. With prefix ARG, update all dynamic
10464 blocks in the buffer."
10465 (interactive "P")
10466 (if arg
10467 (org-update-all-dblocks)
10468 (or (looking-at org-dblock-start-re)
10469 (org-beginning-of-dblock))
10470 (org-update-dblock)))
10472 (defun org-update-dblock ()
10473 "Update the dynamic block at point.
10474 This means to empty the block, parse for parameters and then call
10475 the correct writing function."
10476 (interactive)
10477 (save-window-excursion
10478 (let* ((pos (point))
10479 (line (org-current-line))
10480 (params (org-prepare-dblock))
10481 (name (plist-get params :name))
10482 (indent (plist-get params :indentation-column))
10483 (cmd (intern (concat "org-dblock-write:" name))))
10484 (message "Updating dynamic block `%s' at line %d..." name line)
10485 (funcall cmd params)
10486 (message "Updating dynamic block `%s' at line %d...done" name line)
10487 (goto-char pos)
10488 (when (and indent (> indent 0))
10489 (setq indent (make-string indent ?\ ))
10490 (save-excursion
10491 (org-beginning-of-dblock)
10492 (forward-line 1)
10493 (while (not (looking-at org-dblock-end-re))
10494 (insert indent)
10495 (beginning-of-line 2))
10496 (when (looking-at org-dblock-end-re)
10497 (and (looking-at "[ \t]+")
10498 (replace-match ""))
10499 (insert indent)))))))
10501 (defun org-beginning-of-dblock ()
10502 "Find the beginning of the dynamic block at point.
10503 Error if there is no such block at point."
10504 (let ((pos (point))
10505 beg)
10506 (end-of-line 1)
10507 (if (and (re-search-backward org-dblock-start-re nil t)
10508 (setq beg (match-beginning 0))
10509 (re-search-forward org-dblock-end-re nil t)
10510 (> (match-end 0) pos))
10511 (goto-char beg)
10512 (goto-char pos)
10513 (error "Not in a dynamic block"))))
10515 (defun org-update-all-dblocks ()
10516 "Update all dynamic blocks in the buffer.
10517 This function can be used in a hook."
10518 (interactive)
10519 (when (org-mode-p)
10520 (org-map-dblocks 'org-update-dblock)))
10523 ;;;; Completion
10525 (defconst org-additional-option-like-keywords
10526 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
10527 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
10528 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
10529 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX"
10530 "BEGIN:" "END:"
10531 "ORGTBL" "TBLFM:" "TBLNAME:"
10532 "BEGIN_EXAMPLE" "END_EXAMPLE"
10533 "BEGIN_QUOTE" "END_QUOTE"
10534 "BEGIN_VERSE" "END_VERSE"
10535 "BEGIN_CENTER" "END_CENTER"
10536 "BEGIN_SRC" "END_SRC"
10537 "CATEGORY" "COLUMNS" "PROPERTY"
10538 "CAPTION" "LABEL"
10539 "SETUPFILE"
10540 "BIND"
10541 "MACRO"))
10543 (defcustom org-structure-template-alist
10545 ("s" "#+begin_src ?\n\n#+end_src"
10546 "<src lang=\"?\">\n\n</src>")
10547 ("e" "#+begin_example\n?\n#+end_example"
10548 "<example>\n?\n</example>")
10549 ("q" "#+begin_quote\n?\n#+end_quote"
10550 "<quote>\n?\n</quote>")
10551 ("v" "#+begin_verse\n?\n#+end_verse"
10552 "<verse>\n?\n/verse>")
10553 ("c" "#+begin_center\n?\n#+end_center"
10554 "<center>\n?\n/center>")
10555 ("l" "#+begin_latex\n?\n#+end_latex"
10556 "<literal style=\"latex\">\n?\n</literal>")
10557 ("L" "#+latex: "
10558 "<literal style=\"latex\">?</literal>")
10559 ("h" "#+begin_html\n?\n#+end_html"
10560 "<literal style=\"html\">\n?\n</literal>")
10561 ("H" "#+html: "
10562 "<literal style=\"html\">?</literal>")
10563 ("a" "#+begin_ascii\n?\n#+end_ascii")
10564 ("A" "#+ascii: ")
10565 ("i" "#+include %file ?"
10566 "<include file=%file markup=\"?\">")
10568 "Structure completion elements.
10569 This is a list of abbreviation keys and values. The value gets inserted
10570 if you type `<' followed by the key and then press the completion key,
10571 usually `M-TAB'. %file will be replaced by a file name after prompting
10572 for the file using completion.
10573 There are two templates for each key, the first uses the original Org syntax,
10574 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
10575 the default when the /org-mtags.el/ module has been loaded. See also the
10576 variable `org-mtags-prefer-muse-templates'.
10577 This is an experimental feature, it is undecided if it is going to stay in."
10578 :group 'org-completion
10579 :type '(repeat
10580 (string :tag "Key")
10581 (string :tag "Template")
10582 (string :tag "Muse Template")))
10584 (defun org-try-structure-completion ()
10585 "Try to complete a structure template before point.
10586 This looks for strings like \"<e\" on an otherwise empty line and
10587 expands them."
10588 (let ((l (buffer-substring (point-at-bol) (point)))
10590 (when (and (looking-at "[ \t]*$")
10591 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
10592 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
10593 (org-complete-expand-structure-template (+ -1 (point-at-bol)
10594 (match-beginning 1)) a)
10595 t)))
10597 (defun org-complete-expand-structure-template (start cell)
10598 "Expand a structure template."
10599 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
10600 (rpl (nth (if musep 2 1) cell))
10601 (ind ""))
10602 (delete-region start (point))
10603 (when (string-match "\\`#\\+" rpl)
10604 (cond
10605 ((bolp))
10606 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
10607 (setq ind (buffer-substring (point-at-bol) (point))))
10608 (t (newline))))
10609 (setq start (point))
10610 (if (string-match "%file" rpl)
10611 (setq rpl (replace-match
10612 (concat
10613 "\""
10614 (save-match-data
10615 (abbreviate-file-name (read-file-name "Include file: ")))
10616 "\"")
10617 t t rpl)))
10618 (setq rpl (mapconcat 'identity (split-string rpl "\n")
10619 (concat "\n" ind)))
10620 (insert rpl)
10621 (if (re-search-backward "\\?" start t) (delete-char 1))))
10624 (defun org-complete (&optional arg)
10625 "Perform completion on word at point.
10626 At the beginning of a headline, this completes TODO keywords as given in
10627 `org-todo-keywords'.
10628 If the current word is preceded by a backslash, completes the TeX symbols
10629 that are supported for HTML support.
10630 If the current word is preceded by \"#+\", completes special words for
10631 setting file options.
10632 In the line after \"#+STARTUP:, complete valid keywords.\"
10633 At all other locations, this simply calls the value of
10634 `org-completion-fallback-command'."
10635 (interactive "P")
10636 (org-without-partial-completion
10637 (catch 'exit
10638 (let* ((a nil)
10639 (end (point))
10640 (beg1 (save-excursion
10641 (skip-chars-backward (org-re "[:alnum:]_@#%"))
10642 (point)))
10643 (beg (save-excursion
10644 (skip-chars-backward "a-zA-Z0-9_:$")
10645 (point)))
10646 (confirm (lambda (x) (stringp (car x))))
10647 (searchhead (equal (char-before beg) ?*))
10648 (struct
10649 (when (and (member (char-before beg1) '(?. ?<))
10650 (setq a (assoc (buffer-substring beg1 (point))
10651 org-structure-template-alist)))
10652 (org-complete-expand-structure-template (1- beg1) a)
10653 (throw 'exit t)))
10654 (tag (and (equal (char-before beg1) ?:)
10655 (equal (char-after (point-at-bol)) ?*)))
10656 (prop (or (and (equal (char-before beg1) ?:)
10657 (not (equal (char-after (point-at-bol)) ?*)))
10658 (string-match "^#\\+PROPERTY:.*"
10659 (buffer-substring (point-at-bol) (point)))))
10660 (texp (equal (char-before beg) ?\\))
10661 (link (equal (char-before beg) ?\[))
10662 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
10663 beg)
10664 "#+"))
10665 (startup (string-match "^#\\+STARTUP:.*"
10666 (buffer-substring (point-at-bol) (point))))
10667 (completion-ignore-case opt)
10668 (type nil)
10669 (tbl nil)
10670 (table (cond
10671 (opt
10672 (setq type :opt)
10673 (require 'org-exp)
10674 (append
10675 (delq nil
10676 (mapcar
10677 (lambda (x)
10678 (if (string-match
10679 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
10680 (cons (match-string 2 x)
10681 (match-string 1 x))))
10682 (org-split-string (org-get-current-options) "\n")))
10683 (mapcar 'list org-additional-option-like-keywords)))
10684 (startup
10685 (setq type :startup)
10686 org-startup-options)
10687 (link (append org-link-abbrev-alist-local
10688 org-link-abbrev-alist))
10689 (texp
10690 (setq type :tex)
10691 (append org-entities-user org-entities))
10692 ((string-match "\\`\\*+[ \t]+\\'"
10693 (buffer-substring (point-at-bol) beg))
10694 (setq type :todo)
10695 (mapcar 'list org-todo-keywords-1))
10696 (searchhead
10697 (setq type :searchhead)
10698 (save-excursion
10699 (goto-char (point-min))
10700 (while (re-search-forward org-todo-line-regexp nil t)
10701 (push (list
10702 (org-make-org-heading-search-string
10703 (match-string 3) t))
10704 tbl)))
10705 tbl)
10706 (tag (setq type :tag beg beg1)
10707 (or org-tag-alist (org-get-buffer-tags)))
10708 (prop (setq type :prop beg beg1)
10709 (mapcar 'list (org-buffer-property-keys nil t t)))
10710 (t (progn
10711 (call-interactively org-completion-fallback-command)
10712 (throw 'exit nil)))))
10713 (pattern (buffer-substring-no-properties beg end))
10714 (completion (try-completion pattern table confirm)))
10715 (cond ((eq completion t)
10716 (if (not (assoc (upcase pattern) table))
10717 (message "Already complete")
10718 (if (and (equal type :opt)
10719 (not (member (car (assoc (upcase pattern) table))
10720 org-additional-option-like-keywords)))
10721 (insert (substring (cdr (assoc (upcase pattern) table))
10722 (length pattern)))
10723 (if (memq type '(:tag :prop)) (insert ":")))))
10724 ((null completion)
10725 (message "Can't find completion for \"%s\"" pattern)
10726 (ding))
10727 ((not (string= pattern completion))
10728 (delete-region beg end)
10729 (if (string-match " +$" completion)
10730 (setq completion (replace-match "" t t completion)))
10731 (insert completion)
10732 (if (get-buffer-window "*Completions*")
10733 (delete-window (get-buffer-window "*Completions*")))
10734 (if (assoc completion table)
10735 (if (eq type :todo) (insert " ")
10736 (if (and (memq type '(:tag :prop))
10737 (not (string-match "^#[ \t]*\\+property:"
10738 (org-current-line-string t))))
10739 (insert ":"))))
10740 (if (and (equal type :opt) (assoc completion table))
10741 (message "%s" (substitute-command-keys
10742 "Press \\[org-complete] again to insert example settings"))))
10744 (message "Making completion list...")
10745 (let ((list (sort (all-completions pattern table confirm)
10746 'string<)))
10747 (with-output-to-temp-buffer "*Completions*"
10748 (condition-case nil
10749 ;; Protection needed for XEmacs and emacs 21
10750 (display-completion-list list pattern)
10751 (error (display-completion-list list)))))
10752 (message "Making completion list...%s" "done")))))))
10754 ;;;; TODO, DEADLINE, Comments
10756 (defun org-toggle-comment ()
10757 "Change the COMMENT state of an entry."
10758 (interactive)
10759 (save-excursion
10760 (org-back-to-heading)
10761 (let (case-fold-search)
10762 (if (looking-at (concat outline-regexp
10763 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10764 (replace-match "" t t nil 1)
10765 (if (looking-at outline-regexp)
10766 (progn
10767 (goto-char (match-end 0))
10768 (insert org-comment-string " ")))))))
10770 (defvar org-last-todo-state-is-todo nil
10771 "This is non-nil when the last TODO state change led to a TODO state.
10772 If the last change removed the TODO tag or switched to DONE, then
10773 this is nil.")
10775 (defvar org-setting-tags nil) ; dynamically skipped
10777 (defvar org-todo-setup-filter-hook nil
10778 "Hook for functions that pre-filter todo specs.
10779 Each function takes a todo spec and returns either nil or the spec
10780 transformed into canonical form." )
10782 (defvar org-todo-get-default-hook nil
10783 "Hook for functions that get a default item for todo.
10784 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
10785 nil or a string to be used for the todo mark." )
10787 (defvar org-agenda-headline-snapshot-before-repeat)
10789 (defun org-todo (&optional arg)
10790 "Change the TODO state of an item.
10791 The state of an item is given by a keyword at the start of the heading,
10792 like
10793 *** TODO Write paper
10794 *** DONE Call mom
10796 The different keywords are specified in the variable `org-todo-keywords'.
10797 By default the available states are \"TODO\" and \"DONE\".
10798 So for this example: when the item starts with TODO, it is changed to DONE.
10799 When it starts with DONE, the DONE is removed. And when neither TODO nor
10800 DONE are present, add TODO at the beginning of the heading.
10802 With \\[universal-argument] prefix arg, use completion to determine the new \
10803 state.
10804 With numeric prefix arg, switch to that state.
10805 With a double \\[universal-argument] prefix, switch to the next set of TODO \
10806 keywords (nextset).
10807 With a triple \\[universal-argument] prefix, circumvent any state blocking.
10809 For calling through lisp, arg is also interpreted in the following way:
10810 'none -> empty state
10811 \"\"(empty string) -> switch to empty state
10812 'done -> switch to DONE
10813 'nextset -> switch to the next set of keywords
10814 'previousset -> switch to the previous set of keywords
10815 \"WAITING\" -> switch to the specified keyword, but only if it
10816 really is a member of `org-todo-keywords'."
10817 (interactive "P")
10818 (if (equal arg '(16)) (setq arg 'nextset))
10819 (let ((org-blocker-hook org-blocker-hook)
10820 (case-fold-search nil))
10821 (when (equal arg '(64))
10822 (setq arg nil org-blocker-hook nil))
10823 (when (and org-blocker-hook
10824 (or org-inhibit-blocking
10825 (org-entry-get nil "NOBLOCKING")))
10826 (setq org-blocker-hook nil))
10827 (save-excursion
10828 (catch 'exit
10829 (org-back-to-heading t)
10830 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
10831 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
10832 (looking-at " *"))
10833 (let* ((match-data (match-data))
10834 (startpos (point-at-bol))
10835 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
10836 (org-log-done org-log-done)
10837 (org-log-repeat org-log-repeat)
10838 (org-todo-log-states org-todo-log-states)
10839 (this (match-string 1))
10840 (hl-pos (match-beginning 0))
10841 (head (org-get-todo-sequence-head this))
10842 (ass (assoc head org-todo-kwd-alist))
10843 (interpret (nth 1 ass))
10844 (done-word (nth 3 ass))
10845 (final-done-word (nth 4 ass))
10846 (last-state (or this ""))
10847 (completion-ignore-case t)
10848 (member (member this org-todo-keywords-1))
10849 (tail (cdr member))
10850 (state (cond
10851 ((and org-todo-key-trigger
10852 (or (and (equal arg '(4))
10853 (eq org-use-fast-todo-selection 'prefix))
10854 (and (not arg) org-use-fast-todo-selection
10855 (not (eq org-use-fast-todo-selection
10856 'prefix)))))
10857 ;; Use fast selection
10858 (org-fast-todo-selection))
10859 ((and (equal arg '(4))
10860 (or (not org-use-fast-todo-selection)
10861 (not org-todo-key-trigger)))
10862 ;; Read a state with completion
10863 (org-icompleting-read
10864 "State: " (mapcar (lambda(x) (list x))
10865 org-todo-keywords-1)
10866 nil t))
10867 ((eq arg 'right)
10868 (if this
10869 (if tail (car tail) nil)
10870 (car org-todo-keywords-1)))
10871 ((eq arg 'left)
10872 (if (equal member org-todo-keywords-1)
10874 (if this
10875 (nth (- (length org-todo-keywords-1)
10876 (length tail) 2)
10877 org-todo-keywords-1)
10878 (org-last org-todo-keywords-1))))
10879 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10880 (setq arg nil))) ; hack to fall back to cycling
10881 (arg
10882 ;; user or caller requests a specific state
10883 (cond
10884 ((equal arg "") nil)
10885 ((eq arg 'none) nil)
10886 ((eq arg 'done) (or done-word (car org-done-keywords)))
10887 ((eq arg 'nextset)
10888 (or (car (cdr (member head org-todo-heads)))
10889 (car org-todo-heads)))
10890 ((eq arg 'previousset)
10891 (let ((org-todo-heads (reverse org-todo-heads)))
10892 (or (car (cdr (member head org-todo-heads)))
10893 (car org-todo-heads))))
10894 ((car (member arg org-todo-keywords-1)))
10895 ((stringp arg)
10896 (error "State `%s' not valid in this file" arg))
10897 ((nth (1- (prefix-numeric-value arg))
10898 org-todo-keywords-1))))
10899 ((null member) (or head (car org-todo-keywords-1)))
10900 ((equal this final-done-word) nil) ;; -> make empty
10901 ((null tail) nil) ;; -> first entry
10902 ((memq interpret '(type priority))
10903 (if (eq this-command last-command)
10904 (car tail)
10905 (if (> (length tail) 0)
10906 (or done-word (car org-done-keywords))
10907 nil)))
10909 (car tail))))
10910 (state (or
10911 (run-hook-with-args-until-success
10912 'org-todo-get-default-hook state last-state)
10913 state))
10914 (next (if state (concat " " state " ") " "))
10915 (change-plist (list :type 'todo-state-change :from this :to state
10916 :position startpos))
10917 dolog now-done-p)
10918 (when org-blocker-hook
10919 (setq org-last-todo-state-is-todo
10920 (not (member this org-done-keywords)))
10921 (unless (save-excursion
10922 (save-match-data
10923 (run-hook-with-args-until-failure
10924 'org-blocker-hook change-plist)))
10925 (if (interactive-p)
10926 (error "TODO state change from %s to %s blocked" this state)
10927 ;; fail silently
10928 (message "TODO state change from %s to %s blocked" this state)
10929 (throw 'exit nil))))
10930 (store-match-data match-data)
10931 (replace-match next t t)
10932 (unless (pos-visible-in-window-p hl-pos)
10933 (message "TODO state changed to %s" (org-trim next)))
10934 (unless head
10935 (setq head (org-get-todo-sequence-head state)
10936 ass (assoc head org-todo-kwd-alist)
10937 interpret (nth 1 ass)
10938 done-word (nth 3 ass)
10939 final-done-word (nth 4 ass)))
10940 (when (memq arg '(nextset previousset))
10941 (message "Keyword-Set %d/%d: %s"
10942 (- (length org-todo-sets) -1
10943 (length (memq (assoc state org-todo-sets) org-todo-sets)))
10944 (length org-todo-sets)
10945 (mapconcat 'identity (assoc state org-todo-sets) " ")))
10946 (setq org-last-todo-state-is-todo
10947 (not (member state org-done-keywords)))
10948 (setq now-done-p (and (member state org-done-keywords)
10949 (not (member this org-done-keywords))))
10950 (and logging (org-local-logging logging))
10951 (when (and (or org-todo-log-states org-log-done)
10952 (not (eq org-inhibit-logging t))
10953 (not (memq arg '(nextset previousset))))
10954 ;; we need to look at recording a time and note
10955 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
10956 (nth 2 (assoc this org-todo-log-states))))
10957 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
10958 (setq dolog 'time))
10959 (when (and state
10960 (member state org-not-done-keywords)
10961 (not (member this org-not-done-keywords)))
10962 ;; This is now a todo state and was not one before
10963 ;; If there was a CLOSED time stamp, get rid of it.
10964 (org-add-planning-info nil nil 'closed))
10965 (when (and now-done-p org-log-done)
10966 ;; It is now done, and it was not done before
10967 (org-add-planning-info 'closed (org-current-time))
10968 (if (and (not dolog) (eq 'note org-log-done))
10969 (org-add-log-setup 'done state this 'findpos 'note)))
10970 (when (and state dolog)
10971 ;; This is a non-nil state, and we need to log it
10972 (org-add-log-setup 'state state this 'findpos dolog)))
10973 ;; Fixup tag positioning
10974 (org-todo-trigger-tag-changes state)
10975 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
10976 (when org-provide-todo-statistics
10977 (org-update-parent-todo-statistics))
10978 (run-hooks 'org-after-todo-state-change-hook)
10979 (if (and arg (not (member state org-done-keywords)))
10980 (setq head (org-get-todo-sequence-head state)))
10981 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
10982 ;; Do we need to trigger a repeat?
10983 (when now-done-p
10984 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
10985 ;; This is for the agenda, take a snapshot of the headline.
10986 (save-match-data
10987 (setq org-agenda-headline-snapshot-before-repeat
10988 (org-get-heading))))
10989 (org-auto-repeat-maybe state))
10990 ;; Fixup cursor location if close to the keyword
10991 (if (and (outline-on-heading-p)
10992 (not (bolp))
10993 (save-excursion (beginning-of-line 1)
10994 (looking-at org-todo-line-regexp))
10995 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
10996 (progn
10997 (goto-char (or (match-end 2) (match-end 1)))
10998 (and (looking-at " ") (just-one-space))))
10999 (when org-trigger-hook
11000 (save-excursion
11001 (run-hook-with-args 'org-trigger-hook change-plist))))))))
11003 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11004 "Block turning an entry into a TODO, using the hierarchy.
11005 This checks whether the current task should be blocked from state
11006 changes. Such blocking occurs when:
11008 1. The task has children which are not all in a completed state.
11010 2. A task has a parent with the property :ORDERED:, and there
11011 are siblings prior to the current task with incomplete
11012 status.
11014 3. The parent of the task is blocked because it has siblings that should
11015 be done first, or is child of a block grandparent TODO entry."
11017 (if (not org-enforce-todo-dependencies)
11018 t ; if locally turned off don't block
11019 (catch 'dont-block
11020 ;; If this is not a todo state change, or if this entry is already DONE,
11021 ;; do not block
11022 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11023 (member (plist-get change-plist :from)
11024 (cons 'done org-done-keywords))
11025 (member (plist-get change-plist :to)
11026 (cons 'todo org-not-done-keywords))
11027 (not (plist-get change-plist :to)))
11028 (throw 'dont-block t))
11029 ;; If this task has children, and any are undone, it's blocked
11030 (save-excursion
11031 (org-back-to-heading t)
11032 (let ((this-level (funcall outline-level)))
11033 (outline-next-heading)
11034 (let ((child-level (funcall outline-level)))
11035 (while (and (not (eobp))
11036 (> child-level this-level))
11037 ;; this todo has children, check whether they are all
11038 ;; completed
11039 (if (and (not (org-entry-is-done-p))
11040 (org-entry-is-todo-p))
11041 (throw 'dont-block nil))
11042 (outline-next-heading)
11043 (setq child-level (funcall outline-level))))))
11044 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11045 ;; any previous siblings are undone, it's blocked
11046 (save-excursion
11047 (org-back-to-heading t)
11048 (let* ((pos (point))
11049 (parent-pos (and (org-up-heading-safe) (point))))
11050 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11051 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11052 (forward-line 1)
11053 (re-search-forward org-not-done-heading-regexp pos t))
11054 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11055 ;; Search further up the hierarchy, to see if an anchestor is blocked
11056 (while t
11057 (goto-char parent-pos)
11058 (if (not (looking-at org-not-done-heading-regexp))
11059 (throw 'dont-block t)) ; do not block, parent is not a TODO
11060 (setq pos (point))
11061 (setq parent-pos (and (org-up-heading-safe) (point)))
11062 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11063 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11064 (forward-line 1)
11065 (re-search-forward org-not-done-heading-regexp pos t))
11066 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11068 (defcustom org-track-ordered-property-with-tag nil
11069 "Should the ORDERED property also be shown as a tag?
11070 The ORDERED property decides if an entry should require subtasks to be
11071 completed in sequence. Since a property is not very visible, setting
11072 this option means that toggling the ORDERED property with the command
11073 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11074 not relevant for the behavior, but it makes things more visible.
11076 Note that toggling the tag with tags commands will not change the property
11077 and therefore not influence behavior!
11079 This can be t, meaning the tag ORDERED should be used, It can also be a
11080 string to select a different tag for this task."
11081 :group 'org-todo
11082 :type '(choice
11083 (const :tag "No tracking" nil)
11084 (const :tag "Track with ORDERED tag" t)
11085 (string :tag "Use other tag")))
11087 (defun org-toggle-ordered-property ()
11088 "Toggle the ORDERED property of the current entry.
11089 For better visibility, you can track the value of this property with a tag.
11090 See variable `org-track-ordered-property-with-tag'."
11091 (interactive)
11092 (let* ((t1 org-track-ordered-property-with-tag)
11093 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11094 (save-excursion
11095 (org-back-to-heading)
11096 (if (org-entry-get nil "ORDERED")
11097 (progn
11098 (org-delete-property "ORDERED")
11099 (and tag (org-toggle-tag tag 'off))
11100 (message "Subtasks can be completed in arbitrary order"))
11101 (org-entry-put nil "ORDERED" "t")
11102 (and tag (org-toggle-tag tag 'on))
11103 (message "Subtasks must be completed in sequence")))))
11105 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11106 (defun org-block-todo-from-checkboxes (change-plist)
11107 "Block turning an entry into a TODO, using checkboxes.
11108 This checks whether the current task should be blocked from state
11109 changes because there are unchecked boxes in this entry."
11110 (if (not org-enforce-todo-checkbox-dependencies)
11111 t ; if locally turned off don't block
11112 (catch 'dont-block
11113 ;; If this is not a todo state change, or if this entry is already DONE,
11114 ;; do not block
11115 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11116 (member (plist-get change-plist :from)
11117 (cons 'done org-done-keywords))
11118 (member (plist-get change-plist :to)
11119 (cons 'todo org-not-done-keywords))
11120 (not (plist-get change-plist :to)))
11121 (throw 'dont-block t))
11122 ;; If this task has checkboxes that are not checked, it's blocked
11123 (save-excursion
11124 (org-back-to-heading t)
11125 (let ((beg (point)) end)
11126 (outline-next-heading)
11127 (setq end (point))
11128 (goto-char beg)
11129 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
11130 end t)
11131 (progn
11132 (if (boundp 'org-blocked-by-checkboxes)
11133 (setq org-blocked-by-checkboxes t))
11134 (throw 'dont-block nil)))))
11135 t))) ; do not block
11137 (defun org-entry-blocked-p ()
11138 "Is the current entry blocked?"
11139 (if (org-entry-get nil "NOBLOCKING")
11140 nil ;; Never block this entry
11141 (not
11142 (run-hook-with-args-until-failure
11143 'org-blocker-hook
11144 (list :type 'todo-state-change
11145 :position (point)
11146 :from 'todo
11147 :to 'done)))))
11149 (defun org-update-statistics-cookies (all)
11150 "Update the statistics cookie, either from TODO or from checkboxes.
11151 This should be called with the cursor in a line with a statistics cookie."
11152 (interactive "P")
11153 (if all
11154 (progn
11155 (org-update-checkbox-count 'all)
11156 (org-map-entries 'org-update-parent-todo-statistics))
11157 (if (not (org-on-heading-p))
11158 (org-update-checkbox-count)
11159 (let ((pos (move-marker (make-marker) (point)))
11160 end l1 l2)
11161 (ignore-errors (org-back-to-heading t))
11162 (if (not (org-on-heading-p))
11163 (org-update-checkbox-count)
11164 (setq l1 (org-outline-level))
11165 (setq end (save-excursion
11166 (outline-next-heading)
11167 (if (org-on-heading-p) (setq l2 (org-outline-level)))
11168 (point)))
11169 (if (and (save-excursion
11170 (re-search-forward
11171 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11172 (not (save-excursion (re-search-forward
11173 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11174 (org-update-checkbox-count)
11175 (if (and l2 (> l2 l1))
11176 (progn
11177 (goto-char end)
11178 (org-update-parent-todo-statistics))
11179 (goto-char pos)
11180 (beginning-of-line 1)
11181 (while (re-search-forward
11182 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11183 (point-at-eol) t)
11184 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11185 (goto-char pos)
11186 (move-marker pos nil)))))
11188 (defvar org-entry-property-inherited-from) ;; defined below
11189 (defun org-update-parent-todo-statistics ()
11190 "Update any statistics cookie in the parent of the current headline.
11191 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11192 the entire subtree and this will travel up the hierarchy and update
11193 statistics everywhere."
11194 (interactive)
11195 (let* ((lim 0) prop
11196 (recursive (or (not org-hierarchical-todo-statistics)
11197 (string-match
11198 "\\<recursive\\>"
11199 (or (setq prop (org-entry-get
11200 nil "COOKIE_DATA" 'inherit)) ""))))
11201 (lim (or (and prop (marker-position
11202 org-entry-property-inherited-from))
11203 lim))
11204 (first t)
11205 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11206 level ltoggle l1 new ndel
11207 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
11208 (catch 'exit
11209 (save-excursion
11210 (beginning-of-line 1)
11211 (if (org-at-heading-p)
11212 (setq ltoggle (funcall outline-level))
11213 (error "This should not happen"))
11214 (while (and (setq level (org-up-heading-safe))
11215 (or recursive first)
11216 (>= (point) lim))
11217 (setq first nil cookie-present nil)
11218 (unless (and level
11219 (not (string-match
11220 "\\<checkbox\\>"
11221 (downcase
11222 (or (org-entry-get
11223 nil "COOKIE_DATA")
11224 "")))))
11225 (throw 'exit nil))
11226 (while (re-search-forward box-re (point-at-eol) t)
11227 (setq cnt-all 0 cnt-done 0 cookie-present t)
11228 (setq is-percent (match-end 2))
11229 (save-match-data
11230 (unless (outline-next-heading) (throw 'exit nil))
11231 (while (and (looking-at org-complex-heading-regexp)
11232 (> (setq l1 (length (match-string 1))) level))
11233 (setq kwd (and (or recursive (= l1 ltoggle))
11234 (match-string 2)))
11235 (if (or (eq org-provide-todo-statistics 'all-headlines)
11236 (and (listp org-provide-todo-statistics)
11237 (or (member kwd org-provide-todo-statistics)
11238 (member kwd org-done-keywords))))
11239 (setq cnt-all (1+ cnt-all))
11240 (if (eq org-provide-todo-statistics t)
11241 (and kwd (setq cnt-all (1+ cnt-all)))))
11242 (and (member kwd org-done-keywords)
11243 (setq cnt-done (1+ cnt-done)))
11244 (outline-next-heading)))
11245 (setq new
11246 (if is-percent
11247 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11248 (format "[%d/%d]" cnt-done cnt-all))
11249 ndel (- (match-end 0) (match-beginning 0)))
11250 (goto-char (match-beginning 0))
11251 (insert new)
11252 (delete-region (point) (+ (point) ndel)))
11253 (when cookie-present
11254 (run-hook-with-args 'org-after-todo-statistics-hook
11255 cnt-done (- cnt-all cnt-done))))))
11256 (run-hooks 'org-todo-statistics-hook)))
11258 (defvar org-after-todo-statistics-hook nil
11259 "Hook that is called after a TODO statistics cookie has been updated.
11260 Each function is called with two arguments: the number of not-done entries
11261 and the number of done entries.
11263 For example, the following function, when added to this hook, will switch
11264 an entry to DONE when all children are done, and back to TODO when new
11265 entries are set to a TODO status. Note that this hook is only called
11266 when there is a statistics cookie in the headline!
11268 (defun org-summary-todo (n-done n-not-done)
11269 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11270 (let (org-log-done org-log-states) ; turn off logging
11271 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11274 (defvar org-todo-statistics-hook nil
11275 "Hook that is run whenever Org thinks TODO statistics should be updated.
11276 This hook runs even if there is no statistics cookie present, in which case
11277 `org-after-todo-statistics-hook' would not run.")
11279 (defun org-todo-trigger-tag-changes (state)
11280 "Apply the changes defined in `org-todo-state-tags-triggers'."
11281 (let ((l org-todo-state-tags-triggers)
11282 changes)
11283 (when (or (not state) (equal state ""))
11284 (setq changes (append changes (cdr (assoc "" l)))))
11285 (when (and (stringp state) (> (length state) 0))
11286 (setq changes (append changes (cdr (assoc state l)))))
11287 (when (member state org-not-done-keywords)
11288 (setq changes (append changes (cdr (assoc 'todo l)))))
11289 (when (member state org-done-keywords)
11290 (setq changes (append changes (cdr (assoc 'done l)))))
11291 (dolist (c changes)
11292 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11294 (defun org-local-logging (value)
11295 "Get logging settings from a property VALUE."
11296 (let* (words w a)
11297 ;; directly set the variables, they are already local.
11298 (setq org-log-done nil
11299 org-log-repeat nil
11300 org-todo-log-states nil)
11301 (setq words (org-split-string value))
11302 (while (setq w (pop words))
11303 (cond
11304 ((setq a (assoc w org-startup-options))
11305 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11306 (set (nth 1 a) (nth 2 a))))
11307 ((setq a (org-extract-log-state-settings w))
11308 (and (member (car a) org-todo-keywords-1)
11309 (push a org-todo-log-states)))))))
11311 (defun org-get-todo-sequence-head (kwd)
11312 "Return the head of the TODO sequence to which KWD belongs.
11313 If KWD is not set, check if there is a text property remembering the
11314 right sequence."
11315 (let (p)
11316 (cond
11317 ((not kwd)
11318 (or (get-text-property (point-at-bol) 'org-todo-head)
11319 (progn
11320 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11321 nil (point-at-eol)))
11322 (get-text-property p 'org-todo-head))))
11323 ((not (member kwd org-todo-keywords-1))
11324 (car org-todo-keywords-1))
11325 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11327 (defun org-fast-todo-selection ()
11328 "Fast TODO keyword selection with single keys.
11329 Returns the new TODO keyword, or nil if no state change should occur."
11330 (let* ((fulltable org-todo-key-alist)
11331 (done-keywords org-done-keywords) ;; needed for the faces.
11332 (maxlen (apply 'max (mapcar
11333 (lambda (x)
11334 (if (stringp (car x)) (string-width (car x)) 0))
11335 fulltable)))
11336 (expert nil)
11337 (fwidth (+ maxlen 3 1 3))
11338 (ncol (/ (- (window-width) 4) fwidth))
11339 tg cnt e c tbl
11340 groups ingroup)
11341 (save-excursion
11342 (save-window-excursion
11343 (if expert
11344 (set-buffer (get-buffer-create " *Org todo*"))
11345 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11346 (erase-buffer)
11347 (org-set-local 'org-done-keywords done-keywords)
11348 (setq tbl fulltable cnt 0)
11349 (while (setq e (pop tbl))
11350 (cond
11351 ((equal e '(:startgroup))
11352 (push '() groups) (setq ingroup t)
11353 (when (not (= cnt 0))
11354 (setq cnt 0)
11355 (insert "\n"))
11356 (insert "{ "))
11357 ((equal e '(:endgroup))
11358 (setq ingroup nil cnt 0)
11359 (insert "}\n"))
11360 ((equal e '(:newline))
11361 (when (not (= cnt 0))
11362 (setq cnt 0)
11363 (insert "\n")
11364 (setq e (car tbl))
11365 (while (equal (car tbl) '(:newline))
11366 (insert "\n")
11367 (setq tbl (cdr tbl)))))
11369 (setq tg (car e) c (cdr e))
11370 (if ingroup (push tg (car groups)))
11371 (setq tg (org-add-props tg nil 'face
11372 (org-get-todo-face tg)))
11373 (if (and (= cnt 0) (not ingroup)) (insert " "))
11374 (insert "[" c "] " tg (make-string
11375 (- fwidth 4 (length tg)) ?\ ))
11376 (when (= (setq cnt (1+ cnt)) ncol)
11377 (insert "\n")
11378 (if ingroup (insert " "))
11379 (setq cnt 0)))))
11380 (insert "\n")
11381 (goto-char (point-min))
11382 (if (not expert) (org-fit-window-to-buffer))
11383 (message "[a-z..]:Set [SPC]:clear")
11384 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11385 (cond
11386 ((or (= c ?\C-g)
11387 (and (= c ?q) (not (rassoc c fulltable))))
11388 (setq quit-flag t))
11389 ((= c ?\ ) nil)
11390 ((setq e (rassoc c fulltable) tg (car e))
11392 (t (setq quit-flag t)))))))
11394 (defun org-entry-is-todo-p ()
11395 (member (org-get-todo-state) org-not-done-keywords))
11397 (defun org-entry-is-done-p ()
11398 (member (org-get-todo-state) org-done-keywords))
11400 (defun org-get-todo-state ()
11401 (save-excursion
11402 (org-back-to-heading t)
11403 (and (looking-at org-todo-line-regexp)
11404 (match-end 2)
11405 (match-string 2))))
11407 (defun org-at-date-range-p (&optional inactive-ok)
11408 "Is the cursor inside a date range?"
11409 (interactive)
11410 (save-excursion
11411 (catch 'exit
11412 (let ((pos (point)))
11413 (skip-chars-backward "^[<\r\n")
11414 (skip-chars-backward "<[")
11415 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11416 (>= (match-end 0) pos)
11417 (throw 'exit t))
11418 (skip-chars-backward "^<[\r\n")
11419 (skip-chars-backward "<[")
11420 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11421 (>= (match-end 0) pos)
11422 (throw 'exit t)))
11423 nil)))
11425 (defun org-get-repeat (&optional tagline)
11426 "Check if there is a deadline/schedule with repeater in this entry."
11427 (save-match-data
11428 (save-excursion
11429 (org-back-to-heading t)
11430 (and (re-search-forward (if tagline
11431 (concat tagline "\\s-*" org-repeat-re)
11432 org-repeat-re)
11433 (org-entry-end-position) t)
11434 (match-string-no-properties 1)))))
11436 (defvar org-last-changed-timestamp)
11437 (defvar org-last-inserted-timestamp)
11438 (defvar org-log-post-message)
11439 (defvar org-log-note-purpose)
11440 (defvar org-log-note-how)
11441 (defvar org-log-note-extra)
11442 (defun org-auto-repeat-maybe (done-word)
11443 "Check if the current headline contains a repeated deadline/schedule.
11444 If yes, set TODO state back to what it was and change the base date
11445 of repeating deadline/scheduled time stamps to new date.
11446 This function is run automatically after each state change to a DONE state."
11447 ;; last-state is dynamically scoped into this function
11448 (let* ((repeat (org-get-repeat))
11449 (aa (assoc last-state org-todo-kwd-alist))
11450 (interpret (nth 1 aa))
11451 (head (nth 2 aa))
11452 (whata '(("d" . day) ("m" . month) ("y" . year)))
11453 (msg "Entry repeats: ")
11454 (org-log-done nil)
11455 (org-todo-log-states nil)
11456 re type n what ts time to-state)
11457 (when repeat
11458 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11459 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11460 org-todo-repeat-to-state))
11461 (unless (and to-state (member to-state org-todo-keywords-1))
11462 (setq to-state (if (eq interpret 'type) last-state head)))
11463 (org-todo to-state)
11464 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11465 (org-entry-put nil "LAST_REPEAT" (format-time-string
11466 (org-time-stamp-format t t))))
11467 (when org-log-repeat
11468 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11469 (memq 'org-add-log-note post-command-hook))
11470 ;; OK, we are already setup for some record
11471 (if (eq org-log-repeat 'note)
11472 ;; make sure we take a note, not only a time stamp
11473 (setq org-log-note-how 'note))
11474 ;; Set up for taking a record
11475 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11476 last-state
11477 'findpos org-log-repeat)))
11478 (org-back-to-heading t)
11479 (org-add-planning-info nil nil 'closed)
11480 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11481 org-deadline-time-regexp "\\)\\|\\("
11482 org-ts-regexp "\\)"))
11483 (while (re-search-forward
11484 re (save-excursion (outline-next-heading) (point)) t)
11485 (setq type (if (match-end 1) org-scheduled-string
11486 (if (match-end 3) org-deadline-string "Plain:"))
11487 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11488 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11489 (setq n (string-to-number (match-string 2 ts))
11490 what (match-string 3 ts))
11491 (if (equal what "w") (setq n (* n 7) what "d"))
11492 ;; Preparation, see if we need to modify the start date for the change
11493 (when (match-end 1)
11494 (setq time (save-match-data (org-time-string-to-time ts)))
11495 (cond
11496 ((equal (match-string 1 ts) ".")
11497 ;; Shift starting date to today
11498 (org-timestamp-change
11499 (- (time-to-days (current-time)) (time-to-days time))
11500 'day))
11501 ((equal (match-string 1 ts) "+")
11502 (let ((nshiftmax 10) (nshift 0))
11503 (while (or (= nshift 0)
11504 (<= (time-to-days time)
11505 (time-to-days (current-time))))
11506 (when (= (incf nshift) nshiftmax)
11507 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11508 (error "Abort")))
11509 (org-timestamp-change n (cdr (assoc what whata)))
11510 (org-at-timestamp-p t)
11511 (setq ts (match-string 1))
11512 (setq time (save-match-data (org-time-string-to-time ts)))))
11513 (org-timestamp-change (- n) (cdr (assoc what whata)))
11514 ;; rematch, so that we have everything in place for the real shift
11515 (org-at-timestamp-p t)
11516 (setq ts (match-string 1))
11517 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11518 (org-timestamp-change n (cdr (assoc what whata)))
11519 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11520 (setq org-log-post-message msg)
11521 (message "%s" msg))))
11523 (defun org-show-todo-tree (arg)
11524 "Make a compact tree which shows all headlines marked with TODO.
11525 The tree will show the lines where the regexp matches, and all higher
11526 headlines above the match.
11527 With a \\[universal-argument] prefix, prompt for a regexp to match.
11528 With a numeric prefix N, construct a sparse tree for the Nth element
11529 of `org-todo-keywords-1'."
11530 (interactive "P")
11531 (let ((case-fold-search nil)
11532 (kwd-re
11533 (cond ((null arg) org-not-done-regexp)
11534 ((equal arg '(4))
11535 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11536 (mapcar 'list org-todo-keywords-1))))
11537 (concat "\\("
11538 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11539 "\\)\\>")))
11540 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11541 (regexp-quote (nth (1- (prefix-numeric-value arg))
11542 org-todo-keywords-1)))
11543 (t (error "Invalid prefix argument: %s" arg)))))
11544 (message "%d TODO entries found"
11545 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
11547 (defun org-deadline (&optional remove time)
11548 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11549 With argument REMOVE, remove any deadline from the item.
11550 When TIME is set, it should be an internal time specification, and the
11551 scheduling will use the corresponding date."
11552 (interactive "P")
11553 (let* ((old-date (org-entry-get nil "DEADLINE"))
11554 (repeater (and old-date
11555 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
11556 (match-string 1 old-date))))
11557 (if remove
11558 (progn
11559 (when (and old-date org-log-redeadline)
11560 (org-add-log-setup 'deldeadline nil old-date 'findpos
11561 org-log-redeadline))
11562 (org-remove-timestamp-with-keyword org-deadline-string)
11563 (message "Item no longer has a deadline."))
11564 (org-add-planning-info 'deadline time 'closed)
11565 (when (and old-date org-log-redeadline
11566 (not (equal old-date
11567 (substring org-last-inserted-timestamp 1 -1))))
11568 (org-add-log-setup 'redeadline nil old-date 'findpos
11569 org-log-redeadline))
11570 (when repeater
11571 (save-excursion
11572 (org-back-to-heading t)
11573 (when (re-search-forward (concat org-deadline-string " "
11574 org-last-inserted-timestamp)
11575 (save-excursion
11576 (outline-next-heading) (point)) t)
11577 (goto-char (1- (match-end 0)))
11578 (insert " " repeater)
11579 (setq org-last-inserted-timestamp
11580 (concat (substring org-last-inserted-timestamp 0 -1)
11581 " " repeater
11582 (substring org-last-inserted-timestamp -1))))))
11583 (message "Deadline on %s" org-last-inserted-timestamp))))
11585 (defun org-schedule (&optional remove time)
11586 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11587 With argument REMOVE, remove any scheduling date from the item.
11588 When TIME is set, it should be an internal time specification, and the
11589 scheduling will use the corresponding date."
11590 (interactive "P")
11591 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11592 (repeater (and old-date
11593 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
11594 (match-string 1 old-date))))
11595 (if remove
11596 (progn
11597 (when (and old-date org-log-reschedule)
11598 (org-add-log-setup 'delschedule nil old-date 'findpos
11599 org-log-reschedule))
11600 (org-remove-timestamp-with-keyword org-scheduled-string)
11601 (message "Item is no longer scheduled."))
11602 (org-add-planning-info 'scheduled time 'closed)
11603 (when (and old-date org-log-reschedule
11604 (not (equal old-date
11605 (substring org-last-inserted-timestamp 1 -1))))
11606 (org-add-log-setup 'reschedule nil old-date 'findpos
11607 org-log-reschedule))
11608 (when repeater
11609 (save-excursion
11610 (org-back-to-heading t)
11611 (when (re-search-forward (concat org-scheduled-string " "
11612 org-last-inserted-timestamp)
11613 (save-excursion
11614 (outline-next-heading) (point)) t)
11615 (goto-char (1- (match-end 0)))
11616 (insert " " repeater)
11617 (setq org-last-inserted-timestamp
11618 (concat (substring org-last-inserted-timestamp 0 -1)
11619 " " repeater
11620 (substring org-last-inserted-timestamp -1))))))
11621 (message "Scheduled to %s" org-last-inserted-timestamp))))
11623 (defun org-get-scheduled-time (pom &optional inherit)
11624 "Get the scheduled time as a time tuple, of a format suitable
11625 for calling org-schedule with, or if there is no scheduling,
11626 returns nil."
11627 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
11628 (when time
11629 (apply 'encode-time (org-parse-time-string time)))))
11631 (defun org-get-deadline-time (pom &optional inherit)
11632 "Get the deadline as a time tuple, of a format suitable for
11633 calling org-deadline with, or if there is no scheduling, returns
11634 nil."
11635 (let ((time (org-entry-get pom "DEADLINE" inherit)))
11636 (when time
11637 (apply 'encode-time (org-parse-time-string time)))))
11639 (defun org-remove-timestamp-with-keyword (keyword)
11640 "Remove all time stamps with KEYWORD in the current entry."
11641 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
11642 beg)
11643 (save-excursion
11644 (org-back-to-heading t)
11645 (setq beg (point))
11646 (outline-next-heading)
11647 (while (re-search-backward re beg t)
11648 (replace-match "")
11649 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
11650 (equal (char-before) ?\ ))
11651 (backward-delete-char 1)
11652 (if (string-match "^[ \t]*$" (buffer-substring
11653 (point-at-bol) (point-at-eol)))
11654 (delete-region (point-at-bol)
11655 (min (point-max) (1+ (point-at-eol))))))))))
11657 (defun org-add-planning-info (what &optional time &rest remove)
11658 "Insert new timestamp with keyword in the line directly after the headline.
11659 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11660 If non is given, the user is prompted for a date.
11661 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11662 be removed."
11663 (interactive)
11664 (let (org-time-was-given org-end-time-was-given ts
11665 end default-time default-input)
11667 (catch 'exit
11668 (when (and (not time) (memq what '(scheduled deadline)))
11669 ;; Try to get a default date/time from existing timestamp
11670 (save-excursion
11671 (org-back-to-heading t)
11672 (setq end (save-excursion (outline-next-heading) (point)))
11673 (when (re-search-forward (if (eq what 'scheduled)
11674 org-scheduled-time-regexp
11675 org-deadline-time-regexp)
11676 end t)
11677 (setq ts (match-string 1)
11678 default-time
11679 (apply 'encode-time (org-parse-time-string ts))
11680 default-input (and ts (org-get-compact-tod ts))))))
11681 (when what
11682 ;; If necessary, get the time from the user
11683 (setq time (or time (org-read-date nil 'to-time nil nil
11684 default-time default-input))))
11686 (when (and org-insert-labeled-timestamps-at-point
11687 (member what '(scheduled deadline)))
11688 (insert
11689 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11690 (org-insert-time-stamp time org-time-was-given
11691 nil nil nil (list org-end-time-was-given))
11692 (setq what nil))
11693 (save-excursion
11694 (save-restriction
11695 (let (col list elt ts buffer-invisibility-spec)
11696 (org-back-to-heading t)
11697 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11698 (goto-char (match-end 1))
11699 (setq col (current-column))
11700 (goto-char (match-end 0))
11701 (if (eobp) (insert "\n") (forward-char 1))
11702 (when (and (not what)
11703 (not (looking-at
11704 (concat "[ \t]*"
11705 org-keyword-time-not-clock-regexp))))
11706 ;; Nothing to add, nothing to remove...... :-)
11707 (throw 'exit nil))
11708 (if (and (not (looking-at outline-regexp))
11709 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11710 "[^\r\n]*"))
11711 (not (equal (match-string 1) org-clock-string)))
11712 (narrow-to-region (match-beginning 0) (match-end 0))
11713 (insert-before-markers "\n")
11714 (backward-char 1)
11715 (narrow-to-region (point) (point))
11716 (and org-adapt-indentation (org-indent-to-column col)))
11717 ;; Check if we have to remove something.
11718 (setq list (cons what remove))
11719 (while list
11720 (setq elt (pop list))
11721 (goto-char (point-min))
11722 (when (or (and (eq elt 'scheduled)
11723 (re-search-forward org-scheduled-time-regexp nil t))
11724 (and (eq elt 'deadline)
11725 (re-search-forward org-deadline-time-regexp nil t))
11726 (and (eq elt 'closed)
11727 (re-search-forward org-closed-time-regexp nil t)))
11728 (replace-match "")
11729 (if (looking-at "--+<[^>]+>") (replace-match ""))
11730 (skip-chars-backward " ")
11731 (if (looking-at " +") (replace-match ""))))
11732 (goto-char (point-max))
11733 (and org-adapt-indentation (bolp) (org-indent-to-column col))
11734 (when what
11735 (insert
11736 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
11737 (cond ((eq what 'scheduled) org-scheduled-string)
11738 ((eq what 'deadline) org-deadline-string)
11739 ((eq what 'closed) org-closed-string))
11740 " ")
11741 (setq ts (org-insert-time-stamp
11742 time
11743 (or org-time-was-given
11744 (and (eq what 'closed) org-log-done-with-time))
11745 (eq what 'closed)
11746 nil nil (list org-end-time-was-given)))
11747 (end-of-line 1))
11748 (goto-char (point-min))
11749 (widen)
11750 (if (and (looking-at "[ \t]*\n")
11751 (equal (char-before) ?\n))
11752 (delete-region (1- (point)) (point-at-eol)))
11753 ts))))))
11755 (defvar org-log-note-marker (make-marker))
11756 (defvar org-log-note-purpose nil)
11757 (defvar org-log-note-state nil)
11758 (defvar org-log-note-previous-state nil)
11759 (defvar org-log-note-how nil)
11760 (defvar org-log-note-extra nil)
11761 (defvar org-log-note-window-configuration nil)
11762 (defvar org-log-note-return-to (make-marker))
11763 (defvar org-log-post-message nil
11764 "Message to be displayed after a log note has been stored.
11765 The auto-repeater uses this.")
11767 (defun org-add-note ()
11768 "Add a note to the current entry.
11769 This is done in the same way as adding a state change note."
11770 (interactive)
11771 (org-add-log-setup 'note nil nil 'findpos nil))
11773 (defvar org-property-end-re)
11774 (defun org-add-log-setup (&optional purpose state prev-state
11775 findpos how extra)
11776 "Set up the post command hook to take a note.
11777 If this is about to TODO state change, the new state is expected in STATE.
11778 When FINDPOS is non-nil, find the correct position for the note in
11779 the current entry. If not, assume that it can be inserted at point.
11780 HOW is an indicator what kind of note should be created.
11781 EXTRA is additional text that will be inserted into the notes buffer."
11782 (let* ((org-log-into-drawer (org-log-into-drawer))
11783 (drawer (cond ((stringp org-log-into-drawer)
11784 org-log-into-drawer)
11785 (org-log-into-drawer "LOGBOOK")
11786 (t nil))))
11787 (save-restriction
11788 (save-excursion
11789 (when findpos
11790 (org-back-to-heading t)
11791 (narrow-to-region (point) (save-excursion
11792 (outline-next-heading) (point)))
11793 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11794 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11795 "[^\r\n]*\\)?"))
11796 (goto-char (match-end 0))
11797 (cond
11798 (drawer
11799 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
11800 nil t)
11801 (progn
11802 (goto-char (match-end 0))
11803 (or org-log-states-order-reversed
11804 (and (re-search-forward org-property-end-re nil t)
11805 (goto-char (1- (match-beginning 0))))))
11806 (insert "\n:" drawer ":\n:END:")
11807 (beginning-of-line 0)
11808 (org-indent-line-function)
11809 (beginning-of-line 2)
11810 (org-indent-line-function)
11811 (end-of-line 0)))
11812 ((and org-log-state-notes-insert-after-drawers
11813 (save-excursion
11814 (forward-line) (looking-at org-drawer-regexp)))
11815 (forward-line)
11816 (while (looking-at org-drawer-regexp)
11817 (goto-char (match-end 0))
11818 (re-search-forward org-property-end-re (point-max) t)
11819 (forward-line))
11820 (forward-line -1)))
11821 (unless org-log-states-order-reversed
11822 (and (= (char-after) ?\n) (forward-char 1))
11823 (org-skip-over-state-notes)
11824 (skip-chars-backward " \t\n\r")))
11825 (move-marker org-log-note-marker (point))
11826 (setq org-log-note-purpose purpose
11827 org-log-note-state state
11828 org-log-note-previous-state prev-state
11829 org-log-note-how how
11830 org-log-note-extra extra)
11831 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
11833 (defun org-skip-over-state-notes ()
11834 "Skip past the list of State notes in an entry."
11835 (if (looking-at "\n[ \t]*- State") (forward-char 1))
11836 (when (org-in-item-p)
11837 (let ((limit (org-list-bottom-point)))
11838 (while (looking-at "[ \t]*- State")
11839 (goto-char (or (org-get-next-item (point) limit)
11840 (org-get-end-of-item limit)))))))
11842 (defun org-add-log-note (&optional purpose)
11843 "Pop up a window for taking a note, and add this note later at point."
11844 (remove-hook 'post-command-hook 'org-add-log-note)
11845 (setq org-log-note-window-configuration (current-window-configuration))
11846 (delete-other-windows)
11847 (move-marker org-log-note-return-to (point))
11848 (switch-to-buffer (marker-buffer org-log-note-marker))
11849 (goto-char org-log-note-marker)
11850 (org-switch-to-buffer-other-window "*Org Note*")
11851 (erase-buffer)
11852 (if (memq org-log-note-how '(time state))
11853 (let (current-prefix-arg) (org-store-log-note))
11854 (let ((org-inhibit-startup t)) (org-mode))
11855 (insert (format "# Insert note for %s.
11856 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
11857 (cond
11858 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11859 ((eq org-log-note-purpose 'done) "closed todo item")
11860 ((eq org-log-note-purpose 'state)
11861 (format "state change from \"%s\" to \"%s\""
11862 (or org-log-note-previous-state "")
11863 (or org-log-note-state "")))
11864 ((eq org-log-note-purpose 'reschedule)
11865 "rescheduling")
11866 ((eq org-log-note-purpose 'delschedule)
11867 "no longer scheduled")
11868 ((eq org-log-note-purpose 'redeadline)
11869 "changing deadline")
11870 ((eq org-log-note-purpose 'deldeadline)
11871 "removing deadline")
11872 ((eq org-log-note-purpose 'refile)
11873 "refiling")
11874 ((eq org-log-note-purpose 'note)
11875 "this entry")
11876 (t (error "This should not happen")))))
11877 (if org-log-note-extra (insert org-log-note-extra))
11878 (org-set-local 'org-finish-function 'org-store-log-note)))
11880 (defvar org-note-abort nil) ; dynamically scoped
11881 (defun org-store-log-note ()
11882 "Finish taking a log note, and insert it to where it belongs."
11883 (let ((txt (buffer-string))
11884 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11885 lines ind bul)
11886 (kill-buffer (current-buffer))
11887 (while (string-match "\\`#.*\n[ \t\n]*" txt)
11888 (setq txt (replace-match "" t t txt)))
11889 (if (string-match "\\s-+\\'" txt)
11890 (setq txt (replace-match "" t t txt)))
11891 (setq lines (org-split-string txt "\n"))
11892 (when (and note (string-match "\\S-" note))
11893 (setq note
11894 (org-replace-escapes
11895 note
11896 (list (cons "%u" (user-login-name))
11897 (cons "%U" user-full-name)
11898 (cons "%t" (format-time-string
11899 (org-time-stamp-format 'long 'inactive)
11900 (current-time)))
11901 (cons "%T" (format-time-string
11902 (org-time-stamp-format 'long nil)
11903 (current-time)))
11904 (cons "%s" (if org-log-note-state
11905 (concat "\"" org-log-note-state "\"")
11906 ""))
11907 (cons "%S" (if org-log-note-previous-state
11908 (concat "\"" org-log-note-previous-state "\"")
11909 "\"\"")))))
11910 (if lines (setq note (concat note " \\\\")))
11911 (push note lines))
11912 (when (or current-prefix-arg org-note-abort)
11913 (when org-log-into-drawer
11914 (org-remove-empty-drawer-at
11915 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
11916 org-log-note-marker))
11917 (setq lines nil))
11918 (when lines
11919 (with-current-buffer (marker-buffer org-log-note-marker)
11920 (save-excursion
11921 (goto-char org-log-note-marker)
11922 (move-marker org-log-note-marker nil)
11923 (end-of-line 1)
11924 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
11925 (setq ind (save-excursion
11926 (if (org-in-item-p)
11927 (progn
11928 (goto-char (org-list-top-point))
11929 (org-get-indentation))
11930 (skip-chars-backward " \r\t\n")
11931 (cond
11932 ((and (org-at-heading-p)
11933 org-adapt-indentation)
11934 (1+ (org-current-level)))
11935 ((org-at-heading-p) 0)
11936 (t (org-get-indentation))))))
11937 (setq bul (org-list-bullet-string "-"))
11938 (org-indent-line-to ind)
11939 (insert bul (pop lines))
11940 (let ((ind-body (+ (length bul) ind)))
11941 (while lines
11942 (insert "\n")
11943 (org-indent-line-to ind-body)
11944 (insert (pop lines))))
11945 (message "Note stored")
11946 (org-back-to-heading t)
11947 (org-cycle-hide-drawers 'children)))))
11948 (set-window-configuration org-log-note-window-configuration)
11949 (with-current-buffer (marker-buffer org-log-note-return-to)
11950 (goto-char org-log-note-return-to))
11951 (move-marker org-log-note-return-to nil)
11952 (and org-log-post-message (message "%s" org-log-post-message)))
11954 (defun org-remove-empty-drawer-at (drawer pos)
11955 "Remove an empty drawer DRAWER at position POS.
11956 POS may also be a marker."
11957 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
11958 (save-excursion
11959 (save-restriction
11960 (widen)
11961 (goto-char pos)
11962 (if (org-in-regexp
11963 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
11964 (replace-match ""))))))
11966 (defun org-sparse-tree (&optional arg)
11967 "Create a sparse tree, prompt for the details.
11968 This command can create sparse trees. You first need to select the type
11969 of match used to create the tree:
11971 t Show all TODO entries.
11972 T Show entries with a specific TODO keyword.
11973 m Show entries selected by a tags/property match.
11974 p Enter a property name and its value (both with completion on existing
11975 names/values) and show entries with that property.
11976 r Show entries matching a regular expression (`/' can be used as well)
11977 d Show deadlines due within `org-deadline-warning-days'.
11978 b Show deadlines and scheduled items before a date.
11979 a Show deadlines and scheduled items after a date."
11980 (interactive "P")
11981 (let (ans kwd value)
11982 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date")
11983 (setq ans (read-char-exclusive))
11984 (cond
11985 ((equal ans ?d)
11986 (call-interactively 'org-check-deadlines))
11987 ((equal ans ?b)
11988 (call-interactively 'org-check-before-date))
11989 ((equal ans ?a)
11990 (call-interactively 'org-check-after-date))
11991 ((equal ans ?t)
11992 (org-show-todo-tree nil))
11993 ((equal ans ?T)
11994 (org-show-todo-tree '(4)))
11995 ((member ans '(?T ?m))
11996 (call-interactively 'org-match-sparse-tree))
11997 ((member ans '(?p ?P))
11998 (setq kwd (org-icompleting-read "Property: "
11999 (mapcar 'list (org-buffer-property-keys))))
12000 (setq value (org-icompleting-read "Value: "
12001 (mapcar 'list (org-property-values kwd))))
12002 (unless (string-match "\\`{.*}\\'" value)
12003 (setq value (concat "\"" value "\"")))
12004 (org-match-sparse-tree arg (concat kwd "=" value)))
12005 ((member ans '(?r ?R ?/))
12006 (call-interactively 'org-occur))
12007 (t (error "No such sparse tree command \"%c\"" ans)))))
12009 (defvar org-occur-highlights nil
12010 "List of overlays used for occur matches.")
12011 (make-variable-buffer-local 'org-occur-highlights)
12012 (defvar org-occur-parameters nil
12013 "Parameters of the active org-occur calls.
12014 This is a list, each call to org-occur pushes as cons cell,
12015 containing the regular expression and the callback, onto the list.
12016 The list can contain several entries if `org-occur' has been called
12017 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12018 will only contain one set of parameters. When the highlights are
12019 removed (for example with `C-c C-c', or with the next edit (depending
12020 on `org-remove-highlights-with-change'), this variable is emptied
12021 as well.")
12022 (make-variable-buffer-local 'org-occur-parameters)
12024 (defun org-occur (regexp &optional keep-previous callback)
12025 "Make a compact tree which shows all matches of REGEXP.
12026 The tree will show the lines where the regexp matches, and all higher
12027 headlines above the match. It will also show the heading after the match,
12028 to make sure editing the matching entry is easy.
12029 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12030 call to `org-occur' will be kept, to allow stacking of calls to this
12031 command.
12032 If CALLBACK is non-nil, it is a function which is called to confirm
12033 that the match should indeed be shown."
12034 (interactive "sRegexp: \nP")
12035 (when (equal regexp "")
12036 (error "Regexp cannot be empty"))
12037 (unless keep-previous
12038 (org-remove-occur-highlights nil nil t))
12039 (push (cons regexp callback) org-occur-parameters)
12040 (let ((cnt 0))
12041 (save-excursion
12042 (goto-char (point-min))
12043 (if (or (not keep-previous) ; do not want to keep
12044 (not org-occur-highlights)) ; no previous matches
12045 ;; hide everything
12046 (org-overview))
12047 (while (re-search-forward regexp nil t)
12048 (when (or (not callback)
12049 (save-match-data (funcall callback)))
12050 (setq cnt (1+ cnt))
12051 (when org-highlight-sparse-tree-matches
12052 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12053 (org-show-context 'occur-tree))))
12054 (when org-remove-highlights-with-change
12055 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12056 nil 'local))
12057 (unless org-sparse-tree-open-archived-trees
12058 (org-hide-archived-subtrees (point-min) (point-max)))
12059 (run-hooks 'org-occur-hook)
12060 (if (interactive-p)
12061 (message "%d match(es) for regexp %s" cnt regexp))
12062 cnt))
12064 (defun org-show-context (&optional key)
12065 "Make sure point and context are visible.
12066 How much context is shown depends upon the variables
12067 `org-show-hierarchy-above', `org-show-following-heading'. and
12068 `org-show-siblings'."
12069 (let ((heading-p (org-on-heading-p t))
12070 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12071 (following-p (org-get-alist-option org-show-following-heading key))
12072 (entry-p (org-get-alist-option org-show-entry-below key))
12073 (siblings-p (org-get-alist-option org-show-siblings key)))
12074 (catch 'exit
12075 ;; Show heading or entry text
12076 (if (and heading-p (not entry-p))
12077 (org-flag-heading nil) ; only show the heading
12078 (and (or entry-p (org-invisible-p) (org-invisible-p2))
12079 (org-show-hidden-entry))) ; show entire entry
12080 (when following-p
12081 ;; Show next sibling, or heading below text
12082 (save-excursion
12083 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12084 (org-flag-heading nil))))
12085 (when siblings-p (org-show-siblings))
12086 (when hierarchy-p
12087 ;; show all higher headings, possibly with siblings
12088 (save-excursion
12089 (while (and (condition-case nil
12090 (progn (org-up-heading-all 1) t)
12091 (error nil))
12092 (not (bobp)))
12093 (org-flag-heading nil)
12094 (when siblings-p (org-show-siblings))))))))
12096 (defvar org-reveal-start-hook nil
12097 "Hook run before revealing a location.")
12099 (defun org-reveal (&optional siblings)
12100 "Show current entry, hierarchy above it, and the following headline.
12101 This can be used to show a consistent set of context around locations
12102 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12103 not t for the search context.
12105 With optional argument SIBLINGS, on each level of the hierarchy all
12106 siblings are shown. This repairs the tree structure to what it would
12107 look like when opened with hierarchical calls to `org-cycle'.
12108 With double optional argument \\[universal-argument] \\[universal-argument], \
12109 go to the parent and show the
12110 entire tree."
12111 (interactive "P")
12112 (run-hooks 'org-reveal-start-hook)
12113 (let ((org-show-hierarchy-above t)
12114 (org-show-following-heading t)
12115 (org-show-siblings (if siblings t org-show-siblings)))
12116 (org-show-context nil))
12117 (when (equal siblings '(16))
12118 (save-excursion
12119 (when (org-up-heading-safe)
12120 (org-show-subtree)
12121 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12123 (defun org-highlight-new-match (beg end)
12124 "Highlight from BEG to END and mark the highlight is an occur headline."
12125 (let ((ov (make-overlay beg end)))
12126 (overlay-put ov 'face 'secondary-selection)
12127 (push ov org-occur-highlights)))
12129 (defun org-remove-occur-highlights (&optional beg end noremove)
12130 "Remove the occur highlights from the buffer.
12131 BEG and END are ignored. If NOREMOVE is nil, remove this function
12132 from the `before-change-functions' in the current buffer."
12133 (interactive)
12134 (unless org-inhibit-highlight-removal
12135 (mapc 'delete-overlay org-occur-highlights)
12136 (setq org-occur-highlights nil)
12137 (setq org-occur-parameters nil)
12138 (unless noremove
12139 (remove-hook 'before-change-functions
12140 'org-remove-occur-highlights 'local))))
12142 ;;;; Priorities
12144 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12145 "Regular expression matching the priority indicator.")
12147 (defvar org-remove-priority-next-time nil)
12149 (defun org-priority-up ()
12150 "Increase the priority of the current item."
12151 (interactive)
12152 (org-priority 'up))
12154 (defun org-priority-down ()
12155 "Decrease the priority of the current item."
12156 (interactive)
12157 (org-priority 'down))
12159 (defun org-priority (&optional action)
12160 "Change the priority of an item by ARG.
12161 ACTION can be `set', `up', `down', or a character."
12162 (interactive)
12163 (unless org-enable-priority-commands
12164 (error "Priority commands are disabled"))
12165 (setq action (or action 'set))
12166 (let (current new news have remove)
12167 (save-excursion
12168 (org-back-to-heading t)
12169 (if (looking-at org-priority-regexp)
12170 (setq current (string-to-char (match-string 2))
12171 have t)
12172 (setq current org-default-priority))
12173 (cond
12174 ((eq action 'remove)
12175 (setq remove t new ?\ ))
12176 ((or (eq action 'set)
12177 (if (featurep 'xemacs) (characterp action) (integerp action)))
12178 (if (not (eq action 'set))
12179 (setq new action)
12180 (message "Priority %c-%c, SPC to remove: "
12181 org-highest-priority org-lowest-priority)
12182 (save-match-data
12183 (setq new (read-char-exclusive))))
12184 (if (and (= (upcase org-highest-priority) org-highest-priority)
12185 (= (upcase org-lowest-priority) org-lowest-priority))
12186 (setq new (upcase new)))
12187 (cond ((equal new ?\ ) (setq remove t))
12188 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12189 (error "Priority must be between `%c' and `%c'"
12190 org-highest-priority org-lowest-priority))))
12191 ((eq action 'up)
12192 (if (and (not have) (eq last-command this-command))
12193 (setq new org-lowest-priority)
12194 (setq new (if (and org-priority-start-cycle-with-default (not have))
12195 org-default-priority (1- current)))))
12196 ((eq action 'down)
12197 (if (and (not have) (eq last-command this-command))
12198 (setq new org-highest-priority)
12199 (setq new (if (and org-priority-start-cycle-with-default (not have))
12200 org-default-priority (1+ current)))))
12201 (t (error "Invalid action")))
12202 (if (or (< (upcase new) org-highest-priority)
12203 (> (upcase new) org-lowest-priority))
12204 (setq remove t))
12205 (setq news (format "%c" new))
12206 (if have
12207 (if remove
12208 (replace-match "" t t nil 1)
12209 (replace-match news t t nil 2))
12210 (if remove
12211 (error "No priority cookie found in line")
12212 (let ((case-fold-search nil))
12213 (looking-at org-todo-line-regexp))
12214 (if (match-end 2)
12215 (progn
12216 (goto-char (match-end 2))
12217 (insert " [#" news "]"))
12218 (goto-char (match-beginning 3))
12219 (insert "[#" news "] "))))
12220 (org-preserve-lc (org-set-tags nil 'align)))
12221 (if remove
12222 (message "Priority removed")
12223 (message "Priority of current item set to %s" news))))
12225 (defun org-get-priority (s)
12226 "Find priority cookie and return priority."
12227 (if (functionp org-get-priority-function)
12228 (funcall org-get-priority-function)
12229 (save-match-data
12230 (if (not (string-match org-priority-regexp s))
12231 (* 1000 (- org-lowest-priority org-default-priority))
12232 (* 1000 (- org-lowest-priority
12233 (string-to-char (match-string 2 s))))))))
12235 ;;;; Tags
12237 (defvar org-agenda-archives-mode)
12238 (defvar org-map-continue-from nil
12239 "Position from where mapping should continue.
12240 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
12242 (defvar org-scanner-tags nil
12243 "The current tag list while the tags scanner is running.")
12244 (defvar org-trust-scanner-tags nil
12245 "Should `org-get-tags-at' use the tags fro the scanner.
12246 This is for internal dynamical scoping only.
12247 When this is non-nil, the function `org-get-tags-at' will return the value
12248 of `org-scanner-tags' instead of building the list by itself. This
12249 can lead to large speed-ups when the tags scanner is used in a file with
12250 many entries, and when the list of tags is retrieved, for example to
12251 obtain a list of properties. Building the tags list for each entry in such
12252 a file becomes an N^2 operation - but with this variable set, it scales
12253 as N.")
12255 (defun org-scan-tags (action matcher &optional todo-only)
12256 "Scan headline tags with inheritance and produce output ACTION.
12258 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12259 or `agenda' to produce an entry list for an agenda view. It can also be
12260 a Lisp form or a function that should be called at each matched headline, in
12261 this case the return value is a list of all return values from these calls.
12263 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12264 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12265 only lines with a TODO keyword are included in the output."
12266 (require 'org-agenda)
12267 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
12268 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12269 (org-re
12270 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12271 (props (list 'face 'default
12272 'done-face 'org-agenda-done
12273 'undone-face 'default
12274 'mouse-face 'highlight
12275 'org-not-done-regexp org-not-done-regexp
12276 'org-todo-regexp org-todo-regexp
12277 'help-echo
12278 (format "mouse-2 or RET jump to org file %s"
12279 (abbreviate-file-name
12280 (or (buffer-file-name (buffer-base-buffer))
12281 (buffer-name (buffer-base-buffer)))))))
12282 (case-fold-search nil)
12283 (org-map-continue-from nil)
12284 lspos tags tags-list
12285 (tags-alist (list (cons 0 org-file-tags)))
12286 (llast 0) rtn rtn1 level category i txt
12287 todo marker entry priority)
12288 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12289 (setq action (list 'lambda nil action)))
12290 (save-excursion
12291 (goto-char (point-min))
12292 (when (eq action 'sparse-tree)
12293 (org-overview)
12294 (org-remove-occur-highlights))
12295 (while (re-search-forward re nil t)
12296 (catch :skip
12297 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12298 tags (if (match-end 4) (org-match-string-no-properties 4)))
12299 (goto-char (setq lspos (match-beginning 0)))
12300 (setq level (org-reduced-level (funcall outline-level))
12301 category (org-get-category))
12302 (setq i llast llast level)
12303 ;; remove tag lists from same and sublevels
12304 (while (>= i level)
12305 (when (setq entry (assoc i tags-alist))
12306 (setq tags-alist (delete entry tags-alist)))
12307 (setq i (1- i)))
12308 ;; add the next tags
12309 (when tags
12310 (setq tags (org-split-string tags ":")
12311 tags-alist
12312 (cons (cons level tags) tags-alist)))
12313 ;; compile tags for current headline
12314 (setq tags-list
12315 (if org-use-tag-inheritance
12316 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12317 tags)
12318 org-scanner-tags tags-list)
12319 (when org-use-tag-inheritance
12320 (setcdr (car tags-alist)
12321 (mapcar (lambda (x)
12322 (setq x (copy-sequence x))
12323 (org-add-prop-inherited x))
12324 (cdar tags-alist))))
12325 (when (and tags org-use-tag-inheritance
12326 (or (not (eq t org-use-tag-inheritance))
12327 org-tags-exclude-from-inheritance))
12328 ;; selective inheritance, remove uninherited ones
12329 (setcdr (car tags-alist)
12330 (org-remove-uniherited-tags (cdar tags-alist))))
12331 (when (and (or (not todo-only)
12332 (and (member todo org-not-done-keywords)
12333 (or (not org-agenda-tags-todo-honor-ignore-options)
12334 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12335 (let ((case-fold-search t)) (eval matcher))
12337 (not (member org-archive-tag tags-list))
12338 ;; we have an archive tag, should we use this anyway?
12339 (or (not org-agenda-skip-archived-trees)
12340 (and (eq action 'agenda) org-agenda-archives-mode))))
12341 (unless (eq action 'sparse-tree) (org-agenda-skip))
12343 ;; select this headline
12345 (cond
12346 ((eq action 'sparse-tree)
12347 (and org-highlight-sparse-tree-matches
12348 (org-get-heading) (match-end 0)
12349 (org-highlight-new-match
12350 (match-beginning 0) (match-beginning 1)))
12351 (org-show-context 'tags-tree))
12352 ((eq action 'agenda)
12353 (setq txt (org-format-agenda-item
12355 (concat
12356 (if (eq org-tags-match-list-sublevels 'indented)
12357 (make-string (1- level) ?.) "")
12358 (org-get-heading))
12359 category
12360 tags-list
12362 priority (org-get-priority txt))
12363 (goto-char lspos)
12364 (setq marker (org-agenda-new-marker))
12365 (org-add-props txt props
12366 'org-marker marker 'org-hd-marker marker 'org-category category
12367 'todo-state todo
12368 'priority priority 'type "tagsmatch")
12369 (push txt rtn))
12370 ((functionp action)
12371 (setq org-map-continue-from nil)
12372 (save-excursion
12373 (setq rtn1 (funcall action))
12374 (push rtn1 rtn)))
12375 (t (error "Invalid action")))
12377 ;; if we are to skip sublevels, jump to end of subtree
12378 (unless org-tags-match-list-sublevels
12379 (org-end-of-subtree t)
12380 (backward-char 1))))
12381 ;; Get the correct position from where to continue
12382 (if org-map-continue-from
12383 (goto-char org-map-continue-from)
12384 (and (= (point) lspos) (end-of-line 1)))))
12385 (when (and (eq action 'sparse-tree)
12386 (not org-sparse-tree-open-archived-trees))
12387 (org-hide-archived-subtrees (point-min) (point-max)))
12388 (nreverse rtn)))
12390 (defun org-remove-uniherited-tags (tags)
12391 "Remove all tags that are not inherited from the list TAGS."
12392 (cond
12393 ((eq org-use-tag-inheritance t)
12394 (if org-tags-exclude-from-inheritance
12395 (org-delete-all org-tags-exclude-from-inheritance tags)
12396 tags))
12397 ((not org-use-tag-inheritance) nil)
12398 ((stringp org-use-tag-inheritance)
12399 (delq nil (mapcar
12400 (lambda (x)
12401 (if (and (string-match org-use-tag-inheritance x)
12402 (not (member x org-tags-exclude-from-inheritance)))
12403 x nil))
12404 tags)))
12405 ((listp org-use-tag-inheritance)
12406 (delq nil (mapcar
12407 (lambda (x)
12408 (if (member x org-use-tag-inheritance) x nil))
12409 tags)))))
12411 (defvar todo-only) ;; dynamically scoped
12413 (defun org-match-sparse-tree (&optional todo-only match)
12414 "Create a sparse tree according to tags string MATCH.
12415 MATCH can contain positive and negative selection of tags, like
12416 \"+WORK+URGENT-WITHBOSS\".
12417 If optional argument TODO-ONLY is non-nil, only select lines that are
12418 also TODO lines."
12419 (interactive "P")
12420 (org-prepare-agenda-buffers (list (current-buffer)))
12421 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12423 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12425 (defvar org-cached-props nil)
12426 (defun org-cached-entry-get (pom property)
12427 (if (or (eq t org-use-property-inheritance)
12428 (and (stringp org-use-property-inheritance)
12429 (string-match org-use-property-inheritance property))
12430 (and (listp org-use-property-inheritance)
12431 (member property org-use-property-inheritance)))
12432 ;; Caching is not possible, check it directly
12433 (org-entry-get pom property 'inherit)
12434 ;; Get all properties, so that we can do complicated checks easily
12435 (cdr (assoc property (or org-cached-props
12436 (setq org-cached-props
12437 (org-entry-properties pom)))))))
12439 (defun org-global-tags-completion-table (&optional files)
12440 "Return the list of all tags in all agenda buffer/files."
12441 (save-excursion
12442 (org-uniquify
12443 (delq nil
12444 (apply 'append
12445 (mapcar
12446 (lambda (file)
12447 (set-buffer (find-file-noselect file))
12448 (append (org-get-buffer-tags)
12449 (mapcar (lambda (x) (if (stringp (car-safe x))
12450 (list (car-safe x)) nil))
12451 org-tag-alist)))
12452 (if (and files (car files))
12453 files
12454 (org-agenda-files))))))))
12456 (defun org-make-tags-matcher (match)
12457 "Create the TAGS//TODO matcher form for the selection string MATCH."
12458 ;; todo-only is scoped dynamically into this function, and the function
12459 ;; may change it if the matcher asks for it.
12460 (unless match
12461 ;; Get a new match request, with completion
12462 (let ((org-last-tags-completion-table
12463 (org-global-tags-completion-table)))
12464 (setq match (org-completing-read-no-i
12465 "Match: " 'org-tags-completion-function nil nil nil
12466 'org-tags-history))))
12468 ;; Parse the string and create a lisp form
12469 (let ((match0 match)
12470 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
12471 minus tag mm
12472 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12473 orterms term orlist re-p str-p level-p level-op time-p
12474 prop-p pn pv po cat-p gv rest)
12475 (if (string-match "/+" match)
12476 ;; match contains also a todo-matching request
12477 (progn
12478 (setq tagsmatch (substring match 0 (match-beginning 0))
12479 todomatch (substring match (match-end 0)))
12480 (if (string-match "^!" todomatch)
12481 (setq todo-only t todomatch (substring todomatch 1)))
12482 (if (string-match "^\\s-*$" todomatch)
12483 (setq todomatch nil)))
12484 ;; only matching tags
12485 (setq tagsmatch match todomatch nil))
12487 ;; Make the tags matcher
12488 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12489 (setq tagsmatcher t)
12490 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12491 (while (setq term (pop orterms))
12492 (while (and (equal (substring term -1) "\\") orterms)
12493 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12494 (while (string-match re term)
12495 (setq rest (substring term (match-end 0))
12496 minus (and (match-end 1)
12497 (equal (match-string 1 term) "-"))
12498 tag (save-match-data (replace-regexp-in-string
12499 "\\\\-" "-"
12500 (match-string 2 term)))
12501 re-p (equal (string-to-char tag) ?{)
12502 level-p (match-end 4)
12503 prop-p (match-end 5)
12504 mm (cond
12505 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12506 (level-p
12507 (setq level-op (org-op-to-function (match-string 3 term)))
12508 `(,level-op level ,(string-to-number
12509 (match-string 4 term))))
12510 (prop-p
12511 (setq pn (match-string 5 term)
12512 po (match-string 6 term)
12513 pv (match-string 7 term)
12514 cat-p (equal pn "CATEGORY")
12515 re-p (equal (string-to-char pv) ?{)
12516 str-p (equal (string-to-char pv) ?\")
12517 time-p (save-match-data
12518 (string-match "^\"[[<].*[]>]\"$" pv))
12519 pv (if (or re-p str-p) (substring pv 1 -1) pv))
12520 (if time-p (setq pv (org-matcher-time pv)))
12521 (setq po (org-op-to-function po (if time-p 'time str-p)))
12522 (cond
12523 ((equal pn "CATEGORY")
12524 (setq gv '(get-text-property (point) 'org-category)))
12525 ((equal pn "TODO")
12526 (setq gv 'todo))
12528 (setq gv `(org-cached-entry-get nil ,pn))))
12529 (if re-p
12530 (if (eq po 'org<>)
12531 `(not (string-match ,pv (or ,gv "")))
12532 `(string-match ,pv (or ,gv "")))
12533 (if str-p
12534 `(,po (or ,gv "") ,pv)
12535 `(,po (string-to-number (or ,gv ""))
12536 ,(string-to-number pv) ))))
12537 (t `(member ,tag tags-list)))
12538 mm (if minus (list 'not mm) mm)
12539 term rest)
12540 (push mm tagsmatcher))
12541 (push (if (> (length tagsmatcher) 1)
12542 (cons 'and tagsmatcher)
12543 (car tagsmatcher))
12544 orlist)
12545 (setq tagsmatcher nil))
12546 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
12547 (setq tagsmatcher
12548 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
12549 ;; Make the todo matcher
12550 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
12551 (setq todomatcher t)
12552 (setq orterms (org-split-string todomatch "|") orlist nil)
12553 (while (setq term (pop orterms))
12554 (while (string-match re term)
12555 (setq minus (and (match-end 1)
12556 (equal (match-string 1 term) "-"))
12557 kwd (match-string 2 term)
12558 re-p (equal (string-to-char kwd) ?{)
12559 term (substring term (match-end 0))
12560 mm (if re-p
12561 `(string-match ,(substring kwd 1 -1) todo)
12562 (list 'equal 'todo kwd))
12563 mm (if minus (list 'not mm) mm))
12564 (push mm todomatcher))
12565 (push (if (> (length todomatcher) 1)
12566 (cons 'and todomatcher)
12567 (car todomatcher))
12568 orlist)
12569 (setq todomatcher nil))
12570 (setq todomatcher (if (> (length orlist) 1)
12571 (cons 'or orlist) (car orlist))))
12573 ;; Return the string and lisp forms of the matcher
12574 (setq matcher (if todomatcher
12575 (list 'and tagsmatcher todomatcher)
12576 tagsmatcher))
12577 (cons match0 matcher)))
12579 (defun org-op-to-function (op &optional stringp)
12580 "Turn an operator into the appropriate function."
12581 (setq op
12582 (cond
12583 ((equal op "<" ) '(< string< org-time<))
12584 ((equal op ">" ) '(> org-string> org-time>))
12585 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
12586 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
12587 ((member op '("=" "==")) '(= string= org-time=))
12588 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
12589 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
12591 (defun org<> (a b) (not (= a b)))
12592 (defun org-string<= (a b) (or (string= a b) (string< a b)))
12593 (defun org-string>= (a b) (not (string< a b)))
12594 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
12595 (defun org-string<> (a b) (not (string= a b)))
12596 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
12597 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
12598 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
12599 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
12600 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
12601 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
12602 (defun org-2ft (s)
12603 "Convert S to a floating point time.
12604 If S is already a number, just return it. If it is a string, parse
12605 it as a time string and apply `float-time' to it. If S is nil, just return 0."
12606 (cond
12607 ((numberp s) s)
12608 ((stringp s)
12609 (condition-case nil
12610 (float-time (apply 'encode-time (org-parse-time-string s)))
12611 (error 0.)))
12612 (t 0.)))
12614 (defun org-time-today ()
12615 "Time in seconds today at 0:00.
12616 Returns the float number of seconds since the beginning of the
12617 epoch to the beginning of today (00:00)."
12618 (float-time (apply 'encode-time
12619 (append '(0 0 0) (nthcdr 3 (decode-time))))))
12621 (defun org-matcher-time (s)
12622 "Interpret a time comparison value."
12623 (save-match-data
12624 (cond
12625 ((string= s "<now>") (float-time))
12626 ((string= s "<today>") (org-time-today))
12627 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
12628 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
12629 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
12630 (+ (org-time-today)
12631 (* (string-to-number (match-string 1 s))
12632 (cdr (assoc (match-string 2 s)
12633 '(("d" . 86400.0) ("w" . 604800.0)
12634 ("m" . 2678400.0) ("y" . 31557600.0)))))))
12635 (t (org-2ft s)))))
12637 (defun org-match-any-p (re list)
12638 "Does re match any element of list?"
12639 (setq list (mapcar (lambda (x) (string-match re x)) list))
12640 (delq nil list))
12642 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
12643 (defvar org-tags-overlay (make-overlay 1 1))
12644 (org-detach-overlay org-tags-overlay)
12646 (defun org-get-local-tags-at (&optional pos)
12647 "Get a list of tags defined in the current headline."
12648 (org-get-tags-at pos 'local))
12650 (defun org-get-local-tags ()
12651 "Get a list of tags defined in the current headline."
12652 (org-get-tags-at nil 'local))
12654 (defun org-get-tags-at (&optional pos local)
12655 "Get a list of all headline tags applicable at POS.
12656 POS defaults to point. If tags are inherited, the list contains
12657 the targets in the same sequence as the headlines appear, i.e.
12658 the tags of the current headline come last.
12659 When LOCAL is non-nil, only return tags from the current headline,
12660 ignore inherited ones."
12661 (interactive)
12662 (if (and org-trust-scanner-tags
12663 (or (not pos) (equal pos (point)))
12664 (not local))
12665 org-scanner-tags
12666 (let (tags ltags lastpos parent)
12667 (save-excursion
12668 (save-restriction
12669 (widen)
12670 (goto-char (or pos (point)))
12671 (save-match-data
12672 (catch 'done
12673 (condition-case nil
12674 (progn
12675 (org-back-to-heading t)
12676 (while (not (equal lastpos (point)))
12677 (setq lastpos (point))
12678 (when (looking-at
12679 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
12680 (setq ltags (org-split-string
12681 (org-match-string-no-properties 1) ":"))
12682 (when parent
12683 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
12684 (setq tags (append
12685 (if parent
12686 (org-remove-uniherited-tags ltags)
12687 ltags)
12688 tags)))
12689 (or org-use-tag-inheritance (throw 'done t))
12690 (if local (throw 'done t))
12691 (or (org-up-heading-safe) (error nil))
12692 (setq parent t)))
12693 (error nil)))))
12694 (append (org-remove-uniherited-tags org-file-tags) tags)))))
12696 (defun org-add-prop-inherited (s)
12697 (add-text-properties 0 (length s) '(inherited t) s)
12700 (defun org-toggle-tag (tag &optional onoff)
12701 "Toggle the tag TAG for the current line.
12702 If ONOFF is `on' or `off', don't toggle but set to this state."
12703 (let (res current)
12704 (save-excursion
12705 (org-back-to-heading t)
12706 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
12707 (point-at-eol) t)
12708 (progn
12709 (setq current (match-string 1))
12710 (replace-match ""))
12711 (setq current ""))
12712 (setq current (nreverse (org-split-string current ":")))
12713 (cond
12714 ((eq onoff 'on)
12715 (setq res t)
12716 (or (member tag current) (push tag current)))
12717 ((eq onoff 'off)
12718 (or (not (member tag current)) (setq current (delete tag current))))
12719 (t (if (member tag current)
12720 (setq current (delete tag current))
12721 (setq res t)
12722 (push tag current))))
12723 (end-of-line 1)
12724 (if current
12725 (progn
12726 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
12727 (org-set-tags nil t))
12728 (delete-horizontal-space))
12729 (run-hooks 'org-after-tags-change-hook))
12730 res))
12732 (defun org-align-tags-here (to-col)
12733 ;; Assumes that this is a headline
12734 (let ((pos (point)) (col (current-column)) ncol tags-l p)
12735 (beginning-of-line 1)
12736 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
12737 (< pos (match-beginning 2)))
12738 (progn
12739 (setq tags-l (- (match-end 2) (match-beginning 2)))
12740 (goto-char (match-beginning 1))
12741 (insert " ")
12742 (delete-region (point) (1+ (match-beginning 2)))
12743 (setq ncol (max (1+ (current-column))
12744 (1+ col)
12745 (if (> to-col 0)
12746 to-col
12747 (- (abs to-col) tags-l))))
12748 (setq p (point))
12749 (insert (make-string (- ncol (current-column)) ?\ ))
12750 (setq ncol (current-column))
12751 (when indent-tabs-mode (tabify p (point-at-eol)))
12752 (org-move-to-column (min ncol col) t))
12753 (goto-char pos))))
12755 (defun org-set-tags-command (&optional arg just-align)
12756 "Call the set-tags command for the current entry."
12757 (interactive "P")
12758 (if (org-on-heading-p)
12759 (org-set-tags arg just-align)
12760 (save-excursion
12761 (org-back-to-heading t)
12762 (org-set-tags arg just-align))))
12764 (defun org-set-tags-to (data)
12765 "Set the tags of the current entry to DATA, replacing the current tags.
12766 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
12767 If DATA is nil or the empty string, any tags will be removed."
12768 (interactive "sTags: ")
12769 (setq data
12770 (cond
12771 ((eq data nil) "")
12772 ((equal data "") "")
12773 ((stringp data)
12774 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
12775 ":"))
12776 ((listp data)
12777 (concat ":" (mapconcat 'identity data ":") ":"))
12778 (t nil)))
12779 (when data
12780 (save-excursion
12781 (org-back-to-heading t)
12782 (when (looking-at org-complex-heading-regexp)
12783 (if (match-end 5)
12784 (progn
12785 (goto-char (match-beginning 5))
12786 (insert data)
12787 (delete-region (point) (point-at-eol))
12788 (org-set-tags nil 'align))
12789 (goto-char (point-at-eol))
12790 (insert " " data)
12791 (org-set-tags nil 'align)))
12792 (beginning-of-line 1)
12793 (if (looking-at ".*?\\([ \t]+\\)$")
12794 (delete-region (match-beginning 1) (match-end 1))))))
12796 (defun org-align-all-tags ()
12797 "Align the tags i all headings."
12798 (interactive)
12799 (save-excursion
12800 (or (ignore-errors (org-back-to-heading t))
12801 (outline-next-heading))
12802 (if (org-on-heading-p)
12803 (org-set-tags t)
12804 (message "No headings"))))
12806 (defvar org-indent-indentation-per-level)
12807 (defun org-set-tags (&optional arg just-align)
12808 "Set the tags for the current headline.
12809 With prefix ARG, realign all tags in headings in the current buffer."
12810 (interactive "P")
12811 (let* ((re (concat "^" outline-regexp))
12812 (current (org-get-tags-string))
12813 (col (current-column))
12814 (org-setting-tags t)
12815 table current-tags inherited-tags ; computed below when needed
12816 tags p0 c0 c1 rpl di tc level)
12817 (if arg
12818 (save-excursion
12819 (goto-char (point-min))
12820 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12821 (while (re-search-forward re nil t)
12822 (org-set-tags nil t)
12823 (end-of-line 1)))
12824 (message "All tags realigned to column %d" org-tags-column))
12825 (if just-align
12826 (setq tags current)
12827 ;; Get a new set of tags from the user
12828 (save-excursion
12829 (setq table (append org-tag-persistent-alist
12830 (or org-tag-alist (org-get-buffer-tags))
12831 (and
12832 org-complete-tags-always-offer-all-agenda-tags
12833 (org-global-tags-completion-table
12834 (org-agenda-files))))
12835 org-last-tags-completion-table table
12836 current-tags (org-split-string current ":")
12837 inherited-tags (nreverse
12838 (nthcdr (length current-tags)
12839 (nreverse (org-get-tags-at))))
12840 tags
12841 (if (or (eq t org-use-fast-tag-selection)
12842 (and org-use-fast-tag-selection
12843 (delq nil (mapcar 'cdr table))))
12844 (org-fast-tag-selection
12845 current-tags inherited-tags table
12846 (if org-fast-tag-selection-include-todo
12847 org-todo-key-alist))
12848 (let ((org-add-colon-after-tag-completion t))
12849 (org-trim
12850 (org-without-partial-completion
12851 (org-icompleting-read "Tags: "
12852 'org-tags-completion-function
12853 nil nil current 'org-tags-history)))))))
12854 (while (string-match "[-+&]+" tags)
12855 ;; No boolean logic, just a list
12856 (setq tags (replace-match ":" t t tags))))
12858 (setq tags (replace-regexp-in-string "[ ,]" ":" tags))
12860 (if org-tags-sort-function
12861 (setq tags (mapconcat 'identity
12862 (sort (org-split-string
12863 tags (org-re "[^[:alnum:]_@#%]+"))
12864 org-tags-sort-function) ":")))
12866 (if (string-match "\\`[\t ]*\\'" tags)
12867 (setq tags "")
12868 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
12869 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
12871 ;; Insert new tags at the correct column
12872 (beginning-of-line 1)
12873 (setq level (or (and (looking-at org-outline-regexp)
12874 (- (match-end 0) (point) 1))
12876 (cond
12877 ((and (equal current "") (equal tags "")))
12878 ((re-search-forward
12879 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
12880 (point-at-eol) t)
12881 (if (equal tags "")
12882 (setq rpl "")
12883 (goto-char (match-beginning 0))
12884 (setq c0 (current-column)
12885 ;; compute offset for the case of org-indent-mode active
12886 di (if org-indent-mode
12887 (* (1- org-indent-indentation-per-level) (1- level))
12889 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
12890 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
12891 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
12892 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
12893 (replace-match rpl t t)
12894 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
12895 tags)
12896 (t (error "Tags alignment failed")))
12897 (org-move-to-column col)
12898 (unless just-align
12899 (run-hooks 'org-after-tags-change-hook)))))
12901 (defun org-change-tag-in-region (beg end tag off)
12902 "Add or remove TAG for each entry in the region.
12903 This works in the agenda, and also in an org-mode buffer."
12904 (interactive
12905 (list (region-beginning) (region-end)
12906 (let ((org-last-tags-completion-table
12907 (if (org-mode-p)
12908 (org-get-buffer-tags)
12909 (org-global-tags-completion-table))))
12910 (org-icompleting-read
12911 "Tag: " 'org-tags-completion-function nil nil nil
12912 'org-tags-history))
12913 (progn
12914 (message "[s]et or [r]emove? ")
12915 (equal (read-char-exclusive) ?r))))
12916 (if (fboundp 'deactivate-mark) (deactivate-mark))
12917 (let ((agendap (equal major-mode 'org-agenda-mode))
12918 l1 l2 m buf pos newhead (cnt 0))
12919 (goto-char end)
12920 (setq l2 (1- (org-current-line)))
12921 (goto-char beg)
12922 (setq l1 (org-current-line))
12923 (loop for l from l1 to l2 do
12924 (org-goto-line l)
12925 (setq m (get-text-property (point) 'org-hd-marker))
12926 (when (or (and (org-mode-p) (org-on-heading-p))
12927 (and agendap m))
12928 (setq buf (if agendap (marker-buffer m) (current-buffer))
12929 pos (if agendap m (point)))
12930 (with-current-buffer buf
12931 (save-excursion
12932 (save-restriction
12933 (goto-char pos)
12934 (setq cnt (1+ cnt))
12935 (org-toggle-tag tag (if off 'off 'on))
12936 (setq newhead (org-get-heading)))))
12937 (and agendap (org-agenda-change-all-lines newhead m))))
12938 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
12940 (defun org-tags-completion-function (string predicate &optional flag)
12941 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
12942 (confirm (lambda (x) (stringp (car x)))))
12943 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
12944 (setq s1 (match-string 1 string)
12945 s2 (match-string 2 string))
12946 (setq s1 "" s2 string))
12947 (cond
12948 ((eq flag nil)
12949 ;; try completion
12950 (setq rtn (try-completion s2 ctable confirm))
12951 (if (stringp rtn)
12952 (setq rtn
12953 (concat s1 s2 (substring rtn (length s2))
12954 (if (and org-add-colon-after-tag-completion
12955 (assoc rtn ctable))
12956 ":" ""))))
12957 rtn)
12958 ((eq flag t)
12959 ;; all-completions
12960 (all-completions s2 ctable confirm)
12962 ((eq flag 'lambda)
12963 ;; exact match?
12964 (assoc s2 ctable)))
12967 (defun org-fast-tag-insert (kwd tags face &optional end)
12968 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
12969 (insert (format "%-12s" (concat kwd ":"))
12970 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
12971 (or end "")))
12973 (defun org-fast-tag-show-exit (flag)
12974 (save-excursion
12975 (org-goto-line 3)
12976 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
12977 (replace-match ""))
12978 (when flag
12979 (end-of-line 1)
12980 (org-move-to-column (- (window-width) 19) t)
12981 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
12983 (defun org-set-current-tags-overlay (current prefix)
12984 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
12985 (if (featurep 'xemacs)
12986 (org-overlay-display org-tags-overlay (concat prefix s)
12987 'secondary-selection)
12988 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
12989 (org-overlay-display org-tags-overlay (concat prefix s)))))
12991 (defvar org-last-tag-selection-key nil)
12992 (defun org-fast-tag-selection (current inherited table &optional todo-table)
12993 "Fast tag selection with single keys.
12994 CURRENT is the current list of tags in the headline, INHERITED is the
12995 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
12996 possibly with grouping information. TODO-TABLE is a similar table with
12997 TODO keywords, should these have keys assigned to them.
12998 If the keys are nil, a-z are automatically assigned.
12999 Returns the new tags string, or nil to not change the current settings."
13000 (let* ((fulltable (append table todo-table))
13001 (maxlen (apply 'max (mapcar
13002 (lambda (x)
13003 (if (stringp (car x)) (string-width (car x)) 0))
13004 fulltable)))
13005 (buf (current-buffer))
13006 (expert (eq org-fast-tag-selection-single-key 'expert))
13007 (buffer-tags nil)
13008 (fwidth (+ maxlen 3 1 3))
13009 (ncol (/ (- (window-width) 4) fwidth))
13010 (i-face 'org-done)
13011 (c-face 'org-todo)
13012 tg cnt e c char c1 c2 ntable tbl rtn
13013 ov-start ov-end ov-prefix
13014 (exit-after-next org-fast-tag-selection-single-key)
13015 (done-keywords org-done-keywords)
13016 groups ingroup)
13017 (save-excursion
13018 (beginning-of-line 1)
13019 (if (looking-at
13020 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13021 (setq ov-start (match-beginning 1)
13022 ov-end (match-end 1)
13023 ov-prefix "")
13024 (setq ov-start (1- (point-at-eol))
13025 ov-end (1+ ov-start))
13026 (skip-chars-forward "^\n\r")
13027 (setq ov-prefix
13028 (concat
13029 (buffer-substring (1- (point)) (point))
13030 (if (> (current-column) org-tags-column)
13032 (make-string (- org-tags-column (current-column)) ?\ ))))))
13033 (move-overlay org-tags-overlay ov-start ov-end)
13034 (save-window-excursion
13035 (if expert
13036 (set-buffer (get-buffer-create " *Org tags*"))
13037 (delete-other-windows)
13038 (split-window-vertically)
13039 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13040 (erase-buffer)
13041 (org-set-local 'org-done-keywords done-keywords)
13042 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13043 (org-fast-tag-insert "Current" current c-face "\n\n")
13044 (org-fast-tag-show-exit exit-after-next)
13045 (org-set-current-tags-overlay current ov-prefix)
13046 (setq tbl fulltable char ?a cnt 0)
13047 (while (setq e (pop tbl))
13048 (cond
13049 ((equal (car e) :startgroup)
13050 (push '() groups) (setq ingroup t)
13051 (when (not (= cnt 0))
13052 (setq cnt 0)
13053 (insert "\n"))
13054 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13055 ((equal (car e) :endgroup)
13056 (setq ingroup nil cnt 0)
13057 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13058 ((equal e '(:newline))
13059 (when (not (= cnt 0))
13060 (setq cnt 0)
13061 (insert "\n")
13062 (setq e (car tbl))
13063 (while (equal (car tbl) '(:newline))
13064 (insert "\n")
13065 (setq tbl (cdr tbl)))))
13067 (setq tg (copy-sequence (car e)) c2 nil)
13068 (if (cdr e)
13069 (setq c (cdr e))
13070 ;; automatically assign a character.
13071 (setq c1 (string-to-char
13072 (downcase (substring
13073 tg (if (= (string-to-char tg) ?@) 1 0)))))
13074 (if (or (rassoc c1 ntable) (rassoc c1 table))
13075 (while (or (rassoc char ntable) (rassoc char table))
13076 (setq char (1+ char)))
13077 (setq c2 c1))
13078 (setq c (or c2 char)))
13079 (if ingroup (push tg (car groups)))
13080 (setq tg (org-add-props tg nil 'face
13081 (cond
13082 ((not (assoc tg table))
13083 (org-get-todo-face tg))
13084 ((member tg current) c-face)
13085 ((member tg inherited) i-face)
13086 (t nil))))
13087 (if (and (= cnt 0) (not ingroup)) (insert " "))
13088 (insert "[" c "] " tg (make-string
13089 (- fwidth 4 (length tg)) ?\ ))
13090 (push (cons tg c) ntable)
13091 (when (= (setq cnt (1+ cnt)) ncol)
13092 (insert "\n")
13093 (if ingroup (insert " "))
13094 (setq cnt 0)))))
13095 (setq ntable (nreverse ntable))
13096 (insert "\n")
13097 (goto-char (point-min))
13098 (if (not expert) (org-fit-window-to-buffer))
13099 (setq rtn
13100 (catch 'exit
13101 (while t
13102 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13103 (if (not groups) "no " "")
13104 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13105 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13106 (setq org-last-tag-selection-key c)
13107 (cond
13108 ((= c ?\r) (throw 'exit t))
13109 ((= c ?!)
13110 (setq groups (not groups))
13111 (goto-char (point-min))
13112 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13113 ((= c ?\C-c)
13114 (if (not expert)
13115 (org-fast-tag-show-exit
13116 (setq exit-after-next (not exit-after-next)))
13117 (setq expert nil)
13118 (delete-other-windows)
13119 (split-window-vertically)
13120 (org-switch-to-buffer-other-window " *Org tags*")
13121 (org-fit-window-to-buffer)))
13122 ((or (= c ?\C-g)
13123 (and (= c ?q) (not (rassoc c ntable))))
13124 (org-detach-overlay org-tags-overlay)
13125 (setq quit-flag t))
13126 ((= c ?\ )
13127 (setq current nil)
13128 (if exit-after-next (setq exit-after-next 'now)))
13129 ((= c ?\t)
13130 (condition-case nil
13131 (setq tg (org-icompleting-read
13132 "Tag: "
13133 (or buffer-tags
13134 (with-current-buffer buf
13135 (org-get-buffer-tags)))))
13136 (quit (setq tg "")))
13137 (when (string-match "\\S-" tg)
13138 (add-to-list 'buffer-tags (list tg))
13139 (if (member tg current)
13140 (setq current (delete tg current))
13141 (push tg current)))
13142 (if exit-after-next (setq exit-after-next 'now)))
13143 ((setq e (rassoc c todo-table) tg (car e))
13144 (with-current-buffer buf
13145 (save-excursion (org-todo tg)))
13146 (if exit-after-next (setq exit-after-next 'now)))
13147 ((setq e (rassoc c ntable) tg (car e))
13148 (if (member tg current)
13149 (setq current (delete tg current))
13150 (loop for g in groups do
13151 (if (member tg g)
13152 (mapc (lambda (x)
13153 (setq current (delete x current)))
13154 g)))
13155 (push tg current))
13156 (if exit-after-next (setq exit-after-next 'now))))
13158 ;; Create a sorted list
13159 (setq current
13160 (sort current
13161 (lambda (a b)
13162 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13163 (if (eq exit-after-next 'now) (throw 'exit t))
13164 (goto-char (point-min))
13165 (beginning-of-line 2)
13166 (delete-region (point) (point-at-eol))
13167 (org-fast-tag-insert "Current" current c-face)
13168 (org-set-current-tags-overlay current ov-prefix)
13169 (while (re-search-forward
13170 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13171 (setq tg (match-string 1))
13172 (add-text-properties
13173 (match-beginning 1) (match-end 1)
13174 (list 'face
13175 (cond
13176 ((member tg current) c-face)
13177 ((member tg inherited) i-face)
13178 (t (get-text-property (match-beginning 1) 'face))))))
13179 (goto-char (point-min)))))
13180 (org-detach-overlay org-tags-overlay)
13181 (if rtn
13182 (mapconcat 'identity current ":")
13183 nil))))
13185 (defun org-get-tags-string ()
13186 "Get the TAGS string in the current headline."
13187 (unless (org-on-heading-p t)
13188 (error "Not on a heading"))
13189 (save-excursion
13190 (beginning-of-line 1)
13191 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13192 (org-match-string-no-properties 1)
13193 "")))
13195 (defun org-get-tags ()
13196 "Get the list of tags specified in the current headline."
13197 (org-split-string (org-get-tags-string) ":"))
13199 (defun org-get-buffer-tags ()
13200 "Get a table of all tags used in the buffer, for completion."
13201 (let (tags)
13202 (save-excursion
13203 (goto-char (point-min))
13204 (while (re-search-forward
13205 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13206 (when (equal (char-after (point-at-bol 0)) ?*)
13207 (mapc (lambda (x) (add-to-list 'tags x))
13208 (org-split-string (org-match-string-no-properties 1) ":")))))
13209 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13210 (mapcar 'list tags)))
13212 ;;;; The mapping API
13214 ;;;###autoload
13215 (defun org-map-entries (func &optional match scope &rest skip)
13216 "Call FUNC at each headline selected by MATCH in SCOPE.
13218 FUNC is a function or a lisp form. The function will be called without
13219 arguments, with the cursor positioned at the beginning of the headline.
13220 The return values of all calls to the function will be collected and
13221 returned as a list.
13223 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13224 does not need to preserve point. After evaluation, the cursor will be
13225 moved to the end of the line (presumably of the headline of the
13226 processed entry) and search continues from there. Under some
13227 circumstances, this may not produce the wanted results. For example,
13228 if you have removed (e.g. archived) the current (sub)tree it could
13229 mean that the next entry will be skipped entirely. In such cases, you
13230 can specify the position from where search should continue by making
13231 FUNC set the variable `org-map-continue-from' to the desired buffer
13232 position.
13234 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13235 Only headlines that are matched by this query will be considered during
13236 the iteration. When MATCH is nil or t, all headlines will be
13237 visited by the iteration.
13239 SCOPE determines the scope of this command. It can be any of:
13241 nil The current buffer, respecting the restriction if any
13242 tree The subtree started with the entry at point
13243 file The current buffer, without restriction
13244 file-with-archives
13245 The current buffer, and any archives associated with it
13246 agenda All agenda files
13247 agenda-with-archives
13248 All agenda files with any archive files associated with them
13249 \(file1 file2 ...)
13250 If this is a list, all files in the list will be scanned
13252 The remaining args are treated as settings for the skipping facilities of
13253 the scanner. The following items can be given here:
13255 archive skip trees with the archive tag.
13256 comment skip trees with the COMMENT keyword
13257 function or Emacs Lisp form:
13258 will be used as value for `org-agenda-skip-function', so whenever
13259 the function returns t, FUNC will not be called for that
13260 entry and search will continue from the point where the
13261 function leaves it.
13263 If your function needs to retrieve the tags including inherited tags
13264 at the *current* entry, you can use the value of the variable
13265 `org-scanner-tags' which will be much faster than getting the value
13266 with `org-get-tags-at'. If your function gets properties with
13267 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13268 to t around the call to `org-entry-properties' to get the same speedup.
13269 Note that if your function moves around to retrieve tags and properties at
13270 a *different* entry, you cannot use these techniques."
13271 (let* ((org-agenda-archives-mode nil) ; just to make sure
13272 (org-agenda-skip-archived-trees (memq 'archive skip))
13273 (org-agenda-skip-comment-trees (memq 'comment skip))
13274 (org-agenda-skip-function
13275 (car (org-delete-all '(comment archive) skip)))
13276 (org-tags-match-list-sublevels t)
13277 matcher file res
13278 org-todo-keywords-for-agenda
13279 org-done-keywords-for-agenda
13280 org-todo-keyword-alist-for-agenda
13281 org-drawers-for-agenda
13282 org-tag-alist-for-agenda)
13284 (cond
13285 ((eq match t) (setq matcher t))
13286 ((eq match nil) (setq matcher t))
13287 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13289 (save-excursion
13290 (save-restriction
13291 (when (eq scope 'tree)
13292 (org-back-to-heading t)
13293 (org-narrow-to-subtree)
13294 (setq scope nil))
13296 (if (not scope)
13297 (progn
13298 (org-prepare-agenda-buffers
13299 (list (buffer-file-name (current-buffer))))
13300 (setq res (org-scan-tags func matcher)))
13301 ;; Get the right scope
13302 (cond
13303 ((and scope (listp scope) (symbolp (car scope)))
13304 (setq scope (eval scope)))
13305 ((eq scope 'agenda)
13306 (setq scope (org-agenda-files t)))
13307 ((eq scope 'agenda-with-archives)
13308 (setq scope (org-agenda-files t))
13309 (setq scope (org-add-archive-files scope)))
13310 ((eq scope 'file)
13311 (setq scope (list (buffer-file-name))))
13312 ((eq scope 'file-with-archives)
13313 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13314 (org-prepare-agenda-buffers scope)
13315 (while (setq file (pop scope))
13316 (with-current-buffer (org-find-base-buffer-visiting file)
13317 (save-excursion
13318 (save-restriction
13319 (widen)
13320 (goto-char (point-min))
13321 (setq res (append res (org-scan-tags func matcher))))))))))
13322 res))
13324 ;;;; Properties
13326 ;;; Setting and retrieving properties
13328 (defconst org-special-properties
13329 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13330 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED")
13331 "The special properties valid in Org-mode.
13333 These are properties that are not defined in the property drawer,
13334 but in some other way.")
13336 (defconst org-default-properties
13337 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13338 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13339 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13340 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13341 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13342 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13343 "Some properties that are used by Org-mode for various purposes.
13344 Being in this list makes sure that they are offered for completion.")
13346 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13347 "Regular expression matching the first line of a property drawer.")
13349 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13350 "Regular expression matching the last line of a property drawer.")
13352 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13353 "Regular expression matching the first line of a property drawer.")
13355 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13356 "Regular expression matching the first line of a property drawer.")
13358 (defconst org-property-drawer-re
13359 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13360 org-property-end-re "\\)\n?")
13361 "Matches an entire property drawer.")
13363 (defconst org-clock-drawer-re
13364 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13365 org-property-end-re "\\)\n?")
13366 "Matches an entire clock drawer.")
13368 (defun org-property-action ()
13369 "Do an action on properties."
13370 (interactive)
13371 (let (c)
13372 (org-at-property-p)
13373 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13374 (setq c (read-char-exclusive))
13375 (cond
13376 ((equal c ?s)
13377 (call-interactively 'org-set-property))
13378 ((equal c ?d)
13379 (call-interactively 'org-delete-property))
13380 ((equal c ?D)
13381 (call-interactively 'org-delete-property-globally))
13382 ((equal c ?c)
13383 (call-interactively 'org-compute-property-at-point))
13384 (t (error "No such property action %c" c)))))
13386 (defun org-set-effort (&optional value)
13387 "Set the effort property of the current entry.
13388 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13389 allowed value."
13390 (interactive "P")
13391 (if (equal value 0) (setq value 10))
13392 (let* ((completion-ignore-case t)
13393 (prop org-effort-property)
13394 (cur (org-entry-get nil prop))
13395 (allowed (org-property-get-allowed-values nil prop 'table))
13396 (existing (mapcar 'list (org-property-values prop)))
13398 (val (cond
13399 ((stringp value) value)
13400 ((and allowed (integerp value))
13401 (or (car (nth (1- value) allowed))
13402 (car (org-last allowed))))
13403 (allowed
13404 (message "Select 1-9,0, [RET%s]: %s"
13405 (if cur (concat "=" cur) "")
13406 (mapconcat 'car allowed " "))
13407 (setq rpl (read-char-exclusive))
13408 (if (equal rpl ?\r)
13410 (setq rpl (- rpl ?0))
13411 (if (equal rpl 0) (setq rpl 10))
13412 (if (and (> rpl 0) (<= rpl (length allowed)))
13413 (car (nth (1- rpl) allowed))
13414 (org-completing-read "Effort: " allowed nil))))
13416 (let (org-completion-use-ido org-completion-use-iswitchb)
13417 (org-completing-read
13418 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13419 (concat "[" cur "]") "")
13420 ": ")
13421 existing nil nil "" nil cur))))))
13422 (unless (equal (org-entry-get nil prop) val)
13423 (org-entry-put nil prop val))
13424 (message "%s is now %s" prop val)))
13426 (defun org-at-property-p ()
13427 "Is cursor inside a property drawer?"
13428 (save-excursion
13429 (beginning-of-line 1)
13430 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13431 (save-match-data ;; Used by calling procedures
13432 (let ((p (point))
13433 (range (unless (org-before-first-heading-p)
13434 (org-get-property-block))))
13435 (and range (<= (car range) p) (< p (cdr range))))))))
13437 (defun org-get-property-block (&optional beg end force)
13438 "Return the (beg . end) range of the body of the property drawer.
13439 BEG and END can be beginning and end of subtree, if not given
13440 they will be found.
13441 If the drawer does not exist and FORCE is non-nil, create the drawer."
13442 (catch 'exit
13443 (save-excursion
13444 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13445 (end (or end (progn (outline-next-heading) (point)))))
13446 (goto-char beg)
13447 (if (re-search-forward org-property-start-re end t)
13448 (setq beg (1+ (match-end 0)))
13449 (if force
13450 (save-excursion
13451 (org-insert-property-drawer)
13452 (setq end (progn (outline-next-heading) (point))))
13453 (throw 'exit nil))
13454 (goto-char beg)
13455 (if (re-search-forward org-property-start-re end t)
13456 (setq beg (1+ (match-end 0)))))
13457 (if (re-search-forward org-property-end-re end t)
13458 (setq end (match-beginning 0))
13459 (or force (throw 'exit nil))
13460 (goto-char beg)
13461 (setq end beg)
13462 (org-indent-line-function)
13463 (insert ":END:\n"))
13464 (cons beg end)))))
13466 (defun org-entry-properties (&optional pom which specific)
13467 "Get all properties of the entry at point-or-marker POM.
13468 This includes the TODO keyword, the tags, time strings for deadline,
13469 scheduled, and clocking, and any additional properties defined in the
13470 entry. The return value is an alist, keys may occur multiple times
13471 if the property key was used several times.
13472 POM may also be nil, in which case the current entry is used.
13473 If WHICH is nil or `all', get all properties. If WHICH is
13474 `special' or `standard', only get that subclass. If WHICH
13475 is a string only get exactly this property. Specific can be a string, the
13476 specific property we are interested in. Specifying it can speed
13477 things up because then unnecessary parsing is avoided."
13478 (setq which (or which 'all))
13479 (org-with-point-at pom
13480 (let ((clockstr (substring org-clock-string 0 -1))
13481 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13482 (case-fold-search nil)
13483 beg end range props sum-props key key1 value string clocksum)
13484 (save-excursion
13485 (when (condition-case nil
13486 (and (org-mode-p) (org-back-to-heading t))
13487 (error nil))
13488 (setq beg (point))
13489 (setq sum-props (get-text-property (point) 'org-summaries))
13490 (setq clocksum (get-text-property (point) :org-clock-minutes))
13491 (outline-next-heading)
13492 (setq end (point))
13493 (when (memq which '(all special))
13494 ;; Get the special properties, like TODO and tags
13495 (goto-char beg)
13496 (when (and (or (not specific) (string= specific "TODO"))
13497 (looking-at org-todo-line-regexp) (match-end 2))
13498 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13499 (when (and (or (not specific) (string= specific "PRIORITY"))
13500 (looking-at org-priority-regexp))
13501 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13502 (when (and (or (not specific) (string= specific "TAGS"))
13503 (setq value (org-get-tags-string))
13504 (string-match "\\S-" value))
13505 (push (cons "TAGS" value) props))
13506 (when (and (or (not specific) (string= specific "ALLTAGS"))
13507 (setq value (org-get-tags-at)))
13508 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
13509 ":"))
13510 props))
13511 (when (or (not specific) (string= specific "BLOCKED"))
13512 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
13513 (when (or (not specific)
13514 (member specific
13515 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
13516 "TIMESTAMP" "TIMESTAMP_IA")))
13517 (while (re-search-forward org-maybe-keyword-time-regexp end t)
13518 (setq key (if (match-end 1)
13519 (substring (org-match-string-no-properties 1)
13520 0 -1))
13521 string (if (equal key clockstr)
13522 (org-no-properties
13523 (org-trim
13524 (buffer-substring
13525 (match-beginning 3) (goto-char
13526 (point-at-eol)))))
13527 (substring (org-match-string-no-properties 3)
13528 1 -1)))
13529 ;; Get the correct property name from the key. This is
13530 ;; necessary if the user has configured time keywords.
13531 (setq key1 (concat key ":"))
13532 (cond
13533 ((not key)
13534 (setq key
13535 (if (= (char-after (match-beginning 3)) ?\[)
13536 "TIMESTAMP_IA" "TIMESTAMP")))
13537 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
13538 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
13539 ((equal key1 org-closed-string) (setq key "CLOSED"))
13540 ((equal key1 org-clock-string) (setq key "CLOCK")))
13541 (when (or (equal key "CLOCK") (not (assoc key props)))
13542 (push (cons key string) props))))
13545 (when (memq which '(all standard))
13546 ;; Get the standard properties, like :PROP: ...
13547 (setq range (org-get-property-block beg end))
13548 (when range
13549 (goto-char (car range))
13550 (while (re-search-forward
13551 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
13552 (cdr range) t)
13553 (setq key (org-match-string-no-properties 1)
13554 value (org-trim (or (org-match-string-no-properties 2) "")))
13555 (unless (member key excluded)
13556 (push (cons key (or value "")) props)))))
13557 (if clocksum
13558 (push (cons "CLOCKSUM"
13559 (org-columns-number-to-string (/ (float clocksum) 60.)
13560 'add_times))
13561 props))
13562 (unless (assoc "CATEGORY" props)
13563 (setq value (or (org-get-category)
13564 (progn (org-refresh-category-properties)
13565 (org-get-category))))
13566 (push (cons "CATEGORY" value) props))
13567 (append sum-props (nreverse props)))))))
13569 (defun org-entry-get (pom property &optional inherit literal-nil)
13570 "Get value of PROPERTY for entry at point-or-marker POM.
13571 If INHERIT is non-nil and the entry does not have the property,
13572 then also check higher levels of the hierarchy.
13573 If INHERIT is the symbol `selective', use inheritance only if the setting
13574 in `org-use-property-inheritance' selects PROPERTY for inheritance.
13575 If the property is present but empty, the return value is the empty string.
13576 If the property is not present at all, nil is returned.
13578 If LITERAL-NIL is set, return the string value \"nil\" as a string,
13579 do not interpret it as the list atom nil. This is used for inheritance
13580 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
13581 (org-with-point-at pom
13582 (if (and inherit (if (eq inherit 'selective)
13583 (org-property-inherit-p property)
13585 (org-entry-get-with-inheritance property literal-nil)
13586 (if (member property org-special-properties)
13587 ;; We need a special property. Use `org-entry-properties' to
13588 ;; retrieve it, but specify the wanted property
13589 (cdr (assoc property (org-entry-properties nil 'special property)))
13590 (let ((range (org-get-property-block)))
13591 (if (and range
13592 (goto-char (car range))
13593 (re-search-forward
13594 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
13595 (cdr range) t))
13596 ;; Found the property, return it.
13597 (if (match-end 1)
13598 (if literal-nil
13599 (org-match-string-no-properties 1)
13600 (org-not-nil (org-match-string-no-properties 1)))
13601 "")))))))
13603 (defun org-property-or-variable-value (var &optional inherit)
13604 "Check if there is a property fixing the value of VAR.
13605 If yes, return this value. If not, return the current value of the variable."
13606 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13607 (if (and prop (stringp prop) (string-match "\\S-" prop))
13608 (read prop)
13609 (symbol-value var))))
13611 (defun org-entry-delete (pom property)
13612 "Delete the property PROPERTY from entry at point-or-marker POM."
13613 (org-with-point-at pom
13614 (if (member property org-special-properties)
13615 nil ; cannot delete these properties.
13616 (let ((range (org-get-property-block)))
13617 (if (and range
13618 (goto-char (car range))
13619 (re-search-forward
13620 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
13621 (cdr range) t))
13622 (progn
13623 (delete-region (match-beginning 0) (1+ (point-at-eol)))
13625 nil)))))
13627 ;; Multi-values properties are properties that contain multiple values
13628 ;; These values are assumed to be single words, separated by whitespace.
13629 (defun org-entry-add-to-multivalued-property (pom property value)
13630 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
13631 (let* ((old (org-entry-get pom property))
13632 (values (and old (org-split-string old "[ \t]"))))
13633 (setq value (org-entry-protect-space value))
13634 (unless (member value values)
13635 (setq values (cons value values))
13636 (org-entry-put pom property
13637 (mapconcat 'identity values " ")))))
13639 (defun org-entry-remove-from-multivalued-property (pom property value)
13640 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
13641 (let* ((old (org-entry-get pom property))
13642 (values (and old (org-split-string old "[ \t]"))))
13643 (setq value (org-entry-protect-space value))
13644 (when (member value values)
13645 (setq values (delete value values))
13646 (org-entry-put pom property
13647 (mapconcat 'identity values " ")))))
13649 (defun org-entry-member-in-multivalued-property (pom property value)
13650 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
13651 (let* ((old (org-entry-get pom property))
13652 (values (and old (org-split-string old "[ \t]"))))
13653 (setq value (org-entry-protect-space value))
13654 (member value values)))
13656 (defun org-entry-get-multivalued-property (pom property)
13657 "Return a list of values in a multivalued property."
13658 (let* ((value (org-entry-get pom property))
13659 (values (and value (org-split-string value "[ \t]"))))
13660 (mapcar 'org-entry-restore-space values)))
13662 (defun org-entry-put-multivalued-property (pom property &rest values)
13663 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
13664 VALUES should be a list of strings. Spaces will be protected."
13665 (org-entry-put pom property
13666 (mapconcat 'org-entry-protect-space values " "))
13667 (let* ((value (org-entry-get pom property))
13668 (values (and value (org-split-string value "[ \t]"))))
13669 (mapcar 'org-entry-restore-space values)))
13671 (defun org-entry-protect-space (s)
13672 "Protect spaces and newline in string S."
13673 (while (string-match " " s)
13674 (setq s (replace-match "%20" t t s)))
13675 (while (string-match "\n" s)
13676 (setq s (replace-match "%0A" t t s)))
13679 (defun org-entry-restore-space (s)
13680 "Restore spaces and newline in string S."
13681 (while (string-match "%20" s)
13682 (setq s (replace-match " " t t s)))
13683 (while (string-match "%0A" s)
13684 (setq s (replace-match "\n" t t s)))
13687 (defvar org-entry-property-inherited-from (make-marker)
13688 "Marker pointing to the entry from where a property was inherited.
13689 Each call to `org-entry-get-with-inheritance' will set this marker to the
13690 location of the entry where the inheritance search matched. If there was
13691 no match, the marker will point nowhere.
13692 Note that also `org-entry-get' calls this function, if the INHERIT flag
13693 is set.")
13695 (defun org-entry-get-with-inheritance (property &optional literal-nil)
13696 "Get entry property, and search higher levels if not present.
13697 The search will stop at the first ancestor which has the property defined.
13698 If the value found is \"nil\", return nil to show that the property
13699 should be considered as undefined (this is the meaning of nil here).
13700 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
13701 (move-marker org-entry-property-inherited-from nil)
13702 (let (tmp)
13703 (save-excursion
13704 (save-restriction
13705 (widen)
13706 (catch 'ex
13707 (while t
13708 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
13709 (org-back-to-heading t)
13710 (move-marker org-entry-property-inherited-from (point))
13711 (throw 'ex tmp))
13712 (or (org-up-heading-safe) (throw 'ex nil)))))
13713 (setq tmp (or tmp
13714 (cdr (assoc property org-file-properties))
13715 (cdr (assoc property org-global-properties))
13716 (cdr (assoc property org-global-properties-fixed))))
13717 (if literal-nil tmp (org-not-nil tmp)))))
13719 (defvar org-property-changed-functions nil
13720 "Hook called when the value of a property has changed.
13721 Each hook function should accept two arguments, the name of the property
13722 and the new value.")
13724 (defun org-entry-put (pom property value)
13725 "Set PROPERTY to VALUE for entry at point-or-marker POM."
13726 (org-with-point-at pom
13727 (org-back-to-heading t)
13728 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
13729 range)
13730 (cond
13731 ((equal property "TODO")
13732 (when (and (stringp value) (string-match "\\S-" value)
13733 (not (member value org-todo-keywords-1)))
13734 (error "\"%s\" is not a valid TODO state" value))
13735 (if (or (not value)
13736 (not (string-match "\\S-" value)))
13737 (setq value 'none))
13738 (org-todo value)
13739 (org-set-tags nil 'align))
13740 ((equal property "PRIORITY")
13741 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
13742 (string-to-char value) ?\ ))
13743 (org-set-tags nil 'align))
13744 ((equal property "SCHEDULED")
13745 (if (re-search-forward org-scheduled-time-regexp end t)
13746 (cond
13747 ((eq value 'earlier) (org-timestamp-change -1 'day))
13748 ((eq value 'later) (org-timestamp-change 1 'day))
13749 (t (call-interactively 'org-schedule)))
13750 (call-interactively 'org-schedule)))
13751 ((equal property "DEADLINE")
13752 (if (re-search-forward org-deadline-time-regexp end t)
13753 (cond
13754 ((eq value 'earlier) (org-timestamp-change -1 'day))
13755 ((eq value 'later) (org-timestamp-change 1 'day))
13756 (t (call-interactively 'org-deadline)))
13757 (call-interactively 'org-deadline)))
13758 ((member property org-special-properties)
13759 (error "The %s property can not yet be set with `org-entry-put'"
13760 property))
13761 (t ; a non-special property
13762 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
13763 (setq range (org-get-property-block beg end 'force))
13764 (goto-char (car range))
13765 (if (re-search-forward
13766 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
13767 (progn
13768 (delete-region (match-beginning 1) (match-end 1))
13769 (goto-char (match-beginning 1)))
13770 (goto-char (cdr range))
13771 (insert "\n")
13772 (backward-char 1)
13773 (org-indent-line-function)
13774 (insert ":" property ":"))
13775 (and value (insert " " value))
13776 (org-indent-line-function)))))
13777 (run-hook-with-args 'org-property-changed-functions property value)))
13779 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
13780 "Get all property keys in the current buffer.
13781 With INCLUDE-SPECIALS, also list the special properties that reflect things
13782 like tags and TODO state.
13783 With INCLUDE-DEFAULTS, also include properties that has special meaning
13784 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
13785 With INCLUDE-COLUMNS, also include property names given in COLUMN
13786 formats in the current buffer."
13787 (let (rtn range cfmt s p)
13788 (save-excursion
13789 (save-restriction
13790 (widen)
13791 (goto-char (point-min))
13792 (while (re-search-forward org-property-start-re nil t)
13793 (setq range (org-get-property-block))
13794 (goto-char (car range))
13795 (while (re-search-forward
13796 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
13797 (cdr range) t)
13798 (add-to-list 'rtn (org-match-string-no-properties 1)))
13799 (outline-next-heading))))
13801 (when include-specials
13802 (setq rtn (append org-special-properties rtn)))
13804 (when include-defaults
13805 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
13806 (add-to-list 'rtn org-effort-property))
13808 (when include-columns
13809 (save-excursion
13810 (save-restriction
13811 (widen)
13812 (goto-char (point-min))
13813 (while (re-search-forward
13814 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
13815 nil t)
13816 (setq cfmt (match-string 2) s 0)
13817 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
13818 cfmt s)
13819 (setq s (match-end 0)
13820 p (match-string 1 cfmt))
13821 (unless (or (equal p "ITEM")
13822 (member p org-special-properties))
13823 (add-to-list 'rtn (match-string 1 cfmt))))))))
13825 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
13827 (defun org-property-values (key)
13828 "Return a list of all values of property KEY."
13829 (save-excursion
13830 (save-restriction
13831 (widen)
13832 (goto-char (point-min))
13833 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
13834 values)
13835 (while (re-search-forward re nil t)
13836 (add-to-list 'values (org-trim (match-string 1))))
13837 (delete "" values)))))
13839 (defun org-insert-property-drawer ()
13840 "Insert a property drawer into the current entry."
13841 (interactive)
13842 (org-back-to-heading t)
13843 (looking-at outline-regexp)
13844 (let ((indent (if org-adapt-indentation
13845 (- (match-end 0)(match-beginning 0))
13847 (beg (point))
13848 (re (concat "^[ \t]*" org-keyword-time-regexp))
13849 end hiddenp)
13850 (outline-next-heading)
13851 (setq end (point))
13852 (goto-char beg)
13853 (while (re-search-forward re end t))
13854 (setq hiddenp (org-invisible-p))
13855 (end-of-line 1)
13856 (and (equal (char-after) ?\n) (forward-char 1))
13857 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
13858 (if (member (match-string 1) '("CLOCK:" ":END:"))
13859 ;; just skip this line
13860 (beginning-of-line 2)
13861 ;; Drawer start, find the end
13862 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
13863 (beginning-of-line 1)))
13864 (org-skip-over-state-notes)
13865 (skip-chars-backward " \t\n\r")
13866 (if (eq (char-before) ?*) (forward-char 1))
13867 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
13868 (beginning-of-line 0)
13869 (org-indent-to-column indent)
13870 (beginning-of-line 2)
13871 (org-indent-to-column indent)
13872 (beginning-of-line 0)
13873 (if hiddenp
13874 (save-excursion
13875 (org-back-to-heading t)
13876 (hide-entry))
13877 (org-flag-drawer t))))
13879 (defun org-set-property (property value)
13880 "In the current entry, set PROPERTY to VALUE.
13881 When called interactively, this will prompt for a property name, offering
13882 completion on existing and default properties. And then it will prompt
13883 for a value, offering completion either on allowed values (via an inherited
13884 xxx_ALL property) or on existing values in other instances of this property
13885 in the current file."
13886 (interactive
13887 (let* ((completion-ignore-case t)
13888 (keys (org-buffer-property-keys nil t t))
13889 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
13890 (prop (if (member prop0 keys)
13891 prop0
13892 (or (cdr (assoc (downcase prop0)
13893 (mapcar (lambda (x) (cons (downcase x) x))
13894 keys)))
13895 prop0)))
13896 (cur (org-entry-get nil prop))
13897 (prompt (concat prop " value"
13898 (if (and cur (string-match "\\S-" cur))
13899 (concat " [" cur "]") "") ": "))
13900 (allowed (org-property-get-allowed-values nil prop 'table))
13901 (existing (mapcar 'list (org-property-values prop)))
13902 (val (if allowed
13903 (org-completing-read prompt allowed nil
13904 (not (get-text-property 0 'org-unrestricted
13905 (caar allowed))))
13906 (let (org-completion-use-ido org-completion-use-iswitchb)
13907 (org-completing-read prompt existing nil nil "" nil cur)))))
13908 (list prop (if (equal val "") cur val))))
13909 (unless (equal (org-entry-get nil property) value)
13910 (org-entry-put nil property value)))
13912 (defun org-delete-property (property)
13913 "In the current entry, delete PROPERTY."
13914 (interactive
13915 (let* ((completion-ignore-case t)
13916 (prop (org-icompleting-read "Property: "
13917 (org-entry-properties nil 'standard))))
13918 (list prop)))
13919 (message "Property %s %s" property
13920 (if (org-entry-delete nil property)
13921 "deleted"
13922 "was not present in the entry")))
13924 (defun org-delete-property-globally (property)
13925 "Remove PROPERTY globally, from all entries."
13926 (interactive
13927 (let* ((completion-ignore-case t)
13928 (prop (org-icompleting-read
13929 "Globally remove property: "
13930 (mapcar 'list (org-buffer-property-keys)))))
13931 (list prop)))
13932 (save-excursion
13933 (save-restriction
13934 (widen)
13935 (goto-char (point-min))
13936 (let ((cnt 0))
13937 (while (re-search-forward
13938 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
13939 nil t)
13940 (setq cnt (1+ cnt))
13941 (replace-match ""))
13942 (message "Property \"%s\" removed from %d entries" property cnt)))))
13944 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
13946 (defun org-compute-property-at-point ()
13947 "Compute the property at point.
13948 This looks for an enclosing column format, extracts the operator and
13949 then applies it to the property in the column format's scope."
13950 (interactive)
13951 (unless (org-at-property-p)
13952 (error "Not at a property"))
13953 (let ((prop (org-match-string-no-properties 2)))
13954 (org-columns-get-format-and-top-level)
13955 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
13956 (error "No operator defined for property %s" prop))
13957 (org-columns-compute prop)))
13959 (defvar org-property-allowed-value-functions nil
13960 "Hook for functions supplying allowed values for a specific property.
13961 The functions must take a single argument, the name of the property, and
13962 return a flat list of allowed values. If \":ETC\" is one of
13963 the values, this means that these values are intended as defaults for
13964 completion, but that other values should be allowed too.
13965 The functions must return nil if they are not responsible for this
13966 property.")
13968 (defun org-property-get-allowed-values (pom property &optional table)
13969 "Get allowed values for the property PROPERTY.
13970 When TABLE is non-nil, return an alist that can directly be used for
13971 completion."
13972 (let (vals)
13973 (cond
13974 ((equal property "TODO")
13975 (setq vals (org-with-point-at pom
13976 (append org-todo-keywords-1 '("")))))
13977 ((equal property "PRIORITY")
13978 (let ((n org-lowest-priority))
13979 (while (>= n org-highest-priority)
13980 (push (char-to-string n) vals)
13981 (setq n (1- n)))))
13982 ((member property org-special-properties))
13983 ((setq vals (run-hook-with-args-until-success
13984 'org-property-allowed-value-functions property)))
13986 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
13987 (when (and vals (string-match "\\S-" vals))
13988 (setq vals (car (read-from-string (concat "(" vals ")"))))
13989 (setq vals (mapcar (lambda (x)
13990 (cond ((stringp x) x)
13991 ((numberp x) (number-to-string x))
13992 ((symbolp x) (symbol-name x))
13993 (t "???")))
13994 vals)))))
13995 (when (member ":ETC" vals)
13996 (setq vals (remove ":ETC" vals))
13997 (org-add-props (car vals) '(org-unrestricted t)))
13998 (if table (mapcar 'list vals) vals)))
14000 (defun org-property-previous-allowed-value (&optional previous)
14001 "Switch to the next allowed value for this property."
14002 (interactive)
14003 (org-property-next-allowed-value t))
14005 (defun org-property-next-allowed-value (&optional previous)
14006 "Switch to the next allowed value for this property."
14007 (interactive)
14008 (unless (org-at-property-p)
14009 (error "Not at a property"))
14010 (let* ((key (match-string 2))
14011 (value (match-string 3))
14012 (allowed (or (org-property-get-allowed-values (point) key)
14013 (and (member value '("[ ]" "[-]" "[X]"))
14014 '("[ ]" "[X]"))))
14015 nval)
14016 (unless allowed
14017 (error "Allowed values for this property have not been defined"))
14018 (if previous (setq allowed (reverse allowed)))
14019 (if (member value allowed)
14020 (setq nval (car (cdr (member value allowed)))))
14021 (setq nval (or nval (car allowed)))
14022 (if (equal nval value)
14023 (error "Only one allowed value for this property"))
14024 (org-at-property-p)
14025 (replace-match (concat " :" key ": " nval) t t)
14026 (org-indent-line-function)
14027 (beginning-of-line 1)
14028 (skip-chars-forward " \t")
14029 (run-hook-with-args 'org-property-changed-functions key nval)))
14031 (defun org-find-olp (path &optional this-buffer)
14032 "Return a marker pointing to the entry at outline path OLP.
14033 If anything goes wrong, throw an error.
14034 You can wrap this call to catch the error like this:
14036 (condition-case msg
14037 (org-mobile-locate-entry (match-string 4))
14038 (error (nth 1 msg)))
14040 The return value will then be either a string with the error message,
14041 or a marker if everything is OK.
14043 If THIS-BUFFER is set, the outline path does not contain a file,
14044 only headings."
14045 (let* ((file (if this-buffer buffer-file-name (pop path)))
14046 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14047 (level 1)
14048 (lmin 1)
14049 (lmax 1)
14050 limit re end found pos heading cnt)
14051 (unless buffer (error "File not found :%s" file))
14052 (with-current-buffer buffer
14053 (save-excursion
14054 (save-restriction
14055 (widen)
14056 (setq limit (point-max))
14057 (goto-char (point-min))
14058 (while (setq heading (pop path))
14059 (setq re (format org-complex-heading-regexp-format
14060 (regexp-quote heading)))
14061 (setq cnt 0 pos (point))
14062 (while (re-search-forward re end t)
14063 (setq level (- (match-end 1) (match-beginning 1)))
14064 (if (and (>= level lmin) (<= level lmax))
14065 (setq found (match-beginning 0) cnt (1+ cnt))))
14066 (when (= cnt 0) (error "Heading not found on level %d: %s"
14067 lmax heading))
14068 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14069 lmax heading))
14070 (goto-char found)
14071 (setq lmin (1+ level) lmax (+ lmin (if org-odd-levels-only 1 0)))
14072 (setq end (save-excursion (org-end-of-subtree t t))))
14073 (when (org-on-heading-p)
14074 (move-marker (make-marker) (point))))))))
14076 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14077 "Find node HEADING in BUFFER.
14078 Return a marker to the heading if it was found, or nil if not.
14079 If POS-ONLY is set, return just the position instead of a marker.
14081 The heading text must match exact, but it may have a TODO keyword,
14082 a priority cookie and tags in the standard locations."
14083 (with-current-buffer (or buffer (current-buffer))
14084 (save-excursion
14085 (save-restriction
14086 (widen)
14087 (goto-char (point-min))
14088 (let (case-fold-search)
14089 (if (re-search-forward
14090 (format org-complex-heading-regexp-format
14091 (regexp-quote heading)) nil t)
14092 (if pos-only
14093 (match-beginning 0)
14094 (move-marker (make-marker) (match-beginning 0)))))))))
14096 (defun org-find-exact-heading-in-directory (heading &optional dir)
14097 "Find Org node headline HEADING in all .org files in directory DIR.
14098 When the target headline is found, return a marker to this location."
14099 (let ((files (directory-files (or dir default-directory)
14100 nil "\\`[^.#].*\\.org\\'"))
14101 file visiting m buffer)
14102 (catch 'found
14103 (while (setq file (pop files))
14104 (message "trying %s" file)
14105 (setq visiting (org-find-base-buffer-visiting file))
14106 (setq buffer (or visiting (find-file-noselect file)))
14107 (setq m (org-find-exact-headline-in-buffer
14108 heading buffer))
14109 (when (and (not m) (not visiting)) (kill-buffer buffer))
14110 (and m (throw 'found m))))))
14112 (defun org-find-entry-with-id (ident)
14113 "Locate the entry that contains the ID property with exact value IDENT.
14114 IDENT can be a string, a symbol or a number, this function will search for
14115 the string representation of it.
14116 Return the position where this entry starts, or nil if there is no such entry."
14117 (interactive "sID: ")
14118 (let ((id (cond
14119 ((stringp ident) ident)
14120 ((symbol-name ident) (symbol-name ident))
14121 ((numberp ident) (number-to-string ident))
14122 (t (error "IDENT %s must be a string, symbol or number" ident))))
14123 (case-fold-search nil))
14124 (save-excursion
14125 (save-restriction
14126 (widen)
14127 (goto-char (point-min))
14128 (when (re-search-forward
14129 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14130 nil t)
14131 (org-back-to-heading t)
14132 (point))))))
14134 ;;;; Timestamps
14136 (defvar org-last-changed-timestamp nil)
14137 (defvar org-last-inserted-timestamp nil
14138 "The last time stamp inserted with `org-insert-time-stamp'.")
14139 (defvar org-time-was-given) ; dynamically scoped parameter
14140 (defvar org-end-time-was-given) ; dynamically scoped parameter
14141 (defvar org-ts-what) ; dynamically scoped parameter
14143 (defun org-time-stamp (arg &optional inactive)
14144 "Prompt for a date/time and insert a time stamp.
14145 If the user specifies a time like HH:MM, or if this command is called
14146 with a prefix argument, the time stamp will contain date and time.
14147 Otherwise, only the date will be included. All parts of a date not
14148 specified by the user will be filled in from the current date/time.
14149 So if you press just return without typing anything, the time stamp
14150 will represent the current date/time. If there is already a timestamp
14151 at the cursor, it will be modified."
14152 (interactive "P")
14153 (let* ((ts nil)
14154 (default-time
14155 ;; Default time is either today, or, when entering a range,
14156 ;; the range start.
14157 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14158 (save-excursion
14159 (re-search-backward
14160 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14161 (- (point) 20) t)))
14162 (apply 'encode-time (org-parse-time-string (match-string 1)))
14163 (current-time)))
14164 (default-input (and ts (org-get-compact-tod ts)))
14165 org-time-was-given org-end-time-was-given time)
14166 (cond
14167 ((and (org-at-timestamp-p t)
14168 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14169 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14170 (insert "--")
14171 (setq time (let ((this-command this-command))
14172 (org-read-date arg 'totime nil nil
14173 default-time default-input)))
14174 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14175 ((org-at-timestamp-p t)
14176 (setq time (let ((this-command this-command))
14177 (org-read-date arg 'totime nil nil default-time default-input)))
14178 (when (org-at-timestamp-p t) ; just to get the match data
14179 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14180 (replace-match "")
14181 (setq org-last-changed-timestamp
14182 (org-insert-time-stamp
14183 time (or org-time-was-given arg)
14184 inactive nil nil (list org-end-time-was-given))))
14185 (message "Timestamp updated"))
14187 (setq time (let ((this-command this-command))
14188 (org-read-date arg 'totime nil nil default-time default-input)))
14189 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14190 nil nil (list org-end-time-was-given))))))
14192 ;; FIXME: can we use this for something else, like computing time differences?
14193 (defun org-get-compact-tod (s)
14194 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14195 (let* ((t1 (match-string 1 s))
14196 (h1 (string-to-number (match-string 2 s)))
14197 (m1 (string-to-number (match-string 3 s)))
14198 (t2 (and (match-end 4) (match-string 5 s)))
14199 (h2 (and t2 (string-to-number (match-string 6 s))))
14200 (m2 (and t2 (string-to-number (match-string 7 s))))
14201 dh dm)
14202 (if (not t2)
14204 (setq dh (- h2 h1) dm (- m2 m1))
14205 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14206 (concat t1 "+" (number-to-string dh)
14207 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14209 (defun org-time-stamp-inactive (&optional arg)
14210 "Insert an inactive time stamp.
14211 An inactive time stamp is enclosed in square brackets instead of angle
14212 brackets. It is inactive in the sense that it does not trigger agenda entries,
14213 does not link to the calendar and cannot be changed with the S-cursor keys.
14214 So these are more for recording a certain time/date."
14215 (interactive "P")
14216 (org-time-stamp arg 'inactive))
14218 (defvar org-date-ovl (make-overlay 1 1))
14219 (overlay-put org-date-ovl 'face 'org-warning)
14220 (org-detach-overlay org-date-ovl)
14222 (defvar org-ans1) ; dynamically scoped parameter
14223 (defvar org-ans2) ; dynamically scoped parameter
14225 (defvar org-plain-time-of-day-regexp) ; defined below
14227 (defvar org-overriding-default-time nil) ; dynamically scoped
14228 (defvar org-read-date-overlay nil)
14229 (defvar org-dcst nil) ; dynamically scoped
14230 (defvar org-read-date-history nil)
14231 (defvar org-read-date-final-answer nil)
14233 (defun org-read-date (&optional with-time to-time from-string prompt
14234 default-time default-input)
14235 "Read a date, possibly a time, and make things smooth for the user.
14236 The prompt will suggest to enter an ISO date, but you can also enter anything
14237 which will at least partially be understood by `parse-time-string'.
14238 Unrecognized parts of the date will default to the current day, month, year,
14239 hour and minute. If this command is called to replace a timestamp at point,
14240 of to enter the second timestamp of a range, the default time is taken
14241 from the existing stamp. Furthermore, the command prefers the future,
14242 so if you are giving a date where the year is not given, and the day-month
14243 combination is already past in the current year, it will assume you
14244 mean next year. For details, see the manual. A few examples:
14246 3-2-5 --> 2003-02-05
14247 feb 15 --> currentyear-02-15
14248 2/15 --> currentyear-02-15
14249 sep 12 9 --> 2009-09-12
14250 12:45 --> today 12:45
14251 22 sept 0:34 --> currentyear-09-22 0:34
14252 12 --> currentyear-currentmonth-12
14253 Fri --> nearest Friday (today or later)
14254 etc.
14256 Furthermore you can specify a relative date by giving, as the *first* thing
14257 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14258 change in days weeks, months, years.
14259 With a single plus or minus, the date is relative to today. With a double
14260 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14261 +4d --> four days from today
14262 +4 --> same as above
14263 +2w --> two weeks from today
14264 ++5 --> five days from default date
14266 The function understands only English month and weekday abbreviations,
14267 but this can be configured with the variables `parse-time-months' and
14268 `parse-time-weekdays'.
14270 While prompting, a calendar is popped up - you can also select the
14271 date with the mouse (button 1). The calendar shows a period of three
14272 months. To scroll it to other months, use the keys `>' and `<'.
14273 If you don't like the calendar, turn it off with
14274 \(setq org-read-date-popup-calendar nil)
14276 With optional argument TO-TIME, the date will immediately be converted
14277 to an internal time.
14278 With an optional argument WITH-TIME, the prompt will suggest to also
14279 insert a time. Note that when WITH-TIME is not set, you can still
14280 enter a time, and this function will inform the calling routine about
14281 this change. The calling routine may then choose to change the format
14282 used to insert the time stamp into the buffer to include the time.
14283 With optional argument FROM-STRING, read from this string instead from
14284 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14285 the time/date that is used for everything that is not specified by the
14286 user."
14287 (require 'parse-time)
14288 (let* ((org-time-stamp-rounding-minutes
14289 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14290 (org-dcst org-display-custom-times)
14291 (ct (org-current-time))
14292 (def (or org-overriding-default-time default-time ct))
14293 (defdecode (decode-time def))
14294 (dummy (progn
14295 (when (< (nth 2 defdecode) org-extend-today-until)
14296 (setcar (nthcdr 2 defdecode) -1)
14297 (setcar (nthcdr 1 defdecode) 59)
14298 (setq def (apply 'encode-time defdecode)
14299 defdecode (decode-time def)))))
14300 (calendar-frame-setup nil)
14301 (calendar-setup nil)
14302 (calendar-move-hook nil)
14303 (calendar-view-diary-initially-flag nil)
14304 (calendar-view-holidays-initially-flag nil)
14305 (timestr (format-time-string
14306 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14307 (prompt (concat (if prompt (concat prompt " ") "")
14308 (format "Date+time [%s]: " timestr)))
14309 ans (org-ans0 "") org-ans1 org-ans2 final)
14311 (cond
14312 (from-string (setq ans from-string))
14313 (org-read-date-popup-calendar
14314 (save-excursion
14315 (save-window-excursion
14316 (calendar)
14317 (calendar-forward-day (- (time-to-days def)
14318 (calendar-absolute-from-gregorian
14319 (calendar-current-date))))
14320 (org-eval-in-calendar nil t)
14321 (let* ((old-map (current-local-map))
14322 (map (copy-keymap calendar-mode-map))
14323 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14324 (org-defkey map (kbd "RET") 'org-calendar-select)
14325 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14326 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14327 (org-defkey minibuffer-local-map [(meta shift left)]
14328 (lambda () (interactive)
14329 (org-eval-in-calendar '(calendar-backward-month 1))))
14330 (org-defkey minibuffer-local-map [(meta shift right)]
14331 (lambda () (interactive)
14332 (org-eval-in-calendar '(calendar-forward-month 1))))
14333 (org-defkey minibuffer-local-map [(meta shift up)]
14334 (lambda () (interactive)
14335 (org-eval-in-calendar '(calendar-backward-year 1))))
14336 (org-defkey minibuffer-local-map [(meta shift down)]
14337 (lambda () (interactive)
14338 (org-eval-in-calendar '(calendar-forward-year 1))))
14339 (org-defkey minibuffer-local-map [?\e (shift left)]
14340 (lambda () (interactive)
14341 (org-eval-in-calendar '(calendar-backward-month 1))))
14342 (org-defkey minibuffer-local-map [?\e (shift right)]
14343 (lambda () (interactive)
14344 (org-eval-in-calendar '(calendar-forward-month 1))))
14345 (org-defkey minibuffer-local-map [?\e (shift up)]
14346 (lambda () (interactive)
14347 (org-eval-in-calendar '(calendar-backward-year 1))))
14348 (org-defkey minibuffer-local-map [?\e (shift down)]
14349 (lambda () (interactive)
14350 (org-eval-in-calendar '(calendar-forward-year 1))))
14351 (org-defkey minibuffer-local-map [(shift up)]
14352 (lambda () (interactive)
14353 (org-eval-in-calendar '(calendar-backward-week 1))))
14354 (org-defkey minibuffer-local-map [(shift down)]
14355 (lambda () (interactive)
14356 (org-eval-in-calendar '(calendar-forward-week 1))))
14357 (org-defkey minibuffer-local-map [(shift left)]
14358 (lambda () (interactive)
14359 (org-eval-in-calendar '(calendar-backward-day 1))))
14360 (org-defkey minibuffer-local-map [(shift right)]
14361 (lambda () (interactive)
14362 (org-eval-in-calendar '(calendar-forward-day 1))))
14363 (org-defkey minibuffer-local-map ">"
14364 (lambda () (interactive)
14365 (org-eval-in-calendar '(scroll-calendar-left 1))))
14366 (org-defkey minibuffer-local-map "<"
14367 (lambda () (interactive)
14368 (org-eval-in-calendar '(scroll-calendar-right 1))))
14369 (org-defkey minibuffer-local-map "\C-v"
14370 (lambda () (interactive)
14371 (org-eval-in-calendar
14372 '(calendar-scroll-left-three-months 1))))
14373 (org-defkey minibuffer-local-map "\M-v"
14374 (lambda () (interactive)
14375 (org-eval-in-calendar
14376 '(calendar-scroll-right-three-months 1))))
14377 (run-hooks 'org-read-date-minibuffer-setup-hook)
14378 (unwind-protect
14379 (progn
14380 (use-local-map map)
14381 (add-hook 'post-command-hook 'org-read-date-display)
14382 (setq org-ans0 (read-string prompt default-input
14383 'org-read-date-history nil))
14384 ;; org-ans0: from prompt
14385 ;; org-ans1: from mouse click
14386 ;; org-ans2: from calendar motion
14387 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14388 (remove-hook 'post-command-hook 'org-read-date-display)
14389 (use-local-map old-map)
14390 (when org-read-date-overlay
14391 (delete-overlay org-read-date-overlay)
14392 (setq org-read-date-overlay nil)))))))
14394 (t ; Naked prompt only
14395 (unwind-protect
14396 (setq ans (read-string prompt default-input
14397 'org-read-date-history timestr))
14398 (when org-read-date-overlay
14399 (delete-overlay org-read-date-overlay)
14400 (setq org-read-date-overlay nil)))))
14402 (setq final (org-read-date-analyze ans def defdecode))
14404 ;; One round trip to get rid of 34th of August and stuff like that....
14405 (setq final (decode-time (apply 'encode-time final)))
14407 (setq org-read-date-final-answer ans)
14409 (if to-time
14410 (apply 'encode-time final)
14411 (if (and (boundp 'org-time-was-given) org-time-was-given)
14412 (format "%04d-%02d-%02d %02d:%02d"
14413 (nth 5 final) (nth 4 final) (nth 3 final)
14414 (nth 2 final) (nth 1 final))
14415 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
14417 (defvar def)
14418 (defvar defdecode)
14419 (defvar with-time)
14420 (defvar org-read-date-analyze-futurep nil)
14421 (defun org-read-date-display ()
14422 "Display the current date prompt interpretation in the minibuffer."
14423 (when org-read-date-display-live
14424 (when org-read-date-overlay
14425 (delete-overlay org-read-date-overlay))
14426 (let ((p (point)))
14427 (end-of-line 1)
14428 (while (not (equal (buffer-substring
14429 (max (point-min) (- (point) 4)) (point))
14430 " "))
14431 (insert " "))
14432 (goto-char p))
14433 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
14434 " " (or org-ans1 org-ans2)))
14435 (org-end-time-was-given nil)
14436 (f (org-read-date-analyze ans def defdecode))
14437 (fmts (if org-dcst
14438 org-time-stamp-custom-formats
14439 org-time-stamp-formats))
14440 (fmt (if (or with-time
14441 (and (boundp 'org-time-was-given) org-time-was-given))
14442 (cdr fmts)
14443 (car fmts)))
14444 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
14445 (when (and org-end-time-was-given
14446 (string-match org-plain-time-of-day-regexp txt))
14447 (setq txt (concat (substring txt 0 (match-end 0)) "-"
14448 org-end-time-was-given
14449 (substring txt (match-end 0)))))
14450 (when org-read-date-analyze-futurep
14451 (setq txt (concat txt " (=>F)")))
14452 (setq org-read-date-overlay
14453 (make-overlay (1- (point-at-eol)) (point-at-eol)))
14454 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
14456 (defun org-read-date-analyze (ans def defdecode)
14457 "Analyze the combined answer of the date prompt."
14458 ;; FIXME: cleanup and comment
14459 (let ((nowdecode (decode-time (current-time)))
14460 delta deltan deltaw deltadef year month day
14461 hour minute second wday pm h2 m2 tl wday1
14462 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
14463 (setq org-read-date-analyze-futurep nil)
14464 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
14465 (setq ans "+0"))
14467 (when (setq delta (org-read-date-get-relative ans (current-time) def))
14468 (setq ans (replace-match "" t t ans)
14469 deltan (car delta)
14470 deltaw (nth 1 delta)
14471 deltadef (nth 2 delta)))
14473 ;; Check if there is an iso week date in there
14474 ;; If yes, store the info and postpone interpreting it until the rest
14475 ;; of the parsing is done
14476 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
14477 (setq iso-year (if (match-end 1)
14478 (org-small-year-to-year
14479 (string-to-number (match-string 1 ans))))
14480 iso-weekday (if (match-end 3)
14481 (string-to-number (match-string 3 ans)))
14482 iso-week (string-to-number (match-string 2 ans)))
14483 (setq ans (replace-match "" t t ans)))
14485 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
14486 (when (string-match
14487 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
14488 (setq year (if (match-end 2)
14489 (string-to-number (match-string 2 ans))
14490 (progn (setq kill-year t)
14491 (string-to-number (format-time-string "%Y"))))
14492 month (string-to-number (match-string 3 ans))
14493 day (string-to-number (match-string 4 ans)))
14494 (if (< year 100) (setq year (+ 2000 year)))
14495 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14496 t nil ans)))
14497 ;; Help matching american dates, like 5/30 or 5/30/7
14498 (when (string-match
14499 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
14500 (setq year (if (match-end 4)
14501 (string-to-number (match-string 4 ans))
14502 (progn (setq kill-year t)
14503 (string-to-number (format-time-string "%Y"))))
14504 month (string-to-number (match-string 1 ans))
14505 day (string-to-number (match-string 2 ans)))
14506 (if (< year 100) (setq year (+ 2000 year)))
14507 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14508 t nil ans)))
14509 ;; Help matching am/pm times, because `parse-time-string' does not do that.
14510 ;; If there is a time with am/pm, and *no* time without it, we convert
14511 ;; so that matching will be successful.
14512 (loop for i from 1 to 2 do ; twice, for end time as well
14513 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
14514 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
14515 (setq hour (string-to-number (match-string 1 ans))
14516 minute (if (match-end 3)
14517 (string-to-number (match-string 3 ans))
14519 pm (equal ?p
14520 (string-to-char (downcase (match-string 4 ans)))))
14521 (if (and (= hour 12) (not pm))
14522 (setq hour 0)
14523 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
14524 (setq ans (replace-match (format "%02d:%02d" hour minute)
14525 t t ans))))
14527 ;; Check if a time range is given as a duration
14528 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
14529 (setq hour (string-to-number (match-string 1 ans))
14530 h2 (+ hour (string-to-number (match-string 3 ans)))
14531 minute (string-to-number (match-string 2 ans))
14532 m2 (+ minute (if (match-end 5) (string-to-number
14533 (match-string 5 ans))0)))
14534 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
14535 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
14536 t t ans)))
14538 ;; Check if there is a time range
14539 (when (boundp 'org-end-time-was-given)
14540 (setq org-time-was-given nil)
14541 (when (and (string-match org-plain-time-of-day-regexp ans)
14542 (match-end 8))
14543 (setq org-end-time-was-given (match-string 8 ans))
14544 (setq ans (concat (substring ans 0 (match-beginning 7))
14545 (substring ans (match-end 7))))))
14547 (setq tl (parse-time-string ans)
14548 day (or (nth 3 tl) (nth 3 defdecode))
14549 month (or (nth 4 tl)
14550 (if (and org-read-date-prefer-future
14551 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
14552 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
14553 (nth 4 defdecode)))
14554 year (or (and (not kill-year) (nth 5 tl))
14555 (if (and org-read-date-prefer-future
14556 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
14557 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
14558 (nth 5 defdecode)))
14559 hour (or (nth 2 tl) (nth 2 defdecode))
14560 minute (or (nth 1 tl) (nth 1 defdecode))
14561 second (or (nth 0 tl) 0)
14562 wday (nth 6 tl))
14564 (when (and (eq org-read-date-prefer-future 'time)
14565 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
14566 (equal day (nth 3 nowdecode))
14567 (equal month (nth 4 nowdecode))
14568 (equal year (nth 5 nowdecode))
14569 (nth 2 tl)
14570 (or (< (nth 2 tl) (nth 2 nowdecode))
14571 (and (= (nth 2 tl) (nth 2 nowdecode))
14572 (nth 1 tl)
14573 (< (nth 1 tl) (nth 1 nowdecode)))))
14574 (setq day (1+ day)
14575 futurep t))
14577 ;; Special date definitions below
14578 (cond
14579 (iso-week
14580 ;; There was an iso week
14581 (require 'cal-iso)
14582 (setq futurep nil)
14583 (setq year (or iso-year year)
14584 day (or iso-weekday wday 1)
14585 wday nil ; to make sure that the trigger below does not match
14586 iso-date (calendar-gregorian-from-absolute
14587 (calendar-absolute-from-iso
14588 (list iso-week day year))))
14589 ; FIXME: Should we also push ISO weeks into the future?
14590 ; (when (and org-read-date-prefer-future
14591 ; (not iso-year)
14592 ; (< (calendar-absolute-from-gregorian iso-date)
14593 ; (time-to-days (current-time))))
14594 ; (setq year (1+ year)
14595 ; iso-date (calendar-gregorian-from-absolute
14596 ; (calendar-absolute-from-iso
14597 ; (list iso-week day year)))))
14598 (setq month (car iso-date)
14599 year (nth 2 iso-date)
14600 day (nth 1 iso-date)))
14601 (deltan
14602 (setq futurep nil)
14603 (unless deltadef
14604 (let ((now (decode-time (current-time))))
14605 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
14606 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
14607 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
14608 ((equal deltaw "m") (setq month (+ month deltan)))
14609 ((equal deltaw "y") (setq year (+ year deltan)))))
14610 ((and wday (not (nth 3 tl)))
14611 (setq futurep nil)
14612 ;; Weekday was given, but no day, so pick that day in the week
14613 ;; on or after the derived date.
14614 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
14615 (unless (equal wday wday1)
14616 (setq day (+ day (% (- wday wday1 -7) 7))))))
14617 (if (and (boundp 'org-time-was-given)
14618 (nth 2 tl))
14619 (setq org-time-was-given t))
14620 (if (< year 100) (setq year (+ 2000 year)))
14621 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
14622 (setq org-read-date-analyze-futurep futurep)
14623 (list second minute hour day month year)))
14625 (defvar parse-time-weekdays)
14627 (defun org-read-date-get-relative (s today default)
14628 "Check string S for special relative date string.
14629 TODAY and DEFAULT are internal times, for today and for a default.
14630 Return shift list (N what def-flag)
14631 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
14632 N is the number of WHATs to shift.
14633 DEF-FLAG is t when a double ++ or -- indicates shift relative to
14634 the DEFAULT date rather than TODAY."
14635 (when (and
14636 (string-match
14637 (concat
14638 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
14639 "\\([0-9]+\\)?"
14640 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
14641 "\\([ \t]\\|$\\)") s)
14642 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
14643 (let* ((dir (if (> (match-end 1) (match-beginning 1))
14644 (string-to-char (substring (match-string 1 s) -1))
14645 ?+))
14646 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
14647 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
14648 (what (if (match-end 3) (match-string 3 s) "d"))
14649 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
14650 (date (if rel default today))
14651 (wday (nth 6 (decode-time date)))
14652 delta)
14653 (if wday1
14654 (progn
14655 (setq delta (mod (+ 7 (- wday1 wday)) 7))
14656 (if (= dir ?-) (setq delta (- delta 7)))
14657 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
14658 (list delta "d" rel))
14659 (list (* n (if (= dir ?-) -1 1)) what rel)))))
14661 (defun org-order-calendar-date-args (arg1 arg2 arg3)
14662 "Turn a user-specified date into the internal representation.
14663 The internal representation needed by the calendar is (month day year).
14664 This is a wrapper to handle the brain-dead convention in calendar that
14665 user function argument order change dependent on argument order."
14666 (if (boundp 'calendar-date-style)
14667 (cond
14668 ((eq calendar-date-style 'american)
14669 (list arg1 arg2 arg3))
14670 ((eq calendar-date-style 'european)
14671 (list arg2 arg1 arg3))
14672 ((eq calendar-date-style 'iso)
14673 (list arg2 arg3 arg1)))
14674 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
14675 (if (org-bound-and-true-p european-calendar-style)
14676 (list arg2 arg1 arg3)
14677 (list arg1 arg2 arg3)))))
14679 (defun org-eval-in-calendar (form &optional keepdate)
14680 "Eval FORM in the calendar window and return to current window.
14681 Also, store the cursor date in variable org-ans2."
14682 (let ((sf (selected-frame))
14683 (sw (selected-window)))
14684 (select-window (get-buffer-window "*Calendar*" t))
14685 (eval form)
14686 (when (and (not keepdate) (calendar-cursor-to-date))
14687 (let* ((date (calendar-cursor-to-date))
14688 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14689 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
14690 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
14691 (select-window sw)
14692 (org-select-frame-set-input-focus sf)))
14694 (defun org-calendar-select ()
14695 "Return to `org-read-date' with the date currently selected.
14696 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14697 (interactive)
14698 (when (calendar-cursor-to-date)
14699 (let* ((date (calendar-cursor-to-date))
14700 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14701 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14702 (if (active-minibuffer-window) (exit-minibuffer))))
14704 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
14705 "Insert a date stamp for the date given by the internal TIME.
14706 WITH-HM means use the stamp format that includes the time of the day.
14707 INACTIVE means use square brackets instead of angular ones, so that the
14708 stamp will not contribute to the agenda.
14709 PRE and POST are optional strings to be inserted before and after the
14710 stamp.
14711 The command returns the inserted time stamp."
14712 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
14713 stamp)
14714 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
14715 (insert-before-markers (or pre ""))
14716 (when (listp extra)
14717 (setq extra (car extra))
14718 (if (and (stringp extra)
14719 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
14720 (setq extra (format "-%02d:%02d"
14721 (string-to-number (match-string 1 extra))
14722 (string-to-number (match-string 2 extra))))
14723 (setq extra nil)))
14724 (when extra
14725 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
14726 (insert-before-markers (setq stamp (format-time-string fmt time)))
14727 (insert-before-markers (or post ""))
14728 (setq org-last-inserted-timestamp stamp)))
14730 (defun org-toggle-time-stamp-overlays ()
14731 "Toggle the use of custom time stamp formats."
14732 (interactive)
14733 (setq org-display-custom-times (not org-display-custom-times))
14734 (unless org-display-custom-times
14735 (let ((p (point-min)) (bmp (buffer-modified-p)))
14736 (while (setq p (next-single-property-change p 'display))
14737 (if (and (get-text-property p 'display)
14738 (eq (get-text-property p 'face) 'org-date))
14739 (remove-text-properties
14740 p (setq p (next-single-property-change p 'display))
14741 '(display t))))
14742 (set-buffer-modified-p bmp)))
14743 (if (featurep 'xemacs)
14744 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
14745 (org-restart-font-lock)
14746 (setq org-table-may-need-update t)
14747 (if org-display-custom-times
14748 (message "Time stamps are overlayed with custom format")
14749 (message "Time stamp overlays removed")))
14751 (defun org-display-custom-time (beg end)
14752 "Overlay modified time stamp format over timestamp between BEG and END."
14753 (let* ((ts (buffer-substring beg end))
14754 t1 w1 with-hm tf time str w2 (off 0))
14755 (save-match-data
14756 (setq t1 (org-parse-time-string ts t))
14757 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
14758 (setq off (- (match-end 0) (match-beginning 0)))))
14759 (setq end (- end off))
14760 (setq w1 (- end beg)
14761 with-hm (and (nth 1 t1) (nth 2 t1))
14762 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
14763 time (org-fix-decoded-time t1)
14764 str (org-add-props
14765 (format-time-string
14766 (substring tf 1 -1) (apply 'encode-time time))
14767 nil 'mouse-face 'highlight)
14768 w2 (length str))
14769 (if (not (= w2 w1))
14770 (add-text-properties (1+ beg) (+ 2 beg)
14771 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
14772 (if (featurep 'xemacs)
14773 (progn
14774 (put-text-property beg end 'invisible t)
14775 (put-text-property beg end 'end-glyph (make-glyph str)))
14776 (put-text-property beg end 'display str))))
14778 (defun org-translate-time (string)
14779 "Translate all timestamps in STRING to custom format.
14780 But do this only if the variable `org-display-custom-times' is set."
14781 (when org-display-custom-times
14782 (save-match-data
14783 (let* ((start 0)
14784 (re org-ts-regexp-both)
14785 t1 with-hm inactive tf time str beg end)
14786 (while (setq start (string-match re string start))
14787 (setq beg (match-beginning 0)
14788 end (match-end 0)
14789 t1 (save-match-data
14790 (org-parse-time-string (substring string beg end) t))
14791 with-hm (and (nth 1 t1) (nth 2 t1))
14792 inactive (equal (substring string beg (1+ beg)) "[")
14793 tf (funcall (if with-hm 'cdr 'car)
14794 org-time-stamp-custom-formats)
14795 time (org-fix-decoded-time t1)
14796 str (format-time-string
14797 (concat
14798 (if inactive "[" "<") (substring tf 1 -1)
14799 (if inactive "]" ">"))
14800 (apply 'encode-time time))
14801 string (replace-match str t t string)
14802 start (+ start (length str)))))))
14803 string)
14805 (defun org-fix-decoded-time (time)
14806 "Set 0 instead of nil for the first 6 elements of time.
14807 Don't touch the rest."
14808 (let ((n 0))
14809 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
14811 (defun org-days-to-time (timestamp-string)
14812 "Difference between TIMESTAMP-STRING and now in days."
14813 (- (time-to-days (org-time-string-to-time timestamp-string))
14814 (time-to-days (current-time))))
14816 (defun org-deadline-close (timestamp-string &optional ndays)
14817 "Is the time in TIMESTAMP-STRING close to the current date?"
14818 (setq ndays (or ndays (org-get-wdays timestamp-string)))
14819 (and (< (org-days-to-time timestamp-string) ndays)
14820 (not (org-entry-is-done-p))))
14822 (defun org-get-wdays (ts)
14823 "Get the deadline lead time appropriate for timestring TS."
14824 (cond
14825 ((<= org-deadline-warning-days 0)
14826 ;; 0 or negative, enforce this value no matter what
14827 (- org-deadline-warning-days))
14828 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
14829 ;; lead time is specified.
14830 (floor (* (string-to-number (match-string 1 ts))
14831 (cdr (assoc (match-string 2 ts)
14832 '(("d" . 1) ("w" . 7)
14833 ("m" . 30.4) ("y" . 365.25)))))))
14834 ;; go for the default.
14835 (t org-deadline-warning-days)))
14837 (defun org-calendar-select-mouse (ev)
14838 "Return to `org-read-date' with the date currently selected.
14839 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14840 (interactive "e")
14841 (mouse-set-point ev)
14842 (when (calendar-cursor-to-date)
14843 (let* ((date (calendar-cursor-to-date))
14844 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14845 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14846 (if (active-minibuffer-window) (exit-minibuffer))))
14848 (defun org-check-deadlines (ndays)
14849 "Check if there are any deadlines due or past due.
14850 A deadline is considered due if it happens within `org-deadline-warning-days'
14851 days from today's date. If the deadline appears in an entry marked DONE,
14852 it is not shown. The prefix arg NDAYS can be used to test that many
14853 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
14854 (interactive "P")
14855 (let* ((org-warn-days
14856 (cond
14857 ((equal ndays '(4)) 100000)
14858 (ndays (prefix-numeric-value ndays))
14859 (t (abs org-deadline-warning-days))))
14860 (case-fold-search nil)
14861 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
14862 (callback
14863 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
14865 (message "%d deadlines past-due or due within %d days"
14866 (org-occur regexp nil callback)
14867 org-warn-days)))
14869 (defun org-check-before-date (date)
14870 "Check if there are deadlines or scheduled entries before DATE."
14871 (interactive (list (org-read-date)))
14872 (let ((case-fold-search nil)
14873 (regexp (concat "\\<\\(" org-deadline-string
14874 "\\|" org-scheduled-string
14875 "\\) *<\\([^>]+\\)>"))
14876 (callback
14877 (lambda () (time-less-p
14878 (org-time-string-to-time (match-string 2))
14879 (org-time-string-to-time date)))))
14880 (message "%d entries before %s"
14881 (org-occur regexp nil callback) date)))
14883 (defun org-check-after-date (date)
14884 "Check if there are deadlines or scheduled entries after DATE."
14885 (interactive (list (org-read-date)))
14886 (let ((case-fold-search nil)
14887 (regexp (concat "\\<\\(" org-deadline-string
14888 "\\|" org-scheduled-string
14889 "\\) *<\\([^>]+\\)>"))
14890 (callback
14891 (lambda () (not
14892 (time-less-p
14893 (org-time-string-to-time (match-string 2))
14894 (org-time-string-to-time date))))))
14895 (message "%d entries after %s"
14896 (org-occur regexp nil callback) date)))
14898 (defun org-evaluate-time-range (&optional to-buffer)
14899 "Evaluate a time range by computing the difference between start and end.
14900 Normally the result is just printed in the echo area, but with prefix arg
14901 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
14902 If the time range is actually in a table, the result is inserted into the
14903 next column.
14904 For time difference computation, a year is assumed to be exactly 365
14905 days in order to avoid rounding problems."
14906 (interactive "P")
14908 (org-clock-update-time-maybe)
14909 (save-excursion
14910 (unless (org-at-date-range-p t)
14911 (goto-char (point-at-bol))
14912 (re-search-forward org-tr-regexp-both (point-at-eol) t))
14913 (if (not (org-at-date-range-p t))
14914 (error "Not at a time-stamp range, and none found in current line")))
14915 (let* ((ts1 (match-string 1))
14916 (ts2 (match-string 2))
14917 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
14918 (match-end (match-end 0))
14919 (time1 (org-time-string-to-time ts1))
14920 (time2 (org-time-string-to-time ts2))
14921 (t1 (org-float-time time1))
14922 (t2 (org-float-time time2))
14923 (diff (abs (- t2 t1)))
14924 (negative (< (- t2 t1) 0))
14925 ;; (ys (floor (* 365 24 60 60)))
14926 (ds (* 24 60 60))
14927 (hs (* 60 60))
14928 (fy "%dy %dd %02d:%02d")
14929 (fy1 "%dy %dd")
14930 (fd "%dd %02d:%02d")
14931 (fd1 "%dd")
14932 (fh "%02d:%02d")
14933 y d h m align)
14934 (if havetime
14935 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14937 d (floor (/ diff ds)) diff (mod diff ds)
14938 h (floor (/ diff hs)) diff (mod diff hs)
14939 m (floor (/ diff 60)))
14940 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14942 d (floor (+ (/ diff ds) 0.5))
14943 h 0 m 0))
14944 (if (not to-buffer)
14945 (message "%s" (org-make-tdiff-string y d h m))
14946 (if (org-at-table-p)
14947 (progn
14948 (goto-char match-end)
14949 (setq align t)
14950 (and (looking-at " *|") (goto-char (match-end 0))))
14951 (goto-char match-end))
14952 (if (looking-at
14953 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
14954 (replace-match ""))
14955 (if negative (insert " -"))
14956 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
14957 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
14958 (insert " " (format fh h m))))
14959 (if align (org-table-align))
14960 (message "Time difference inserted")))))
14962 (defun org-make-tdiff-string (y d h m)
14963 (let ((fmt "")
14964 (l nil))
14965 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
14966 l (push y l)))
14967 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
14968 l (push d l)))
14969 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
14970 l (push h l)))
14971 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
14972 l (push m l)))
14973 (apply 'format fmt (nreverse l))))
14975 (defun org-time-string-to-time (s)
14976 (apply 'encode-time (org-parse-time-string s)))
14977 (defun org-time-string-to-seconds (s)
14978 (org-float-time (org-time-string-to-time s)))
14980 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
14981 "Convert a time stamp to an absolute day number.
14982 If there is a specifier for a cyclic time stamp, get the closest date to
14983 DAYNR.
14984 PREFER and SHOW-ALL are passed through to `org-closest-date'.
14985 the variable date is bound by the calendar when this is called."
14986 (cond
14987 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
14988 (if (org-diary-sexp-entry (match-string 1 s) "" date)
14989 daynr
14990 (+ daynr 1000)))
14991 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
14992 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
14993 (time-to-days (current-time))) (match-string 0 s)
14994 prefer show-all))
14995 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
14997 (defun org-days-to-iso-week (days)
14998 "Return the iso week number."
14999 (require 'cal-iso)
15000 (car (calendar-iso-from-absolute days)))
15002 (defun org-small-year-to-year (year)
15003 "Convert 2-digit years into 4-digit years.
15004 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15005 The year 2000 cannot be abbreviated. Any year larger than 99
15006 is returned unchanged."
15007 (if (< year 38)
15008 (setq year (+ 2000 year))
15009 (if (< year 100)
15010 (setq year (+ 1900 year))))
15011 year)
15013 (defun org-time-from-absolute (d)
15014 "Return the time corresponding to date D.
15015 D may be an absolute day number, or a calendar-type list (month day year)."
15016 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15017 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15019 (defun org-calendar-holiday ()
15020 "List of holidays, for Diary display in Org-mode."
15021 (require 'holidays)
15022 (let ((hl (funcall
15023 (if (fboundp 'calendar-check-holidays)
15024 'calendar-check-holidays 'check-calendar-holidays) date)))
15025 (if hl (mapconcat 'identity hl "; "))))
15027 (defun org-diary-sexp-entry (sexp entry date)
15028 "Process a SEXP diary ENTRY for DATE."
15029 (require 'diary-lib)
15030 (let ((result (if calendar-debug-sexp
15031 (let ((stack-trace-on-error t))
15032 (eval (car (read-from-string sexp))))
15033 (condition-case nil
15034 (eval (car (read-from-string sexp)))
15035 (error
15036 (beep)
15037 (message "Bad sexp at line %d in %s: %s"
15038 (org-current-line)
15039 (buffer-file-name) sexp)
15040 (sleep-for 2))))))
15041 (cond ((stringp result) (split-string result "; "))
15042 ((and (consp result)
15043 (not (consp (cdr result)))
15044 (stringp (cdr result))) (cdr result))
15045 ((and (consp result)
15046 (stringp (car result))) result)
15047 (result entry)
15048 (t nil))))
15050 (defun org-diary-to-ical-string (frombuf)
15051 "Get iCalendar entries from diary entries in buffer FROMBUF.
15052 This uses the icalendar.el library."
15053 (let* ((tmpdir (if (featurep 'xemacs)
15054 (temp-directory)
15055 temporary-file-directory))
15056 (tmpfile (make-temp-name
15057 (expand-file-name "orgics" tmpdir)))
15058 buf rtn b e)
15059 (with-current-buffer frombuf
15060 (icalendar-export-region (point-min) (point-max) tmpfile)
15061 (setq buf (find-buffer-visiting tmpfile))
15062 (set-buffer buf)
15063 (goto-char (point-min))
15064 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15065 (setq b (match-beginning 0)))
15066 (goto-char (point-max))
15067 (if (re-search-backward "^END:VEVENT" nil t)
15068 (setq e (match-end 0)))
15069 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15070 (kill-buffer buf)
15071 (delete-file tmpfile)
15072 rtn))
15074 (defun org-closest-date (start current change prefer show-all)
15075 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15076 When PREFER is `past' return a date that is either CURRENT or past.
15077 When PREFER is `future', return a date that is either CURRENT or future.
15078 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15079 ;; Make the proper lists from the dates
15080 (catch 'exit
15081 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15082 dn dw sday cday n1 n2 n0
15083 d m y y1 y2 date1 date2 nmonths nm ny m2)
15085 (setq start (org-date-to-gregorian start)
15086 current (org-date-to-gregorian
15087 (if show-all
15088 current
15089 (time-to-days (current-time))))
15090 sday (calendar-absolute-from-gregorian start)
15091 cday (calendar-absolute-from-gregorian current))
15093 (if (<= cday sday) (throw 'exit sday))
15095 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15096 (setq dn (string-to-number (match-string 1 change))
15097 dw (cdr (assoc (match-string 2 change) a1)))
15098 (error "Invalid change specifier: %s" change))
15099 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15100 (cond
15101 ((eq dw 'day)
15102 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15103 n2 (+ n1 dn)))
15104 ((eq dw 'year)
15105 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15106 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15107 (setq date1 (list m d y1)
15108 n1 (calendar-absolute-from-gregorian date1)
15109 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15110 n2 (calendar-absolute-from-gregorian date2)))
15111 ((eq dw 'month)
15112 ;; approx number of month between the two dates
15113 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15114 ;; How often does dn fit in there?
15115 (setq d (nth 1 start) m (car start) y (nth 2 start)
15116 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15117 m (+ m nm)
15118 ny (floor (/ m 12))
15119 y (+ y ny)
15120 m (- m (* ny 12)))
15121 (while (> m 12) (setq m (- m 12) y (1+ y)))
15122 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15123 (setq m2 (+ m dn) y2 y)
15124 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15125 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15126 (while (<= n2 cday)
15127 (setq n1 n2 m m2 y y2)
15128 (setq m2 (+ m dn) y2 y)
15129 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15130 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15131 ;; Make sure n1 is the earlier date
15132 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15133 (if show-all
15134 (cond
15135 ((eq prefer 'past) (if (= cday n2) n2 n1))
15136 ((eq prefer 'future) (if (= cday n1) n1 n2))
15137 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15138 (cond
15139 ((eq prefer 'past) (if (= cday n2) n2 n1))
15140 ((eq prefer 'future) (if (= cday n1) n1 n2))
15141 (t (if (= cday n1) n1 n2)))))))
15143 (defun org-date-to-gregorian (date)
15144 "Turn any specification of DATE into a Gregorian date for the calendar."
15145 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15146 ((and (listp date) (= (length date) 3)) date)
15147 ((stringp date)
15148 (setq date (org-parse-time-string date))
15149 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15150 ((listp date)
15151 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15153 (defun org-parse-time-string (s &optional nodefault)
15154 "Parse the standard Org-mode time string.
15155 This should be a lot faster than the normal `parse-time-string'.
15156 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15157 hour and minute fields will be nil if not given."
15158 (if (string-match org-ts-regexp0 s)
15159 (list 0
15160 (if (or (match-beginning 8) (not nodefault))
15161 (string-to-number (or (match-string 8 s) "0")))
15162 (if (or (match-beginning 7) (not nodefault))
15163 (string-to-number (or (match-string 7 s) "0")))
15164 (string-to-number (match-string 4 s))
15165 (string-to-number (match-string 3 s))
15166 (string-to-number (match-string 2 s))
15167 nil nil nil)
15168 (error "Not a standard Org-mode time string: %s" s)))
15170 (defun org-timestamp-up (&optional arg)
15171 "Increase the date item at the cursor by one.
15172 If the cursor is on the year, change the year. If it is on the month or
15173 the day, change that.
15174 With prefix ARG, change by that many units."
15175 (interactive "p")
15176 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15178 (defun org-timestamp-down (&optional arg)
15179 "Decrease the date item at the cursor by one.
15180 If the cursor is on the year, change the year. If it is on the month or
15181 the day, change that.
15182 With prefix ARG, change by that many units."
15183 (interactive "p")
15184 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15186 (defun org-timestamp-up-day (&optional arg)
15187 "Increase the date in the time stamp by one day.
15188 With prefix ARG, change that many days."
15189 (interactive "p")
15190 (if (and (not (org-at-timestamp-p t))
15191 (org-on-heading-p))
15192 (org-todo 'up)
15193 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15195 (defun org-timestamp-down-day (&optional arg)
15196 "Decrease the date in the time stamp by one day.
15197 With prefix ARG, change that many days."
15198 (interactive "p")
15199 (if (and (not (org-at-timestamp-p t))
15200 (org-on-heading-p))
15201 (org-todo 'down)
15202 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15204 (defun org-at-timestamp-p (&optional inactive-ok)
15205 "Determine if the cursor is in or at a timestamp."
15206 (interactive)
15207 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15208 (pos (point))
15209 (ans (or (looking-at tsr)
15210 (save-excursion
15211 (skip-chars-backward "^[<\n\r\t")
15212 (if (> (point) (point-min)) (backward-char 1))
15213 (and (looking-at tsr)
15214 (> (- (match-end 0) pos) -1))))))
15215 (and ans
15216 (boundp 'org-ts-what)
15217 (setq org-ts-what
15218 (cond
15219 ((= pos (match-beginning 0)) 'bracket)
15220 ((= pos (1- (match-end 0))) 'bracket)
15221 ((org-pos-in-match-range pos 2) 'year)
15222 ((org-pos-in-match-range pos 3) 'month)
15223 ((org-pos-in-match-range pos 7) 'hour)
15224 ((org-pos-in-match-range pos 8) 'minute)
15225 ((or (org-pos-in-match-range pos 4)
15226 (org-pos-in-match-range pos 5)) 'day)
15227 ((and (> pos (or (match-end 8) (match-end 5)))
15228 (< pos (match-end 0)))
15229 (- pos (or (match-end 8) (match-end 5))))
15230 (t 'day))))
15231 ans))
15233 (defun org-toggle-timestamp-type ()
15234 "Toggle the type (<active> or [inactive]) of a time stamp."
15235 (interactive)
15236 (when (org-at-timestamp-p t)
15237 (let ((beg (match-beginning 0)) (end (match-end 0))
15238 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
15239 (save-excursion
15240 (goto-char beg)
15241 (while (re-search-forward "[][<>]" end t)
15242 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
15243 t t)))
15244 (message "Timestamp is now %sactive"
15245 (if (equal (char-after beg) ?<) "" "in")))))
15247 (defun org-timestamp-change (n &optional what updown)
15248 "Change the date in the time stamp at point.
15249 The date will be changed by N times WHAT. WHAT can be `day', `month',
15250 `year', `minute', `second'. If WHAT is not given, the cursor position
15251 in the timestamp determines what will be changed."
15252 (let ((pos (point))
15253 with-hm inactive
15254 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
15255 org-ts-what
15256 extra rem
15257 ts time time0)
15258 (if (not (org-at-timestamp-p t))
15259 (error "Not at a timestamp"))
15260 (if (and (not what) (eq org-ts-what 'bracket))
15261 (org-toggle-timestamp-type)
15262 (if (and (not what) (not (eq org-ts-what 'day))
15263 org-display-custom-times
15264 (get-text-property (point) 'display)
15265 (not (get-text-property (1- (point)) 'display)))
15266 (setq org-ts-what 'day))
15267 (setq org-ts-what (or what org-ts-what)
15268 inactive (= (char-after (match-beginning 0)) ?\[)
15269 ts (match-string 0))
15270 (replace-match "")
15271 (if (string-match
15272 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
15274 (setq extra (match-string 1 ts)))
15275 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15276 (setq with-hm t))
15277 (setq time0 (org-parse-time-string ts))
15278 (when (and updown
15279 (eq org-ts-what 'minute)
15280 (not current-prefix-arg))
15281 ;; This looks like s-up and s-down. Change by one rounding step.
15282 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
15283 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
15284 (setcar (cdr time0) (+ (nth 1 time0)
15285 (if (> n 0) (- rem) (- dm rem))))))
15286 (setq time
15287 (encode-time (or (car time0) 0)
15288 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
15289 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
15290 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
15291 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
15292 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
15293 (nthcdr 6 time0)))
15294 (when (and (member org-ts-what '(hour minute))
15295 extra
15296 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
15297 (setq extra (org-modify-ts-extra
15298 extra
15299 (if (eq org-ts-what 'hour) 2 5)
15300 n dm)))
15301 (when (integerp org-ts-what)
15302 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
15303 (if (eq what 'calendar)
15304 (let ((cal-date (org-get-date-from-calendar)))
15305 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15306 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15307 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15308 (setcar time0 (or (car time0) 0))
15309 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15310 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15311 (setq time (apply 'encode-time time0))))
15312 (setq org-last-changed-timestamp
15313 (org-insert-time-stamp time with-hm inactive nil nil extra))
15314 (org-clock-update-time-maybe)
15315 (goto-char pos)
15316 ;; Try to recenter the calendar window, if any
15317 (if (and org-calendar-follow-timestamp-change
15318 (get-buffer-window "*Calendar*" t)
15319 (memq org-ts-what '(day month year)))
15320 (org-recenter-calendar (time-to-days time))))))
15322 (defun org-modify-ts-extra (s pos n dm)
15323 "Change the different parts of the lead-time and repeat fields in timestamp."
15324 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15325 ng h m new rem)
15326 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15327 (cond
15328 ((or (org-pos-in-match-range pos 2)
15329 (org-pos-in-match-range pos 3))
15330 (setq m (string-to-number (match-string 3 s))
15331 h (string-to-number (match-string 2 s)))
15332 (if (org-pos-in-match-range pos 2)
15333 (setq h (+ h n))
15334 (setq n (* dm (org-no-warnings (signum n))))
15335 (when (not (= 0 (setq rem (% m dm))))
15336 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
15337 (setq m (+ m n)))
15338 (if (< m 0) (setq m (+ m 60) h (1- h)))
15339 (if (> m 59) (setq m (- m 60) h (1+ h)))
15340 (setq h (min 24 (max 0 h)))
15341 (setq ng 1 new (format "-%02d:%02d" h m)))
15342 ((org-pos-in-match-range pos 6)
15343 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15344 ((org-pos-in-match-range pos 5)
15345 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
15347 ((org-pos-in-match-range pos 9)
15348 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
15349 ((org-pos-in-match-range pos 8)
15350 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
15352 (when ng
15353 (setq s (concat
15354 (substring s 0 (match-beginning ng))
15356 (substring s (match-end ng))))))
15359 (defun org-recenter-calendar (date)
15360 "If the calendar is visible, recenter it to DATE."
15361 (let* ((win (selected-window))
15362 (cwin (get-buffer-window "*Calendar*" t))
15363 (calendar-move-hook nil))
15364 (when cwin
15365 (select-window cwin)
15366 (calendar-goto-date (if (listp date) date
15367 (calendar-gregorian-from-absolute date)))
15368 (select-window win))))
15370 (defun org-goto-calendar (&optional arg)
15371 "Go to the Emacs calendar at the current date.
15372 If there is a time stamp in the current line, go to that date.
15373 A prefix ARG can be used to force the current date."
15374 (interactive "P")
15375 (let ((tsr org-ts-regexp) diff
15376 (calendar-move-hook nil)
15377 (calendar-view-holidays-initially-flag nil)
15378 (calendar-view-diary-initially-flag nil))
15379 (if (or (org-at-timestamp-p)
15380 (save-excursion
15381 (beginning-of-line 1)
15382 (looking-at (concat ".*" tsr))))
15383 (let ((d1 (time-to-days (current-time)))
15384 (d2 (time-to-days
15385 (org-time-string-to-time (match-string 1)))))
15386 (setq diff (- d2 d1))))
15387 (calendar)
15388 (calendar-goto-today)
15389 (if (and diff (not arg)) (calendar-forward-day diff))))
15391 (defun org-get-date-from-calendar ()
15392 "Return a list (month day year) of date at point in calendar."
15393 (with-current-buffer "*Calendar*"
15394 (save-match-data
15395 (calendar-cursor-to-date))))
15397 (defun org-date-from-calendar ()
15398 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
15399 If there is already a time stamp at the cursor position, update it."
15400 (interactive)
15401 (if (org-at-timestamp-p t)
15402 (org-timestamp-change 0 'calendar)
15403 (let ((cal-date (org-get-date-from-calendar)))
15404 (org-insert-time-stamp
15405 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
15407 (defun org-minutes-to-hh:mm-string (m)
15408 "Compute H:MM from a number of minutes."
15409 (let ((h (/ m 60)))
15410 (setq m (- m (* 60 h)))
15411 (format org-time-clocksum-format h m)))
15413 (defun org-hh:mm-string-to-minutes (s)
15414 "Convert a string H:MM to a number of minutes.
15415 If the string is just a number, interpret it as minutes.
15416 In fact, the first hh:mm or number in the string will be taken,
15417 there can be extra stuff in the string.
15418 If no number is found, the return value is 0."
15419 (cond
15420 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
15421 (+ (* (string-to-number (match-string 1 s)) 60)
15422 (string-to-number (match-string 2 s))))
15423 ((string-match "\\([0-9]+\\)" s)
15424 (string-to-number (match-string 1 s)))
15425 (t 0)))
15427 ;;;; Files
15429 (defun org-save-all-org-buffers ()
15430 "Save all Org-mode buffers without user confirmation."
15431 (interactive)
15432 (message "Saving all Org-mode buffers...")
15433 (save-some-buffers t 'org-mode-p)
15434 (when (featurep 'org-id) (org-id-locations-save))
15435 (message "Saving all Org-mode buffers... done"))
15437 (defun org-revert-all-org-buffers ()
15438 "Revert all Org-mode buffers.
15439 Prompt for confirmation when there are unsaved changes.
15440 Be sure you know what you are doing before letting this function
15441 overwrite your changes.
15443 This function is useful in a setup where one tracks org files
15444 with a version control system, to revert on one machine after pulling
15445 changes from another. I believe the procedure must be like this:
15447 1. M-x org-save-all-org-buffers
15448 2. Pull changes from the other machine, resolve conflicts
15449 3. M-x org-revert-all-org-buffers"
15450 (interactive)
15451 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
15452 (error "Abort"))
15453 (save-excursion
15454 (save-window-excursion
15455 (mapc
15456 (lambda (b)
15457 (when (and (with-current-buffer b (org-mode-p))
15458 (with-current-buffer b buffer-file-name))
15459 (switch-to-buffer b)
15460 (revert-buffer t 'no-confirm)))
15461 (buffer-list))
15462 (when (and (featurep 'org-id) org-id-track-globally)
15463 (org-id-locations-load)))))
15465 ;;;; Agenda files
15467 ;;;###autoload
15468 (defun org-switchb (&optional arg)
15469 "Switch between Org buffers.
15470 With a prefix argument, restrict available to files.
15471 With two prefix arguments, restrict available buffers to agenda files.
15473 Defaults to `iswitchb' for buffer name completion.
15474 Set `org-completion-use-ido' to make it use ido instead."
15475 (interactive "P")
15476 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
15477 ((equal arg '(16)) (org-buffer-list 'agenda))
15478 (t (org-buffer-list))))
15479 (org-completion-use-iswitchb org-completion-use-iswitchb)
15480 (org-completion-use-ido org-completion-use-ido))
15481 (unless (or org-completion-use-ido org-completion-use-iswitchb)
15482 (setq org-completion-use-iswitchb t))
15483 (switch-to-buffer
15484 (org-icompleting-read "Org buffer: "
15485 (mapcar 'list (mapcar 'buffer-name blist))
15486 nil t))))
15488 ;;; Define some older names previously used for this functionality
15489 ;;;###autoload
15490 (defalias 'org-ido-switchb 'org-switchb)
15491 ;;;###autoload
15492 (defalias 'org-iswitchb 'org-switchb)
15494 (defun org-buffer-list (&optional predicate exclude-tmp)
15495 "Return a list of Org buffers.
15496 PREDICATE can be `export', `files' or `agenda'.
15498 export restrict the list to Export buffers.
15499 files restrict the list to buffers visiting Org files.
15500 agenda restrict the list to buffers visiting agenda files.
15502 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
15503 (let* ((bfn nil)
15504 (agenda-files (and (eq predicate 'agenda)
15505 (mapcar 'file-truename (org-agenda-files t))))
15506 (filter
15507 (cond
15508 ((eq predicate 'files)
15509 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
15510 ((eq predicate 'export)
15511 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
15512 ((eq predicate 'agenda)
15513 (lambda (b)
15514 (with-current-buffer b
15515 (and (eq major-mode 'org-mode)
15516 (setq bfn (buffer-file-name b))
15517 (member (file-truename bfn) agenda-files)))))
15518 (t (lambda (b) (with-current-buffer b
15519 (or (eq major-mode 'org-mode)
15520 (string-match "\*Org .*Export"
15521 (buffer-name b)))))))))
15522 (delq nil
15523 (mapcar
15524 (lambda(b)
15525 (if (and (funcall filter b)
15526 (or (not exclude-tmp)
15527 (not (string-match "tmp" (buffer-name b)))))
15529 nil))
15530 (buffer-list)))))
15532 (defun org-agenda-files (&optional unrestricted archives)
15533 "Get the list of agenda files.
15534 Optional UNRESTRICTED means return the full list even if a restriction
15535 is currently in place.
15536 When ARCHIVES is t, include all archive files that are really being
15537 used by the agenda files. If ARCHIVE is `ifmode', do this only if
15538 `org-agenda-archives-mode' is t."
15539 (let ((files
15540 (cond
15541 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
15542 ((stringp org-agenda-files) (org-read-agenda-file-list))
15543 ((listp org-agenda-files) org-agenda-files)
15544 (t (error "Invalid value of `org-agenda-files'")))))
15545 (setq files (apply 'append
15546 (mapcar (lambda (f)
15547 (if (file-directory-p f)
15548 (directory-files
15549 f t org-agenda-file-regexp)
15550 (list f)))
15551 files)))
15552 (when org-agenda-skip-unavailable-files
15553 (setq files (delq nil
15554 (mapcar (function
15555 (lambda (file)
15556 (and (file-readable-p file) file)))
15557 files))))
15558 (when (or (eq archives t)
15559 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
15560 (setq files (org-add-archive-files files)))
15561 files))
15563 (defun org-agenda-file-p (&optional file)
15564 "Return non-nil, if FILE is an agenda file.
15565 If FILE is omitted, use the file associated with the current
15566 buffer."
15567 (member (or file (buffer-file-name))
15568 (org-agenda-files t)))
15570 (defun org-edit-agenda-file-list ()
15571 "Edit the list of agenda files.
15572 Depending on setup, this either uses customize to edit the variable
15573 `org-agenda-files', or it visits the file that is holding the list. In the
15574 latter case, the buffer is set up in a way that saving it automatically kills
15575 the buffer and restores the previous window configuration."
15576 (interactive)
15577 (if (stringp org-agenda-files)
15578 (let ((cw (current-window-configuration)))
15579 (find-file org-agenda-files)
15580 (org-set-local 'org-window-configuration cw)
15581 (org-add-hook 'after-save-hook
15582 (lambda ()
15583 (set-window-configuration
15584 (prog1 org-window-configuration
15585 (kill-buffer (current-buffer))))
15586 (org-install-agenda-files-menu)
15587 (message "New agenda file list installed"))
15588 nil 'local)
15589 (message "%s" (substitute-command-keys
15590 "Edit list and finish with \\[save-buffer]")))
15591 (customize-variable 'org-agenda-files)))
15593 (defun org-store-new-agenda-file-list (list)
15594 "Set new value for the agenda file list and save it correctly."
15595 (if (stringp org-agenda-files)
15596 (let ((fe (org-read-agenda-file-list t)) b u)
15597 (while (setq b (find-buffer-visiting org-agenda-files))
15598 (kill-buffer b))
15599 (with-temp-file org-agenda-files
15600 (insert
15601 (mapconcat
15602 (lambda (f) ;; Keep un-expanded entries.
15603 (if (setq u (assoc f fe))
15604 (cdr u)
15606 list "\n")
15607 "\n")))
15608 (let ((org-mode-hook nil) (org-inhibit-startup t)
15609 (org-insert-mode-line-in-empty-file nil))
15610 (setq org-agenda-files list)
15611 (customize-save-variable 'org-agenda-files org-agenda-files))))
15613 (defun org-read-agenda-file-list (&optional pair-with-expansion)
15614 "Read the list of agenda files from a file.
15615 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
15616 filenames, used by `org-store-new-agenda-file-list' to write back
15617 un-expanded file names."
15618 (when (file-directory-p org-agenda-files)
15619 (error "`org-agenda-files' cannot be a single directory"))
15620 (when (stringp org-agenda-files)
15621 (with-temp-buffer
15622 (insert-file-contents org-agenda-files)
15623 (mapcar
15624 (lambda (f)
15625 (let ((e (expand-file-name (substitute-in-file-name f)
15626 org-directory)))
15627 (if pair-with-expansion
15628 (cons e f)
15629 e)))
15630 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
15632 ;;;###autoload
15633 (defun org-cycle-agenda-files ()
15634 "Cycle through the files in `org-agenda-files'.
15635 If the current buffer visits an agenda file, find the next one in the list.
15636 If the current buffer does not, find the first agenda file."
15637 (interactive)
15638 (let* ((fs (org-agenda-files t))
15639 (files (append fs (list (car fs))))
15640 (tcf (if buffer-file-name (file-truename buffer-file-name)))
15641 file)
15642 (unless files (error "No agenda files"))
15643 (catch 'exit
15644 (while (setq file (pop files))
15645 (if (equal (file-truename file) tcf)
15646 (when (car files)
15647 (find-file (car files))
15648 (throw 'exit t))))
15649 (find-file (car fs)))
15650 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
15652 (defun org-agenda-file-to-front (&optional to-end)
15653 "Move/add the current file to the top of the agenda file list.
15654 If the file is not present in the list, it is added to the front. If it is
15655 present, it is moved there. With optional argument TO-END, add/move to the
15656 end of the list."
15657 (interactive "P")
15658 (let ((org-agenda-skip-unavailable-files nil)
15659 (file-alist (mapcar (lambda (x)
15660 (cons (file-truename x) x))
15661 (org-agenda-files t)))
15662 (ctf (file-truename buffer-file-name))
15663 x had)
15664 (setq x (assoc ctf file-alist) had x)
15666 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
15667 (if to-end
15668 (setq file-alist (append (delq x file-alist) (list x)))
15669 (setq file-alist (cons x (delq x file-alist))))
15670 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
15671 (org-install-agenda-files-menu)
15672 (message "File %s to %s of agenda file list"
15673 (if had "moved" "added") (if to-end "end" "front"))))
15675 (defun org-remove-file (&optional file)
15676 "Remove current file from the list of files in variable `org-agenda-files'.
15677 These are the files which are being checked for agenda entries.
15678 Optional argument FILE means use this file instead of the current."
15679 (interactive)
15680 (let* ((org-agenda-skip-unavailable-files nil)
15681 (file (or file buffer-file-name))
15682 (true-file (file-truename file))
15683 (afile (abbreviate-file-name file))
15684 (files (delq nil (mapcar
15685 (lambda (x)
15686 (if (equal true-file
15687 (file-truename x))
15688 nil x))
15689 (org-agenda-files t)))))
15690 (if (not (= (length files) (length (org-agenda-files t))))
15691 (progn
15692 (org-store-new-agenda-file-list files)
15693 (org-install-agenda-files-menu)
15694 (message "Removed file: %s" afile))
15695 (message "File was not in list: %s (not removed)" afile))))
15697 (defun org-file-menu-entry (file)
15698 (vector file (list 'find-file file) t))
15700 (defun org-check-agenda-file (file)
15701 "Make sure FILE exists. If not, ask user what to do."
15702 (when (not (file-exists-p file))
15703 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
15704 (abbreviate-file-name file))
15705 (let ((r (downcase (read-char-exclusive))))
15706 (cond
15707 ((equal r ?r)
15708 (org-remove-file file)
15709 (throw 'nextfile t))
15710 (t (error "Abort"))))))
15712 (defun org-get-agenda-file-buffer (file)
15713 "Get a buffer visiting FILE. If the buffer needs to be created, add
15714 it to the list of buffers which might be released later."
15715 (let ((buf (org-find-base-buffer-visiting file)))
15716 (if buf
15717 buf ; just return it
15718 ;; Make a new buffer and remember it
15719 (setq buf (find-file-noselect file))
15720 (if buf (push buf org-agenda-new-buffers))
15721 buf)))
15723 (defun org-release-buffers (blist)
15724 "Release all buffers in list, asking the user for confirmation when needed.
15725 When a buffer is unmodified, it is just killed. When modified, it is saved
15726 \(if the user agrees) and then killed."
15727 (let (buf file)
15728 (while (setq buf (pop blist))
15729 (setq file (buffer-file-name buf))
15730 (when (and (buffer-modified-p buf)
15731 file
15732 (y-or-n-p (format "Save file %s? " file)))
15733 (with-current-buffer buf (save-buffer)))
15734 (kill-buffer buf))))
15736 (defun org-prepare-agenda-buffers (files)
15737 "Create buffers for all agenda files, protect archived trees and comments."
15738 (interactive)
15739 (let ((pa '(:org-archived t))
15740 (pc '(:org-comment t))
15741 (pall '(:org-archived t :org-comment t))
15742 (inhibit-read-only t)
15743 (rea (concat ":" org-archive-tag ":"))
15744 bmp file re)
15745 (save-excursion
15746 (save-restriction
15747 (while (setq file (pop files))
15748 (catch 'nextfile
15749 (if (bufferp file)
15750 (set-buffer file)
15751 (org-check-agenda-file file)
15752 (set-buffer (org-get-agenda-file-buffer file)))
15753 (widen)
15754 (setq bmp (buffer-modified-p))
15755 (org-refresh-category-properties)
15756 (setq org-todo-keywords-for-agenda
15757 (append org-todo-keywords-for-agenda org-todo-keywords-1))
15758 (setq org-done-keywords-for-agenda
15759 (append org-done-keywords-for-agenda org-done-keywords))
15760 (setq org-todo-keyword-alist-for-agenda
15761 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
15762 (setq org-drawers-for-agenda
15763 (append org-drawers-for-agenda org-drawers))
15764 (setq org-tag-alist-for-agenda
15765 (append org-tag-alist-for-agenda org-tag-alist))
15767 (save-excursion
15768 (remove-text-properties (point-min) (point-max) pall)
15769 (when org-agenda-skip-archived-trees
15770 (goto-char (point-min))
15771 (while (re-search-forward rea nil t)
15772 (if (org-on-heading-p t)
15773 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
15774 (goto-char (point-min))
15775 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
15776 (while (re-search-forward re nil t)
15777 (add-text-properties
15778 (match-beginning 0) (org-end-of-subtree t) pc)))
15779 (set-buffer-modified-p bmp)))))
15780 (setq org-todo-keywords-for-agenda
15781 (org-uniquify org-todo-keywords-for-agenda))
15782 (setq org-todo-keyword-alist-for-agenda
15783 (org-uniquify org-todo-keyword-alist-for-agenda)
15784 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
15786 ;;;; Embedded LaTeX
15788 (defvar org-cdlatex-mode-map (make-sparse-keymap)
15789 "Keymap for the minor `org-cdlatex-mode'.")
15791 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
15792 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
15793 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
15794 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
15795 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
15797 (defvar org-cdlatex-texmathp-advice-is-done nil
15798 "Flag remembering if we have applied the advice to texmathp already.")
15800 (define-minor-mode org-cdlatex-mode
15801 "Toggle the minor `org-cdlatex-mode'.
15802 This mode supports entering LaTeX environment and math in LaTeX fragments
15803 in Org-mode.
15804 \\{org-cdlatex-mode-map}"
15805 nil " OCDL" nil
15806 (when org-cdlatex-mode (require 'cdlatex))
15807 (unless org-cdlatex-texmathp-advice-is-done
15808 (setq org-cdlatex-texmathp-advice-is-done t)
15809 (defadvice texmathp (around org-math-always-on activate)
15810 "Always return t in org-mode buffers.
15811 This is because we want to insert math symbols without dollars even outside
15812 the LaTeX math segments. If Orgmode thinks that point is actually inside
15813 an embedded LaTeX fragment, let texmathp do its job.
15814 \\[org-cdlatex-mode-map]"
15815 (interactive)
15816 (let (p)
15817 (cond
15818 ((not (org-mode-p)) ad-do-it)
15819 ((eq this-command 'cdlatex-math-symbol)
15820 (setq ad-return-value t
15821 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
15823 (let ((p (org-inside-LaTeX-fragment-p)))
15824 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
15825 (setq ad-return-value t
15826 texmathp-why '("Org-mode embedded math" . 0))
15827 (if p ad-do-it)))))))))
15829 (defun turn-on-org-cdlatex ()
15830 "Unconditionally turn on `org-cdlatex-mode'."
15831 (org-cdlatex-mode 1))
15833 (defun org-inside-LaTeX-fragment-p ()
15834 "Test if point is inside a LaTeX fragment.
15835 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
15836 sequence appearing also before point.
15837 Even though the matchers for math are configurable, this function assumes
15838 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
15839 delimiters are skipped when they have been removed by customization.
15840 The return value is nil, or a cons cell with the delimiter and
15841 and the position of this delimiter.
15843 This function does a reasonably good job, but can locally be fooled by
15844 for example currency specifications. For example it will assume being in
15845 inline math after \"$22.34\". The LaTeX fragment formatter will only format
15846 fragments that are properly closed, but during editing, we have to live
15847 with the uncertainty caused by missing closing delimiters. This function
15848 looks only before point, not after."
15849 (catch 'exit
15850 (let ((pos (point))
15851 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
15852 (lim (progn
15853 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
15854 (point)))
15855 dd-on str (start 0) m re)
15856 (goto-char pos)
15857 (when dodollar
15858 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
15859 re (nth 1 (assoc "$" org-latex-regexps)))
15860 (while (string-match re str start)
15861 (cond
15862 ((= (match-end 0) (length str))
15863 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
15864 ((= (match-end 0) (- (length str) 5))
15865 (throw 'exit nil))
15866 (t (setq start (match-end 0))))))
15867 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
15868 (goto-char pos)
15869 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
15870 (and (match-beginning 2) (throw 'exit nil))
15871 ;; count $$
15872 (while (re-search-backward "\\$\\$" lim t)
15873 (setq dd-on (not dd-on)))
15874 (goto-char pos)
15875 (if dd-on (cons "$$" m))))))
15877 (defun org-inside-latex-macro-p ()
15878 "Is point inside a LaTeX macro or its arguments?"
15879 (save-match-data
15880 (org-in-regexp
15881 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
15883 (defun org-try-cdlatex-tab ()
15884 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
15885 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
15886 - inside a LaTeX fragment, or
15887 - after the first word in a line, where an abbreviation expansion could
15888 insert a LaTeX environment."
15889 (when org-cdlatex-mode
15890 (cond
15891 ((save-excursion
15892 (skip-chars-backward "a-zA-Z0-9*")
15893 (skip-chars-backward " \t")
15894 (bolp))
15895 (cdlatex-tab) t)
15896 ((org-inside-LaTeX-fragment-p)
15897 (cdlatex-tab) t)
15898 (t nil))))
15900 (defun org-cdlatex-underscore-caret (&optional arg)
15901 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
15902 Revert to the normal definition outside of these fragments."
15903 (interactive "P")
15904 (if (org-inside-LaTeX-fragment-p)
15905 (call-interactively 'cdlatex-sub-superscript)
15906 (let (org-cdlatex-mode)
15907 (call-interactively (key-binding (vector last-input-event))))))
15909 (defun org-cdlatex-math-modify (&optional arg)
15910 "Execute `cdlatex-math-modify' in LaTeX fragments.
15911 Revert to the normal definition outside of these fragments."
15912 (interactive "P")
15913 (if (org-inside-LaTeX-fragment-p)
15914 (call-interactively 'cdlatex-math-modify)
15915 (let (org-cdlatex-mode)
15916 (call-interactively (key-binding (vector last-input-event))))))
15918 (defvar org-latex-fragment-image-overlays nil
15919 "List of overlays carrying the images of latex fragments.")
15920 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
15922 (defun org-remove-latex-fragment-image-overlays ()
15923 "Remove all overlays with LaTeX fragment images in current buffer."
15924 (mapc 'delete-overlay org-latex-fragment-image-overlays)
15925 (setq org-latex-fragment-image-overlays nil))
15927 (defun org-preview-latex-fragment (&optional subtree)
15928 "Preview the LaTeX fragment at point, or all locally or globally.
15929 If the cursor is in a LaTeX fragment, create the image and overlay
15930 it over the source code. If there is no fragment at point, display
15931 all fragments in the current text, from one headline to the next. With
15932 prefix SUBTREE, display all fragments in the current subtree. With a
15933 double prefix arg \\[universal-argument] \\[universal-argument], or when \
15934 the cursor is before the first headline,
15935 display all fragments in the buffer.
15936 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
15937 (interactive "P")
15938 (org-remove-latex-fragment-image-overlays)
15939 (save-excursion
15940 (save-restriction
15941 (let (beg end at msg)
15942 (cond
15943 ((or (equal subtree '(16))
15944 (not (save-excursion
15945 (re-search-backward (concat "^" outline-regexp) nil t))))
15946 (setq beg (point-min) end (point-max)
15947 msg "Creating images for buffer...%s"))
15948 ((equal subtree '(4))
15949 (org-back-to-heading)
15950 (setq beg (point) end (org-end-of-subtree t)
15951 msg "Creating images for subtree...%s"))
15953 (if (setq at (org-inside-LaTeX-fragment-p))
15954 (goto-char (max (point-min) (- (cdr at) 2)))
15955 (org-back-to-heading))
15956 (setq beg (point) end (progn (outline-next-heading) (point))
15957 msg (if at "Creating image...%s"
15958 "Creating images for entry...%s"))))
15959 (message msg "")
15960 (narrow-to-region beg end)
15961 (goto-char beg)
15962 (org-format-latex
15963 (concat "ltxpng/" (file-name-sans-extension
15964 (file-name-nondirectory
15965 buffer-file-name)))
15966 default-directory 'overlays msg at 'forbuffer 'dvipng)
15967 (message msg "done. Use `C-c C-c' to remove images.")))))
15969 (defvar org-latex-regexps
15970 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
15971 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
15972 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
15973 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15974 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15975 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
15976 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
15977 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
15978 "Regular expressions for matching embedded LaTeX.")
15980 (defvar org-export-have-math nil) ;; dynamic scoping
15981 (defun org-format-latex (prefix &optional dir overlays msg at
15982 forbuffer processing-type)
15983 "Replace LaTeX fragments with links to an image, and produce images.
15984 Some of the options can be changed using the variable
15985 `org-format-latex-options'."
15986 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
15987 (let* ((prefixnodir (file-name-nondirectory prefix))
15988 (absprefix (expand-file-name prefix dir))
15989 (todir (file-name-directory absprefix))
15990 (opt org-format-latex-options)
15991 (matchers (plist-get opt :matchers))
15992 (re-list org-latex-regexps)
15993 (org-format-latex-header-extra
15994 (plist-get (org-infile-export-plist) :latex-header-extra))
15995 (cnt 0) txt hash link beg end re e checkdir
15996 executables-checked string
15997 m n block linkfile movefile ov)
15998 ;; Check the different regular expressions
15999 (while (setq e (pop re-list))
16000 (setq m (car e) re (nth 1 e) n (nth 2 e)
16001 block (if (nth 3 e) "\n\n" ""))
16002 (when (member m matchers)
16003 (goto-char (point-min))
16004 (while (re-search-forward re nil t)
16005 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16006 (not (get-text-property (match-beginning n)
16007 'org-protected))
16008 (or (not overlays)
16009 (not (eq (get-char-property (match-beginning n)
16010 'org-overlay-type)
16011 'org-latex-overlay))))
16012 (setq org-export-have-math t)
16013 (cond
16014 ((eq processing-type 'verbatim)
16015 ;; Leave the text verbatim, just protect it
16016 (add-text-properties (match-beginning n) (match-end n)
16017 '(org-protected t)))
16018 ((eq processing-type 'mathjax)
16019 ;; Prepare for MathJax processing
16020 (setq string (match-string n))
16021 (if (member m '("$" "$1"))
16022 (save-excursion
16023 (delete-region (match-beginning n) (match-end n))
16024 (goto-char (match-beginning n))
16025 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16026 "\\)")
16027 '(org-protected t))))
16028 (add-text-properties (match-beginning n) (match-end n)
16029 '(org-protected t))))
16030 ((or (eq processing-type 'dvipng) t)
16031 ;; Process to an image
16032 (setq txt (match-string n)
16033 beg (match-beginning n) end (match-end n)
16034 cnt (1+ cnt))
16035 (let (print-length print-level) ; make sure full list is printed
16036 (setq hash (sha1 (prin1-to-string
16037 (list org-format-latex-header
16038 org-format-latex-header-extra
16039 org-export-latex-default-packages-alist
16040 org-export-latex-packages-alist
16041 org-format-latex-options
16042 forbuffer txt)))
16043 linkfile (format "%s_%s.png" prefix hash)
16044 movefile (format "%s_%s.png" absprefix hash)))
16045 (setq link (concat block "[[file:" linkfile "]]" block))
16046 (if msg (message msg cnt))
16047 (goto-char beg)
16048 (unless checkdir ; make sure the directory exists
16049 (setq checkdir t)
16050 (or (file-directory-p todir) (make-directory todir t)))
16052 (unless executables-checked
16053 (org-check-external-command
16054 "latex" "needed to convert LaTeX fragments to images")
16055 (org-check-external-command
16056 "dvipng" "needed to convert LaTeX fragments to images")
16057 (setq executables-checked t))
16059 (unless (file-exists-p movefile)
16060 (org-create-formula-image
16061 txt movefile opt forbuffer))
16062 (if overlays
16063 (progn
16064 (mapc (lambda (o)
16065 (if (eq (overlay-get o 'org-overlay-type)
16066 'org-latex-overlay)
16067 (delete-overlay o)))
16068 (overlays-in beg end))
16069 (setq ov (make-overlay beg end))
16070 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16071 (if (featurep 'xemacs)
16072 (progn
16073 (overlay-put ov 'invisible t)
16074 (overlay-put
16075 ov 'end-glyph
16076 (make-glyph (vector 'png :file movefile))))
16077 (overlay-put
16078 ov 'display
16079 (list 'image :type 'png :file movefile :ascent 'center)))
16080 (push ov org-latex-fragment-image-overlays)
16081 (goto-char end))
16082 (delete-region beg end)
16083 (insert (org-add-props link
16084 (list 'org-latex-src
16085 (replace-regexp-in-string
16086 "\"" "" txt)))))))))))))
16088 ;; This function borrows from Ganesh Swami's latex2png.el
16089 (defun org-create-formula-image (string tofile options buffer)
16090 "This calls dvipng."
16091 (require 'org-latex)
16092 (let* ((tmpdir (if (featurep 'xemacs)
16093 (temp-directory)
16094 temporary-file-directory))
16095 (texfilebase (make-temp-name
16096 (expand-file-name "orgtex" tmpdir)))
16097 (texfile (concat texfilebase ".tex"))
16098 (dvifile (concat texfilebase ".dvi"))
16099 (pngfile (concat texfilebase ".png"))
16100 (fnh (if (featurep 'xemacs)
16101 (font-height (get-face-font 'default))
16102 (face-attribute 'default :height nil)))
16103 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
16104 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
16105 (fg (or (plist-get options (if buffer :foreground :html-foreground))
16106 "Black"))
16107 (bg (or (plist-get options (if buffer :background :html-background))
16108 "Transparent")))
16109 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
16110 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
16111 (with-temp-file texfile
16112 (insert (org-splice-latex-header
16113 org-format-latex-header
16114 org-export-latex-default-packages-alist
16115 org-export-latex-packages-alist t
16116 org-format-latex-header-extra))
16117 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
16118 (require 'org-latex)
16119 (org-export-latex-fix-inputenc))
16120 (let ((dir default-directory))
16121 (condition-case nil
16122 (progn
16123 (cd tmpdir)
16124 (call-process "latex" nil nil nil texfile))
16125 (error nil))
16126 (cd dir))
16127 (if (not (file-exists-p dvifile))
16128 (progn (message "Failed to create dvi file from %s" texfile) nil)
16129 (condition-case nil
16130 (call-process "dvipng" nil nil nil
16131 "-fg" fg "-bg" bg
16132 "-D" dpi
16133 ;;"-x" scale "-y" scale
16134 "-T" "tight"
16135 "-o" pngfile
16136 dvifile)
16137 (error nil))
16138 (if (not (file-exists-p pngfile))
16139 (if org-format-latex-signal-error
16140 (error "Failed to create png file from %s" texfile)
16141 (message "Failed to create png file from %s" texfile)
16142 nil)
16143 ;; Use the requested file name and clean up
16144 (copy-file pngfile tofile 'replace)
16145 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16146 (delete-file (concat texfilebase e)))
16147 pngfile))))
16149 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
16150 "Fill a LaTeX header template TPL.
16151 In the template, the following place holders will be recognized:
16153 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
16154 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
16155 [PACKAGES] \\usepackage statements for PKG
16156 [NO-PACKAGES] do not include PKG
16157 [EXTRA] the string EXTRA
16158 [NO-EXTRA] do not include EXTRA
16160 For backward compatibility, if both the positive and the negative place
16161 holder is missing, the positive one (without the \"NO-\") will be
16162 assumed to be present at the end of the template.
16163 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
16164 EXTRA is a string.
16165 SNIPPETS-P indicates if this is run to create snippet images for HTML."
16166 (let (rpl (end ""))
16167 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
16168 (setq rpl (if (or (match-end 1) (not def-pkg))
16169 "" (org-latex-packages-to-string def-pkg snippets-p t))
16170 tpl (replace-match rpl t t tpl))
16171 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
16173 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
16174 (setq rpl (if (or (match-end 1) (not pkg))
16175 "" (org-latex-packages-to-string pkg snippets-p t))
16176 tpl (replace-match rpl t t tpl))
16177 (if pkg (setq end
16178 (concat end "\n"
16179 (org-latex-packages-to-string pkg snippets-p)))))
16181 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
16182 (setq rpl (if (or (match-end 1) (not extra))
16183 "" (concat extra "\n"))
16184 tpl (replace-match rpl t t tpl))
16185 (if (and extra (string-match "\\S-" extra))
16186 (setq end (concat end "\n" extra))))
16188 (if (string-match "\\S-" end)
16189 (concat tpl "\n" end)
16190 tpl)))
16192 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
16193 "Turn an alist of packages into a string with the \\usepackage macros."
16194 (setq pkg (mapconcat (lambda(p)
16195 (cond
16196 ((stringp p) p)
16197 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
16198 (format "%% Package %s omitted" (cadr p)))
16199 ((equal "" (car p))
16200 (format "\\usepackage{%s}" (cadr p)))
16202 (format "\\usepackage[%s]{%s}"
16203 (car p) (cadr p)))))
16205 "\n"))
16206 (if newline (concat pkg "\n") pkg))
16208 (defun org-dvipng-color (attr)
16209 "Return an rgb color specification for dvipng."
16210 (apply 'format "rgb %s %s %s"
16211 (mapcar 'org-normalize-color
16212 (color-values (face-attribute 'default attr nil)))))
16214 (defun org-normalize-color (value)
16215 "Return string to be used as color value for an RGB component."
16216 (format "%g" (/ value 65535.0)))
16218 ;; Image display
16221 (defvar org-inline-image-overlays nil)
16222 (make-variable-buffer-local 'org-inline-image-overlays)
16224 (defun org-toggle-inline-images (&optional include-linked)
16225 "Toggle the display of inline images.
16226 INCLUDE-LINKED is passed to `org-display-inline-images'."
16227 (interactive "P")
16228 (if org-inline-image-overlays
16229 (progn
16230 (org-remove-inline-images)
16231 (message "Inline image display turned off"))
16232 (org-display-inline-images include-linked)
16233 (if org-inline-image-overlays
16234 (message "%d images displayed inline"
16235 (length org-inline-image-overlays))
16236 (message "No images to display inline"))))
16238 (defun org-display-inline-images (&optional include-linked refresh beg end)
16239 "Display inline images.
16240 Normally only links without a description part are inlined, because this
16241 is how it will work for export. When INCLUDE-LINKED is set, also links
16242 with a description part will be inlined. This can be nice for a quick
16243 look at those images, but it does not reflect what exported files will look
16244 like.
16245 When REFRESH is set, refresh existing images between BEG and END.
16246 This will create new image displays only if necessary.
16247 BEG and END default to the buffer boundaries."
16248 (interactive "P")
16249 (unless refresh
16250 (org-remove-inline-images)
16251 (clear-image-cache))
16252 (save-excursion
16253 (save-restriction
16254 (widen)
16255 (setq beg (or beg (point-min)) end (or end (point-max)))
16256 (goto-char (point-min))
16257 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
16258 (substring (org-image-file-name-regexp) 0 -2)
16259 "\\)\\]" (if include-linked "" "\\]")))
16260 old file ov img)
16261 (while (re-search-forward re end t)
16262 (setq old (get-char-property-and-overlay (match-beginning 1)
16263 'org-image-overlay))
16264 (setq file (expand-file-name
16265 (concat (or (match-string 3) "") (match-string 4))))
16266 (when (file-exists-p file)
16267 (if (and (car-safe old) refresh)
16268 (image-refresh (overlay-get (cdr old) 'display))
16269 (setq img (save-match-data (create-image file)))
16270 (when img
16271 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
16272 (overlay-put ov 'display img)
16273 (overlay-put ov 'face 'default)
16274 (overlay-put ov 'org-image-overlay t)
16275 (overlay-put ov 'modification-hooks
16276 (list 'org-display-inline-modification-hook))
16277 (push ov org-inline-image-overlays)))))))))
16279 (defun org-display-inline-modification-hook (ov after beg end &optional len)
16280 "Remove inline-display overlay if a corresponding region is modified."
16281 (let ((inhibit-modification-hooks t))
16282 (when (and ov after)
16283 (delete ov org-inline-image-overlays)
16284 (delete-overlay ov))))
16286 (defun org-remove-inline-images ()
16287 "Remove inline display of images."
16288 (interactive)
16289 (mapc 'delete-overlay org-inline-image-overlays)
16290 (setq org-inline-image-overlays nil))
16292 ;;;; Key bindings
16294 ;; Make `C-c C-x' a prefix key
16295 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
16297 ;; TAB key with modifiers
16298 (org-defkey org-mode-map "\C-i" 'org-cycle)
16299 (org-defkey org-mode-map [(tab)] 'org-cycle)
16300 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
16301 (org-defkey org-mode-map [(meta tab)] 'org-complete)
16302 (org-defkey org-mode-map "\M-\t" 'org-complete)
16303 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
16304 ;; The following line is necessary under Suse GNU/Linux
16305 (unless (featurep 'xemacs)
16306 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
16307 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
16308 (define-key org-mode-map [backtab] 'org-shifttab)
16310 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
16311 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
16312 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
16314 ;; Cursor keys with modifiers
16315 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
16316 (org-defkey org-mode-map [(meta right)] 'org-metaright)
16317 (org-defkey org-mode-map [(meta up)] 'org-metaup)
16318 (org-defkey org-mode-map [(meta down)] 'org-metadown)
16320 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
16321 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
16322 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
16323 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
16325 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
16326 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
16327 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
16328 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
16330 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
16331 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
16333 ;; Babel keys
16334 (define-key org-mode-map org-babel-key-prefix org-babel-map)
16335 (mapc (lambda (pair)
16336 (define-key org-babel-map (car pair) (cdr pair)))
16337 org-babel-key-bindings)
16339 ;;; Extra keys for tty access.
16340 ;; We only set them when really needed because otherwise the
16341 ;; menus don't show the simple keys
16343 (when (or org-use-extra-keys
16344 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
16345 (not window-system))
16346 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
16347 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
16348 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
16349 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
16350 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
16351 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
16352 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
16353 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
16354 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
16355 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
16356 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
16357 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
16358 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
16359 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
16360 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
16361 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
16362 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
16363 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
16364 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
16365 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
16366 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
16367 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
16368 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
16369 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
16370 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
16371 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
16372 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
16373 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
16375 ;; All the other keys
16377 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
16378 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
16379 (if (boundp 'narrow-map)
16380 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
16381 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
16382 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
16383 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
16384 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
16385 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
16386 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
16387 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
16388 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
16389 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
16390 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
16391 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
16392 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
16393 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
16394 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
16395 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
16396 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
16397 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
16398 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
16399 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
16400 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
16401 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
16402 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
16403 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
16404 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
16405 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
16406 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
16407 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
16408 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
16409 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
16410 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
16411 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
16412 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
16413 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
16414 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
16415 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
16416 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
16417 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
16418 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
16419 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
16420 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
16421 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
16422 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16423 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
16424 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
16425 (org-defkey org-mode-map "\C-c^" 'org-sort)
16426 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
16427 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
16428 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
16429 (org-defkey org-mode-map "\C-m" 'org-return)
16430 (org-defkey org-mode-map "\C-j" 'org-return-indent)
16431 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
16432 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
16433 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
16434 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
16435 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
16436 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
16437 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
16438 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
16439 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
16440 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
16441 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
16442 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
16443 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
16444 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
16445 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
16446 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
16447 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
16448 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
16449 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
16450 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
16452 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
16453 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
16454 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
16455 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
16457 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
16458 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
16459 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
16460 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
16461 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
16462 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
16463 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
16464 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
16465 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
16466 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
16467 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
16468 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
16469 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
16470 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
16471 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
16472 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
16473 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
16474 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
16476 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
16477 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
16478 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
16479 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
16480 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
16482 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
16484 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
16486 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
16487 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
16489 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
16492 (when (featurep 'xemacs)
16493 (org-defkey org-mode-map 'button3 'popup-mode-menu))
16496 (defconst org-speed-commands-default
16498 ("Outline Navigation")
16499 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
16500 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
16501 ("f" . (org-speed-move-safe 'org-forward-same-level))
16502 ("b" . (org-speed-move-safe 'org-backward-same-level))
16503 ("u" . (org-speed-move-safe 'outline-up-heading))
16504 ("j" . org-goto)
16505 ("g" . (org-refile t))
16506 ("Outline Visibility")
16507 ("c" . org-cycle)
16508 ("C" . org-shifttab)
16509 (" " . org-display-outline-path)
16510 ("Outline Structure Editing")
16511 ("U" . org-shiftmetaup)
16512 ("D" . org-shiftmetadown)
16513 ("r" . org-metaright)
16514 ("l" . org-metaleft)
16515 ("R" . org-shiftmetaright)
16516 ("L" . org-shiftmetaleft)
16517 ("i" . (progn (forward-char 1) (call-interactively
16518 'org-insert-heading-respect-content)))
16519 ("^" . org-sort)
16520 ("w" . org-refile)
16521 ("a" . org-archive-subtree-default-with-confirmation)
16522 ("." . outline-mark-subtree)
16523 ("Clock Commands")
16524 ("I" . org-clock-in)
16525 ("O" . org-clock-out)
16526 ("Meta Data Editing")
16527 ("t" . org-todo)
16528 ("0" . (org-priority ?\ ))
16529 ("1" . (org-priority ?A))
16530 ("2" . (org-priority ?B))
16531 ("3" . (org-priority ?C))
16532 (";" . org-set-tags-command)
16533 ("e" . org-set-effort)
16534 ("Agenda Views etc")
16535 ("v" . org-agenda)
16536 ("/" . org-sparse-tree)
16537 ("Misc")
16538 ("o" . org-open-at-point)
16539 ("?" . org-speed-command-help)
16540 ("<" . (org-agenda-set-restriction-lock 'subtree))
16541 (">" . (org-agenda-remove-restriction-lock))
16543 "The default speed commands.")
16545 (defun org-print-speed-command (e)
16546 (if (> (length (car e)) 1)
16547 (progn
16548 (princ "\n")
16549 (princ (car e))
16550 (princ "\n")
16551 (princ (make-string (length (car e)) ?-))
16552 (princ "\n"))
16553 (princ (car e))
16554 (princ " ")
16555 (if (symbolp (cdr e))
16556 (princ (symbol-name (cdr e)))
16557 (prin1 (cdr e)))
16558 (princ "\n")))
16560 (defun org-speed-command-help ()
16561 "Show the available speed commands."
16562 (interactive)
16563 (if (not org-use-speed-commands)
16564 (error "Speed commands are not activated, customize `org-use-speed-commands'")
16565 (with-output-to-temp-buffer "*Help*"
16566 (princ "User-defined Speed commands\n===========================\n")
16567 (mapc 'org-print-speed-command org-speed-commands-user)
16568 (princ "\n")
16569 (princ "Built-in Speed commands\n=======================\n")
16570 (mapc 'org-print-speed-command org-speed-commands-default))
16571 (with-current-buffer "*Help*"
16572 (setq truncate-lines t))))
16574 (defun org-speed-move-safe (cmd)
16575 "Execute CMD, but make sure that the cursor always ends up in a headline.
16576 If not, return to the original position and throw an error."
16577 (interactive)
16578 (let ((pos (point)))
16579 (call-interactively cmd)
16580 (unless (and (bolp) (org-on-heading-p))
16581 (goto-char pos)
16582 (error "Boundary reached while executing %s" cmd))))
16584 (defvar org-self-insert-command-undo-counter 0)
16586 (defvar org-table-auto-blank-field) ; defined in org-table.el
16587 (defvar org-speed-command nil)
16589 (defun org-speed-command-default-hook (keys)
16590 "Hook for activating single-letter speed commands.
16591 `org-speed-commands-default' specifies a minimal command set. Use
16592 `org-speed-commands-user' for further customization."
16593 (when (or (and (bolp) (looking-at outline-regexp))
16594 (and (functionp org-use-speed-commands)
16595 (funcall org-use-speed-commands)))
16596 (cdr (assoc keys (append org-speed-commands-user
16597 org-speed-commands-default)))))
16599 (defun org-babel-speed-command-hook (keys)
16600 "Hook for activating single-letter code block commands."
16601 (when (and (bolp) (looking-at org-babel-src-block-regexp))
16602 (cdr (assoc keys org-babel-key-bindings))))
16604 (defcustom org-speed-command-hook
16605 '(org-speed-command-default-hook org-babel-speed-command-hook)
16606 "Hook for activating speed commands at strategic locations.
16607 Hook functions are called in sequence until a valid handler is
16608 found.
16610 Each hook takes a single argument, a user-pressed command key
16611 which is also a `self-insert-command' from the global map.
16613 Within the hook, examine the cursor position and the command key
16614 and return nil or a valid handler as appropriate. Handler could
16615 be one of an interactive command, a function, or a form.
16617 Set `org-use-speed-commands' to non-nil value to enable this
16618 hook. The default setting is `org-speed-command-default-hook'."
16619 :group 'org-structure
16620 :type 'hook)
16622 (defun org-self-insert-command (N)
16623 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
16624 If the cursor is in a table looking at whitespace, the whitespace is
16625 overwritten, and the table is not marked as requiring realignment."
16626 (interactive "p")
16627 (cond
16628 ((and org-use-speed-commands
16629 (setq org-speed-command
16630 (run-hook-with-args-until-success
16631 'org-speed-command-hook (this-command-keys))))
16632 (cond
16633 ((commandp org-speed-command)
16634 (setq this-command org-speed-command)
16635 (call-interactively org-speed-command))
16636 ((functionp org-speed-command)
16637 (funcall org-speed-command))
16638 ((and org-speed-command (listp org-speed-command))
16639 (eval org-speed-command))
16640 (t (let (org-use-speed-commands)
16641 (call-interactively 'org-self-insert-command)))))
16642 ((and
16643 (org-table-p)
16644 (progn
16645 ;; check if we blank the field, and if that triggers align
16646 (and (featurep 'org-table) org-table-auto-blank-field
16647 (member last-command
16648 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
16649 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
16650 ;; got extra space, this field does not determine column width
16651 (let (org-table-may-need-update) (org-table-blank-field))
16652 ;; no extra space, this field may determine column width
16653 (org-table-blank-field)))
16655 (eq N 1)
16656 (looking-at "[^|\n]* |"))
16657 (let (org-table-may-need-update)
16658 (goto-char (1- (match-end 0)))
16659 (delete-backward-char 1)
16660 (goto-char (match-beginning 0))
16661 (self-insert-command N)))
16663 (setq org-table-may-need-update t)
16664 (self-insert-command N)
16665 (org-fix-tags-on-the-fly)
16666 (if org-self-insert-cluster-for-undo
16667 (if (not (eq last-command 'org-self-insert-command))
16668 (setq org-self-insert-command-undo-counter 1)
16669 (if (>= org-self-insert-command-undo-counter 20)
16670 (setq org-self-insert-command-undo-counter 1)
16671 (and (> org-self-insert-command-undo-counter 0)
16672 buffer-undo-list
16673 (not (cadr buffer-undo-list)) ; remove nil entry
16674 (setcdr buffer-undo-list (cddr buffer-undo-list)))
16675 (setq org-self-insert-command-undo-counter
16676 (1+ org-self-insert-command-undo-counter))))))))
16678 (defun org-fix-tags-on-the-fly ()
16679 (when (and (equal (char-after (point-at-bol)) ?*)
16680 (org-on-heading-p))
16681 (org-align-tags-here org-tags-column)))
16683 (defun org-delete-backward-char (N)
16684 "Like `delete-backward-char', insert whitespace at field end in tables.
16685 When deleting backwards, in tables this function will insert whitespace in
16686 front of the next \"|\" separator, to keep the table aligned. The table will
16687 still be marked for re-alignment if the field did fill the entire column,
16688 because, in this case the deletion might narrow the column."
16689 (interactive "p")
16690 (if (and (org-table-p)
16691 (eq N 1)
16692 (string-match "|" (buffer-substring (point-at-bol) (point)))
16693 (looking-at ".*?|"))
16694 (let ((pos (point))
16695 (noalign (looking-at "[^|\n\r]* |"))
16696 (c org-table-may-need-update))
16697 (backward-delete-char N)
16698 (if (not overwrite-mode)
16699 (progn
16700 (skip-chars-forward "^|")
16701 (insert " ")
16702 (goto-char (1- pos))))
16703 ;; noalign: if there were two spaces at the end, this field
16704 ;; does not determine the width of the column.
16705 (if noalign (setq org-table-may-need-update c)))
16706 (backward-delete-char N)
16707 (org-fix-tags-on-the-fly)))
16709 (defun org-delete-char (N)
16710 "Like `delete-char', but insert whitespace at field end in tables.
16711 When deleting characters, in tables this function will insert whitespace in
16712 front of the next \"|\" separator, to keep the table aligned. The table will
16713 still be marked for re-alignment if the field did fill the entire column,
16714 because, in this case the deletion might narrow the column."
16715 (interactive "p")
16716 (if (and (org-table-p)
16717 (not (bolp))
16718 (not (= (char-after) ?|))
16719 (eq N 1))
16720 (if (looking-at ".*?|")
16721 (let ((pos (point))
16722 (noalign (looking-at "[^|\n\r]* |"))
16723 (c org-table-may-need-update))
16724 (replace-match (concat
16725 (substring (match-string 0) 1 -1)
16726 " |"))
16727 (goto-char pos)
16728 ;; noalign: if there were two spaces at the end, this field
16729 ;; does not determine the width of the column.
16730 (if noalign (setq org-table-may-need-update c)))
16731 (delete-char N))
16732 (delete-char N)
16733 (org-fix-tags-on-the-fly)))
16735 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
16736 (put 'org-self-insert-command 'delete-selection t)
16737 (put 'orgtbl-self-insert-command 'delete-selection t)
16738 (put 'org-delete-char 'delete-selection 'supersede)
16739 (put 'org-delete-backward-char 'delete-selection 'supersede)
16740 (put 'org-yank 'delete-selection 'yank)
16742 ;; Make `flyspell-mode' delay after some commands
16743 (put 'org-self-insert-command 'flyspell-delayed t)
16744 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
16745 (put 'org-delete-char 'flyspell-delayed t)
16746 (put 'org-delete-backward-char 'flyspell-delayed t)
16748 ;; Make pabbrev-mode expand after org-mode commands
16749 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
16750 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
16752 ;; How to do this: Measure non-white length of current string
16753 ;; If equal to column width, we should realign.
16755 (defun org-remap (map &rest commands)
16756 "In MAP, remap the functions given in COMMANDS.
16757 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
16758 (let (new old)
16759 (while commands
16760 (setq old (pop commands) new (pop commands))
16761 (if (fboundp 'command-remapping)
16762 (org-defkey map (vector 'remap old) new)
16763 (substitute-key-definition old new map global-map)))))
16765 (when (eq org-enable-table-editor 'optimized)
16766 ;; If the user wants maximum table support, we need to hijack
16767 ;; some standard editing functions
16768 (org-remap org-mode-map
16769 'self-insert-command 'org-self-insert-command
16770 'delete-char 'org-delete-char
16771 'delete-backward-char 'org-delete-backward-char)
16772 (org-defkey org-mode-map "|" 'org-force-self-insert))
16774 (defvar org-ctrl-c-ctrl-c-hook nil
16775 "Hook for functions attaching themselves to `C-c C-c'.
16776 This can be used to add additional functionality to the C-c C-c key which
16777 executes context-dependent commands.
16778 Each function will be called with no arguments. The function must check
16779 if the context is appropriate for it to act. If yes, it should do its
16780 thing and then return a non-nil value. If the context is wrong,
16781 just do nothing and return nil.")
16783 (defvar org-tab-first-hook nil
16784 "Hook for functions to attach themselves to TAB.
16785 See `org-ctrl-c-ctrl-c-hook' for more information.
16786 This hook runs as the first action when TAB is pressed, even before
16787 `org-cycle' messes around with the `outline-regexp' to cater for
16788 inline tasks and plain list item folding.
16789 If any function in this hook returns t, any other actions that
16790 would have been caused by TAB (such as table field motion or visibility
16791 cycling) will not occur.")
16793 (defvar org-tab-after-check-for-table-hook nil
16794 "Hook for functions to attach themselves to TAB.
16795 See `org-ctrl-c-ctrl-c-hook' for more information.
16796 This hook runs after it has been established that the cursor is not in a
16797 table, but before checking if the cursor is in a headline or if global cycling
16798 should be done.
16799 If any function in this hook returns t, not other actions like visibility
16800 cycling will be done.")
16802 (defvar org-tab-after-check-for-cycling-hook nil
16803 "Hook for functions to attach themselves to TAB.
16804 See `org-ctrl-c-ctrl-c-hook' for more information.
16805 This hook runs after it has been established that not table field motion and
16806 not visibility should be done because of current context. This is probably
16807 the place where a package like yasnippets can hook in.")
16809 (defvar org-tab-before-tab-emulation-hook nil
16810 "Hook for functions to attach themselves to TAB.
16811 See `org-ctrl-c-ctrl-c-hook' for more information.
16812 This hook runs after every other options for TAB have been exhausted, but
16813 before indentation and \t insertion takes place.")
16815 (defvar org-metaleft-hook nil
16816 "Hook for functions attaching themselves to `M-left'.
16817 See `org-ctrl-c-ctrl-c-hook' for more information.")
16818 (defvar org-metaright-hook nil
16819 "Hook for functions attaching themselves to `M-right'.
16820 See `org-ctrl-c-ctrl-c-hook' for more information.")
16821 (defvar org-metaup-hook nil
16822 "Hook for functions attaching themselves to `M-up'.
16823 See `org-ctrl-c-ctrl-c-hook' for more information.")
16824 (defvar org-metadown-hook nil
16825 "Hook for functions attaching themselves to `M-down'.
16826 See `org-ctrl-c-ctrl-c-hook' for more information.")
16827 (defvar org-shiftmetaleft-hook nil
16828 "Hook for functions attaching themselves to `M-S-left'.
16829 See `org-ctrl-c-ctrl-c-hook' for more information.")
16830 (defvar org-shiftmetaright-hook nil
16831 "Hook for functions attaching themselves to `M-S-right'.
16832 See `org-ctrl-c-ctrl-c-hook' for more information.")
16833 (defvar org-shiftmetaup-hook nil
16834 "Hook for functions attaching themselves to `M-S-up'.
16835 See `org-ctrl-c-ctrl-c-hook' for more information.")
16836 (defvar org-shiftmetadown-hook nil
16837 "Hook for functions attaching themselves to `M-S-down'.
16838 See `org-ctrl-c-ctrl-c-hook' for more information.")
16839 (defvar org-metareturn-hook nil
16840 "Hook for functions attaching themselves to `M-RET'.
16841 See `org-ctrl-c-ctrl-c-hook' for more information.")
16842 (defvar org-shiftup-hook nil
16843 "Hook for functions attaching themselves to `S-up'.
16844 See `org-ctrl-c-ctrl-c-hook' for more information.")
16845 (defvar org-shiftup-final-hook nil
16846 "Hook for functions attaching themselves to `S-up'.
16847 This one runs after all other options except shift-select have been excluded.
16848 See `org-ctrl-c-ctrl-c-hook' for more information.")
16849 (defvar org-shiftdown-hook nil
16850 "Hook for functions attaching themselves to `S-down'.
16851 See `org-ctrl-c-ctrl-c-hook' for more information.")
16852 (defvar org-shiftdown-final-hook nil
16853 "Hook for functions attaching themselves to `S-down'.
16854 This one runs after all other options except shift-select have been excluded.
16855 See `org-ctrl-c-ctrl-c-hook' for more information.")
16856 (defvar org-shiftleft-hook nil
16857 "Hook for functions attaching themselves to `S-left'.
16858 See `org-ctrl-c-ctrl-c-hook' for more information.")
16859 (defvar org-shiftleft-final-hook nil
16860 "Hook for functions attaching themselves to `S-left'.
16861 This one runs after all other options except shift-select have been excluded.
16862 See `org-ctrl-c-ctrl-c-hook' for more information.")
16863 (defvar org-shiftright-hook nil
16864 "Hook for functions attaching themselves to `S-right'.
16865 See `org-ctrl-c-ctrl-c-hook' for more information.")
16866 (defvar org-shiftright-final-hook nil
16867 "Hook for functions attaching themselves to `S-right'.
16868 This one runs after all other options except shift-select have been excluded.
16869 See `org-ctrl-c-ctrl-c-hook' for more information.")
16871 (defun org-modifier-cursor-error ()
16872 "Throw an error, a modified cursor command was applied in wrong context."
16873 (error "This command is active in special context like tables, headlines or items"))
16875 (defun org-shiftselect-error ()
16876 "Throw an error because Shift-Cursor command was applied in wrong context."
16877 (if (and (boundp 'shift-select-mode) shift-select-mode)
16878 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
16879 (error "This command works only in special context like headlines or timestamps")))
16881 (defun org-call-for-shift-select (cmd)
16882 (let ((this-command-keys-shift-translated t))
16883 (call-interactively cmd)))
16885 (defun org-shifttab (&optional arg)
16886 "Global visibility cycling or move to previous table field.
16887 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
16888 on context.
16889 See the individual commands for more information."
16890 (interactive "P")
16891 (cond
16892 ((org-at-table-p) (call-interactively 'org-table-previous-field))
16893 ((integerp arg)
16894 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
16895 (message "Content view to level: %d" arg)
16896 (org-content (prefix-numeric-value arg2))
16897 (setq org-cycle-global-status 'overview)))
16898 (t (call-interactively 'org-global-cycle))))
16900 (defun org-shiftmetaleft ()
16901 "Promote subtree or delete table column.
16902 Calls `org-promote-subtree', `org-outdent-item',
16903 or `org-table-delete-column', depending on context.
16904 See the individual commands for more information."
16905 (interactive)
16906 (cond
16907 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
16908 ((org-at-table-p) (call-interactively 'org-table-delete-column))
16909 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
16910 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
16911 (t (org-modifier-cursor-error))))
16913 (defun org-shiftmetaright ()
16914 "Demote subtree or insert table column.
16915 Calls `org-demote-subtree', `org-indent-item',
16916 or `org-table-insert-column', depending on context.
16917 See the individual commands for more information."
16918 (interactive)
16919 (cond
16920 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
16921 ((org-at-table-p) (call-interactively 'org-table-insert-column))
16922 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
16923 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
16924 (t (org-modifier-cursor-error))))
16926 (defun org-shiftmetaup (&optional arg)
16927 "Move subtree up or kill table row.
16928 Calls `org-move-subtree-up' or `org-table-kill-row' or
16929 `org-move-item-up' depending on context. See the individual commands
16930 for more information."
16931 (interactive "P")
16932 (cond
16933 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
16934 ((org-at-table-p) (call-interactively 'org-table-kill-row))
16935 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
16936 ((org-at-item-p) (call-interactively 'org-move-item-up))
16937 (t (org-modifier-cursor-error))))
16939 (defun org-shiftmetadown (&optional arg)
16940 "Move subtree down or insert table row.
16941 Calls `org-move-subtree-down' or `org-table-insert-row' or
16942 `org-move-item-down', depending on context. See the individual
16943 commands for more information."
16944 (interactive "P")
16945 (cond
16946 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
16947 ((org-at-table-p) (call-interactively 'org-table-insert-row))
16948 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16949 ((org-at-item-p) (call-interactively 'org-move-item-down))
16950 (t (org-modifier-cursor-error))))
16952 (defsubst org-hidden-tree-error ()
16953 (error
16954 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
16956 (defun org-metaleft (&optional arg)
16957 "Promote heading or move table column to left.
16958 Calls `org-do-promote' or `org-table-move-column', depending on context.
16959 With no specific context, calls the Emacs default `backward-word'.
16960 See the individual commands for more information."
16961 (interactive "P")
16962 (cond
16963 ((run-hook-with-args-until-success 'org-metaleft-hook))
16964 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
16965 ((or (org-on-heading-p)
16966 (and (org-region-active-p)
16967 (save-excursion
16968 (goto-char (region-beginning))
16969 (org-on-heading-p))))
16970 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
16971 (call-interactively 'org-do-promote))
16972 ((or (org-at-item-p)
16973 (and (org-region-active-p)
16974 (save-excursion
16975 (goto-char (region-beginning))
16976 (org-at-item-p))))
16977 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
16978 (call-interactively 'org-outdent-item))
16979 (t (call-interactively 'backward-word))))
16981 (defun org-metaright (&optional arg)
16982 "Demote subtree or move table column to right.
16983 Calls `org-do-demote' or `org-table-move-column', depending on context.
16984 With no specific context, calls the Emacs default `forward-word'.
16985 See the individual commands for more information."
16986 (interactive "P")
16987 (cond
16988 ((run-hook-with-args-until-success 'org-metaright-hook))
16989 ((org-at-table-p) (call-interactively 'org-table-move-column))
16990 ((or (org-on-heading-p)
16991 (and (org-region-active-p)
16992 (save-excursion
16993 (goto-char (region-beginning))
16994 (org-on-heading-p))))
16995 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
16996 (call-interactively 'org-do-demote))
16997 ((or (org-at-item-p)
16998 (and (org-region-active-p)
16999 (save-excursion
17000 (goto-char (region-beginning))
17001 (org-at-item-p))))
17002 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17003 (call-interactively 'org-indent-item))
17004 (t (call-interactively 'forward-word))))
17006 (defun org-check-for-hidden (what)
17007 "Check if there are hidden headlines/items in the current visual line.
17008 WHAT can be either `headlines' or `items'. If the current line is
17009 an outline or item heading and it has a folded subtree below it,
17010 this function returns t, nil otherwise."
17011 (let ((re (cond
17012 ((eq what 'headlines) (concat "^" org-outline-regexp))
17013 ((eq what 'items) (concat "^" (org-item-re t)))
17014 (t (error "This should not happen"))))
17015 beg end)
17016 (save-excursion
17017 (catch 'exit
17018 (unless (org-region-active-p)
17019 (setq beg (point-at-bol))
17020 (beginning-of-line 2)
17021 (while (and (not (eobp)) ;; this is like `next-line'
17022 (get-char-property (1- (point)) 'invisible))
17023 (beginning-of-line 2))
17024 (setq end (point))
17025 (goto-char beg)
17026 (goto-char (point-at-eol))
17027 (setq end (max end (point)))
17028 (while (re-search-forward re end t)
17029 (if (get-char-property (match-beginning 0) 'invisible)
17030 (throw 'exit t))))
17031 nil))))
17033 (defun org-metaup (&optional arg)
17034 "Move subtree up or move table row up.
17035 Calls `org-move-subtree-up' or `org-table-move-row' or
17036 `org-move-item-up', depending on context. See the individual commands
17037 for more information."
17038 (interactive "P")
17039 (cond
17040 ((run-hook-with-args-until-success 'org-metaup-hook))
17041 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
17042 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17043 ((org-at-item-p) (call-interactively 'org-move-item-up))
17044 (t (transpose-lines 1) (beginning-of-line -1))))
17046 (defun org-metadown (&optional arg)
17047 "Move subtree down or move table row down.
17048 Calls `org-move-subtree-down' or `org-table-move-row' or
17049 `org-move-item-down', depending on context. See the individual
17050 commands for more information."
17051 (interactive "P")
17052 (cond
17053 ((run-hook-with-args-until-success 'org-metadown-hook))
17054 ((org-at-table-p) (call-interactively 'org-table-move-row))
17055 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17056 ((org-at-item-p) (call-interactively 'org-move-item-down))
17057 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
17059 (defun org-shiftup (&optional arg)
17060 "Increase item in timestamp or increase priority of current headline.
17061 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
17062 depending on context. See the individual commands for more information."
17063 (interactive "P")
17064 (cond
17065 ((run-hook-with-args-until-success 'org-shiftup-hook))
17066 ((and org-support-shift-select (org-region-active-p))
17067 (org-call-for-shift-select 'previous-line))
17068 ((org-at-timestamp-p t)
17069 (call-interactively (if org-edit-timestamp-down-means-later
17070 'org-timestamp-down 'org-timestamp-up)))
17071 ((and (not (eq org-support-shift-select 'always))
17072 org-enable-priority-commands
17073 (org-on-heading-p))
17074 (call-interactively 'org-priority-up))
17075 ((and (not org-support-shift-select) (org-at-item-p))
17076 (call-interactively 'org-previous-item))
17077 ((org-clocktable-try-shift 'up arg))
17078 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
17079 (org-support-shift-select
17080 (org-call-for-shift-select 'previous-line))
17081 (t (org-shiftselect-error))))
17083 (defun org-shiftdown (&optional arg)
17084 "Decrease item in timestamp or decrease priority of current headline.
17085 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
17086 depending on context. See the individual commands for more information."
17087 (interactive "P")
17088 (cond
17089 ((run-hook-with-args-until-success 'org-shiftdown-hook))
17090 ((and org-support-shift-select (org-region-active-p))
17091 (org-call-for-shift-select 'next-line))
17092 ((org-at-timestamp-p t)
17093 (call-interactively (if org-edit-timestamp-down-means-later
17094 'org-timestamp-up 'org-timestamp-down)))
17095 ((and (not (eq org-support-shift-select 'always))
17096 org-enable-priority-commands
17097 (org-on-heading-p))
17098 (call-interactively 'org-priority-down))
17099 ((and (not org-support-shift-select) (org-at-item-p))
17100 (call-interactively 'org-next-item))
17101 ((org-clocktable-try-shift 'down arg))
17102 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
17103 (org-support-shift-select
17104 (org-call-for-shift-select 'next-line))
17105 (t (org-shiftselect-error))))
17107 (defun org-shiftright (&optional arg)
17108 "Cycle the thing at point or in the current line, depending on context.
17109 Depending on context, this does one of the following:
17111 - switch a timestamp at point one day into the future
17112 - on a headline, switch to the next TODO keyword.
17113 - on an item, switch entire list to the next bullet type
17114 - on a property line, switch to the next allowed value
17115 - on a clocktable definition line, move time block into the future"
17116 (interactive "P")
17117 (cond
17118 ((run-hook-with-args-until-success 'org-shiftright-hook))
17119 ((and org-support-shift-select (org-region-active-p))
17120 (org-call-for-shift-select 'forward-char))
17121 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
17122 ((and (not (eq org-support-shift-select 'always))
17123 (org-on-heading-p))
17124 (let ((org-inhibit-logging
17125 (not org-treat-S-cursor-todo-selection-as-state-change))
17126 (org-inhibit-blocking
17127 (not org-treat-S-cursor-todo-selection-as-state-change)))
17128 (org-call-with-arg 'org-todo 'right)))
17129 ((or (and org-support-shift-select
17130 (not (eq org-support-shift-select 'always))
17131 (org-at-item-bullet-p))
17132 (and (not org-support-shift-select) (org-at-item-p)))
17133 (org-call-with-arg 'org-cycle-list-bullet nil))
17134 ((and (not (eq org-support-shift-select 'always))
17135 (org-at-property-p))
17136 (call-interactively 'org-property-next-allowed-value))
17137 ((org-clocktable-try-shift 'right arg))
17138 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
17139 (org-support-shift-select
17140 (org-call-for-shift-select 'forward-char))
17141 (t (org-shiftselect-error))))
17143 (defun org-shiftleft (&optional arg)
17144 "Cycle the thing at point or in the current line, depending on context.
17145 Depending on context, this does one of the following:
17147 - switch a timestamp at point one day into the past
17148 - on a headline, switch to the previous TODO keyword.
17149 - on an item, switch entire list to the previous bullet type
17150 - on a property line, switch to the previous allowed value
17151 - on a clocktable definition line, move time block into the past"
17152 (interactive "P")
17153 (cond
17154 ((run-hook-with-args-until-success 'org-shiftleft-hook))
17155 ((and org-support-shift-select (org-region-active-p))
17156 (org-call-for-shift-select 'backward-char))
17157 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
17158 ((and (not (eq org-support-shift-select 'always))
17159 (org-on-heading-p))
17160 (let ((org-inhibit-logging
17161 (not org-treat-S-cursor-todo-selection-as-state-change))
17162 (org-inhibit-blocking
17163 (not org-treat-S-cursor-todo-selection-as-state-change)))
17164 (org-call-with-arg 'org-todo 'left)))
17165 ((or (and org-support-shift-select
17166 (not (eq org-support-shift-select 'always))
17167 (org-at-item-bullet-p))
17168 (and (not org-support-shift-select) (org-at-item-p)))
17169 (org-call-with-arg 'org-cycle-list-bullet 'previous))
17170 ((and (not (eq org-support-shift-select 'always))
17171 (org-at-property-p))
17172 (call-interactively 'org-property-previous-allowed-value))
17173 ((org-clocktable-try-shift 'left arg))
17174 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
17175 (org-support-shift-select
17176 (org-call-for-shift-select 'backward-char))
17177 (t (org-shiftselect-error))))
17179 (defun org-shiftcontrolright ()
17180 "Switch to next TODO set."
17181 (interactive)
17182 (cond
17183 ((and org-support-shift-select (org-region-active-p))
17184 (org-call-for-shift-select 'forward-word))
17185 ((and (not (eq org-support-shift-select 'always))
17186 (org-on-heading-p))
17187 (org-call-with-arg 'org-todo 'nextset))
17188 (org-support-shift-select
17189 (org-call-for-shift-select 'forward-word))
17190 (t (org-shiftselect-error))))
17192 (defun org-shiftcontrolleft ()
17193 "Switch to previous TODO set."
17194 (interactive)
17195 (cond
17196 ((and org-support-shift-select (org-region-active-p))
17197 (org-call-for-shift-select 'backward-word))
17198 ((and (not (eq org-support-shift-select 'always))
17199 (org-on-heading-p))
17200 (org-call-with-arg 'org-todo 'previousset))
17201 (org-support-shift-select
17202 (org-call-for-shift-select 'backward-word))
17203 (t (org-shiftselect-error))))
17205 (defun org-ctrl-c-ret ()
17206 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
17207 (interactive)
17208 (cond
17209 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
17210 (t (call-interactively 'org-insert-heading))))
17212 (defun org-copy-special ()
17213 "Copy region in table or copy current subtree.
17214 Calls `org-table-copy' or `org-copy-subtree', depending on context.
17215 See the individual commands for more information."
17216 (interactive)
17217 (call-interactively
17218 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
17220 (defun org-cut-special ()
17221 "Cut region in table or cut current subtree.
17222 Calls `org-table-copy' or `org-cut-subtree', depending on context.
17223 See the individual commands for more information."
17224 (interactive)
17225 (call-interactively
17226 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
17228 (defun org-paste-special (arg)
17229 "Paste rectangular region into table, or past subtree relative to level.
17230 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
17231 See the individual commands for more information."
17232 (interactive "P")
17233 (if (org-at-table-p)
17234 (org-table-paste-rectangle)
17235 (org-paste-subtree arg)))
17237 (defun org-edit-special (&optional arg)
17238 "Call a special editor for the stuff at point.
17239 When at a table, call the formula editor with `org-table-edit-formulas'.
17240 When at the first line of an src example, call `org-edit-src-code'.
17241 When in an #+include line, visit the include file. Otherwise call
17242 `ffap' to visit the file at point."
17243 (interactive)
17244 ;; possibly prep session before editing source
17245 (when arg
17246 (let* ((info (org-babel-get-src-block-info))
17247 (lang (nth 0 info))
17248 (params (nth 2 info))
17249 (session (cdr (assoc :session params))))
17250 (when (and info session) ;; we are in a source-code block with a session
17251 (funcall
17252 (intern (concat "org-babel-prep-session:" lang)) session params))))
17253 (cond ;; proceed with `org-edit-special'
17254 ((save-excursion
17255 (beginning-of-line 1)
17256 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
17257 (find-file (org-trim (match-string 1))))
17258 ((org-edit-src-code))
17259 ((org-edit-fixed-width-region))
17260 ((org-at-table.el-p)
17261 (org-edit-src-code))
17262 ((or (org-at-table-p)
17263 (save-excursion
17264 (beginning-of-line 1)
17265 (looking-at "[ \t]*#\\+TBLFM:")))
17266 (call-interactively 'org-table-edit-formulas))
17267 (t (call-interactively 'ffap))))
17270 (defun org-ctrl-c-ctrl-c (&optional arg)
17271 "Set tags in headline, or update according to changed information at point.
17273 This command does many different things, depending on context:
17275 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
17276 this is what we do.
17278 - If the cursor is on a statistics cookie, update it.
17280 - If the cursor is in a headline, prompt for tags and insert them
17281 into the current line, aligned to `org-tags-column'. When called
17282 with prefix arg, realign all tags in the current buffer.
17284 - If the cursor is in one of the special #+KEYWORD lines, this
17285 triggers scanning the buffer for these lines and updating the
17286 information.
17288 - If the cursor is inside a table, realign the table. This command
17289 works even if the automatic table editor has been turned off.
17291 - If the cursor is on a #+TBLFM line, re-apply the formulas to
17292 the entire table.
17294 - If the cursor is at a footnote reference or definition, jump to
17295 the corresponding definition or references, respectively.
17297 - If the cursor is a the beginning of a dynamic block, update it.
17299 - If the current buffer is a capture buffer, close note and file it.
17301 - If the cursor is on a <<<target>>>, update radio targets and
17302 corresponding links in this buffer.
17304 - If the cursor is on a numbered item in a plain list, renumber the
17305 ordered list.
17307 - If the cursor is on a checkbox, toggle it.
17309 - If the cursor is on a code block, evaluate it. The variable
17310 `org-confirm-babel-evaluate' can be used to control prompting
17311 before code block evaluation, by default every code block
17312 evaluation requires confirmation. Code block evaluation can be
17313 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
17314 (interactive "P")
17315 (let ((org-enable-table-editor t))
17316 (cond
17317 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
17318 org-occur-highlights
17319 org-latex-fragment-image-overlays)
17320 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
17321 (org-remove-occur-highlights)
17322 (org-remove-latex-fragment-image-overlays)
17323 (message "Temporary highlights/overlays removed from current buffer"))
17324 ((and (local-variable-p 'org-finish-function (current-buffer))
17325 (fboundp org-finish-function))
17326 (funcall org-finish-function))
17327 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
17328 ((or (looking-at org-property-start-re)
17329 (org-at-property-p))
17330 (call-interactively 'org-property-action))
17331 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
17332 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
17333 (or (org-on-heading-p) (org-at-item-p)))
17334 (call-interactively 'org-update-statistics-cookies))
17335 ((org-on-heading-p) (call-interactively 'org-set-tags))
17336 ((org-at-table.el-p)
17337 (message "Use C-c ' to edit table.el tables"))
17338 ((org-at-table-p)
17339 (org-table-maybe-eval-formula)
17340 (if arg
17341 (call-interactively 'org-table-recalculate)
17342 (org-table-maybe-recalculate-line))
17343 (call-interactively 'org-table-align)
17344 (orgtbl-send-table 'maybe))
17345 ((or (org-footnote-at-reference-p)
17346 (org-footnote-at-definition-p))
17347 (call-interactively 'org-footnote-action))
17348 ((org-at-item-checkbox-p)
17349 (call-interactively 'org-list-repair)
17350 (call-interactively 'org-toggle-checkbox)
17351 (org-list-send-list 'maybe))
17352 ((org-at-item-p)
17353 (call-interactively 'org-list-repair)
17354 (when arg (call-interactively 'org-toggle-checkbox))
17355 (org-list-send-list 'maybe))
17356 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
17357 ;; Dynamic block
17358 (beginning-of-line 1)
17359 (save-excursion (org-update-dblock)))
17360 ((save-excursion
17361 (beginning-of-line 1)
17362 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
17363 (cond
17364 ((equal (match-string 1) "TBLFM")
17365 ;; Recalculate the table before this line
17366 (save-excursion
17367 (beginning-of-line 1)
17368 (skip-chars-backward " \r\n\t")
17369 (if (org-at-table-p)
17370 (org-call-with-arg 'org-table-recalculate (or arg t)))))
17372 (let ((org-inhibit-startup-visibility-stuff t)
17373 (org-startup-align-all-tables nil))
17374 (org-save-outline-visibility 'use-markers (org-mode-restart)))
17375 (message "Local setup has been refreshed"))))
17376 ((org-clock-update-time-maybe))
17377 (t (error "C-c C-c can do nothing useful at this location")))))
17379 (defun org-mode-restart ()
17380 "Restart Org-mode, to scan again for special lines.
17381 Also updates the keyword regular expressions."
17382 (interactive)
17383 (org-mode)
17384 (message "Org-mode restarted"))
17386 (defun org-kill-note-or-show-branches ()
17387 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
17388 (interactive)
17389 (if (not org-finish-function)
17390 (progn
17391 (hide-subtree)
17392 (call-interactively 'show-branches))
17393 (let ((org-note-abort t))
17394 (funcall org-finish-function))))
17396 (defun org-return (&optional indent)
17397 "Goto next table row or insert a newline.
17398 Calls `org-table-next-row' or `newline', depending on context.
17399 See the individual commands for more information."
17400 (interactive)
17401 (cond
17402 ((bobp) (if indent (newline-and-indent) (newline)))
17403 ((org-at-table-p)
17404 (org-table-justify-field-maybe)
17405 (call-interactively 'org-table-next-row))
17406 ((and org-return-follows-link
17407 (eq (get-text-property (point) 'face) 'org-link))
17408 (call-interactively 'org-open-at-point))
17409 ((and (org-at-heading-p)
17410 (looking-at
17411 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
17412 (org-show-entry)
17413 (end-of-line 1)
17414 (newline))
17415 (t (if indent (newline-and-indent) (newline)))))
17417 (defun org-return-indent ()
17418 "Goto next table row or insert a newline and indent.
17419 Calls `org-table-next-row' or `newline-and-indent', depending on
17420 context. See the individual commands for more information."
17421 (interactive)
17422 (org-return t))
17424 (defun org-ctrl-c-star ()
17425 "Compute table, or change heading status of lines.
17426 Calls `org-table-recalculate' or `org-toggle-heading',
17427 depending on context."
17428 (interactive)
17429 (cond
17430 ((org-at-table-p)
17431 (call-interactively 'org-table-recalculate))
17433 ;; Convert all lines in region to list items
17434 (call-interactively 'org-toggle-heading))))
17436 (defun org-ctrl-c-minus ()
17437 "Insert separator line in table or modify bullet status of line.
17438 Also turns a plain line or a region of lines into list items.
17439 Calls `org-table-insert-hline', `org-toggle-item', or
17440 `org-cycle-list-bullet', depending on context."
17441 (interactive)
17442 (cond
17443 ((org-at-table-p)
17444 (call-interactively 'org-table-insert-hline))
17445 ((org-region-active-p)
17446 (call-interactively 'org-toggle-item))
17447 ((org-in-item-p)
17448 (call-interactively 'org-cycle-list-bullet))
17450 (call-interactively 'org-toggle-item))))
17452 (defun org-toggle-item ()
17453 "Convert headings or normal lines to items, items to normal lines.
17454 If there is no active region, only the current line is considered.
17456 If the first line in the region is a headline, convert all headlines to items.
17458 If the first line in the region is an item, convert all items to normal lines.
17460 If the first line is normal text, add an item bullet to each line."
17461 (interactive)
17462 (let (l2 l beg end)
17463 (if (org-region-active-p)
17464 (setq beg (region-beginning) end (region-end))
17465 (setq beg (point-at-bol)
17466 end (min (1+ (point-at-eol)) (point-max))))
17467 (save-excursion
17468 (goto-char end)
17469 (setq l2 (org-current-line))
17470 (goto-char beg)
17471 (beginning-of-line 1)
17472 (setq l (1- (org-current-line)))
17473 (if (org-at-item-p)
17474 ;; We already have items, de-itemize
17475 (while (< (setq l (1+ l)) l2)
17476 (when (org-at-item-p)
17477 (skip-chars-forward " \t")
17478 (delete-region (point) (match-end 0)))
17479 (beginning-of-line 2))
17480 (if (org-on-heading-p)
17481 ;; Headings, convert to items
17482 (while (< (setq l (1+ l)) l2)
17483 (if (looking-at org-outline-regexp)
17484 (replace-match (org-list-bullet-string "-") t t))
17485 (beginning-of-line 2))
17486 ;; normal lines, turn them into items
17487 (while (< (setq l (1+ l)) l2)
17488 (unless (org-at-item-p)
17489 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
17490 (replace-match
17491 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
17492 (beginning-of-line 2)))))))
17494 (defun org-toggle-heading (&optional nstars)
17495 "Convert headings to normal text, or items or text to headings.
17496 If there is no active region, only the current line is considered.
17498 If the first line is a heading, remove the stars from all headlines
17499 in the region.
17501 If the first line is a plain list item, turn all plain list items
17502 into headings.
17504 If the first line is a normal line, turn each and every line in the
17505 region into a heading.
17507 When converting a line into a heading, the number of stars is chosen
17508 such that the lines become children of the current entry. However,
17509 when a prefix argument is given, its value determines the number of
17510 stars to add."
17511 (interactive "P")
17512 (let (l2 l itemp beg end)
17513 (if (org-region-active-p)
17514 (setq beg (region-beginning) end (region-end))
17515 (setq beg (point-at-bol)
17516 end (min (1+ (point-at-eol)) (point-max))))
17517 (save-excursion
17518 (goto-char end)
17519 (setq l2 (org-current-line))
17520 (goto-char beg)
17521 (beginning-of-line 1)
17522 (setq l (1- (org-current-line)))
17523 (if (org-on-heading-p)
17524 ;; We already have headlines, de-star them
17525 (while (< (setq l (1+ l)) l2)
17526 (when (org-on-heading-p t)
17527 (and (looking-at outline-regexp) (replace-match "")))
17528 (beginning-of-line 2))
17529 (setq itemp (org-at-item-p))
17530 (let* ((stars
17531 (if nstars
17532 (make-string (prefix-numeric-value current-prefix-arg)
17534 (save-excursion
17535 (if (re-search-backward org-complex-heading-regexp nil t)
17536 (match-string 1) ""))))
17537 (add-stars (cond (nstars "")
17538 ((equal stars "") "*")
17539 (org-odd-levels-only "**")
17540 (t "*")))
17541 (rpl (concat stars add-stars " ")))
17542 (while (< (setq l (1+ l)) l2)
17543 (if itemp
17544 (and (org-at-item-p) (replace-match rpl t t))
17545 (unless (org-on-heading-p)
17546 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
17547 (replace-match (concat rpl (match-string 2))))))
17548 (beginning-of-line 2)))))))
17550 (defun org-meta-return (&optional arg)
17551 "Insert a new heading or wrap a region in a table.
17552 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
17553 See the individual commands for more information."
17554 (interactive "P")
17555 (cond
17556 ((run-hook-with-args-until-success 'org-metareturn-hook))
17557 ((org-at-table-p)
17558 (call-interactively 'org-table-wrap-region))
17559 (t (call-interactively 'org-insert-heading))))
17561 ;;; Menu entries
17563 ;; Define the Org-mode menus
17564 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
17565 '("Tbl"
17566 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
17567 ["Next Field" org-cycle (org-at-table-p)]
17568 ["Previous Field" org-shifttab (org-at-table-p)]
17569 ["Next Row" org-return (org-at-table-p)]
17570 "--"
17571 ["Blank Field" org-table-blank-field (org-at-table-p)]
17572 ["Edit Field" org-table-edit-field (org-at-table-p)]
17573 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
17574 "--"
17575 ("Column"
17576 ["Move Column Left" org-metaleft (org-at-table-p)]
17577 ["Move Column Right" org-metaright (org-at-table-p)]
17578 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
17579 ["Insert Column" org-shiftmetaright (org-at-table-p)])
17580 ("Row"
17581 ["Move Row Up" org-metaup (org-at-table-p)]
17582 ["Move Row Down" org-metadown (org-at-table-p)]
17583 ["Delete Row" org-shiftmetaup (org-at-table-p)]
17584 ["Insert Row" org-shiftmetadown (org-at-table-p)]
17585 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
17586 "--"
17587 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
17588 ("Rectangle"
17589 ["Copy Rectangle" org-copy-special (org-at-table-p)]
17590 ["Cut Rectangle" org-cut-special (org-at-table-p)]
17591 ["Paste Rectangle" org-paste-special (org-at-table-p)]
17592 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
17593 "--"
17594 ("Calculate"
17595 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
17596 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
17597 ["Edit Formulas" org-edit-special (org-at-table-p)]
17598 "--"
17599 ["Recalculate line" org-table-recalculate (org-at-table-p)]
17600 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
17601 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
17602 "--"
17603 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
17604 "--"
17605 ["Sum Column/Rectangle" org-table-sum
17606 (or (org-at-table-p) (org-region-active-p))]
17607 ["Which Column?" org-table-current-column (org-at-table-p)])
17608 ["Debug Formulas"
17609 org-table-toggle-formula-debugger
17610 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
17611 ["Show Col/Row Numbers"
17612 org-table-toggle-coordinate-overlays
17613 :style toggle
17614 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
17615 "--"
17616 ["Create" org-table-create (and (not (org-at-table-p))
17617 org-enable-table-editor)]
17618 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
17619 ["Import from File" org-table-import (not (org-at-table-p))]
17620 ["Export to File" org-table-export (org-at-table-p)]
17621 "--"
17622 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
17624 (easy-menu-define org-org-menu org-mode-map "Org menu"
17625 '("Org"
17626 ("Show/Hide"
17627 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
17628 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
17629 ["Sparse Tree..." org-sparse-tree t]
17630 ["Reveal Context" org-reveal t]
17631 ["Show All" show-all t]
17632 "--"
17633 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
17634 "--"
17635 ["New Heading" org-insert-heading t]
17636 ("Navigate Headings"
17637 ["Up" outline-up-heading t]
17638 ["Next" outline-next-visible-heading t]
17639 ["Previous" outline-previous-visible-heading t]
17640 ["Next Same Level" outline-forward-same-level t]
17641 ["Previous Same Level" outline-backward-same-level t]
17642 "--"
17643 ["Jump" org-goto t])
17644 ("Edit Structure"
17645 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
17646 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
17647 "--"
17648 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
17649 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
17650 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
17651 "--"
17652 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
17653 "--"
17654 ["Promote Heading" org-metaleft (not (org-at-table-p))]
17655 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
17656 ["Demote Heading" org-metaright (not (org-at-table-p))]
17657 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
17658 "--"
17659 ["Sort Region/Children" org-sort (not (org-at-table-p))]
17660 "--"
17661 ["Convert to odd levels" org-convert-to-odd-levels t]
17662 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
17663 ("Editing"
17664 ["Emphasis..." org-emphasize t]
17665 ["Edit Source Example" org-edit-special t]
17666 "--"
17667 ["Footnote new/jump" org-footnote-action t]
17668 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
17669 ("Archive"
17670 ["Archive (default method)" org-archive-subtree-default t]
17671 "--"
17672 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
17673 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
17674 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
17676 "--"
17677 ("Hyperlinks"
17678 ["Store Link (Global)" org-store-link t]
17679 ["Find existing link to here" org-occur-link-in-agenda-files t]
17680 ["Insert Link" org-insert-link t]
17681 ["Follow Link" org-open-at-point t]
17682 "--"
17683 ["Next link" org-next-link t]
17684 ["Previous link" org-previous-link t]
17685 "--"
17686 ["Descriptive Links"
17687 (progn (add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
17688 :style radio
17689 :selected (member '(org-link) buffer-invisibility-spec)]
17690 ["Literal Links"
17691 (progn
17692 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
17693 :style radio
17694 :selected (not (member '(org-link) buffer-invisibility-spec))])
17695 "--"
17696 ("TODO Lists"
17697 ["TODO/DONE/-" org-todo t]
17698 ("Select keyword"
17699 ["Next keyword" org-shiftright (org-on-heading-p)]
17700 ["Previous keyword" org-shiftleft (org-on-heading-p)]
17701 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
17702 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
17703 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
17704 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
17705 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
17706 "--"
17707 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
17708 :selected org-enforce-todo-dependencies :style toggle :active t]
17709 "Settings for tree at point"
17710 ["Do Children sequentially" org-toggle-ordered-property :style radio
17711 :selected (ignore-errors (org-entry-get nil "ORDERED"))
17712 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
17713 ["Do Children parallel" org-toggle-ordered-property :style radio
17714 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
17715 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
17716 "--"
17717 ["Set Priority" org-priority t]
17718 ["Priority Up" org-shiftup t]
17719 ["Priority Down" org-shiftdown t]
17720 "--"
17721 ["Get news from all feeds" org-feed-update-all t]
17722 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
17723 ["Customize feeds" (customize-variable 'org-feed-alist) t])
17724 ("TAGS and Properties"
17725 ["Set Tags" org-set-tags-command t]
17726 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
17727 "--"
17728 ["Set property" org-set-property t]
17729 ["Column view of properties" org-columns t]
17730 ["Insert Column View DBlock" org-insert-columns-dblock t])
17731 ("Dates and Scheduling"
17732 ["Timestamp" org-time-stamp t]
17733 ["Timestamp (inactive)" org-time-stamp-inactive t]
17734 ("Change Date"
17735 ["1 Day Later" org-shiftright t]
17736 ["1 Day Earlier" org-shiftleft t]
17737 ["1 ... Later" org-shiftup t]
17738 ["1 ... Earlier" org-shiftdown t])
17739 ["Compute Time Range" org-evaluate-time-range t]
17740 ["Schedule Item" org-schedule t]
17741 ["Deadline" org-deadline t]
17742 "--"
17743 ["Custom time format" org-toggle-time-stamp-overlays
17744 :style radio :selected org-display-custom-times]
17745 "--"
17746 ["Goto Calendar" org-goto-calendar t]
17747 ["Date from Calendar" org-date-from-calendar t]
17748 "--"
17749 ["Start/Restart Timer" org-timer-start t]
17750 ["Pause/Continue Timer" org-timer-pause-or-continue t]
17751 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
17752 ["Insert Timer String" org-timer t]
17753 ["Insert Timer Item" org-timer-item t])
17754 ("Logging work"
17755 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
17756 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
17757 ["Clock out" org-clock-out t]
17758 ["Clock cancel" org-clock-cancel t]
17759 "--"
17760 ["Mark as default task" org-clock-mark-default-task t]
17761 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
17762 ["Goto running clock" org-clock-goto t]
17763 "--"
17764 ["Display times" org-clock-display t]
17765 ["Create clock table" org-clock-report t]
17766 "--"
17767 ["Record DONE time"
17768 (progn (setq org-log-done (not org-log-done))
17769 (message "Switching to %s will %s record a timestamp"
17770 (car org-done-keywords)
17771 (if org-log-done "automatically" "not")))
17772 :style toggle :selected org-log-done])
17773 "--"
17774 ["Agenda Command..." org-agenda t]
17775 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
17776 ("File List for Agenda")
17777 ("Special views current file"
17778 ["TODO Tree" org-show-todo-tree t]
17779 ["Check Deadlines" org-check-deadlines t]
17780 ["Timeline" org-timeline t]
17781 ["Tags/Property tree" org-match-sparse-tree t])
17782 "--"
17783 ["Export/Publish..." org-export t]
17784 ("LaTeX"
17785 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
17786 :selected org-cdlatex-mode]
17787 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
17788 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
17789 ["Modify math symbol" org-cdlatex-math-modify
17790 (org-inside-LaTeX-fragment-p)]
17791 ["Insert citation" org-reftex-citation t]
17792 "--"
17793 ["Template for BEAMER" org-insert-beamer-options-template t])
17794 "--"
17795 ("MobileOrg"
17796 ["Push Files and Views" org-mobile-push t]
17797 ["Get Captured and Flagged" org-mobile-pull t]
17798 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
17799 "--"
17800 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
17801 "--"
17802 ("Documentation"
17803 ["Show Version" org-version t]
17804 ["Info Documentation" org-info t])
17805 ("Customize"
17806 ["Browse Org Group" org-customize t]
17807 "--"
17808 ["Expand This Menu" org-create-customize-menu
17809 (fboundp 'customize-menu-create)])
17810 ["Send bug report" org-submit-bug-report t]
17811 "--"
17812 ("Refresh/Reload"
17813 ["Refresh setup current buffer" org-mode-restart t]
17814 ["Reload Org (after update)" org-reload t]
17815 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
17818 (defun org-info (&optional node)
17819 "Read documentation for Org-mode in the info system.
17820 With optional NODE, go directly to that node."
17821 (interactive)
17822 (info (format "(org)%s" (or node ""))))
17824 ;;;###autoload
17825 (defun org-submit-bug-report ()
17826 "Submit a bug report on Org-mode via mail.
17828 Don't hesitate to report any problems or inaccurate documentation.
17830 If you don't have setup sending mail from (X)Emacs, please copy the
17831 output buffer into your mail program, as it gives us important
17832 information about your Org-mode version and configuration."
17833 (interactive)
17834 (require 'reporter)
17835 (org-load-modules-maybe)
17836 (org-require-autoloaded-modules)
17837 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
17838 (reporter-submit-bug-report
17839 "emacs-orgmode@gnu.org"
17840 (org-version)
17841 (let (list)
17842 (save-window-excursion
17843 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
17844 (delete-other-windows)
17845 (erase-buffer)
17846 (insert "You are about to submit a bug report to the Org-mode mailing list.
17848 We would like to add your full Org-mode and Outline configuration to the
17849 bug report. This greatly simplifies the work of the maintainer and
17850 other experts on the mailing list.
17852 HOWEVER, some variables you have customized may contain private
17853 information. The names of customers, colleagues, or friends, might
17854 appear in the form of file names, tags, todo states, or search strings.
17855 If you answer yes to the prompt, you might want to check and remove
17856 such private information before sending the email.")
17857 (add-text-properties (point-min) (point-max) '(face org-warning))
17858 (when (yes-or-no-p "Include your Org-mode configuration ")
17859 (mapatoms
17860 (lambda (v)
17861 (and (boundp v)
17862 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
17863 (or (and (symbol-value v)
17864 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
17865 (and
17866 (get v 'custom-type) (get v 'standard-value)
17867 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
17868 (push v list)))))
17869 (kill-buffer (get-buffer "*Warn about privacy*"))
17870 list))
17871 nil nil
17872 "Remember to cover the basics, that is, what you expected to happen and
17873 what in fact did happen. You don't know how to make a good report? See
17875 http://orgmode.org/manual/Feedback.html#Feedback
17877 Your bug report will be posted to the Org-mode mailing list.
17878 ------------------------------------------------------------------------")
17879 (save-excursion
17880 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
17881 (replace-match "\\1Bug: \\3 [\\2]")))))
17884 (defun org-install-agenda-files-menu ()
17885 (let ((bl (buffer-list)))
17886 (save-excursion
17887 (while bl
17888 (set-buffer (pop bl))
17889 (if (org-mode-p) (setq bl nil)))
17890 (when (org-mode-p)
17891 (easy-menu-change
17892 '("Org") "File List for Agenda"
17893 (append
17894 (list
17895 ["Edit File List" (org-edit-agenda-file-list) t]
17896 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
17897 ["Remove Current File from List" org-remove-file t]
17898 ["Cycle through agenda files" org-cycle-agenda-files t]
17899 ["Occur in all agenda files" org-occur-in-agenda-files t]
17900 "--")
17901 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
17903 ;;;; Documentation
17905 ;;;###autoload
17906 (defun org-require-autoloaded-modules ()
17907 (interactive)
17908 (mapc 'require
17909 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
17910 org-docbook org-exp org-html org-icalendar
17911 org-id org-latex
17912 org-publish org-remember org-table
17913 org-timer org-xoxo)))
17915 ;;;###autoload
17916 (defun org-reload (&optional uncompiled)
17917 "Reload all org lisp files.
17918 With prefix arg UNCOMPILED, load the uncompiled versions."
17919 (interactive "P")
17920 (require 'find-func)
17921 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
17922 (dir-org (file-name-directory (org-find-library-name "org")))
17923 (dir-org-contrib (ignore-errors
17924 (file-name-directory
17925 (org-find-library-name "org-contribdir"))))
17926 (babel-files
17927 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
17928 (append (list nil "comint" "eval" "exp" "keys"
17929 "lob" "ref" "table" "tangle")
17930 (delq nil
17931 (mapcar
17932 (lambda (lang)
17933 (when (cdr lang) (symbol-name (car lang))))
17934 org-babel-load-languages)))))
17935 (files
17936 (append (directory-files dir-org t file-re)
17937 babel-files
17938 (and dir-org-contrib
17939 (directory-files dir-org-contrib t file-re))))
17940 (remove-re (concat (if (featurep 'xemacs)
17941 "org-colview" "org-colview-xemacs")
17942 "\\'")))
17943 (setq files (mapcar 'file-name-sans-extension files))
17944 (setq files (mapcar
17945 (lambda (x) (if (string-match remove-re x) nil x))
17946 files))
17947 (setq files (delq nil files))
17948 (mapc
17949 (lambda (f)
17950 (when (featurep (intern (file-name-nondirectory f)))
17951 (if (and (not uncompiled)
17952 (file-exists-p (concat f ".elc")))
17953 (load (concat f ".elc") nil nil t)
17954 (load (concat f ".el") nil nil t))))
17955 files))
17956 (org-version))
17958 ;;;###autoload
17959 (defun org-customize ()
17960 "Call the customize function with org as argument."
17961 (interactive)
17962 (org-load-modules-maybe)
17963 (org-require-autoloaded-modules)
17964 (customize-browse 'org))
17966 (defun org-create-customize-menu ()
17967 "Create a full customization menu for Org-mode, insert it into the menu."
17968 (interactive)
17969 (org-load-modules-maybe)
17970 (org-require-autoloaded-modules)
17971 (if (fboundp 'customize-menu-create)
17972 (progn
17973 (easy-menu-change
17974 '("Org") "Customize"
17975 `(["Browse Org group" org-customize t]
17976 "--"
17977 ,(customize-menu-create 'org)
17978 ["Set" Custom-set t]
17979 ["Save" Custom-save t]
17980 ["Reset to Current" Custom-reset-current t]
17981 ["Reset to Saved" Custom-reset-saved t]
17982 ["Reset to Standard Settings" Custom-reset-standard t]))
17983 (message "\"Org\"-menu now contains full customization menu"))
17984 (error "Cannot expand menu (outdated version of cus-edit.el)")))
17986 ;;;; Miscellaneous stuff
17988 ;;; Generally useful functions
17990 (defun org-get-at-bol (property)
17991 "Get text property PROPERTY at beginning of line."
17992 (get-text-property (point-at-bol) property))
17994 (defun org-find-text-property-in-string (prop s)
17995 "Return the first non-nil value of property PROP in string S."
17996 (or (get-text-property 0 prop s)
17997 (get-text-property (or (next-single-property-change 0 prop s) 0)
17998 prop s)))
18000 (defun org-display-warning (message) ;; Copied from Emacs-Muse
18001 "Display the given MESSAGE as a warning."
18002 (if (fboundp 'display-warning)
18003 (display-warning 'org message
18004 (if (featurep 'xemacs) 'warning :warning))
18005 (let ((buf (get-buffer-create "*Org warnings*")))
18006 (with-current-buffer buf
18007 (goto-char (point-max))
18008 (insert "Warning (Org): " message)
18009 (unless (bolp)
18010 (newline)))
18011 (display-buffer buf)
18012 (sit-for 0))))
18014 (defun org-in-commented-line ()
18015 "Is point in a line starting with `#'?"
18016 (equal (char-after (point-at-bol)) ?#))
18018 (defun org-in-indented-comment-line ()
18019 "Is point in a line starting with `#' after some white space?"
18020 (save-excursion
18021 (save-match-data
18022 (goto-char (point-at-bol))
18023 (looking-at "[ \t]*#"))))
18025 (defun org-in-verbatim-emphasis ()
18026 (save-match-data
18027 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
18029 (defun org-goto-marker-or-bmk (marker &optional bookmark)
18030 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
18031 (if (and marker (marker-buffer marker)
18032 (buffer-live-p (marker-buffer marker)))
18033 (progn
18034 (switch-to-buffer (marker-buffer marker))
18035 (if (or (> marker (point-max)) (< marker (point-min)))
18036 (widen))
18037 (goto-char marker)
18038 (org-show-context 'org-goto))
18039 (if bookmark
18040 (bookmark-jump bookmark)
18041 (error "Cannot find location"))))
18043 (defun org-quote-csv-field (s)
18044 "Quote field for inclusion in CSV material."
18045 (if (string-match "[\",]" s)
18046 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
18049 (defun org-plist-delete (plist property)
18050 "Delete PROPERTY from PLIST.
18051 This is in contrast to merely setting it to 0."
18052 (let (p)
18053 (while plist
18054 (if (not (eq property (car plist)))
18055 (setq p (plist-put p (car plist) (nth 1 plist))))
18056 (setq plist (cddr plist)))
18059 (defun org-force-self-insert (N)
18060 "Needed to enforce self-insert under remapping."
18061 (interactive "p")
18062 (self-insert-command N))
18064 (defun org-string-width (s)
18065 "Compute width of string, ignoring invisible characters.
18066 This ignores character with invisibility property `org-link', and also
18067 characters with property `org-cwidth', because these will become invisible
18068 upon the next fontification round."
18069 (let (b l)
18070 (when (or (eq t buffer-invisibility-spec)
18071 (assq 'org-link buffer-invisibility-spec))
18072 (while (setq b (text-property-any 0 (length s)
18073 'invisible 'org-link s))
18074 (setq s (concat (substring s 0 b)
18075 (substring s (or (next-single-property-change
18076 b 'invisible s) (length s)))))))
18077 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
18078 (setq s (concat (substring s 0 b)
18079 (substring s (or (next-single-property-change
18080 b 'org-cwidth s) (length s))))))
18081 (setq l (string-width s) b -1)
18082 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
18083 (setq l (- l (get-text-property b 'org-dwidth-n s))))
18086 (defun org-shorten-string (s maxlength)
18087 "Shorten string S so tht it is no longer than MAXLENGTH characters.
18088 If the string is shorter or has length MAXLENGTH, just return the
18089 original string. If it is longer, the functions finds a space in the
18090 string, breaks this string off at that locations and adds three dots
18091 as ellipsis. Including the ellipsis, the string will not be longer
18092 than MAXLENGTH. If finding a good breaking point in the string does
18093 not work, the string is just chopped off in the middle of a word
18094 if necessary."
18095 (if (<= (length s) maxlength)
18097 (let* ((n (max (- maxlength 4) 1))
18098 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
18099 (if (string-match re s)
18100 (concat (match-string 1 s) "...")
18101 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
18103 (defun org-get-indentation (&optional line)
18104 "Get the indentation of the current line, interpreting tabs.
18105 When LINE is given, assume it represents a line and compute its indentation."
18106 (if line
18107 (if (string-match "^ *" (org-remove-tabs line))
18108 (match-end 0))
18109 (save-excursion
18110 (beginning-of-line 1)
18111 (skip-chars-forward " \t")
18112 (current-column))))
18114 (defun org-remove-tabs (s &optional width)
18115 "Replace tabulators in S with spaces.
18116 Assumes that s is a single line, starting in column 0."
18117 (setq width (or width tab-width))
18118 (while (string-match "\t" s)
18119 (setq s (replace-match
18120 (make-string
18121 (- (* width (/ (+ (match-beginning 0) width) width))
18122 (match-beginning 0)) ?\ )
18123 t t s)))
18126 (defun org-fix-indentation (line ind)
18127 "Fix indentation in LINE.
18128 IND is a cons cell with target and minimum indentation.
18129 If the current indentation in LINE is smaller than the minimum,
18130 leave it alone. If it is larger than ind, set it to the target."
18131 (let* ((l (org-remove-tabs line))
18132 (i (org-get-indentation l))
18133 (i1 (car ind)) (i2 (cdr ind)))
18134 (if (>= i i2) (setq l (substring line i2)))
18135 (if (> i1 0)
18136 (concat (make-string i1 ?\ ) l)
18137 l)))
18139 (defun org-remove-indentation (code &optional n)
18140 "Remove the maximum common indentation from the lines in CODE.
18141 N may optionally be the number of spaces to remove."
18142 (with-temp-buffer
18143 (insert code)
18144 (org-do-remove-indentation n)
18145 (buffer-string)))
18147 (defun org-do-remove-indentation (&optional n)
18148 "Remove the maximum common indentation from the buffer."
18149 (untabify (point-min) (point-max))
18150 (let ((min 10000) re)
18151 (if n
18152 (setq min n)
18153 (goto-char (point-min))
18154 (while (re-search-forward "^ *[^ \n]" nil t)
18155 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
18156 (unless (or (= min 0) (= min 10000))
18157 (setq re (format "^ \\{%d\\}" min))
18158 (goto-char (point-min))
18159 (while (re-search-forward re nil t)
18160 (replace-match "")
18161 (end-of-line 1))
18162 min)))
18164 (defun org-fill-template (template alist)
18165 "Find each %key of ALIST in TEMPLATE and replace it."
18166 (let ((case-fold-search nil)
18167 entry key value)
18168 (setq alist (sort (copy-sequence alist)
18169 (lambda (a b) (< (length (car a)) (length (car b))))))
18170 (while (setq entry (pop alist))
18171 (setq template
18172 (replace-regexp-in-string
18173 (concat "%" (regexp-quote (car entry)))
18174 (cdr entry) template t t)))
18175 template))
18177 (defun org-base-buffer (buffer)
18178 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
18179 (if (not buffer)
18180 buffer
18181 (or (buffer-base-buffer buffer)
18182 buffer)))
18184 (defun org-trim (s)
18185 "Remove whitespace at beginning and end of string."
18186 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
18187 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
18190 (defun org-wrap (string &optional width lines)
18191 "Wrap string to either a number of lines, or a width in characters.
18192 If WIDTH is non-nil, the string is wrapped to that width, however many lines
18193 that costs. If there is a word longer than WIDTH, the text is actually
18194 wrapped to the length of that word.
18195 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
18196 many lines, whatever width that takes.
18197 The return value is a list of lines, without newlines at the end."
18198 (let* ((words (org-split-string string "[ \t\n]+"))
18199 (maxword (apply 'max (mapcar 'org-string-width words)))
18200 w ll)
18201 (cond (width
18202 (org-do-wrap words (max maxword width)))
18203 (lines
18204 (setq w maxword)
18205 (setq ll (org-do-wrap words maxword))
18206 (if (<= (length ll) lines)
18208 (setq ll words)
18209 (while (> (length ll) lines)
18210 (setq w (1+ w))
18211 (setq ll (org-do-wrap words w)))
18212 ll))
18213 (t (error "Cannot wrap this")))))
18215 (defun org-do-wrap (words width)
18216 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
18217 (let (lines line)
18218 (while words
18219 (setq line (pop words))
18220 (while (and words (< (+ (length line) (length (car words))) width))
18221 (setq line (concat line " " (pop words))))
18222 (setq lines (push line lines)))
18223 (nreverse lines)))
18225 (defun org-split-string (string &optional separators)
18226 "Splits STRING into substrings at SEPARATORS.
18227 No empty strings are returned if there are matches at the beginning
18228 and end of string."
18229 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
18230 (start 0)
18231 notfirst
18232 (list nil))
18233 (while (and (string-match rexp string
18234 (if (and notfirst
18235 (= start (match-beginning 0))
18236 (< start (length string)))
18237 (1+ start) start))
18238 (< (match-beginning 0) (length string)))
18239 (setq notfirst t)
18240 (or (eq (match-beginning 0) 0)
18241 (and (eq (match-beginning 0) (match-end 0))
18242 (eq (match-beginning 0) start))
18243 (setq list
18244 (cons (substring string start (match-beginning 0))
18245 list)))
18246 (setq start (match-end 0)))
18247 (or (eq start (length string))
18248 (setq list
18249 (cons (substring string start)
18250 list)))
18251 (nreverse list)))
18253 (defun org-quote-vert (s)
18254 "Replace \"|\" with \"\\vert\"."
18255 (while (string-match "|" s)
18256 (setq s (replace-match "\\vert" t t s)))
18259 (defun org-uuidgen-p (s)
18260 "Is S an ID created by UUIDGEN?"
18261 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
18263 (defun org-context ()
18264 "Return a list of contexts of the current cursor position.
18265 If several contexts apply, all are returned.
18266 Each context entry is a list with a symbol naming the context, and
18267 two positions indicating start and end of the context. Possible
18268 contexts are:
18270 :headline anywhere in a headline
18271 :headline-stars on the leading stars in a headline
18272 :todo-keyword on a TODO keyword (including DONE) in a headline
18273 :tags on the TAGS in a headline
18274 :priority on the priority cookie in a headline
18275 :item on the first line of a plain list item
18276 :item-bullet on the bullet/number of a plain list item
18277 :checkbox on the checkbox in a plain list item
18278 :table in an org-mode table
18279 :table-special on a special filed in a table
18280 :table-table in a table.el table
18281 :link on a hyperlink
18282 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
18283 :target on a <<target>>
18284 :radio-target on a <<<radio-target>>>
18285 :latex-fragment on a LaTeX fragment
18286 :latex-preview on a LaTeX fragment with overlayed preview image
18288 This function expects the position to be visible because it uses font-lock
18289 faces as a help to recognize the following contexts: :table-special, :link,
18290 and :keyword."
18291 (let* ((f (get-text-property (point) 'face))
18292 (faces (if (listp f) f (list f)))
18293 (p (point)) clist o)
18294 ;; First the large context
18295 (cond
18296 ((org-on-heading-p t)
18297 (push (list :headline (point-at-bol) (point-at-eol)) clist)
18298 (when (progn
18299 (beginning-of-line 1)
18300 (looking-at org-todo-line-tags-regexp))
18301 (push (org-point-in-group p 1 :headline-stars) clist)
18302 (push (org-point-in-group p 2 :todo-keyword) clist)
18303 (push (org-point-in-group p 4 :tags) clist))
18304 (goto-char p)
18305 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
18306 (if (looking-at "\\[#[A-Z0-9]\\]")
18307 (push (org-point-in-group p 0 :priority) clist)))
18309 ((org-at-item-p)
18310 (push (org-point-in-group p 2 :item-bullet) clist)
18311 (push (list :item (point-at-bol)
18312 (save-excursion (org-end-of-item) (point)))
18313 clist)
18314 (and (org-at-item-checkbox-p)
18315 (push (org-point-in-group p 0 :checkbox) clist)))
18317 ((org-at-table-p)
18318 (push (list :table (org-table-begin) (org-table-end)) clist)
18319 (if (memq 'org-formula faces)
18320 (push (list :table-special
18321 (previous-single-property-change p 'face)
18322 (next-single-property-change p 'face)) clist)))
18323 ((org-at-table-p 'any)
18324 (push (list :table-table) clist)))
18325 (goto-char p)
18327 ;; Now the small context
18328 (cond
18329 ((org-at-timestamp-p)
18330 (push (org-point-in-group p 0 :timestamp) clist))
18331 ((memq 'org-link faces)
18332 (push (list :link
18333 (previous-single-property-change p 'face)
18334 (next-single-property-change p 'face)) clist))
18335 ((memq 'org-special-keyword faces)
18336 (push (list :keyword
18337 (previous-single-property-change p 'face)
18338 (next-single-property-change p 'face)) clist))
18339 ((org-on-target-p)
18340 (push (org-point-in-group p 0 :target) clist)
18341 (goto-char (1- (match-beginning 0)))
18342 (if (looking-at org-radio-target-regexp)
18343 (push (org-point-in-group p 0 :radio-target) clist))
18344 (goto-char p))
18345 ((setq o (car (delq nil
18346 (mapcar
18347 (lambda (x)
18348 (if (memq x org-latex-fragment-image-overlays) x))
18349 (overlays-at (point))))))
18350 (push (list :latex-fragment
18351 (overlay-start o) (overlay-end o)) clist)
18352 (push (list :latex-preview
18353 (overlay-start o) (overlay-end o)) clist))
18354 ((org-inside-LaTeX-fragment-p)
18355 ;; FIXME: positions wrong.
18356 (push (list :latex-fragment (point) (point)) clist)))
18358 (setq clist (nreverse (delq nil clist)))
18359 clist))
18361 ;; FIXME: Compare with at-regexp-p Do we need both?
18362 (defun org-in-regexp (re &optional nlines visually)
18363 "Check if point is inside a match of regexp.
18364 Normally only the current line is checked, but you can include NLINES extra
18365 lines both before and after point into the search.
18366 If VISUALLY is set, require that the cursor is not after the match but
18367 really on, so that the block visually is on the match."
18368 (catch 'exit
18369 (let ((pos (point))
18370 (eol (point-at-eol (+ 1 (or nlines 0))))
18371 (inc (if visually 1 0)))
18372 (save-excursion
18373 (beginning-of-line (- 1 (or nlines 0)))
18374 (while (re-search-forward re eol t)
18375 (if (and (<= (match-beginning 0) pos)
18376 (>= (+ inc (match-end 0)) pos))
18377 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
18379 (defun org-at-regexp-p (regexp)
18380 "Is point inside a match of REGEXP in the current line?"
18381 (catch 'exit
18382 (save-excursion
18383 (let ((pos (point)) (end (point-at-eol)))
18384 (beginning-of-line 1)
18385 (while (re-search-forward regexp end t)
18386 (if (and (<= (match-beginning 0) pos)
18387 (>= (match-end 0) pos))
18388 (throw 'exit t)))
18389 nil))))
18391 (defun org-in-regexps-block-p (start-re end-re &optional bound)
18392 "Return t if the current point is between matches of START-RE and END-RE.
18393 This will also return t if point is on one of the two matches or
18394 in an unfinished block. END-RE can be a string or a form
18395 returning a string.
18397 An optional third argument bounds the search for START-RE. It
18398 defaults to previous heading or `point-min'."
18399 (let ((pos (point))
18400 (limit (or bound (save-excursion (outline-previous-heading)))))
18401 (save-excursion
18402 ;; we're on a block when point is on start-re...
18403 (or (org-at-regexp-p start-re)
18404 ;; ... or start-re can be found above...
18405 (and (re-search-backward start-re limit t)
18406 ;; ... but no end-re between start-re and point.
18407 (not (re-search-forward (eval end-re) pos t)))))))
18409 (defun org-occur-in-agenda-files (regexp &optional nlines)
18410 "Call `multi-occur' with buffers for all agenda files."
18411 (interactive "sOrg-files matching: \np")
18412 (let* ((files (org-agenda-files))
18413 (tnames (mapcar 'file-truename files))
18414 (extra org-agenda-text-search-extra-files)
18416 (when (eq (car extra) 'agenda-archives)
18417 (setq extra (cdr extra))
18418 (setq files (org-add-archive-files files)))
18419 (while (setq f (pop extra))
18420 (unless (member (file-truename f) tnames)
18421 (add-to-list 'files f 'append)
18422 (add-to-list 'tnames (file-truename f) 'append)))
18423 (multi-occur
18424 (mapcar (lambda (x)
18425 (with-current-buffer
18426 (or (get-file-buffer x) (find-file-noselect x))
18427 (widen)
18428 (current-buffer)))
18429 files)
18430 regexp)))
18432 (if (boundp 'occur-mode-find-occurrence-hook)
18433 ;; Emacs 23
18434 (add-hook 'occur-mode-find-occurrence-hook
18435 (lambda ()
18436 (when (org-mode-p)
18437 (org-reveal))))
18438 ;; Emacs 22
18439 (defadvice occur-mode-goto-occurrence
18440 (after org-occur-reveal activate)
18441 (and (org-mode-p) (org-reveal)))
18442 (defadvice occur-mode-goto-occurrence-other-window
18443 (after org-occur-reveal activate)
18444 (and (org-mode-p) (org-reveal)))
18445 (defadvice occur-mode-display-occurrence
18446 (after org-occur-reveal activate)
18447 (when (org-mode-p)
18448 (let ((pos (occur-mode-find-occurrence)))
18449 (with-current-buffer (marker-buffer pos)
18450 (save-excursion
18451 (goto-char pos)
18452 (org-reveal)))))))
18454 (defun org-occur-link-in-agenda-files ()
18455 "Create a link and search for it in the agendas.
18456 The link is not stored in `org-stored-links', it is just created
18457 for the search purpose."
18458 (interactive)
18459 (let ((link (condition-case nil
18460 (org-store-link nil)
18461 (error "Unable to create a link to here"))))
18462 (org-occur-in-agenda-files (regexp-quote link))))
18464 (defun org-uniquify (list)
18465 "Remove duplicate elements from LIST."
18466 (let (res)
18467 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
18468 res))
18470 (defun org-delete-all (elts list)
18471 "Remove all elements in ELTS from LIST."
18472 (while elts
18473 (setq list (delete (pop elts) list)))
18474 list)
18476 (defun org-count (cl-item cl-seq)
18477 "Count the number of occurrences of ITEM in SEQ.
18478 Taken from `count' in cl-seq.el with all keyword arguments removed."
18479 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
18480 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
18481 (while (< cl-start cl-end)
18482 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
18483 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
18484 (setq cl-start (1+ cl-start)))
18485 cl-count))
18487 (defun org-remove-if (predicate seq)
18488 "Remove everything from SEQ that fulfills PREDICATE."
18489 (let (res e)
18490 (while seq
18491 (setq e (pop seq))
18492 (if (not (funcall predicate e)) (push e res)))
18493 (nreverse res)))
18495 (defun org-remove-if-not (predicate seq)
18496 "Remove everything from SEQ that does not fulfill PREDICATE."
18497 (let (res e)
18498 (while seq
18499 (setq e (pop seq))
18500 (if (funcall predicate e) (push e res)))
18501 (nreverse res)))
18503 (defun org-back-over-empty-lines ()
18504 "Move backwards over whitespace, to the beginning of the first empty line.
18505 Returns the number of empty lines passed."
18506 (let ((pos (point)))
18507 (skip-chars-backward " \t\n\r")
18508 (beginning-of-line 2)
18509 (goto-char (min (point) pos))
18510 (count-lines (point) pos)))
18512 (defun org-skip-whitespace ()
18513 (skip-chars-forward " \t\n\r"))
18515 (defun org-point-in-group (point group &optional context)
18516 "Check if POINT is in match-group GROUP.
18517 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
18518 match. If the match group does not exist or point is not inside it,
18519 return nil."
18520 (and (match-beginning group)
18521 (>= point (match-beginning group))
18522 (<= point (match-end group))
18523 (if context
18524 (list context (match-beginning group) (match-end group))
18525 t)))
18527 (defun org-switch-to-buffer-other-window (&rest args)
18528 "Switch to buffer in a second window on the current frame.
18529 In particular, do not allow pop-up frames.
18530 Returns the newly created buffer."
18531 (let (pop-up-frames special-display-buffer-names special-display-regexps
18532 special-display-function)
18533 (apply 'switch-to-buffer-other-window args)))
18535 (defun org-combine-plists (&rest plists)
18536 "Create a single property list from all plists in PLISTS.
18537 The process starts by copying the first list, and then setting properties
18538 from the other lists. Settings in the last list are the most significant
18539 ones and overrule settings in the other lists."
18540 (let ((rtn (copy-sequence (pop plists)))
18541 p v ls)
18542 (while plists
18543 (setq ls (pop plists))
18544 (while ls
18545 (setq p (pop ls) v (pop ls))
18546 (setq rtn (plist-put rtn p v))))
18547 rtn))
18549 (defun org-move-line-down (arg)
18550 "Move the current line down. With prefix argument, move it past ARG lines."
18551 (interactive "p")
18552 (let ((col (current-column))
18553 beg end pos)
18554 (beginning-of-line 1) (setq beg (point))
18555 (beginning-of-line 2) (setq end (point))
18556 (beginning-of-line (+ 1 arg))
18557 (setq pos (move-marker (make-marker) (point)))
18558 (insert (delete-and-extract-region beg end))
18559 (goto-char pos)
18560 (org-move-to-column col)))
18562 (defun org-move-line-up (arg)
18563 "Move the current line up. With prefix argument, move it past ARG lines."
18564 (interactive "p")
18565 (let ((col (current-column))
18566 beg end pos)
18567 (beginning-of-line 1) (setq beg (point))
18568 (beginning-of-line 2) (setq end (point))
18569 (beginning-of-line (- arg))
18570 (setq pos (move-marker (make-marker) (point)))
18571 (insert (delete-and-extract-region beg end))
18572 (goto-char pos)
18573 (org-move-to-column col)))
18575 (defun org-replace-escapes (string table)
18576 "Replace %-escapes in STRING with values in TABLE.
18577 TABLE is an association list with keys like \"%a\" and string values.
18578 The sequences in STRING may contain normal field width and padding information,
18579 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
18580 so values can contain further %-escapes if they are define later in TABLE."
18581 (let ((tbl (copy-alist table))
18582 (case-fold-search nil)
18583 (pchg 0)
18584 e re rpl)
18585 (while (setq e (pop tbl))
18586 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
18587 (when (and (cdr e) (string-match re (cdr e)))
18588 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
18589 (safe "SREF"))
18590 (add-text-properties 0 3 (list 'sref sref) safe)
18591 (setcdr e (replace-match safe t t (cdr e)))))
18592 (while (string-match re string)
18593 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
18594 (cdr e)))
18595 (setq string (replace-match rpl t t string))))
18596 (while (setq pchg (next-property-change pchg string))
18597 (let ((sref (get-text-property pchg 'sref string)))
18598 (when (and sref (string-match "SREF" string pchg))
18599 (setq string (replace-match sref t t string)))))
18600 string))
18602 (defun org-sublist (list start end)
18603 "Return a section of LIST, from START to END.
18604 Counting starts at 1."
18605 (let (rtn (c start))
18606 (setq list (nthcdr (1- start) list))
18607 (while (and list (<= c end))
18608 (push (pop list) rtn)
18609 (setq c (1+ c)))
18610 (nreverse rtn)))
18612 (defun org-find-base-buffer-visiting (file)
18613 "Like `find-buffer-visiting' but always return the base buffer and
18614 not an indirect buffer."
18615 (let ((buf (or (get-file-buffer file)
18616 (find-buffer-visiting file))))
18617 (if buf
18618 (or (buffer-base-buffer buf) buf)
18619 nil)))
18621 (defun org-image-file-name-regexp (&optional extensions)
18622 "Return regexp matching the file names of images.
18623 If EXTENSIONS is given, only match these."
18624 (if (and (not extensions) (fboundp 'image-file-name-regexp))
18625 (image-file-name-regexp)
18626 (let ((image-file-name-extensions
18627 (or extensions
18628 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
18629 "xbm" "xpm" "pbm" "pgm" "ppm"))))
18630 (concat "\\."
18631 (regexp-opt (nconc (mapcar 'upcase
18632 image-file-name-extensions)
18633 image-file-name-extensions)
18635 "\\'"))))
18637 (defun org-file-image-p (file &optional extensions)
18638 "Return non-nil if FILE is an image."
18639 (save-match-data
18640 (string-match (org-image-file-name-regexp extensions) file)))
18642 (defun org-get-cursor-date ()
18643 "Return the date at cursor in as a time.
18644 This works in the calendar and in the agenda, anywhere else it just
18645 returns the current time."
18646 (let (date day defd)
18647 (cond
18648 ((eq major-mode 'calendar-mode)
18649 (setq date (calendar-cursor-to-date)
18650 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18651 ((eq major-mode 'org-agenda-mode)
18652 (setq day (get-text-property (point) 'day))
18653 (if day
18654 (setq date (calendar-gregorian-from-absolute day)
18655 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
18656 (nth 2 date))))))
18657 (or defd (current-time))))
18659 (defvar org-agenda-action-marker (make-marker)
18660 "Marker pointing to the entry for the next agenda action.")
18662 (defun org-mark-entry-for-agenda-action ()
18663 "Mark the current entry as target of an agenda action.
18664 Agenda actions are actions executed from the agenda with the key `k',
18665 which make use of the date at the cursor."
18666 (interactive)
18667 (move-marker org-agenda-action-marker
18668 (save-excursion (org-back-to-heading t) (point))
18669 (current-buffer))
18670 (message
18671 "Entry marked for action; press `k' at desired date in agenda or calendar"))
18673 ;;; Paragraph filling stuff.
18674 ;; We want this to be just right, so use the full arsenal.
18676 (defun org-indent-line-function ()
18677 "Indent line depending on context."
18678 (interactive)
18679 (let* ((pos (point))
18680 (itemp (org-at-item-p))
18681 (case-fold-search t)
18682 (org-drawer-regexp (or org-drawer-regexp "\000"))
18683 (inline-task-p (and (featurep 'org-inlinetask)
18684 (org-inlinetask-in-task-p)))
18685 column bpos bcol tpos tcol)
18686 (beginning-of-line 1)
18687 (cond
18688 ;; Comments
18689 ((looking-at "# ") (setq column 0))
18690 ;; Headings
18691 ((looking-at "\\*+ ") (setq column 0))
18692 ;; Literal examples
18693 ((looking-at "[ \t]*:[ \t]")
18694 (setq column (org-get-indentation))) ; do nothing
18695 ;; Drawers
18696 ((and (looking-at "[ \t]*:END:")
18697 (save-excursion (re-search-backward org-drawer-regexp nil t)))
18698 (save-excursion
18699 (goto-char (1- (match-beginning 1)))
18700 (setq column (current-column))))
18701 ;; Special blocks
18702 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
18703 (save-excursion
18704 (re-search-backward
18705 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
18706 (setq column (org-get-indentation (match-string 0))))
18707 ((and (not (looking-at "[ \t]*#\\+begin_"))
18708 (org-in-regexps-block-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
18709 (save-excursion
18710 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
18711 (setq column
18712 (if (equal (downcase (match-string 1)) "src")
18713 ;; src blocks: let `org-edit-src-exit' handle them
18714 (org-get-indentation)
18715 (org-get-indentation (match-string 0)))))
18716 ;; Lists
18717 ((org-in-item-p)
18718 (org-beginning-of-item)
18719 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\(:?\\[@\\(:?start:\\)?[0-9]+\\][ \t]*\\)?\\[[- X]\\][ \t]*\\|.*? :: \\)?")
18720 (setq bpos (match-beginning 1) tpos (match-end 0)
18721 bcol (progn (goto-char bpos) (current-column))
18722 tcol (progn (goto-char tpos) (current-column)))
18723 (if (> tcol (+ bcol org-description-max-indent))
18724 (setq tcol (+ bcol 5)))
18725 (goto-char pos)
18726 (setq column (if itemp (org-get-indentation) tcol)))
18727 ;; This line has nothing special, look at the previous relevant
18728 ;; line to compute indentation
18730 (beginning-of-line 0)
18731 (while (and (not (bobp))
18732 (not (looking-at org-drawer-regexp))
18733 ;; skip comments, verbatim, empty lines, tables,
18734 ;; inline tasks, lists, drawers and blocks
18735 (or (and (looking-at "[ \t]*:END:")
18736 (re-search-backward org-drawer-regexp nil t))
18737 (and (looking-at "[ \t]*#\\+end_")
18738 (re-search-backward "[ \t]*#\\+begin_"nil t))
18739 (looking-at "[ \t]*[\n:#|]")
18740 (and (org-in-item-p) (goto-char (org-list-top-point)))
18741 (and (not inline-task-p)
18742 (featurep 'org-inlinetask)
18743 (org-inlinetask-in-task-p))))
18744 (beginning-of-line 0))
18745 (cond
18746 ;; There was an heading above.
18747 ((looking-at "\\*+[ \t]+")
18748 (if (not org-adapt-indentation)
18749 (setq column 0)
18750 (goto-char (match-end 0))
18751 (setq column (current-column))))
18752 ;; A drawer had started and is unfinished
18753 ((looking-at org-drawer-regexp)
18754 (goto-char (1- (match-beginning 1)))
18755 (setq column (current-column)))
18756 ;; Else, nothing noticeable found: get indentation and go on.
18757 (t (setq column (org-get-indentation))))))
18758 ;; Now apply indentation and move cursor accordingly
18759 (goto-char pos)
18760 (if (<= (current-column) (current-indentation))
18761 (org-indent-line-to column)
18762 (save-excursion (org-indent-line-to column)))
18763 ;; Special polishing for properties, see `org-property-format'
18764 (setq column (current-column))
18765 (beginning-of-line 1)
18766 (if (looking-at
18767 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
18768 (replace-match (concat (match-string 1)
18769 (format org-property-format
18770 (match-string 2) (match-string 3)))
18771 t t))
18772 (org-move-to-column column)))
18774 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
18775 "Variable to store copy of `adaptive-fill-regexp'.
18776 Since `adaptive-fill-regexp' is set to never match, we need to
18777 store a backup of its value before entering `org-mode' so that
18778 the functionality can be provided as a fall-back.")
18780 (defun org-set-autofill-regexps ()
18781 (interactive)
18782 ;; In the paragraph separator we include headlines, because filling
18783 ;; text in a line directly attached to a headline would otherwise
18784 ;; fill the headline as well.
18785 (org-set-local 'comment-start-skip "^#+[ \t]*")
18786 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
18787 ;; The paragraph starter includes hand-formatted lists.
18788 (org-set-local
18789 'paragraph-start
18790 (concat
18791 "\f" "\\|"
18792 "[ ]*$" "\\|"
18793 "\\*+ " "\\|"
18794 "[ \t]*#" "\\|"
18795 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
18796 "[ \t]*[:|]" "\\|"
18797 "\\$\\$" "\\|"
18798 "\\\\\\(begin\\|end\\|[][]\\)"))
18799 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
18800 ;; But only if the user has not turned off tables or fixed-width regions
18801 (org-set-local
18802 'auto-fill-inhibit-regexp
18803 (concat "\\*+ \\|#\\+"
18804 "\\|[ \t]*" org-keyword-time-regexp
18805 (if (or org-enable-table-editor org-enable-fixed-width-editor)
18806 (concat
18807 "\\|[ \t]*["
18808 (if org-enable-table-editor "|" "")
18809 (if org-enable-fixed-width-editor ":" "")
18810 "]"))))
18811 ;; We use our own fill-paragraph function, to make sure that tables
18812 ;; and fixed-width regions are not wrapped. That function will pass
18813 ;; through to `fill-paragraph' when appropriate.
18814 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
18815 ;; Adaptive filling: To get full control, first make sure that
18816 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
18817 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
18818 (org-set-local 'org-adaptive-fill-regexp-backup
18819 adaptive-fill-regexp))
18820 (org-set-local 'adaptive-fill-regexp "\000")
18821 (org-set-local 'adaptive-fill-function
18822 'org-adaptive-fill-function)
18823 (org-set-local
18824 'align-mode-rules-list
18825 '((org-in-buffer-settings
18826 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
18827 (modes . '(org-mode))))))
18829 (defun org-fill-paragraph (&optional justify)
18830 "Re-align a table, pass through to fill-paragraph if no table."
18831 (let ((table-p (org-at-table-p))
18832 (table.el-p (org-at-table.el-p)))
18833 (cond ((and (equal (char-after (point-at-bol)) ?*)
18834 (save-excursion (goto-char (point-at-bol))
18835 (looking-at outline-regexp)))
18836 t) ; skip headlines
18837 (table.el-p t) ; skip table.el tables
18838 (table-p (org-table-align) t) ; align org-mode tables
18839 (t nil)))) ; call paragraph-fill
18841 ;; For reference, this is the default value of adaptive-fill-regexp
18842 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
18844 (defun org-adaptive-fill-function ()
18845 "Return a fill prefix for org-mode files.
18846 In particular, this makes sure hanging paragraphs for hand-formatted lists
18847 work correctly."
18848 (cond
18849 ;; Comment line
18850 ((looking-at "#[ \t]+")
18851 (match-string-no-properties 0))
18852 ;; Description list
18853 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
18854 (save-excursion
18855 (if (> (match-end 1) (+ (match-beginning 1)
18856 org-description-max-indent))
18857 (goto-char (+ (match-beginning 1) 5))
18858 (goto-char (match-end 0)))
18859 (make-string (current-column) ?\ )))
18860 ;; Ordered or unordered list
18861 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)")
18862 (save-excursion
18863 (goto-char (match-end 0))
18864 (make-string (current-column) ?\ )))
18865 ;; Other text
18866 ((looking-at org-adaptive-fill-regexp-backup)
18867 (match-string-no-properties 0))))
18869 ;;; Other stuff.
18871 (defun org-toggle-fixed-width-section (arg)
18872 "Toggle the fixed-width export.
18873 If there is no active region, the QUOTE keyword at the current headline is
18874 inserted or removed. When present, it causes the text between this headline
18875 and the next to be exported as fixed-width text, and unmodified.
18876 If there is an active region, this command adds or removes a colon as the
18877 first character of this line. If the first character of a line is a colon,
18878 this line is also exported in fixed-width font."
18879 (interactive "P")
18880 (let* ((cc 0)
18881 (regionp (org-region-active-p))
18882 (beg (if regionp (region-beginning) (point)))
18883 (end (if regionp (region-end)))
18884 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
18885 (case-fold-search nil)
18886 (re "[ \t]*\\(: \\)")
18887 off)
18888 (if regionp
18889 (save-excursion
18890 (goto-char beg)
18891 (setq cc (current-column))
18892 (beginning-of-line 1)
18893 (setq off (looking-at re))
18894 (while (> nlines 0)
18895 (setq nlines (1- nlines))
18896 (beginning-of-line 1)
18897 (cond
18898 (arg
18899 (org-move-to-column cc t)
18900 (insert ": \n")
18901 (forward-line -1))
18902 ((and off (looking-at re))
18903 (replace-match "" t t nil 1))
18904 ((not off) (org-move-to-column cc t) (insert ": ")))
18905 (forward-line 1)))
18906 (save-excursion
18907 (org-back-to-heading)
18908 (if (looking-at (concat outline-regexp
18909 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
18910 (replace-match "" t t nil 1)
18911 (if (looking-at outline-regexp)
18912 (progn
18913 (goto-char (match-end 0))
18914 (insert org-quote-string " "))))))))
18916 (defun org-reftex-citation ()
18917 "Use reftex-citation to insert a citation into the buffer.
18918 This looks for a line like
18920 #+BIBLIOGRAPHY: foo plain option:-d
18922 and derives from it that foo.bib is the bibliography file relevant
18923 for this document. It then installs the necessary environment for RefTeX
18924 to work in this buffer and calls `reftex-citation' to insert a citation
18925 into the buffer.
18927 Export of such citations to both LaTeX and HTML is handled by the contributed
18928 package org-exp-bibtex by Taru Karttunen."
18929 (interactive)
18930 (let ((reftex-docstruct-symbol 'rds)
18931 (reftex-cite-format "\\cite{%l}")
18932 rds bib)
18933 (save-excursion
18934 (save-restriction
18935 (widen)
18936 (let ((case-fold-search t)
18937 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
18938 (if (not (save-excursion
18939 (or (re-search-forward re nil t)
18940 (re-search-backward re nil t))))
18941 (error "No bibliography defined in file")
18942 (setq bib (concat (match-string 1) ".bib")
18943 rds (list (list 'bib bib)))))))
18944 (call-interactively 'reftex-citation)))
18946 ;;;; Functions extending outline functionality
18948 (defun org-beginning-of-line (&optional arg)
18949 "Go to the beginning of the current line. If that is invisible, continue
18950 to a visible line beginning. This makes the function of C-a more intuitive.
18951 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
18952 first attempt, and only move to after the tags when the cursor is already
18953 beyond the end of the headline."
18954 (interactive "P")
18955 (let ((pos (point))
18956 (special (if (consp org-special-ctrl-a/e)
18957 (car org-special-ctrl-a/e)
18958 org-special-ctrl-a/e))
18959 refpos)
18960 (if (org-bound-and-true-p line-move-visual)
18961 (beginning-of-visual-line 1)
18962 (beginning-of-line 1))
18963 (if (and arg (fboundp 'move-beginning-of-line))
18964 (call-interactively 'move-beginning-of-line)
18965 (if (bobp)
18967 (backward-char 1)
18968 (if (org-truely-invisible-p)
18969 (while (and (not (bobp)) (org-truely-invisible-p))
18970 (backward-char 1)
18971 (beginning-of-line 1))
18972 (forward-char 1))))
18973 (when special
18974 (cond
18975 ((and (looking-at org-complex-heading-regexp)
18976 (= (char-after (match-end 1)) ?\ ))
18977 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
18978 (point-at-eol)))
18979 (goto-char
18980 (if (eq special t)
18981 (cond ((> pos refpos) refpos)
18982 ((= pos (point)) refpos)
18983 (t (point)))
18984 (cond ((> pos (point)) (point))
18985 ((not (eq last-command this-command)) (point))
18986 (t refpos)))))
18987 ((org-at-item-p)
18988 (goto-char
18989 (if (eq special t)
18990 (cond ((> pos (match-end 4)) (match-end 4))
18991 ((= pos (point)) (match-end 4))
18992 (t (point)))
18993 (cond ((> pos (point)) (point))
18994 ((not (eq last-command this-command)) (point))
18995 (t (match-end 4))))))))
18996 (org-no-warnings
18997 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
18999 (defun org-end-of-line (&optional arg)
19000 "Go to the end of the line.
19001 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
19002 first attempt, and only move to after the tags when the cursor is already
19003 beyond the end of the headline."
19004 (interactive "P")
19005 (let ((special (if (consp org-special-ctrl-a/e)
19006 (cdr org-special-ctrl-a/e)
19007 org-special-ctrl-a/e)))
19008 (if (or (not special)
19009 (not (org-on-heading-p))
19010 arg)
19011 (call-interactively
19012 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
19013 ((fboundp 'move-end-of-line) 'move-end-of-line)
19014 (t 'end-of-line)))
19015 (let ((pos (point)))
19016 (beginning-of-line 1)
19017 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
19018 (if (eq special t)
19019 (if (or (< pos (match-beginning 1))
19020 (= pos (match-end 0)))
19021 (goto-char (match-beginning 1))
19022 (goto-char (match-end 0)))
19023 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
19024 (goto-char (match-end 0))
19025 (goto-char (match-beginning 1))))
19026 (call-interactively (if (fboundp 'move-end-of-line)
19027 'move-end-of-line
19028 'end-of-line)))))
19029 (org-no-warnings
19030 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
19032 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
19033 (define-key org-mode-map "\C-e" 'org-end-of-line)
19035 (defun org-backward-sentence (&optional arg)
19036 "Go to beginning of sentence, or beginning of table field.
19037 This will call `backward-sentence' or `org-table-beginning-of-field',
19038 depending on context."
19039 (interactive "P")
19040 (cond
19041 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
19042 (t (call-interactively 'backward-sentence))))
19044 (defun org-forward-sentence (&optional arg)
19045 "Go to end of sentence, or end of table field.
19046 This will call `forward-sentence' or `org-table-end-of-field',
19047 depending on context."
19048 (interactive "P")
19049 (cond
19050 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
19051 (t (call-interactively 'forward-sentence))))
19053 (define-key org-mode-map "\M-a" 'org-backward-sentence)
19054 (define-key org-mode-map "\M-e" 'org-forward-sentence)
19056 (defun org-kill-line (&optional arg)
19057 "Kill line, to tags or end of line."
19058 (interactive "P")
19059 (cond
19060 ((or (not org-special-ctrl-k)
19061 (bolp)
19062 (not (org-on-heading-p)))
19063 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
19064 org-ctrl-k-protect-subtree)
19065 (if (or (eq org-ctrl-k-protect-subtree 'error)
19066 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
19067 (error "C-k aborted - would kill hidden subtree")))
19068 (call-interactively 'kill-line))
19069 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
19070 (kill-region (point) (match-beginning 1))
19071 (org-set-tags nil t))
19072 (t (kill-region (point) (point-at-eol)))))
19074 (define-key org-mode-map "\C-k" 'org-kill-line)
19076 (defun org-yank (&optional arg)
19077 "Yank. If the kill is a subtree, treat it specially.
19078 This command will look at the current kill and check if is a single
19079 subtree, or a series of subtrees[1]. If it passes the test, and if the
19080 cursor is at the beginning of a line or after the stars of a currently
19081 empty headline, then the yank is handled specially. How exactly depends
19082 on the value of the following variables, both set by default.
19084 org-yank-folded-subtrees
19085 When set, the subtree(s) will be folded after insertion, but only
19086 if doing so would now swallow text after the yanked text.
19088 org-yank-adjusted-subtrees
19089 When set, the subtree will be promoted or demoted in order to
19090 fit into the local outline tree structure, which means that the level
19091 will be adjusted so that it becomes the smaller one of the two
19092 *visible* surrounding headings.
19094 Any prefix to this command will cause `yank' to be called directly with
19095 no special treatment. In particular, a simple \\[universal-argument] prefix \
19096 will just
19097 plainly yank the text as it is.
19099 \[1] The test checks if the first non-white line is a heading
19100 and if there are no other headings with fewer stars."
19101 (interactive "P")
19102 (org-yank-generic 'yank arg))
19104 (defun org-yank-generic (command arg)
19105 "Perform some yank-like command.
19107 This function implements the behavior described in the `org-yank'
19108 documentation. However, it has been generalized to work for any
19109 interactive command with similar behavior."
19111 ;; pretend to be command COMMAND
19112 (setq this-command command)
19114 (if arg
19115 (call-interactively command)
19117 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
19118 (and (org-kill-is-subtree-p)
19119 (or (bolp)
19120 (and (looking-at "[ \t]*$")
19121 (string-match
19122 "\\`\\*+\\'"
19123 (buffer-substring (point-at-bol) (point)))))))
19124 swallowp)
19125 (cond
19126 ((and subtreep org-yank-folded-subtrees)
19127 (let ((beg (point))
19128 end)
19129 (if (and subtreep org-yank-adjusted-subtrees)
19130 (org-paste-subtree nil nil 'for-yank)
19131 (call-interactively command))
19133 (setq end (point))
19134 (goto-char beg)
19135 (when (and (bolp) subtreep
19136 (not (setq swallowp
19137 (org-yank-folding-would-swallow-text beg end))))
19138 (or (looking-at outline-regexp)
19139 (re-search-forward (concat "^" outline-regexp) end t))
19140 (while (and (< (point) end) (looking-at outline-regexp))
19141 (hide-subtree)
19142 (org-cycle-show-empty-lines 'folded)
19143 (condition-case nil
19144 (outline-forward-same-level 1)
19145 (error (goto-char end)))))
19146 (when swallowp
19147 (message
19148 "Inserted text not folded because that would swallow text"))
19150 (goto-char end)
19151 (skip-chars-forward " \t\n\r")
19152 (beginning-of-line 1)
19153 (push-mark beg 'nomsg)))
19154 ((and subtreep org-yank-adjusted-subtrees)
19155 (let ((beg (point-at-bol)))
19156 (org-paste-subtree nil nil 'for-yank)
19157 (push-mark beg 'nomsg)))
19159 (call-interactively command))))))
19161 (defun org-yank-folding-would-swallow-text (beg end)
19162 "Would hide-subtree at BEG swallow any text after END?"
19163 (let (level)
19164 (save-excursion
19165 (goto-char beg)
19166 (when (or (looking-at outline-regexp)
19167 (re-search-forward (concat "^" outline-regexp) end t))
19168 (setq level (org-outline-level)))
19169 (goto-char end)
19170 (skip-chars-forward " \t\r\n\v\f")
19171 (if (or (eobp)
19172 (and (bolp) (looking-at org-outline-regexp)
19173 (<= (org-outline-level) level)))
19174 nil ; Nothing would be swallowed
19175 t)))) ; something would swallow
19177 (define-key org-mode-map "\C-y" 'org-yank)
19179 (defun org-invisible-p ()
19180 "Check if point is at a character currently not visible."
19181 ;; Early versions of noutline don't have `outline-invisible-p'.
19182 (if (fboundp 'outline-invisible-p)
19183 (outline-invisible-p)
19184 (get-char-property (point) 'invisible)))
19186 (defun org-truely-invisible-p ()
19187 "Check if point is at a character currently not visible.
19188 This version does not only check the character property, but also
19189 `visible-mode'."
19190 ;; Early versions of noutline don't have `outline-invisible-p'.
19191 (if (org-bound-and-true-p visible-mode)
19193 (if (fboundp 'outline-invisible-p)
19194 (outline-invisible-p)
19195 (get-char-property (point) 'invisible))))
19197 (defun org-invisible-p2 ()
19198 "Check if point is at a character currently not visible."
19199 (save-excursion
19200 (if (and (eolp) (not (bobp))) (backward-char 1))
19201 ;; Early versions of noutline don't have `outline-invisible-p'.
19202 (if (fboundp 'outline-invisible-p)
19203 (outline-invisible-p)
19204 (get-char-property (point) 'invisible))))
19206 (defun org-back-to-heading (&optional invisible-ok)
19207 "Call `outline-back-to-heading', but provide a better error message."
19208 (condition-case nil
19209 (outline-back-to-heading invisible-ok)
19210 (error (error "Before first headline at position %d in buffer %s"
19211 (point) (current-buffer)))))
19213 (defun org-beginning-of-defun ()
19214 "Go to the beginning of the subtree, i.e. back to the heading."
19215 (org-back-to-heading))
19216 (defun org-end-of-defun ()
19217 "Go to the end of the subtree."
19218 (org-end-of-subtree nil t))
19220 (defun org-before-first-heading-p ()
19221 "Before first heading?"
19222 (save-excursion
19223 (null (re-search-backward "^\\*+ " nil t))))
19225 (defun org-on-heading-p (&optional ignored)
19226 (outline-on-heading-p t))
19227 (defun org-at-heading-p (&optional ignored)
19228 (outline-on-heading-p t))
19230 (defun org-point-at-end-of-empty-headline ()
19231 "If point is at the end of an empty headline, return t, else nil.
19232 If the heading only contains a TODO keyword, it is still still considered
19233 empty."
19234 (and (looking-at "[ \t]*$")
19235 (save-excursion
19236 (beginning-of-line 1)
19237 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
19238 "\\)?[ \t]*$")))))
19239 (defun org-at-heading-or-item-p ()
19240 (or (org-on-heading-p) (org-at-item-p)))
19242 (defun org-on-target-p ()
19243 (or (org-in-regexp org-radio-target-regexp)
19244 (org-in-regexp org-target-regexp)))
19246 (defun org-up-heading-all (arg)
19247 "Move to the heading line of which the present line is a subheading.
19248 This function considers both visible and invisible heading lines.
19249 With argument, move up ARG levels."
19250 (if (fboundp 'outline-up-heading-all)
19251 (outline-up-heading-all arg) ; emacs 21 version of outline.el
19252 (outline-up-heading arg t))) ; emacs 22 version of outline.el
19254 (defun org-up-heading-safe ()
19255 "Move to the heading line of which the present line is a subheading.
19256 This version will not throw an error. It will return the level of the
19257 headline found, or nil if no higher level is found.
19259 Also, this function will be a lot faster than `outline-up-heading',
19260 because it relies on stars being the outline starters. This can really
19261 make a significant difference in outlines with very many siblings."
19262 (let (start-level re)
19263 (org-back-to-heading t)
19264 (setq start-level (funcall outline-level))
19265 (if (equal start-level 1)
19267 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
19268 (if (re-search-backward re nil t)
19269 (funcall outline-level)))))
19271 (defun org-first-sibling-p ()
19272 "Is this heading the first child of its parents?"
19273 (interactive)
19274 (let ((re (concat "^" outline-regexp))
19275 level l)
19276 (unless (org-at-heading-p t)
19277 (error "Not at a heading"))
19278 (setq level (funcall outline-level))
19279 (save-excursion
19280 (if (not (re-search-backward re nil t))
19282 (setq l (funcall outline-level))
19283 (< l level)))))
19285 (defun org-goto-sibling (&optional previous)
19286 "Goto the next sibling, even if it is invisible.
19287 When PREVIOUS is set, go to the previous sibling instead. Returns t
19288 when a sibling was found. When none is found, return nil and don't
19289 move point."
19290 (let ((fun (if previous 're-search-backward 're-search-forward))
19291 (pos (point))
19292 (re (concat "^" outline-regexp))
19293 level l)
19294 (when (condition-case nil (org-back-to-heading t) (error nil))
19295 (setq level (funcall outline-level))
19296 (catch 'exit
19297 (or previous (forward-char 1))
19298 (while (funcall fun re nil t)
19299 (setq l (funcall outline-level))
19300 (when (< l level) (goto-char pos) (throw 'exit nil))
19301 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
19302 (goto-char pos)
19303 nil))))
19305 (defun org-show-siblings ()
19306 "Show all siblings of the current headline."
19307 (save-excursion
19308 (while (org-goto-sibling) (org-flag-heading nil)))
19309 (save-excursion
19310 (while (org-goto-sibling 'previous)
19311 (org-flag-heading nil))))
19313 (defun org-goto-first-child ()
19314 "Goto the first child, even if it is invisible.
19315 Return t when a child was found. Otherwise don't move point and
19316 return nil."
19317 (let (level (pos (point)) (re (concat "^" outline-regexp)))
19318 (when (condition-case nil (org-back-to-heading t) (error nil))
19319 (setq level (outline-level))
19320 (forward-char 1)
19321 (if (and (re-search-forward re nil t) (> (outline-level) level))
19322 (progn (goto-char (match-beginning 0)) t)
19323 (goto-char pos) nil))))
19325 (defun org-show-hidden-entry ()
19326 "Show an entry where even the heading is hidden."
19327 (save-excursion
19328 (org-show-entry)))
19330 (defun org-flag-heading (flag &optional entry)
19331 "Flag the current heading. FLAG non-nil means make invisible.
19332 When ENTRY is non-nil, show the entire entry."
19333 (save-excursion
19334 (org-back-to-heading t)
19335 ;; Check if we should show the entire entry
19336 (if entry
19337 (progn
19338 (org-show-entry)
19339 (save-excursion
19340 (and (outline-next-heading)
19341 (org-flag-heading nil))))
19342 (outline-flag-region (max (point-min) (1- (point)))
19343 (save-excursion (outline-end-of-heading) (point))
19344 flag))))
19346 (defun org-get-next-sibling ()
19347 "Move to next heading of the same level, and return point.
19348 If there is no such heading, return nil.
19349 This is like outline-next-sibling, but invisible headings are ok."
19350 (let ((level (funcall outline-level)))
19351 (outline-next-heading)
19352 (while (and (not (eobp)) (> (funcall outline-level) level))
19353 (outline-next-heading))
19354 (if (or (eobp) (< (funcall outline-level) level))
19356 (point))))
19358 (defun org-get-last-sibling ()
19359 "Move to previous heading of the same level, and return point.
19360 If there is no such heading, return nil."
19361 (let ((opoint (point))
19362 (level (funcall outline-level)))
19363 (outline-previous-heading)
19364 (when (and (/= (point) opoint) (outline-on-heading-p t))
19365 (while (and (> (funcall outline-level) level)
19366 (not (bobp)))
19367 (outline-previous-heading))
19368 (if (< (funcall outline-level) level)
19370 (point)))))
19372 (defun org-end-of-subtree (&optional invisible-OK to-heading)
19373 ;; This contains an exact copy of the original function, but it uses
19374 ;; `org-back-to-heading', to make it work also in invisible
19375 ;; trees. And is uses an invisible-OK argument.
19376 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
19377 ;; Furthermore, when used inside Org, finding the end of a large subtree
19378 ;; with many children and grandchildren etc, this can be much faster
19379 ;; than the outline version.
19380 (org-back-to-heading invisible-OK)
19381 (let ((first t)
19382 (level (funcall outline-level)))
19383 (if (and (org-mode-p) (< level 1000))
19384 ;; A true heading (not a plain list item), in Org-mode
19385 ;; This means we can easily find the end by looking
19386 ;; only for the right number of stars. Using a regexp to do
19387 ;; this is so much faster than using a Lisp loop.
19388 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
19389 (forward-char 1)
19390 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
19391 ;; something else, do it the slow way
19392 (while (and (not (eobp))
19393 (or first (> (funcall outline-level) level)))
19394 (setq first nil)
19395 (outline-next-heading)))
19396 (unless to-heading
19397 (if (memq (preceding-char) '(?\n ?\^M))
19398 (progn
19399 ;; Go to end of line before heading
19400 (forward-char -1)
19401 (if (memq (preceding-char) '(?\n ?\^M))
19402 ;; leave blank line before heading
19403 (forward-char -1))))))
19404 (point))
19406 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
19407 "Use Org version in org-mode, for dramatic speed-up."
19408 (if (eq major-mode 'org-mode)
19409 (progn
19410 (org-end-of-subtree nil t)
19411 (unless (eobp) (backward-char 1)))
19412 ad-do-it))
19414 (defun org-forward-same-level (arg &optional invisible-ok)
19415 "Move forward to the arg'th subheading at same level as this one.
19416 Stop at the first and last subheadings of a superior heading.
19417 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
19418 it wil also look at invisible ones."
19419 (interactive "p")
19420 (org-back-to-heading invisible-ok)
19421 (org-on-heading-p)
19422 (let* ((level (- (match-end 0) (match-beginning 0) 1))
19423 (re (format "^\\*\\{1,%d\\} " level))
19425 (forward-char 1)
19426 (while (> arg 0)
19427 (while (and (re-search-forward re nil 'move)
19428 (setq l (- (match-end 0) (match-beginning 0) 1))
19429 (= l level)
19430 (not invisible-ok)
19431 (progn (backward-char 1) (org-invisible-p)))
19432 (if (< l level) (setq arg 1)))
19433 (setq arg (1- arg)))
19434 (beginning-of-line 1)))
19436 (defun org-backward-same-level (arg &optional invisible-ok)
19437 "Move backward to the arg'th subheading at same level as this one.
19438 Stop at the first and last subheadings of a superior heading."
19439 (interactive "p")
19440 (org-back-to-heading)
19441 (org-on-heading-p)
19442 (let* ((level (- (match-end 0) (match-beginning 0) 1))
19443 (re (format "^\\*\\{1,%d\\} " level))
19445 (while (> arg 0)
19446 (while (and (re-search-backward re nil 'move)
19447 (setq l (- (match-end 0) (match-beginning 0) 1))
19448 (= l level)
19449 (not invisible-ok)
19450 (org-invisible-p))
19451 (if (< l level) (setq arg 1)))
19452 (setq arg (1- arg)))))
19454 (defun org-show-subtree ()
19455 "Show everything after this heading at deeper levels."
19456 (outline-flag-region
19457 (point)
19458 (save-excursion
19459 (org-end-of-subtree t t))
19460 nil))
19462 (defun org-show-entry ()
19463 "Show the body directly following this heading.
19464 Show the heading too, if it is currently invisible."
19465 (interactive)
19466 (save-excursion
19467 (condition-case nil
19468 (progn
19469 (org-back-to-heading t)
19470 (outline-flag-region
19471 (max (point-min) (1- (point)))
19472 (save-excursion
19473 (if (re-search-forward
19474 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
19475 (match-beginning 1)
19476 (point-max)))
19477 nil)
19478 (org-cycle-hide-drawers 'children))
19479 (error nil))))
19481 (defun org-make-options-regexp (kwds &optional extra)
19482 "Make a regular expression for keyword lines."
19483 (concat
19485 "#?[ \t]*\\+\\("
19486 (mapconcat 'regexp-quote kwds "\\|")
19487 (if extra (concat "\\|" extra))
19488 "\\):[ \t]*"
19489 "\\(.*\\)"))
19491 ;; Make isearch reveal the necessary context
19492 (defun org-isearch-end ()
19493 "Reveal context after isearch exits."
19494 (when isearch-success ; only if search was successful
19495 (if (featurep 'xemacs)
19496 ;; Under XEmacs, the hook is run in the correct place,
19497 ;; we directly show the context.
19498 (org-show-context 'isearch)
19499 ;; In Emacs the hook runs *before* restoring the overlays.
19500 ;; So we have to use a one-time post-command-hook to do this.
19501 ;; (Emacs 22 has a special variable, see function `org-mode')
19502 (unless (and (boundp 'isearch-mode-end-hook-quit)
19503 isearch-mode-end-hook-quit)
19504 ;; Only when the isearch was not quitted.
19505 (org-add-hook 'post-command-hook 'org-isearch-post-command
19506 'append 'local)))))
19508 (defun org-isearch-post-command ()
19509 "Remove self from hook, and show context."
19510 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
19511 (org-show-context 'isearch))
19514 ;;;; Integration with and fixes for other packages
19516 ;;; Imenu support
19518 (defvar org-imenu-markers nil
19519 "All markers currently used by Imenu.")
19520 (make-variable-buffer-local 'org-imenu-markers)
19522 (defun org-imenu-new-marker (&optional pos)
19523 "Return a new marker for use by Imenu, and remember the marker."
19524 (let ((m (make-marker)))
19525 (move-marker m (or pos (point)))
19526 (push m org-imenu-markers)
19529 (defun org-imenu-get-tree ()
19530 "Produce the index for Imenu."
19531 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
19532 (setq org-imenu-markers nil)
19533 (let* ((n org-imenu-depth)
19534 (re (concat "^" outline-regexp))
19535 (subs (make-vector (1+ n) nil))
19536 (last-level 0)
19537 m level head)
19538 (save-excursion
19539 (save-restriction
19540 (widen)
19541 (goto-char (point-max))
19542 (while (re-search-backward re nil t)
19543 (setq level (org-reduced-level (funcall outline-level)))
19544 (when (<= level n)
19545 (looking-at org-complex-heading-regexp)
19546 (setq head (org-link-display-format
19547 (org-match-string-no-properties 4))
19548 m (org-imenu-new-marker))
19549 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
19550 (if (>= level last-level)
19551 (push (cons head m) (aref subs level))
19552 (push (cons head (aref subs (1+ level))) (aref subs level))
19553 (loop for i from (1+ level) to n do (aset subs i nil)))
19554 (setq last-level level)))))
19555 (aref subs 1)))
19557 (eval-after-load "imenu"
19558 '(progn
19559 (add-hook 'imenu-after-jump-hook
19560 (lambda ()
19561 (if (eq major-mode 'org-mode)
19562 (org-show-context 'org-goto))))))
19564 (defun org-link-display-format (link)
19565 "Replace a link with either the description, or the link target
19566 if no description is present"
19567 (save-match-data
19568 (if (string-match org-bracket-link-analytic-regexp link)
19569 (replace-match (if (match-end 5)
19570 (match-string 5 link)
19571 (concat (match-string 1 link)
19572 (match-string 3 link)))
19573 nil t link)
19574 link)))
19576 ;; Speedbar support
19578 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
19579 "Overlay marking the agenda restriction line in speedbar.")
19580 (overlay-put org-speedbar-restriction-lock-overlay
19581 'face 'org-agenda-restriction-lock)
19582 (overlay-put org-speedbar-restriction-lock-overlay
19583 'help-echo "Agendas are currently limited to this item.")
19584 (org-detach-overlay org-speedbar-restriction-lock-overlay)
19586 (defun org-speedbar-set-agenda-restriction ()
19587 "Restrict future agenda commands to the location at point in speedbar.
19588 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
19589 (interactive)
19590 (require 'org-agenda)
19591 (let (p m tp np dir txt)
19592 (cond
19593 ((setq p (text-property-any (point-at-bol) (point-at-eol)
19594 'org-imenu t))
19595 (setq m (get-text-property p 'org-imenu-marker))
19596 (with-current-buffer (marker-buffer m)
19597 (goto-char m)
19598 (org-agenda-set-restriction-lock 'subtree)))
19599 ((setq p (text-property-any (point-at-bol) (point-at-eol)
19600 'speedbar-function 'speedbar-find-file))
19601 (setq tp (previous-single-property-change
19602 (1+ p) 'speedbar-function)
19603 np (next-single-property-change
19604 tp 'speedbar-function)
19605 dir (speedbar-line-directory)
19606 txt (buffer-substring-no-properties (or tp (point-min))
19607 (or np (point-max))))
19608 (with-current-buffer (find-file-noselect
19609 (let ((default-directory dir))
19610 (expand-file-name txt)))
19611 (unless (org-mode-p)
19612 (error "Cannot restrict to non-Org-mode file"))
19613 (org-agenda-set-restriction-lock 'file)))
19614 (t (error "Don't know how to restrict Org-mode's agenda")))
19615 (move-overlay org-speedbar-restriction-lock-overlay
19616 (point-at-bol) (point-at-eol))
19617 (setq current-prefix-arg nil)
19618 (org-agenda-maybe-redo)))
19620 (eval-after-load "speedbar"
19621 '(progn
19622 (speedbar-add-supported-extension ".org")
19623 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
19624 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
19625 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
19626 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19627 (add-hook 'speedbar-visiting-tag-hook
19628 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
19630 ;;; Fixes and Hacks for problems with other packages
19632 ;; Make flyspell not check words in links, to not mess up our keymap
19633 (defun org-mode-flyspell-verify ()
19634 "Don't let flyspell put overlays at active buttons."
19635 (and (not (get-text-property (max (1- (point)) (point-min)) 'keymap))
19636 (not (get-text-property (max (1- (point)) (point-min)) 'org-no-flyspell))))
19638 (defun org-remove-flyspell-overlays-in (beg end)
19639 "Remove flyspell overlays in region."
19640 (and (org-bound-and-true-p flyspell-mode)
19641 (fboundp 'flyspell-delete-region-overlays)
19642 (flyspell-delete-region-overlays beg end))
19643 (add-text-properties beg end '(org-no-flyspell t)))
19645 ;; Make `bookmark-jump' shows the jump location if it was hidden.
19646 (eval-after-load "bookmark"
19647 '(if (boundp 'bookmark-after-jump-hook)
19648 ;; We can use the hook
19649 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
19650 ;; Hook not available, use advice
19651 (defadvice bookmark-jump (after org-make-visible activate)
19652 "Make the position visible."
19653 (org-bookmark-jump-unhide))))
19655 ;; Make sure saveplace shows the location if it was hidden
19656 (eval-after-load "saveplace"
19657 '(defadvice save-place-find-file-hook (after org-make-visible activate)
19658 "Make the position visible."
19659 (org-bookmark-jump-unhide)))
19661 ;; Make sure ecb shows the location if it was hidden
19662 (eval-after-load "ecb"
19663 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
19664 "Make hierarchy visible when jumping into location from ECB tree buffer."
19665 (if (eq major-mode 'org-mode)
19666 (org-show-context))))
19668 (defun org-bookmark-jump-unhide ()
19669 "Unhide the current position, to show the bookmark location."
19670 (and (org-mode-p)
19671 (or (org-invisible-p)
19672 (save-excursion (goto-char (max (point-min) (1- (point))))
19673 (org-invisible-p)))
19674 (org-show-context 'bookmark-jump)))
19676 ;; Make session.el ignore our circular variable
19677 (eval-after-load "session"
19678 '(add-to-list 'session-globals-exclude 'org-mark-ring))
19680 ;;;; Experimental code
19682 (defun org-closed-in-range ()
19683 "Sparse tree of items closed in a certain time range.
19684 Still experimental, may disappear in the future."
19685 (interactive)
19686 ;; Get the time interval from the user.
19687 (let* ((time1 (org-float-time
19688 (org-read-date nil 'to-time nil "Starting date: ")))
19689 (time2 (org-float-time
19690 (org-read-date nil 'to-time nil "End date:")))
19691 ;; callback function
19692 (callback (lambda ()
19693 (let ((time
19694 (org-float-time
19695 (apply 'encode-time
19696 (org-parse-time-string
19697 (match-string 1))))))
19698 ;; check if time in interval
19699 (and (>= time time1) (<= time time2))))))
19700 ;; make tree, check each match with the callback
19701 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
19703 ;;;; Finish up
19705 (provide 'org)
19707 (run-hooks 'org-load-hook)
19709 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
19711 ;;; org.el ends here