Release 7.5
[org-mode/org-tableheadings.git] / lisp / org.el
blob92f24065b6452b264e3598201fe246c9254f36c1
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, 2011
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.5
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
79 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
80 (when (fboundp 'defvaralias)
81 (unless (boundp 'calendar-view-holidays-initially-flag)
82 (defvaralias 'calendar-view-holidays-initially-flag
83 'view-calendar-holidays-initially))
84 (unless (boundp 'calendar-view-diary-initially-flag)
85 (defvaralias 'calendar-view-diary-initially-flag
86 'view-diary-entries-initially))
87 (unless (boundp 'diary-fancy-buffer)
88 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
90 (require 'outline) (require 'noutline)
91 ;; Other stuff we need.
92 (require 'time-date)
93 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
94 (require 'easymenu)
95 (require 'overlay)
97 (require 'org-macs)
98 (require 'org-entities)
99 (require 'org-compat)
100 (require 'org-faces)
101 (require 'org-list)
102 (require 'org-pcomplete)
103 (require 'org-src)
104 (require 'org-footnote)
106 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
107 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
108 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
110 ;; babel
111 (require 'ob)
112 (require 'ob-table)
113 (require 'ob-lob)
114 (require 'ob-ref)
115 (require 'ob-tangle)
116 (require 'ob-comint)
117 (require 'ob-keys)
119 ;; load languages based on value of `org-babel-load-languages'
120 (defvar org-babel-load-languages)
121 ;;;###autoload
122 (defun org-babel-do-load-languages (sym value)
123 "Load the languages defined in `org-babel-load-languages'."
124 (set-default sym value)
125 (mapc (lambda (pair)
126 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
127 (if active
128 (progn
129 (require (intern (concat "ob-" lang))))
130 (progn
131 (funcall 'fmakunbound
132 (intern (concat "org-babel-execute:" lang)))
133 (funcall 'fmakunbound
134 (intern (concat "org-babel-expand-body:" lang)))))))
135 org-babel-load-languages))
137 (defcustom org-babel-load-languages '((emacs-lisp . t))
138 "Languages which can be evaluated in Org-mode buffers.
139 This list can be used to load support for any of the languages
140 below, note that each language will depend on a different set of
141 system executables and/or Emacs modes. When a language is
142 \"loaded\", then code blocks in that language can be evaluated
143 with `org-babel-execute-src-block' bound by default to C-c
144 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
145 be set to remove code block evaluation from the C-c C-c
146 keybinding. By default only Emacs Lisp (which has no
147 requirements) is loaded."
148 :group 'org-babel
149 :set 'org-babel-do-load-languages
150 :type '(alist :tag "Babel Languages"
151 :key-type
152 (choice
153 (const :tag "C" C)
154 (const :tag "R" R)
155 (const :tag "Asymptote" asymptote)
156 (const :tag "Calc" calc)
157 (const :tag "Clojure" clojure)
158 (const :tag "CSS" css)
159 (const :tag "Ditaa" ditaa)
160 (const :tag "Dot" dot)
161 (const :tag "Emacs Lisp" emacs-lisp)
162 (const :tag "Gnuplot" gnuplot)
163 (const :tag "Haskell" haskell)
164 (const :tag "Javascript" js)
165 (const :tag "Latex" latex)
166 (const :tag "Ledger" ledger)
167 (const :tag "Matlab" matlab)
168 (const :tag "Mscgen" mscgen)
169 (const :tag "Ocaml" ocaml)
170 (const :tag "Octave" octave)
171 (const :tag "Org" org)
172 (const :tag "Perl" perl)
173 (const :tag "PlantUML" plantuml)
174 (const :tag "Python" python)
175 (const :tag "Ruby" ruby)
176 (const :tag "Sass" sass)
177 (const :tag "Scheme" scheme)
178 (const :tag "Screen" screen)
179 (const :tag "Shell Script" sh)
180 (const :tag "Sql" sql)
181 (const :tag "Sqlite" sqlite))
182 :value-type (boolean :tag "Activate" :value t)))
184 ;;;; Customization variables
185 (defcustom org-clone-delete-id nil
186 "Remove ID property of clones of a subtree.
187 When non-nil, clones of a subtree don't inherit the ID property.
188 Otherwise they inherit the ID property with a new unique
189 identifier."
190 :type 'boolean
191 :group 'org-id)
193 ;;; Version
195 (defconst org-version "7.5"
196 "The version number of the file org.el.")
198 (defun org-version (&optional here)
199 "Show the org-mode version in the echo area.
200 With prefix arg HERE, insert it at point."
201 (interactive "P")
202 (let* ((origin default-directory)
203 (version org-version)
204 (git-version)
205 (dir (concat (file-name-directory (locate-library "org")) "../" )))
206 (when (and (file-exists-p (expand-file-name ".git" dir))
207 (executable-find "git"))
208 (unwind-protect
209 (progn
210 (cd dir)
211 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
212 (with-current-buffer "*Shell Command Output*"
213 (goto-char (point-min))
214 (setq git-version (buffer-substring (point) (point-at-eol))))
215 (subst-char-in-string ?- ?. git-version t)
216 (when (string-match "\\S-"
217 (shell-command-to-string
218 "git diff-index --name-only HEAD --"))
219 (setq git-version (concat git-version ".dirty")))
220 (setq version (concat version " (" git-version ")"))))
221 (cd origin)))
222 (setq version (format "Org-mode version %s" version))
223 (if here (insert version))
224 (message version)))
226 ;;; Compatibility constants
228 ;;; The custom variables
230 (defgroup org nil
231 "Outline-based notes management and organizer."
232 :tag "Org"
233 :group 'outlines
234 :group 'calendar)
236 (defcustom org-mode-hook nil
237 "Mode hook for Org-mode, run after the mode was turned on."
238 :group 'org
239 :type 'hook)
241 (defcustom org-load-hook nil
242 "Hook that is run after org.el has been loaded."
243 :group 'org
244 :type 'hook)
246 (defvar org-modules) ; defined below
247 (defvar org-modules-loaded nil
248 "Have the modules been loaded already?")
250 (defun org-load-modules-maybe (&optional force)
251 "Load all extensions listed in `org-modules'."
252 (when (or force (not org-modules-loaded))
253 (mapc (lambda (ext)
254 (condition-case nil (require ext)
255 (error (message "Problems while trying to load feature `%s'" ext))))
256 org-modules)
257 (setq org-modules-loaded t)))
259 (defun org-set-modules (var value)
260 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
261 (set var value)
262 (when (featurep 'org)
263 (org-load-modules-maybe 'force)))
265 (when (org-bound-and-true-p org-modules)
266 (let ((a (member 'org-infojs org-modules)))
267 (and a (setcar a 'org-jsinfo))))
269 (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)
270 "Modules that should always be loaded together with org.el.
271 If a description starts with <C>, the file is not part of Emacs
272 and loading it will require that you have downloaded and properly installed
273 the org-mode distribution.
275 You can also use this system to load external packages (i.e. neither Org
276 core modules, nor modules from the CONTRIB directory). Just add symbols
277 to the end of the list. If the package is called org-xyz.el, then you need
278 to add the symbol `xyz', and the package must have a call to
280 (provide 'org-xyz)"
281 :group 'org
282 :set 'org-set-modules
283 :type
284 '(set :greedy t
285 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
286 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
287 (const :tag " crypt: Encryption of subtrees" org-crypt)
288 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
289 (const :tag " docview: Links to doc-view buffers" org-docview)
290 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
291 (const :tag " id: Global IDs for identifying entries" org-id)
292 (const :tag " info: Links to Info nodes" org-info)
293 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
294 (const :tag " habit: Track your consistency with habits" org-habit)
295 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
296 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
297 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
298 (const :tag " mew Links to Mew folders/messages" org-mew)
299 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
300 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
301 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
302 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
303 (const :tag " vm: Links to VM folders/messages" org-vm)
304 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
305 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
306 (const :tag " mouse: Additional mouse support" org-mouse)
307 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
309 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
310 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
311 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
312 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
313 (const :tag "C collector: Collect properties into tables" org-collector)
314 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
315 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
316 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
317 (const :tag "C eval: Include command output as text" org-eval)
318 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
319 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
320 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
321 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
322 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
324 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
326 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
327 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
328 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
329 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
330 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
331 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
332 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
333 (const :tag "C mtags: Support for muse-like tags" org-mtags)
334 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
335 (const :tag "C registry: A registry for Org-mode links" org-registry)
336 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
337 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
338 (const :tag "C secretary: Team management with org-mode" org-secretary)
339 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
340 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
341 (const :tag "C track: Keep up with Org-mode development" org-track)
342 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
343 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
344 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
346 (defcustom org-support-shift-select nil
347 "Non-nil means make shift-cursor commands select text when possible.
349 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
350 selecting a region, or enlarge regions started in this way.
351 In Org-mode, in special contexts, these same keys are used for other
352 purposes, important enough to compete with shift selection. Org tries
353 to balance these needs by supporting `shift-select-mode' outside these
354 special contexts, under control of this variable.
356 The default of this variable is nil, to avoid confusing behavior. Shifted
357 cursor keys will then execute Org commands in the following contexts:
358 - on a headline, changing TODO state (left/right) and priority (up/down)
359 - on a time stamp, changing the time
360 - in a plain list item, changing the bullet type
361 - in a property definition line, switching between allowed values
362 - in the BEGIN line of a clock table (changing the time block).
363 Outside these contexts, the commands will throw an error.
365 When this variable is t and the cursor is not in a special context,
366 Org-mode will support shift-selection for making and enlarging regions.
367 To make this more effective, the bullet cycling will no longer happen
368 anywhere in an item line, but only if the cursor is exactly on the bullet.
370 If you set this variable to the symbol `always', then the keys
371 will not be special in headlines, property lines, and item lines, to make
372 shift selection work there as well. If this is what you want, you can
373 use the following alternative commands: `C-c C-t' and `C-c ,' to
374 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
375 TODO sets, `C-c -' to cycle item bullet types, and properties can be
376 edited by hand or in column view.
378 However, when the cursor is on a timestamp, shift-cursor commands
379 will still edit the time stamp - this is just too good to give up.
381 XEmacs user should have this variable set to nil, because shift-select-mode
382 is Emacs 23 only."
383 :group 'org
384 :type '(choice
385 (const :tag "Never" nil)
386 (const :tag "When outside special context" t)
387 (const :tag "Everywhere except timestamps" always)))
389 (defgroup org-startup nil
390 "Options concerning startup of Org-mode."
391 :tag "Org Startup"
392 :group 'org)
394 (defcustom org-startup-folded t
395 "Non-nil means entering Org-mode will switch to OVERVIEW.
396 This can also be configured on a per-file basis by adding one of
397 the following lines anywhere in the buffer:
399 #+STARTUP: fold (or `overview', this is equivalent)
400 #+STARTUP: nofold (or `showall', this is equivalent)
401 #+STARTUP: content
402 #+STARTUP: showeverything"
403 :group 'org-startup
404 :type '(choice
405 (const :tag "nofold: show all" nil)
406 (const :tag "fold: overview" t)
407 (const :tag "content: all headlines" content)
408 (const :tag "show everything, even drawers" showeverything)))
410 (defcustom org-startup-truncated t
411 "Non-nil means entering Org-mode will set `truncate-lines'.
412 This is useful since some lines containing links can be very long and
413 uninteresting. Also tables look terrible when wrapped."
414 :group 'org-startup
415 :type 'boolean)
417 (defcustom org-startup-indented nil
418 "Non-nil means turn on `org-indent-mode' on startup.
419 This can also be configured on a per-file basis by adding one of
420 the following lines anywhere in the buffer:
422 #+STARTUP: indent
423 #+STARTUP: noindent"
424 :group 'org-structure
425 :type '(choice
426 (const :tag "Not" nil)
427 (const :tag "Globally (slow on startup in large files)" t)))
429 (defcustom org-use-sub-superscripts t
430 "Non-nil means interpret \"_\" and \"^\" for export.
431 When this option is turned on, you can use TeX-like syntax for sub- and
432 superscripts. Several characters after \"_\" or \"^\" will be
433 considered as a single item - so grouping with {} is normally not
434 needed. For example, the following things will be parsed as single
435 sub- or superscripts.
437 10^24 or 10^tau several digits will be considered 1 item.
438 10^-12 or 10^-tau a leading sign with digits or a word
439 x^2-y^3 will be read as x^2 - y^3, because items are
440 terminated by almost any nonword/nondigit char.
441 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
443 Still, ambiguity is possible - so when in doubt use {} to enclose the
444 sub/superscript. If you set this variable to the symbol `{}',
445 the braces are *required* in order to trigger interpretations as
446 sub/superscript. This can be helpful in documents that need \"_\"
447 frequently in plain text.
449 Not all export backends support this, but HTML does.
451 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
452 :group 'org-startup
453 :group 'org-export-translation
454 :type '(choice
455 (const :tag "Always interpret" t)
456 (const :tag "Only with braces" {})
457 (const :tag "Never interpret" nil)))
459 (if (fboundp 'defvaralias)
460 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
463 (defcustom org-startup-with-beamer-mode nil
464 "Non-nil means turn on `org-beamer-mode' on startup.
465 This can also be configured on a per-file basis by adding one of
466 the following lines anywhere in the buffer:
468 #+STARTUP: beamer"
469 :group 'org-startup
470 :type 'boolean)
472 (defcustom org-startup-align-all-tables nil
473 "Non-nil means align all tables when visiting a file.
474 This is useful when the column width in tables is forced with <N> cookies
475 in table fields. Such tables will look correct only after the first re-align.
476 This can also be configured on a per-file basis by adding one of
477 the following lines anywhere in the buffer:
478 #+STARTUP: align
479 #+STARTUP: noalign"
480 :group 'org-startup
481 :type 'boolean)
483 (defcustom org-startup-with-inline-images nil
484 "Non-nil means show inline images when loading a new Org file.
485 This can also be configured on a per-file basis by adding one of
486 the following lines anywhere in the buffer:
487 #+STARTUP: inlineimages
488 #+STARTUP: noinlineimages"
489 :group 'org-startup
490 :type 'boolean)
492 (defcustom org-insert-mode-line-in-empty-file nil
493 "Non-nil means insert the first line setting Org-mode in empty files.
494 When the function `org-mode' is called interactively in an empty file, this
495 normally means that the file name does not automatically trigger Org-mode.
496 To ensure that the file will always be in Org-mode in the future, a
497 line enforcing Org-mode will be inserted into the buffer, if this option
498 has been set."
499 :group 'org-startup
500 :type 'boolean)
502 (defcustom org-replace-disputed-keys nil
503 "Non-nil means use alternative key bindings for some keys.
504 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
505 These keys are also used by other packages like shift-selection-mode'
506 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
507 If you want to use Org-mode together with one of these other modes,
508 or more generally if you would like to move some Org-mode commands to
509 other keys, set this variable and configure the keys with the variable
510 `org-disputed-keys'.
512 This option is only relevant at load-time of Org-mode, and must be set
513 *before* org.el is loaded. Changing it requires a restart of Emacs to
514 become effective."
515 :group 'org-startup
516 :type 'boolean)
518 (defcustom org-use-extra-keys nil
519 "Non-nil means use extra key sequence definitions for certain commands.
520 This happens automatically if you run XEmacs or if `window-system'
521 is nil. This variable lets you do the same manually. You must
522 set it before loading org.
524 Example: on Carbon Emacs 22 running graphically, with an external
525 keyboard on a Powerbook, the default way of setting M-left might
526 not work for either Alt or ESC. Setting this variable will make
527 it work for ESC."
528 :group 'org-startup
529 :type 'boolean)
531 (if (fboundp 'defvaralias)
532 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
534 (defcustom org-disputed-keys
535 '(([(shift up)] . [(meta p)])
536 ([(shift down)] . [(meta n)])
537 ([(shift left)] . [(meta -)])
538 ([(shift right)] . [(meta +)])
539 ([(control shift right)] . [(meta shift +)])
540 ([(control shift left)] . [(meta shift -)]))
541 "Keys for which Org-mode and other modes compete.
542 This is an alist, cars are the default keys, second element specifies
543 the alternative to use when `org-replace-disputed-keys' is t.
545 Keys can be specified in any syntax supported by `define-key'.
546 The value of this option takes effect only at Org-mode's startup,
547 therefore you'll have to restart Emacs to apply it after changing."
548 :group 'org-startup
549 :type 'alist)
551 (defun org-key (key)
552 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
553 Or return the original if not disputed.
554 Also apply the translations defined in `org-xemacs-key-equivalents'."
555 (when org-replace-disputed-keys
556 (let* ((nkey (key-description key))
557 (x (org-find-if (lambda (x)
558 (equal (key-description (car x)) nkey))
559 org-disputed-keys)))
560 (setq key (if x (cdr x) key))))
561 (when (featurep 'xemacs)
562 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
563 key)
565 (defun org-find-if (predicate seq)
566 (catch 'exit
567 (while seq
568 (if (funcall predicate (car seq))
569 (throw 'exit (car seq))
570 (pop seq)))))
572 (defun org-defkey (keymap key def)
573 "Define a key, possibly translated, as returned by `org-key'."
574 (define-key keymap (org-key key) def))
576 (defcustom org-ellipsis nil
577 "The ellipsis to use in the Org-mode outline.
578 When nil, just use the standard three dots. When a string, use that instead,
579 When a face, use the standard 3 dots, but with the specified face.
580 The change affects only Org-mode (which will then use its own display table).
581 Changing this requires executing `M-x org-mode' in a buffer to become
582 effective."
583 :group 'org-startup
584 :type '(choice (const :tag "Default" nil)
585 (face :tag "Face" :value org-warning)
586 (string :tag "String" :value "...#")))
588 (defvar org-display-table nil
589 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
591 (defgroup org-keywords nil
592 "Keywords in Org-mode."
593 :tag "Org Keywords"
594 :group 'org)
596 (defcustom org-deadline-string "DEADLINE:"
597 "String to mark deadline entries.
598 A deadline is this string, followed by a time stamp. Should be a word,
599 terminated by a colon. You can insert a schedule keyword and
600 a timestamp with \\[org-deadline].
601 Changes become only effective after restarting Emacs."
602 :group 'org-keywords
603 :type 'string)
605 (defcustom org-scheduled-string "SCHEDULED:"
606 "String to mark scheduled TODO entries.
607 A schedule is this string, followed by a time stamp. Should be a word,
608 terminated by a colon. You can insert a schedule keyword and
609 a timestamp with \\[org-schedule].
610 Changes become only effective after restarting Emacs."
611 :group 'org-keywords
612 :type 'string)
614 (defcustom org-closed-string "CLOSED:"
615 "String used as the prefix for timestamps logging closing a TODO entry."
616 :group 'org-keywords
617 :type 'string)
619 (defcustom org-clock-string "CLOCK:"
620 "String used as prefix for timestamps clocking work hours on an item."
621 :group 'org-keywords
622 :type 'string)
624 (defcustom org-comment-string "COMMENT"
625 "Entries starting with this keyword will never be exported.
626 An entry can be toggled between COMMENT and normal with
627 \\[org-toggle-comment].
628 Changes become only effective after restarting Emacs."
629 :group 'org-keywords
630 :type 'string)
632 (defcustom org-quote-string "QUOTE"
633 "Entries starting with this keyword will be exported in fixed-width font.
634 Quoting applies only to the text in the entry following the headline, and does
635 not extend beyond the next headline, even if that is lower level.
636 An entry can be toggled between QUOTE and normal with
637 \\[org-toggle-fixed-width-section]."
638 :group 'org-keywords
639 :type 'string)
641 (defconst org-repeat-re
642 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
643 "Regular expression for specifying repeated events.
644 After a match, group 1 contains the repeat expression.")
646 (defgroup org-structure nil
647 "Options concerning the general structure of Org-mode files."
648 :tag "Org Structure"
649 :group 'org)
651 (defgroup org-reveal-location nil
652 "Options about how to make context of a location visible."
653 :tag "Org Reveal Location"
654 :group 'org-structure)
656 (defconst org-context-choice
657 '(choice
658 (const :tag "Always" t)
659 (const :tag "Never" nil)
660 (repeat :greedy t :tag "Individual contexts"
661 (cons
662 (choice :tag "Context"
663 (const agenda)
664 (const org-goto)
665 (const occur-tree)
666 (const tags-tree)
667 (const link-search)
668 (const mark-goto)
669 (const bookmark-jump)
670 (const isearch)
671 (const default))
672 (boolean))))
673 "Contexts for the reveal options.")
675 (defcustom org-show-hierarchy-above '((default . t))
676 "Non-nil means show full hierarchy when revealing a location.
677 Org-mode often shows locations in an org-mode file which might have
678 been invisible before. When this is set, the hierarchy of headings
679 above the exposed location is shown.
680 Turning this off for example for sparse trees makes them very compact.
681 Instead of t, this can also be an alist specifying this option for different
682 contexts. Valid contexts are
683 agenda when exposing an entry from the agenda
684 org-goto when using the command `org-goto' on key C-c C-j
685 occur-tree when using the command `org-occur' on key C-c /
686 tags-tree when constructing a sparse tree based on tags matches
687 link-search when exposing search matches associated with a link
688 mark-goto when exposing the jump goal of a mark
689 bookmark-jump when exposing a bookmark location
690 isearch when exiting from an incremental search
691 default default for all contexts not set explicitly"
692 :group 'org-reveal-location
693 :type org-context-choice)
695 (defcustom org-show-following-heading '((default . nil))
696 "Non-nil means show following heading when revealing a location.
697 Org-mode often shows locations in an org-mode file which might have
698 been invisible before. When this is set, the heading following the
699 match is shown.
700 Turning this off for example for sparse trees makes them very compact,
701 but makes it harder to edit the location of the match. In such a case,
702 use the command \\[org-reveal] to show more context.
703 Instead of t, this can also be an alist specifying this option for different
704 contexts. See `org-show-hierarchy-above' for valid contexts."
705 :group 'org-reveal-location
706 :type org-context-choice)
708 (defcustom org-show-siblings '((default . nil) (isearch t))
709 "Non-nil means show all sibling heading when revealing a location.
710 Org-mode often shows locations in an org-mode file which might have
711 been invisible before. When this is set, the sibling of the current entry
712 heading are all made visible. If `org-show-hierarchy-above' is t,
713 the same happens on each level of the hierarchy above the current entry.
715 By default this is on for the isearch context, off for all other contexts.
716 Turning this off for example for sparse trees makes them very compact,
717 but makes it harder to edit the location of the match. In such a case,
718 use the command \\[org-reveal] to show more context.
719 Instead of t, this can also be an alist specifying this option for different
720 contexts. See `org-show-hierarchy-above' for valid contexts."
721 :group 'org-reveal-location
722 :type org-context-choice)
724 (defcustom org-show-entry-below '((default . nil))
725 "Non-nil means show the entry below a headline when revealing a location.
726 Org-mode often shows locations in an org-mode file which might have
727 been invisible before. When this is set, the text below the headline that is
728 exposed is also shown.
730 By default this is off for all contexts.
731 Instead of t, this can also be an alist specifying this option for different
732 contexts. See `org-show-hierarchy-above' for valid contexts."
733 :group 'org-reveal-location
734 :type org-context-choice)
736 (defcustom org-indirect-buffer-display 'other-window
737 "How should indirect tree buffers be displayed?
738 This applies to indirect buffers created with the commands
739 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
740 Valid values are:
741 current-window Display in the current window
742 other-window Just display in another window.
743 dedicated-frame Create one new frame, and re-use it each time.
744 new-frame Make a new frame each time. Note that in this case
745 previously-made indirect buffers are kept, and you need to
746 kill these buffers yourself."
747 :group 'org-structure
748 :group 'org-agenda-windows
749 :type '(choice
750 (const :tag "In current window" current-window)
751 (const :tag "In current frame, other window" other-window)
752 (const :tag "Each time a new frame" new-frame)
753 (const :tag "One dedicated frame" dedicated-frame)))
755 (defcustom org-use-speed-commands nil
756 "Non-nil means activate single letter commands at beginning of a headline.
757 This may also be a function to test for appropriate locations where speed
758 commands should be active."
759 :group 'org-structure
760 :type '(choice
761 (const :tag "Never" nil)
762 (const :tag "At beginning of headline stars" t)
763 (function)))
765 (defcustom org-speed-commands-user nil
766 "Alist of additional speed commands.
767 This list will be checked before `org-speed-commands-default'
768 when the variable `org-use-speed-commands' is non-nil
769 and when the cursor is at the beginning of a headline.
770 The car if each entry is a string with a single letter, which must
771 be assigned to `self-insert-command' in the global map.
772 The cdr is either a command to be called interactively, a function
773 to be called, or a form to be evaluated.
774 An entry that is just a list with a single string will be interpreted
775 as a descriptive headline that will be added when listing the speed
776 commands in the Help buffer using the `?' speed command."
777 :group 'org-structure
778 :type '(repeat :value ("k" . ignore)
779 (choice :value ("k" . ignore)
780 (list :tag "Descriptive Headline" (string :tag "Headline"))
781 (cons :tag "Letter and Command"
782 (string :tag "Command letter")
783 (choice
784 (function)
785 (sexp))))))
787 (defgroup org-cycle nil
788 "Options concerning visibility cycling in Org-mode."
789 :tag "Org Cycle"
790 :group 'org-structure)
792 (defcustom org-cycle-skip-children-state-if-no-children t
793 "Non-nil means skip CHILDREN state in entries that don't have any."
794 :group 'org-cycle
795 :type 'boolean)
797 (defcustom org-cycle-max-level nil
798 "Maximum level which should still be subject to visibility cycling.
799 Levels higher than this will, for cycling, be treated as text, not a headline.
800 When `org-odd-levels-only' is set, a value of N in this variable actually
801 means 2N-1 stars as the limiting headline.
802 When nil, cycle all levels.
803 Note that the limiting level of cycling is also influenced by
804 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
805 `org-inlinetask-min-level' is, cycling will be limited to levels one less
806 than its value."
807 :group 'org-cycle
808 :type '(choice
809 (const :tag "No limit" nil)
810 (integer :tag "Maximum level")))
812 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
813 "Names of drawers. Drawers are not opened by cycling on the headline above.
814 Drawers only open with a TAB on the drawer line itself. A drawer looks like
815 this:
816 :DRAWERNAME:
817 .....
818 :END:
819 The drawer \"PROPERTIES\" is special for capturing properties through
820 the property API.
822 Drawers can be defined on the per-file basis with a line like:
824 #+DRAWERS: HIDDEN STATE PROPERTIES"
825 :group 'org-structure
826 :group 'org-cycle
827 :type '(repeat (string :tag "Drawer Name")))
829 (defcustom org-hide-block-startup nil
830 "Non-nil means entering Org-mode will fold all blocks.
831 This can also be set in on a per-file basis with
833 #+STARTUP: hideblocks
834 #+STARTUP: showblocks"
835 :group 'org-startup
836 :group 'org-cycle
837 :type 'boolean)
839 (defcustom org-cycle-global-at-bob nil
840 "Cycle globally if cursor is at beginning of buffer and not at a headline.
841 This makes it possible to do global cycling without having to use S-TAB or
842 \\[universal-argument] TAB. For this special case to work, the first line \
843 of the buffer
844 must not be a headline - it may be empty or some other text. When used in
845 this way, `org-cycle-hook' is disables temporarily, to make sure the
846 cursor stays at the beginning of the buffer.
847 When this option is nil, don't do anything special at the beginning
848 of the buffer."
849 :group 'org-cycle
850 :type 'boolean)
852 (defcustom org-cycle-level-after-item/entry-creation t
853 "Non-nil means cycle entry level or item indentation in new empty entries.
855 When the cursor is at the end of an empty headline, i.e with only stars
856 and maybe a TODO keyword, TAB will then switch the entry to become a child,
857 and then all possible ancestor states, before returning to the original state.
858 This makes data entry extremely fast: M-RET to create a new headline,
859 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
861 When the cursor is at the end of an empty plain list item, one TAB will
862 make it a subitem, two or more tabs will back up to make this an item
863 higher up in the item hierarchy."
864 :group 'org-cycle
865 :type 'boolean)
867 (defcustom org-cycle-emulate-tab t
868 "Where should `org-cycle' emulate TAB.
869 nil Never
870 white Only in completely white lines
871 whitestart Only at the beginning of lines, before the first non-white char
872 t Everywhere except in headlines
873 exc-hl-bol Everywhere except at the start of a headline
874 If TAB is used in a place where it does not emulate TAB, the current subtree
875 visibility is cycled."
876 :group 'org-cycle
877 :type '(choice (const :tag "Never" nil)
878 (const :tag "Only in completely white lines" white)
879 (const :tag "Before first char in a line" whitestart)
880 (const :tag "Everywhere except in headlines" t)
881 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
884 (defcustom org-cycle-separator-lines 2
885 "Number of empty lines needed to keep an empty line between collapsed trees.
886 If you leave an empty line between the end of a subtree and the following
887 headline, this empty line is hidden when the subtree is folded.
888 Org-mode will leave (exactly) one empty line visible if the number of
889 empty lines is equal or larger to the number given in this variable.
890 So the default 2 means at least 2 empty lines after the end of a subtree
891 are needed to produce free space between a collapsed subtree and the
892 following headline.
894 If the number is negative, and the number of empty lines is at least -N,
895 all empty lines are shown.
897 Special case: when 0, never leave empty lines in collapsed view."
898 :group 'org-cycle
899 :type 'integer)
900 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
902 (defcustom org-pre-cycle-hook nil
903 "Hook that is run before visibility cycling is happening.
904 The function(s) in this hook must accept a single argument which indicates
905 the new state that will be set right after running this hook. The
906 argument is a symbol. Before a global state change, it can have the values
907 `overview', `content', or `all'. Before a local state change, it can have
908 the values `folded', `children', or `subtree'."
909 :group 'org-cycle
910 :type 'hook)
912 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
913 org-cycle-hide-drawers
914 org-cycle-show-empty-lines
915 org-optimize-window-after-visibility-change)
916 "Hook that is run after `org-cycle' has changed the buffer visibility.
917 The function(s) in this hook must accept a single argument which indicates
918 the new state that was set by the most recent `org-cycle' command. The
919 argument is a symbol. After a global state change, it can have the values
920 `overview', `content', or `all'. After a local state change, it can have
921 the values `folded', `children', or `subtree'."
922 :group 'org-cycle
923 :type 'hook)
925 (defgroup org-edit-structure nil
926 "Options concerning structure editing in Org-mode."
927 :tag "Org Edit Structure"
928 :group 'org-structure)
930 (defcustom org-odd-levels-only nil
931 "Non-nil means skip even levels and only use odd levels for the outline.
932 This has the effect that two stars are being added/taken away in
933 promotion/demotion commands. It also influences how levels are
934 handled by the exporters.
935 Changing it requires restart of `font-lock-mode' to become effective
936 for fontification also in regions already fontified.
937 You may also set this on a per-file basis by adding one of the following
938 lines to the buffer:
940 #+STARTUP: odd
941 #+STARTUP: oddeven"
942 :group 'org-edit-structure
943 :group 'org-appearance
944 :type 'boolean)
946 (defcustom org-adapt-indentation t
947 "Non-nil means adapt indentation to outline node level.
949 When this variable is set, Org assumes that you write outlines by
950 indenting text in each node to align with the headline (after the stars).
951 The following issues are influenced by this variable:
953 - When this is set and the *entire* text in an entry is indented, the
954 indentation is increased by one space in a demotion command, and
955 decreased by one in a promotion command. If any line in the entry
956 body starts with text at column 0, indentation is not changed at all.
958 - Property drawers and planning information is inserted indented when
959 this variable s set. When nil, they will not be indented.
961 - TAB indents a line relative to context. The lines below a headline
962 will be indented when this variable is set.
964 Note that this is all about true indentation, by adding and removing
965 space characters. See also `org-indent.el' which does level-dependent
966 indentation in a virtual way, i.e. at display time in Emacs."
967 :group 'org-edit-structure
968 :type 'boolean)
970 (defcustom org-special-ctrl-a/e nil
971 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
973 When t, `C-a' will bring back the cursor to the beginning of the
974 headline text, i.e. after the stars and after a possible TODO keyword.
975 In an item, this will be the position after the bullet.
976 When the cursor is already at that position, another `C-a' will bring
977 it to the beginning of the line.
979 `C-e' will jump to the end of the headline, ignoring the presence of tags
980 in the headline. A second `C-e' will then jump to the true end of the
981 line, after any tags. This also means that, when this variable is
982 non-nil, `C-e' also will never jump beyond the end of the heading of a
983 folded section, i.e. not after the ellipses.
985 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
986 going to the true line boundary first. Only a directly following, identical
987 keypress will bring the cursor to the special positions.
989 This may also be a cons cell where the behavior for `C-a' and `C-e' is
990 set separately."
991 :group 'org-edit-structure
992 :type '(choice
993 (const :tag "off" nil)
994 (const :tag "on: after stars/bullet and before tags first" t)
995 (const :tag "reversed: true line boundary first" reversed)
996 (cons :tag "Set C-a and C-e separately"
997 (choice :tag "Special C-a"
998 (const :tag "off" nil)
999 (const :tag "on: after stars/bullet first" t)
1000 (const :tag "reversed: before stars/bullet first" reversed))
1001 (choice :tag "Special C-e"
1002 (const :tag "off" nil)
1003 (const :tag "on: before tags first" t)
1004 (const :tag "reversed: after tags first" reversed)))))
1005 (if (fboundp 'defvaralias)
1006 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1008 (defcustom org-special-ctrl-k nil
1009 "Non-nil means `C-k' will behave specially in headlines.
1010 When nil, `C-k' will call the default `kill-line' command.
1011 When t, the following will happen while the cursor is in the headline:
1013 - When the cursor is at the beginning of a headline, kill the entire
1014 line and possible the folded subtree below the line.
1015 - When in the middle of the headline text, kill the headline up to the tags.
1016 - When after the headline text, kill the tags."
1017 :group 'org-edit-structure
1018 :type 'boolean)
1020 (defcustom org-ctrl-k-protect-subtree nil
1021 "Non-nil means, do not delete a hidden subtree with C-k.
1022 When set to the symbol `error', simply throw an error when C-k is
1023 used to kill (part-of) a headline that has hidden text behind it.
1024 Any other non-nil value will result in a query to the user, if it is
1025 OK to kill that hidden subtree. When nil, kill without remorse."
1026 :group 'org-edit-structure
1027 :type '(choice
1028 (const :tag "Do not protect hidden subtrees" nil)
1029 (const :tag "Protect hidden subtrees with a security query" t)
1030 (const :tag "Never kill a hidden subtree with C-k" error)))
1032 (defcustom org-yank-folded-subtrees t
1033 "Non-nil means when yanking subtrees, fold them.
1034 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1035 it starts with a heading and all other headings in it are either children
1036 or siblings, then fold all the subtrees. However, do this only if no
1037 text after the yank would be swallowed into a folded tree by this action."
1038 :group 'org-edit-structure
1039 :type 'boolean)
1041 (defcustom org-yank-adjusted-subtrees nil
1042 "Non-nil means when yanking subtrees, adjust the level.
1043 With this setting, `org-paste-subtree' is used to insert the subtree, see
1044 this function for details."
1045 :group 'org-edit-structure
1046 :type 'boolean)
1048 (defcustom org-M-RET-may-split-line '((default . t))
1049 "Non-nil means M-RET will split the line at the cursor position.
1050 When nil, it will go to the end of the line before making a
1051 new line.
1052 You may also set this option in a different way for different
1053 contexts. Valid contexts are:
1055 headline when creating a new headline
1056 item when creating a new item
1057 table in a table field
1058 default the value to be used for all contexts not explicitly
1059 customized"
1060 :group 'org-structure
1061 :group 'org-table
1062 :type '(choice
1063 (const :tag "Always" t)
1064 (const :tag "Never" nil)
1065 (repeat :greedy t :tag "Individual contexts"
1066 (cons
1067 (choice :tag "Context"
1068 (const headline)
1069 (const item)
1070 (const table)
1071 (const default))
1072 (boolean)))))
1075 (defcustom org-insert-heading-respect-content nil
1076 "Non-nil means insert new headings after the current subtree.
1077 When nil, the new heading is created directly after the current line.
1078 The commands \\[org-insert-heading-respect-content] and
1079 \\[org-insert-todo-heading-respect-content] turn this variable on
1080 for the duration of the command."
1081 :group 'org-structure
1082 :type 'boolean)
1084 (defcustom org-blank-before-new-entry '((heading . auto)
1085 (plain-list-item . auto))
1086 "Should `org-insert-heading' leave a blank line before new heading/item?
1087 The value is an alist, with `heading' and `plain-list-item' as car,
1088 and a boolean flag as cdr. The cdr may also be the symbol `auto', and then
1089 Org will look at the surrounding headings/items and try to make an
1090 intelligent decision whether to insert a blank line or not.
1092 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1093 set, the setting here is ignored and no empty line is inserted, to avoid
1094 breaking the list structure."
1095 :group 'org-edit-structure
1096 :type '(list
1097 (cons (const heading)
1098 (choice (const :tag "Never" nil)
1099 (const :tag "Always" t)
1100 (const :tag "Auto" auto)))
1101 (cons (const plain-list-item)
1102 (choice (const :tag "Never" nil)
1103 (const :tag "Always" t)
1104 (const :tag "Auto" auto)))))
1106 (defcustom org-insert-heading-hook nil
1107 "Hook being run after inserting a new heading."
1108 :group 'org-edit-structure
1109 :type 'hook)
1111 (defcustom org-enable-fixed-width-editor t
1112 "Non-nil means lines starting with \":\" are treated as fixed-width.
1113 This currently only means they are never auto-wrapped.
1114 When nil, such lines will be treated like ordinary lines.
1115 See also the QUOTE keyword."
1116 :group 'org-edit-structure
1117 :type 'boolean)
1119 (defcustom org-goto-auto-isearch t
1120 "Non-nil means typing characters in `org-goto' starts incremental search."
1121 :group 'org-edit-structure
1122 :type 'boolean)
1124 (defgroup org-sparse-trees nil
1125 "Options concerning sparse trees in Org-mode."
1126 :tag "Org Sparse Trees"
1127 :group 'org-structure)
1129 (defcustom org-highlight-sparse-tree-matches t
1130 "Non-nil means highlight all matches that define a sparse tree.
1131 The highlights will automatically disappear the next time the buffer is
1132 changed by an edit command."
1133 :group 'org-sparse-trees
1134 :type 'boolean)
1136 (defcustom org-remove-highlights-with-change t
1137 "Non-nil means any change to the buffer will remove temporary highlights.
1138 Such highlights are created by `org-occur' and `org-clock-display'.
1139 When nil, `C-c C-c needs to be used to get rid of the highlights.
1140 The highlights created by `org-preview-latex-fragment' always need
1141 `C-c C-c' to be removed."
1142 :group 'org-sparse-trees
1143 :group 'org-time
1144 :type 'boolean)
1147 (defcustom org-occur-hook '(org-first-headline-recenter)
1148 "Hook that is run after `org-occur' has constructed a sparse tree.
1149 This can be used to recenter the window to show as much of the structure
1150 as possible."
1151 :group 'org-sparse-trees
1152 :type 'hook)
1154 (defgroup org-imenu-and-speedbar nil
1155 "Options concerning imenu and speedbar in Org-mode."
1156 :tag "Org Imenu and Speedbar"
1157 :group 'org-structure)
1159 (defcustom org-imenu-depth 2
1160 "The maximum level for Imenu access to Org-mode headlines.
1161 This also applied for speedbar access."
1162 :group 'org-imenu-and-speedbar
1163 :type 'integer)
1165 (defgroup org-table nil
1166 "Options concerning tables in Org-mode."
1167 :tag "Org Table"
1168 :group 'org)
1170 (defcustom org-enable-table-editor 'optimized
1171 "Non-nil means lines starting with \"|\" are handled by the table editor.
1172 When nil, such lines will be treated like ordinary lines.
1174 When equal to the symbol `optimized', the table editor will be optimized to
1175 do the following:
1176 - Automatic overwrite mode in front of whitespace in table fields.
1177 This makes the structure of the table stay in tact as long as the edited
1178 field does not exceed the column width.
1179 - Minimize the number of realigns. Normally, the table is aligned each time
1180 TAB or RET are pressed to move to another field. With optimization this
1181 happens only if changes to a field might have changed the column width.
1182 Optimization requires replacing the functions `self-insert-command',
1183 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1184 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1185 very good at guessing when a re-align will be necessary, but you can always
1186 force one with \\[org-ctrl-c-ctrl-c].
1188 If you would like to use the optimized version in Org-mode, but the
1189 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1191 This variable can be used to turn on and off the table editor during a session,
1192 but in order to toggle optimization, a restart is required.
1194 See also the variable `org-table-auto-blank-field'."
1195 :group 'org-table
1196 :type '(choice
1197 (const :tag "off" nil)
1198 (const :tag "on" t)
1199 (const :tag "on, optimized" optimized)))
1201 (defcustom org-self-insert-cluster-for-undo t
1202 "Non-nil means cluster self-insert commands for undo when possible.
1203 If this is set, then, like in the Emacs command loop, 20 consecutive
1204 characters will be undone together.
1205 This is configurable, because there is some impact on typing performance."
1206 :group 'org-table
1207 :type 'boolean)
1209 (defcustom org-table-tab-recognizes-table.el t
1210 "Non-nil means TAB will automatically notice a table.el table.
1211 When it sees such a table, it moves point into it and - if necessary -
1212 calls `table-recognize-table'."
1213 :group 'org-table-editing
1214 :type 'boolean)
1216 (defgroup org-link nil
1217 "Options concerning links in Org-mode."
1218 :tag "Org Link"
1219 :group 'org)
1221 (defvar org-link-abbrev-alist-local nil
1222 "Buffer-local version of `org-link-abbrev-alist', which see.
1223 The value of this is taken from the #+LINK lines.")
1224 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1226 (defcustom org-link-abbrev-alist nil
1227 "Alist of link abbreviations.
1228 The car of each element is a string, to be replaced at the start of a link.
1229 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1230 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1232 [[linkkey:tag][description]]
1234 The 'linkkey' must be a word word, starting with a letter, followed
1235 by letters, numbers, '-' or '_'.
1237 If REPLACE is a string, the tag will simply be appended to create the link.
1238 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1239 the placeholder \"%h\" will cause a url-encoded version of the tag to
1240 be inserted at that point (see the function `url-hexify-string').
1242 REPLACE may also be a function that will be called with the tag as the
1243 only argument to create the link, which should be returned as a string.
1245 See the manual for examples."
1246 :group 'org-link
1247 :type '(repeat
1248 (cons
1249 (string :tag "Protocol")
1250 (choice
1251 (string :tag "Format")
1252 (function)))))
1254 (defcustom org-descriptive-links t
1255 "Non-nil means hide link part and only show description of bracket links.
1256 Bracket links are like [[link][description]]. This variable sets the initial
1257 state in new org-mode buffers. The setting can then be toggled on a
1258 per-buffer basis from the Org->Hyperlinks menu."
1259 :group 'org-link
1260 :type 'boolean)
1262 (defcustom org-link-file-path-type 'adaptive
1263 "How the path name in file links should be stored.
1264 Valid values are:
1266 relative Relative to the current directory, i.e. the directory of the file
1267 into which the link is being inserted.
1268 absolute Absolute path, if possible with ~ for home directory.
1269 noabbrev Absolute path, no abbreviation of home directory.
1270 adaptive Use relative path for files in the current directory and sub-
1271 directories of it. For other files, use an absolute path."
1272 :group 'org-link
1273 :type '(choice
1274 (const relative)
1275 (const absolute)
1276 (const noabbrev)
1277 (const adaptive)))
1279 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1280 "Types of links that should be activated in Org-mode files.
1281 This is a list of symbols, each leading to the activation of a certain link
1282 type. In principle, it does not hurt to turn on most link types - there may
1283 be a small gain when turning off unused link types. The types are:
1285 bracket The recommended [[link][description]] or [[link]] links with hiding.
1286 angle Links in angular brackets that may contain whitespace like
1287 <bbdb:Carsten Dominik>.
1288 plain Plain links in normal text, no whitespace, like http://google.com.
1289 radio Text that is matched by a radio target, see manual for details.
1290 tag Tag settings in a headline (link to tag search).
1291 date Time stamps (link to calendar).
1292 footnote Footnote labels.
1294 Changing this variable requires a restart of Emacs to become effective."
1295 :group 'org-link
1296 :type '(set :greedy t
1297 (const :tag "Double bracket links" bracket)
1298 (const :tag "Angular bracket links" angle)
1299 (const :tag "Plain text links" plain)
1300 (const :tag "Radio target matches" radio)
1301 (const :tag "Tags" tag)
1302 (const :tag "Timestamps" date)
1303 (const :tag "Footnotes" footnote)))
1305 (defcustom org-make-link-description-function nil
1306 "Function to use to generate link descriptions from links.
1307 If nil the link location will be used. This function must take
1308 two parameters; the first is the link and the second the
1309 description `org-insert-link' has generated, and should return the
1310 description to use."
1311 :group 'org-link
1312 :type 'function)
1314 (defgroup org-link-store nil
1315 "Options concerning storing links in Org-mode."
1316 :tag "Org Store Link"
1317 :group 'org-link)
1319 (defcustom org-email-link-description-format "Email %c: %.30s"
1320 "Format of the description part of a link to an email or usenet message.
1321 The following %-escapes will be replaced by corresponding information:
1323 %F full \"From\" field
1324 %f name, taken from \"From\" field, address if no name
1325 %T full \"To\" field
1326 %t first name in \"To\" field, address if no name
1327 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1328 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1329 %s subject
1330 %d date
1331 %m message-id.
1333 You may use normal field width specification between the % and the letter.
1334 This is for example useful to limit the length of the subject.
1336 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1337 :group 'org-link-store
1338 :type 'string)
1340 (defcustom org-from-is-user-regexp
1341 (let (r1 r2)
1342 (when (and user-mail-address (not (string= user-mail-address "")))
1343 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1344 (when (and user-full-name (not (string= user-full-name "")))
1345 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1346 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1347 "Regexp matched against the \"From:\" header of an email or usenet message.
1348 It should match if the message is from the user him/herself."
1349 :group 'org-link-store
1350 :type 'regexp)
1352 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1353 "Non-nil means storing a link to an Org file will use entry IDs.
1355 Note that before this variable is even considered, org-id must be loaded,
1356 so please customize `org-modules' and turn it on.
1358 The variable can have the following values:
1360 t Create an ID if needed to make a link to the current entry.
1362 create-if-interactive
1363 If `org-store-link' is called directly (interactively, as a user
1364 command), do create an ID to support the link. But when doing the
1365 job for remember, only use the ID if it already exists. The
1366 purpose of this setting is to avoid proliferation of unwanted
1367 IDs, just because you happen to be in an Org file when you
1368 call `org-remember' that automatically and preemptively
1369 creates a link. If you do want to get an ID link in a remember
1370 template to an entry not having an ID, create it first by
1371 explicitly creating a link to it, using `C-c C-l' first.
1373 create-if-interactive-and-no-custom-id
1374 Like create-if-interactive, but do not create an ID if there is
1375 a CUSTOM_ID property defined in the entry. This is the default.
1377 use-existing
1378 Use existing ID, do not create one.
1380 nil Never use an ID to make a link, instead link using a text search for
1381 the headline text."
1382 :group 'org-link-store
1383 :type '(choice
1384 (const :tag "Create ID to make link" t)
1385 (const :tag "Create if storing link interactively"
1386 create-if-interactive)
1387 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1388 create-if-interactive-and-no-custom-id)
1389 (const :tag "Only use existing" use-existing)
1390 (const :tag "Do not use ID to create link" nil)))
1392 (defcustom org-context-in-file-links t
1393 "Non-nil means file links from `org-store-link' contain context.
1394 A search string will be added to the file name with :: as separator and
1395 used to find the context when the link is activated by the command
1396 `org-open-at-point'. When this option is t, the entire active region
1397 will be placed in the search string of the file link. If set to a
1398 positive integer, only the first n lines of context will be stored.
1400 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1401 negates this setting for the duration of the command."
1402 :group 'org-link-store
1403 :type '(choice boolean integer))
1405 (defcustom org-keep-stored-link-after-insertion nil
1406 "Non-nil means keep link in list for entire session.
1408 The command `org-store-link' adds a link pointing to the current
1409 location to an internal list. These links accumulate during a session.
1410 The command `org-insert-link' can be used to insert links into any
1411 Org-mode file (offering completion for all stored links). When this
1412 option is nil, every link which has been inserted once using \\[org-insert-link]
1413 will be removed from the list, to make completing the unused links
1414 more efficient."
1415 :group 'org-link-store
1416 :type 'boolean)
1418 (defgroup org-link-follow nil
1419 "Options concerning following links in Org-mode."
1420 :tag "Org Follow Link"
1421 :group 'org-link)
1423 (defcustom org-link-translation-function nil
1424 "Function to translate links with different syntax to Org syntax.
1425 This can be used to translate links created for example by the Planner
1426 or emacs-wiki packages to Org syntax.
1427 The function must accept two parameters, a TYPE containing the link
1428 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1429 which is everything after the link protocol. It should return a cons
1430 with possibly modified values of type and path.
1431 Org contains a function for this, so if you set this variable to
1432 `org-translate-link-from-planner', you should be able follow many
1433 links created by planner."
1434 :group 'org-link-follow
1435 :type 'function)
1437 (defcustom org-follow-link-hook nil
1438 "Hook that is run after a link has been followed."
1439 :group 'org-link-follow
1440 :type 'hook)
1442 (defcustom org-tab-follows-link nil
1443 "Non-nil means on links TAB will follow the link.
1444 Needs to be set before org.el is loaded.
1445 This really should not be used, it does not make sense, and the
1446 implementation is bad."
1447 :group 'org-link-follow
1448 :type 'boolean)
1450 (defcustom org-return-follows-link nil
1451 "Non-nil means on links RET will follow the link."
1452 :group 'org-link-follow
1453 :type 'boolean)
1455 (defcustom org-mouse-1-follows-link
1456 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1457 "Non-nil means mouse-1 on a link will follow the link.
1458 A longer mouse click will still set point. Does not work on XEmacs.
1459 Needs to be set before org.el is loaded."
1460 :group 'org-link-follow
1461 :type 'boolean)
1463 (defcustom org-mark-ring-length 4
1464 "Number of different positions to be recorded in the ring.
1465 Changing this requires a restart of Emacs to work correctly."
1466 :group 'org-link-follow
1467 :type 'integer)
1469 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1470 "Non-nil means internal links in Org files must exactly match a headline.
1471 When nil, the link search tries to match a phrase with all words
1472 in the search text."
1473 :group 'org-link-follow
1474 :type '(choice
1475 (const :tag "Use fuzy text search" nil)
1476 (const :tag "Match only exact headline" t)
1477 (const :tag "Match extact headline or query to create it"
1478 query-to-create)))
1480 (defcustom org-link-frame-setup
1481 '((vm . vm-visit-folder-other-frame)
1482 (gnus . org-gnus-no-new-news)
1483 (file . find-file-other-window)
1484 (wl . wl-other-frame))
1485 "Setup the frame configuration for following links.
1486 When following a link with Emacs, it may often be useful to display
1487 this link in another window or frame. This variable can be used to
1488 set this up for the different types of links.
1489 For VM, use any of
1490 `vm-visit-folder'
1491 `vm-visit-folder-other-window'
1492 `vm-visit-folder-other-frame'
1493 For Gnus, use any of
1494 `gnus'
1495 `gnus-other-frame'
1496 `org-gnus-no-new-news'
1497 For FILE, use any of
1498 `find-file'
1499 `find-file-other-window'
1500 `find-file-other-frame'
1501 For Wanderlust use any of
1502 `wl'
1503 `wl-other-frame'
1504 For the calendar, use the variable `calendar-setup'.
1505 For BBDB, it is currently only possible to display the matches in
1506 another window."
1507 :group 'org-link-follow
1508 :type '(list
1509 (cons (const vm)
1510 (choice
1511 (const vm-visit-folder)
1512 (const vm-visit-folder-other-window)
1513 (const vm-visit-folder-other-frame)))
1514 (cons (const gnus)
1515 (choice
1516 (const gnus)
1517 (const gnus-other-frame)
1518 (const org-gnus-no-new-news)))
1519 (cons (const file)
1520 (choice
1521 (const find-file)
1522 (const find-file-other-window)
1523 (const find-file-other-frame)))
1524 (cons (const wl)
1525 (choice
1526 (const wl)
1527 (const wl-other-frame)))))
1529 (defcustom org-display-internal-link-with-indirect-buffer nil
1530 "Non-nil means use indirect buffer to display infile links.
1531 Activating internal links (from one location in a file to another location
1532 in the same file) normally just jumps to the location. When the link is
1533 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1534 is displayed in
1535 another window. When this option is set, the other window actually displays
1536 an indirect buffer clone of the current buffer, to avoid any visibility
1537 changes to the current buffer."
1538 :group 'org-link-follow
1539 :type 'boolean)
1541 (defcustom org-open-non-existing-files nil
1542 "Non-nil means `org-open-file' will open non-existing files.
1543 When nil, an error will be generated.
1544 This variable applies only to external applications because they
1545 might choke on non-existing files. If the link is to a file that
1546 will be opened in Emacs, the variable is ignored."
1547 :group 'org-link-follow
1548 :type 'boolean)
1550 (defcustom org-open-directory-means-index-dot-org nil
1551 "Non-nil means a link to a directory really means to index.org.
1552 When nil, following a directory link will run dired or open a finder/explorer
1553 window on that directory."
1554 :group 'org-link-follow
1555 :type 'boolean)
1557 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1558 "Function and arguments to call for following mailto links.
1559 This is a list with the first element being a Lisp function, and the
1560 remaining elements being arguments to the function. In string arguments,
1561 %a will be replaced by the address, and %s will be replaced by the subject
1562 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1563 :group 'org-link-follow
1564 :type '(choice
1565 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1566 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1567 (const :tag "message-mail" (message-mail "%a" "%s"))
1568 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1570 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1571 "Non-nil means ask for confirmation before executing shell links.
1572 Shell links can be dangerous: just think about a link
1574 [[shell:rm -rf ~/*][Google Search]]
1576 This link would show up in your Org-mode document as \"Google Search\",
1577 but really it would remove your entire home directory.
1578 Therefore we advise against setting this variable to nil.
1579 Just change it to `y-or-n-p' if you want to confirm with a
1580 single keystroke rather than having to type \"yes\"."
1581 :group 'org-link-follow
1582 :type '(choice
1583 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1584 (const :tag "with y-or-n (faster)" y-or-n-p)
1585 (const :tag "no confirmation (dangerous)" nil)))
1586 (put 'org-confirm-shell-link-function
1587 'safe-local-variable
1588 '(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1590 (defcustom org-confirm-shell-link-not-regexp ""
1591 "A regexp to skip confirmation for shell links."
1592 :group 'org-link-follow
1593 :type 'regexp)
1595 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1596 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1597 Elisp links can be dangerous: just think about a link
1599 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1601 This link would show up in your Org-mode document as \"Google Search\",
1602 but really it would remove your entire home directory.
1603 Therefore we advise against setting this variable to nil.
1604 Just change it to `y-or-n-p' if you want to confirm with a
1605 single keystroke rather than having to type \"yes\"."
1606 :group 'org-link-follow
1607 :type '(choice
1608 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1609 (const :tag "with y-or-n (faster)" y-or-n-p)
1610 (const :tag "no confirmation (dangerous)" nil)))
1611 (put 'org-confirm-shell-link-function
1612 'safe-local-variable
1613 '(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1615 (defcustom org-confirm-elisp-link-not-regexp ""
1616 "A regexp to skip confirmation for Elisp links."
1617 :group 'org-link-follow
1618 :type 'regexp)
1620 (defconst org-file-apps-defaults-gnu
1621 '((remote . emacs)
1622 (system . mailcap)
1623 (t . mailcap))
1624 "Default file applications on a UNIX or GNU/Linux system.
1625 See `org-file-apps'.")
1627 (defconst org-file-apps-defaults-macosx
1628 '((remote . emacs)
1629 (t . "open %s")
1630 (system . "open %s")
1631 ("ps.gz" . "gv %s")
1632 ("eps.gz" . "gv %s")
1633 ("dvi" . "xdvi %s")
1634 ("fig" . "xfig %s"))
1635 "Default file applications on a MacOS X system.
1636 The system \"open\" is known as a default, but we use X11 applications
1637 for some files for which the OS does not have a good default.
1638 See `org-file-apps'.")
1640 (defconst org-file-apps-defaults-windowsnt
1641 (list
1642 '(remote . emacs)
1643 (cons t
1644 (list (if (featurep 'xemacs)
1645 'mswindows-shell-execute
1646 'w32-shell-execute)
1647 "open" 'file))
1648 (cons 'system
1649 (list (if (featurep 'xemacs)
1650 'mswindows-shell-execute
1651 'w32-shell-execute)
1652 "open" 'file)))
1653 "Default file applications on a Windows NT system.
1654 The system \"open\" is used for most files.
1655 See `org-file-apps'.")
1657 (defcustom org-file-apps
1659 (auto-mode . emacs)
1660 ("\\.mm\\'" . default)
1661 ("\\.x?html?\\'" . default)
1662 ("\\.pdf\\'" . default)
1664 "External applications for opening `file:path' items in a document.
1665 Org-mode uses system defaults for different file types, but
1666 you can use this variable to set the application for a given file
1667 extension. The entries in this list are cons cells where the car identifies
1668 files and the cdr the corresponding command. Possible values for the
1669 file identifier are
1670 \"string\" A string as a file identifier can be interpreted in different
1671 ways, depending on its contents:
1673 - Alphanumeric characters only:
1674 Match links with this file extension.
1675 Example: (\"pdf\" . \"evince %s\")
1676 to open PDFs with evince.
1678 - Regular expression: Match links where the
1679 filename matches the regexp. If you want to
1680 use groups here, use shy groups.
1682 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1683 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1684 to open *.html and *.xhtml with firefox.
1686 - Regular expression which contains (non-shy) groups:
1687 Match links where the whole link, including \"::\", and
1688 anything after that, matches the regexp.
1689 In a custom command string, %1, %2, etc. are replaced with
1690 the parts of the link that were matched by the groups.
1691 For backwards compatibility, if a command string is given
1692 that does not use any of the group matches, this case is
1693 handled identically to the second one (i.e. match against
1694 file name only).
1695 In a custom lisp form, you can access the group matches with
1696 (match-string n link).
1698 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1699 to open [[file:document.pdf::5]] with evince at page 5.
1701 `directory' Matches a directory
1702 `remote' Matches a remote file, accessible through tramp or efs.
1703 Remote files most likely should be visited through Emacs
1704 because external applications cannot handle such paths.
1705 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1706 so all files Emacs knows how to handle. Using this with
1707 command `emacs' will open most files in Emacs. Beware that this
1708 will also open html files inside Emacs, unless you add
1709 (\"html\" . default) to the list as well.
1710 t Default for files not matched by any of the other options.
1711 `system' The system command to open files, like `open' on Windows
1712 and Mac OS X, and mailcap under GNU/Linux. This is the command
1713 that will be selected if you call `C-c C-o' with a double
1714 \\[universal-argument] \\[universal-argument] prefix.
1716 Possible values for the command are:
1717 `emacs' The file will be visited by the current Emacs process.
1718 `default' Use the default application for this file type, which is the
1719 association for t in the list, most likely in the system-specific
1720 part.
1721 This can be used to overrule an unwanted setting in the
1722 system-specific variable.
1723 `system' Use the system command for opening files, like \"open\".
1724 This command is specified by the entry whose car is `system'.
1725 Most likely, the system-specific version of this variable
1726 does define this command, but you can overrule/replace it
1727 here.
1728 string A command to be executed by a shell; %s will be replaced
1729 by the path to the file.
1730 sexp A Lisp form which will be evaluated. The file path will
1731 be available in the Lisp variable `file'.
1732 For more examples, see the system specific constants
1733 `org-file-apps-defaults-macosx'
1734 `org-file-apps-defaults-windowsnt'
1735 `org-file-apps-defaults-gnu'."
1736 :group 'org-link-follow
1737 :type '(repeat
1738 (cons (choice :value ""
1739 (string :tag "Extension")
1740 (const :tag "System command to open files" system)
1741 (const :tag "Default for unrecognized files" t)
1742 (const :tag "Remote file" remote)
1743 (const :tag "Links to a directory" directory)
1744 (const :tag "Any files that have Emacs modes"
1745 auto-mode))
1746 (choice :value ""
1747 (const :tag "Visit with Emacs" emacs)
1748 (const :tag "Use default" default)
1749 (const :tag "Use the system command" system)
1750 (string :tag "Command")
1751 (sexp :tag "Lisp form")))))
1755 (defgroup org-refile nil
1756 "Options concerning refiling entries in Org-mode."
1757 :tag "Org Refile"
1758 :group 'org)
1760 (defcustom org-directory "~/org"
1761 "Directory with org files.
1762 This is just a default location to look for Org files. There is no need
1763 at all to put your files into this directory. It is only used in the
1764 following situations:
1766 1. When a remember template specifies a target file that is not an
1767 absolute path. The path will then be interpreted relative to
1768 `org-directory'
1769 2. When a remember note is filed away in an interactive way (when exiting the
1770 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1771 with `org-directory' as the default path."
1772 :group 'org-refile
1773 :group 'org-remember
1774 :type 'directory)
1776 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1777 "Default target for storing notes.
1778 Used as a fall back file for org-remember.el and org-capture.el, for
1779 templates that do not specify a target file."
1780 :group 'org-refile
1781 :group 'org-remember
1782 :type '(choice
1783 (const :tag "Default from remember-data-file" nil)
1784 file))
1786 (defcustom org-goto-interface 'outline
1787 "The default interface to be used for `org-goto'.
1788 Allowed values are:
1789 outline The interface shows an outline of the relevant file
1790 and the correct heading is found by moving through
1791 the outline or by searching with incremental search.
1792 outline-path-completion Headlines in the current buffer are offered via
1793 completion. This is the interface also used by
1794 the refile command."
1795 :group 'org-refile
1796 :type '(choice
1797 (const :tag "Outline" outline)
1798 (const :tag "Outline-path-completion" outline-path-completion)))
1800 (defcustom org-goto-max-level 5
1801 "Maximum target level when running `org-goto' with refile interface."
1802 :group 'org-refile
1803 :type 'integer)
1805 (defcustom org-reverse-note-order nil
1806 "Non-nil means store new notes at the beginning of a file or entry.
1807 When nil, new notes will be filed to the end of a file or entry.
1808 This can also be a list with cons cells of regular expressions that
1809 are matched against file names, and values."
1810 :group 'org-remember
1811 :group 'org-refile
1812 :type '(choice
1813 (const :tag "Reverse always" t)
1814 (const :tag "Reverse never" nil)
1815 (repeat :tag "By file name regexp"
1816 (cons regexp boolean))))
1818 (defcustom org-log-refile nil
1819 "Information to record when a task is refiled.
1821 Possible values are:
1823 nil Don't add anything
1824 time Add a time stamp to the task
1825 note Prompt for a note and add it with template `org-log-note-headings'
1827 This option can also be set with on a per-file-basis with
1829 #+STARTUP: nologrefile
1830 #+STARTUP: logrefile
1831 #+STARTUP: lognoterefile
1833 You can have local logging settings for a subtree by setting the LOGGING
1834 property to one or more of these keywords.
1836 When bulk-refiling from the agenda, the value `note' is forbidden and
1837 will temporarily be changed to `time'."
1838 :group 'org-refile
1839 :group 'org-progress
1840 :type '(choice
1841 (const :tag "No logging" nil)
1842 (const :tag "Record timestamp" time)
1843 (const :tag "Record timestamp with note." note)))
1845 (defcustom org-refile-targets nil
1846 "Targets for refiling entries with \\[org-refile].
1847 This is list of cons cells. Each cell contains:
1848 - a specification of the files to be considered, either a list of files,
1849 or a symbol whose function or variable value will be used to retrieve
1850 a file name or a list of file names. If you use `org-agenda-files' for
1851 that, all agenda files will be scanned for targets. Nil means consider
1852 headings in the current buffer.
1853 - A specification of how to find candidate refile targets. This may be
1854 any of:
1855 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1856 This tag has to be present in all target headlines, inheritance will
1857 not be considered.
1858 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1859 todo keyword.
1860 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1861 headlines that are refiling targets.
1862 - a cons cell (:level . N). Any headline of level N is considered a target.
1863 Note that, when `org-odd-levels-only' is set, level corresponds to
1864 order in hierarchy, not to the number of stars.
1865 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1866 Note that, when `org-odd-levels-only' is set, level corresponds to
1867 order in hierarchy, not to the number of stars.
1869 You can set the variable `org-refile-target-verify-function' to a function
1870 to verify each headline found by the simple criteria above.
1872 When this variable is nil, all top-level headlines in the current buffer
1873 are used, equivalent to the value `((nil . (:level . 1))'."
1874 :group 'org-refile
1875 :type '(repeat
1876 (cons
1877 (choice :value org-agenda-files
1878 (const :tag "All agenda files" org-agenda-files)
1879 (const :tag "Current buffer" nil)
1880 (function) (variable) (file))
1881 (choice :tag "Identify target headline by"
1882 (cons :tag "Specific tag" (const :value :tag) (string))
1883 (cons :tag "TODO keyword" (const :value :todo) (string))
1884 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1885 (cons :tag "Level number" (const :value :level) (integer))
1886 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1888 (defcustom org-refile-target-verify-function nil
1889 "Function to verify if the headline at point should be a refile target.
1890 The function will be called without arguments, with point at the
1891 beginning of the headline. It should return t and leave point
1892 where it is if the headline is a valid target for refiling.
1894 If the target should not be selected, the function must return nil.
1895 In addition to this, it may move point to a place from where the search
1896 should be continued. For example, the function may decide that the entire
1897 subtree of the current entry should be excluded and move point to the end
1898 of the subtree."
1899 :group 'org-refile
1900 :type 'function)
1902 (defcustom org-refile-use-cache nil
1903 "Non-nil means cache refile targets to speed up the process.
1904 The cache for a particular file will be updated automatically when
1905 the buffer has been killed, or when any of the marker used for flagging
1906 refile targets no longer points at a live buffer.
1907 If you have added new entries to a buffer that might themselves be targets,
1908 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1909 find that easier, `C-u C-u C-u C-c C-w'."
1910 :group 'org-refile
1911 :type 'boolean)
1913 (defcustom org-refile-use-outline-path nil
1914 "Non-nil means provide refile targets as paths.
1915 So a level 3 headline will be available as level1/level2/level3.
1917 When the value is `file', also include the file name (without directory)
1918 into the path. In this case, you can also stop the completion after
1919 the file name, to get entries inserted as top level in the file.
1921 When `full-file-path', include the full file path."
1922 :group 'org-refile
1923 :type '(choice
1924 (const :tag "Not" nil)
1925 (const :tag "Yes" t)
1926 (const :tag "Start with file name" file)
1927 (const :tag "Start with full file path" full-file-path)))
1929 (defcustom org-outline-path-complete-in-steps t
1930 "Non-nil means complete the outline path in hierarchical steps.
1931 When Org-mode uses the refile interface to select an outline path
1932 \(see variable `org-refile-use-outline-path'), the completion of
1933 the path can be done is a single go, or if can be done in steps down
1934 the headline hierarchy. Going in steps is probably the best if you
1935 do not use a special completion package like `ido' or `icicles'.
1936 However, when using these packages, going in one step can be very
1937 fast, while still showing the whole path to the entry."
1938 :group 'org-refile
1939 :type 'boolean)
1941 (defcustom org-refile-allow-creating-parent-nodes nil
1942 "Non-nil means allow to create new nodes as refile targets.
1943 New nodes are then created by adding \"/new node name\" to the completion
1944 of an existing node. When the value of this variable is `confirm',
1945 new node creation must be confirmed by the user (recommended)
1946 When nil, the completion must match an existing entry.
1948 Note that, if the new heading is not seen by the criteria
1949 listed in `org-refile-targets', multiple instances of the same
1950 heading would be created by trying again to file under the new
1951 heading."
1952 :group 'org-refile
1953 :type '(choice
1954 (const :tag "Never" nil)
1955 (const :tag "Always" t)
1956 (const :tag "Prompt for confirmation" confirm)))
1958 (defgroup org-todo nil
1959 "Options concerning TODO items in Org-mode."
1960 :tag "Org TODO"
1961 :group 'org)
1963 (defgroup org-progress nil
1964 "Options concerning Progress logging in Org-mode."
1965 :tag "Org Progress"
1966 :group 'org-time)
1968 (defvar org-todo-interpretation-widgets
1970 (:tag "Sequence (cycling hits every state)" sequence)
1971 (:tag "Type (cycling directly to DONE)" type))
1972 "The available interpretation symbols for customizing `org-todo-keywords'.
1973 Interested libraries should add to this list.")
1975 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1976 "List of TODO entry keyword sequences and their interpretation.
1977 \\<org-mode-map>This is a list of sequences.
1979 Each sequence starts with a symbol, either `sequence' or `type',
1980 indicating if the keywords should be interpreted as a sequence of
1981 action steps, or as different types of TODO items. The first
1982 keywords are states requiring action - these states will select a headline
1983 for inclusion into the global TODO list Org-mode produces. If one of
1984 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
1985 signify that no further action is necessary. If \"|\" is not found,
1986 the last keyword is treated as the only DONE state of the sequence.
1988 The command \\[org-todo] cycles an entry through these states, and one
1989 additional state where no keyword is present. For details about this
1990 cycling, see the manual.
1992 TODO keywords and interpretation can also be set on a per-file basis with
1993 the special #+SEQ_TODO and #+TYP_TODO lines.
1995 Each keyword can optionally specify a character for fast state selection
1996 \(in combination with the variable `org-use-fast-todo-selection')
1997 and specifiers for state change logging, using the same syntax
1998 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1999 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2000 indicates to record a time stamp each time this state is selected.
2002 Each keyword may also specify if a timestamp or a note should be
2003 recorded when entering or leaving the state, by adding additional
2004 characters in the parenthesis after the keyword. This looks like this:
2005 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2006 record only the time of the state change. With X and Y being either
2007 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2008 Y when leaving the state if and only if the *target* state does not
2009 define X. You may omit any of the fast-selection key or X or /Y,
2010 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2012 For backward compatibility, this variable may also be just a list
2013 of keywords - in this case the interpretation (sequence or type) will be
2014 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2015 :group 'org-todo
2016 :group 'org-keywords
2017 :type '(choice
2018 (repeat :tag "Old syntax, just keywords"
2019 (string :tag "Keyword"))
2020 (repeat :tag "New syntax"
2021 (cons
2022 (choice
2023 :tag "Interpretation"
2024 ;;Quick and dirty way to see
2025 ;;`org-todo-interpretations'. This takes the
2026 ;;place of item arguments
2027 :convert-widget
2028 (lambda (widget)
2029 (widget-put widget
2030 :args (mapcar
2031 #'(lambda (x)
2032 (widget-convert
2033 (cons 'const x)))
2034 org-todo-interpretation-widgets))
2035 widget))
2036 (repeat
2037 (string :tag "Keyword"))))))
2039 (defvar org-todo-keywords-1 nil
2040 "All TODO and DONE keywords active in a buffer.")
2041 (make-variable-buffer-local 'org-todo-keywords-1)
2042 (defvar org-todo-keywords-for-agenda nil)
2043 (defvar org-done-keywords-for-agenda nil)
2044 (defvar org-drawers-for-agenda nil)
2045 (defvar org-todo-keyword-alist-for-agenda nil)
2046 (defvar org-tag-alist-for-agenda nil)
2047 (defvar org-agenda-contributing-files nil)
2048 (defvar org-not-done-keywords nil)
2049 (make-variable-buffer-local 'org-not-done-keywords)
2050 (defvar org-done-keywords nil)
2051 (make-variable-buffer-local 'org-done-keywords)
2052 (defvar org-todo-heads nil)
2053 (make-variable-buffer-local 'org-todo-heads)
2054 (defvar org-todo-sets nil)
2055 (make-variable-buffer-local 'org-todo-sets)
2056 (defvar org-todo-log-states nil)
2057 (make-variable-buffer-local 'org-todo-log-states)
2058 (defvar org-todo-kwd-alist nil)
2059 (make-variable-buffer-local 'org-todo-kwd-alist)
2060 (defvar org-todo-key-alist nil)
2061 (make-variable-buffer-local 'org-todo-key-alist)
2062 (defvar org-todo-key-trigger nil)
2063 (make-variable-buffer-local 'org-todo-key-trigger)
2065 (defcustom org-todo-interpretation 'sequence
2066 "Controls how TODO keywords are interpreted.
2067 This variable is in principle obsolete and is only used for
2068 backward compatibility, if the interpretation of todo keywords is
2069 not given already in `org-todo-keywords'. See that variable for
2070 more information."
2071 :group 'org-todo
2072 :group 'org-keywords
2073 :type '(choice (const sequence)
2074 (const type)))
2076 (defcustom org-use-fast-todo-selection t
2077 "Non-nil means use the fast todo selection scheme with C-c C-t.
2078 This variable describes if and under what circumstances the cycling
2079 mechanism for TODO keywords will be replaced by a single-key, direct
2080 selection scheme.
2082 When nil, fast selection is never used.
2084 When the symbol `prefix', it will be used when `org-todo' is called with
2085 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2086 in an agenda buffer.
2088 When t, fast selection is used by default. In this case, the prefix
2089 argument forces cycling instead.
2091 In all cases, the special interface is only used if access keys have actually
2092 been assigned by the user, i.e. if keywords in the configuration are followed
2093 by a letter in parenthesis, like TODO(t)."
2094 :group 'org-todo
2095 :type '(choice
2096 (const :tag "Never" nil)
2097 (const :tag "By default" t)
2098 (const :tag "Only with C-u C-c C-t" prefix)))
2100 (defcustom org-provide-todo-statistics t
2101 "Non-nil means update todo statistics after insert and toggle.
2102 ALL-HEADLINES means update todo statistics by including headlines
2103 with no TODO keyword as well, counting them as not done.
2104 A list of TODO keywords means the same, but skip keywords that are
2105 not in this list.
2107 When this is set, todo statistics is updated in the parent of the
2108 current entry each time a todo state is changed."
2109 :group 'org-todo
2110 :type '(choice
2111 (const :tag "Yes, only for TODO entries" t)
2112 (const :tag "Yes, including all entries" 'all-headlines)
2113 (repeat :tag "Yes, for TODOs in this list"
2114 (string :tag "TODO keyword"))
2115 (other :tag "No TODO statistics" nil)))
2117 (defcustom org-hierarchical-todo-statistics t
2118 "Non-nil means TODO statistics covers just direct children.
2119 When nil, all entries in the subtree are considered.
2120 This has only an effect if `org-provide-todo-statistics' is set.
2121 To set this to nil for only a single subtree, use a COOKIE_DATA
2122 property and include the word \"recursive\" into the value."
2123 :group 'org-todo
2124 :type 'boolean)
2126 (defcustom org-after-todo-state-change-hook nil
2127 "Hook which is run after the state of a TODO item was changed.
2128 The new state (a string with a TODO keyword, or nil) is available in the
2129 Lisp variable `state'."
2130 :group 'org-todo
2131 :type 'hook)
2133 (defvar org-blocker-hook nil
2134 "Hook for functions that are allowed to block a state change.
2136 Each function gets as its single argument a property list, see
2137 `org-trigger-hook' for more information about this list.
2139 If any of the functions in this hook returns nil, the state change
2140 is blocked.")
2142 (defvar org-trigger-hook nil
2143 "Hook for functions that are triggered by a state change.
2145 Each function gets as its single argument a property list with at least
2146 the following elements:
2148 (:type type-of-change :position pos-at-entry-start
2149 :from old-state :to new-state)
2151 Depending on the type, more properties may be present.
2153 This mechanism is currently implemented for:
2155 TODO state changes
2156 ------------------
2157 :type todo-state-change
2158 :from previous state (keyword as a string), or nil, or a symbol
2159 'todo' or 'done', to indicate the general type of state.
2160 :to new state, like in :from")
2162 (defcustom org-enforce-todo-dependencies nil
2163 "Non-nil means undone TODO entries will block switching the parent to DONE.
2164 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2165 be blocked if any prior sibling is not yet done.
2166 Finally, if the parent is blocked because of ordered siblings of its own,
2167 the child will also be blocked.
2168 This variable needs to be set before org.el is loaded, and you need to
2169 restart Emacs after a change to make the change effective. The only way
2170 to change is while Emacs is running is through the customize interface."
2171 :set (lambda (var val)
2172 (set var val)
2173 (if val
2174 (add-hook 'org-blocker-hook
2175 'org-block-todo-from-children-or-siblings-or-parent)
2176 (remove-hook 'org-blocker-hook
2177 'org-block-todo-from-children-or-siblings-or-parent)))
2178 :group 'org-todo
2179 :type 'boolean)
2181 (defcustom org-enforce-todo-checkbox-dependencies nil
2182 "Non-nil means unchecked boxes will block switching the parent to DONE.
2183 When this is nil, checkboxes have no influence on switching TODO states.
2184 When non-nil, you first need to check off all check boxes before the TODO
2185 entry can be switched to DONE.
2186 This variable needs to be set before org.el is loaded, and you need to
2187 restart Emacs after a change to make the change effective. The only way
2188 to change is while Emacs is running is through the customize interface."
2189 :set (lambda (var val)
2190 (set var val)
2191 (if val
2192 (add-hook 'org-blocker-hook
2193 'org-block-todo-from-checkboxes)
2194 (remove-hook 'org-blocker-hook
2195 'org-block-todo-from-checkboxes)))
2196 :group 'org-todo
2197 :type 'boolean)
2199 (defcustom org-treat-insert-todo-heading-as-state-change nil
2200 "Non-nil means inserting a TODO heading is treated as state change.
2201 So when the command \\[org-insert-todo-heading] is used, state change
2202 logging will apply if appropriate. When nil, the new TODO item will
2203 be inserted directly, and no logging will take place."
2204 :group 'org-todo
2205 :type 'boolean)
2207 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2208 "Non-nil means switching TODO states with S-cursor counts as state change.
2209 This is the default behavior. However, setting this to nil allows a
2210 convenient way to select a TODO state and bypass any logging associated
2211 with that."
2212 :group 'org-todo
2213 :type 'boolean)
2215 (defcustom org-todo-state-tags-triggers nil
2216 "Tag changes that should be triggered by TODO state changes.
2217 This is a list. Each entry is
2219 (state-change (tag . flag) .......)
2221 State-change can be a string with a state, and empty string to indicate the
2222 state that has no TODO keyword, or it can be one of the symbols `todo'
2223 or `done', meaning any not-done or done state, respectively."
2224 :group 'org-todo
2225 :group 'org-tags
2226 :type '(repeat
2227 (cons (choice :tag "When changing to"
2228 (const :tag "Not-done state" todo)
2229 (const :tag "Done state" done)
2230 (string :tag "State"))
2231 (repeat
2232 (cons :tag "Tag action"
2233 (string :tag "Tag")
2234 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2236 (defcustom org-log-done nil
2237 "Information to record when a task moves to the DONE state.
2239 Possible values are:
2241 nil Don't add anything, just change the keyword
2242 time Add a time stamp to the task
2243 note Prompt for a note and add it with template `org-log-note-headings'
2245 This option can also be set with on a per-file-basis with
2247 #+STARTUP: nologdone
2248 #+STARTUP: logdone
2249 #+STARTUP: lognotedone
2251 You can have local logging settings for a subtree by setting the LOGGING
2252 property to one or more of these keywords."
2253 :group 'org-todo
2254 :group 'org-progress
2255 :type '(choice
2256 (const :tag "No logging" nil)
2257 (const :tag "Record CLOSED timestamp" time)
2258 (const :tag "Record CLOSED timestamp with note." note)))
2260 ;; Normalize old uses of org-log-done.
2261 (cond
2262 ((eq org-log-done t) (setq org-log-done 'time))
2263 ((and (listp org-log-done) (memq 'done org-log-done))
2264 (setq org-log-done 'note)))
2266 (defcustom org-log-reschedule nil
2267 "Information to record when the scheduling date of a tasks is modified.
2269 Possible values are:
2271 nil Don't add anything, just change the date
2272 time Add a time stamp to the task
2273 note Prompt for a note and add it with template `org-log-note-headings'
2275 This option can also be set with on a per-file-basis with
2277 #+STARTUP: nologreschedule
2278 #+STARTUP: logreschedule
2279 #+STARTUP: lognotereschedule"
2280 :group 'org-todo
2281 :group 'org-progress
2282 :type '(choice
2283 (const :tag "No logging" nil)
2284 (const :tag "Record timestamp" time)
2285 (const :tag "Record timestamp with note." note)))
2287 (defcustom org-log-redeadline nil
2288 "Information to record when the deadline date of a tasks is modified.
2290 Possible values are:
2292 nil Don't add anything, just change the date
2293 time Add a time stamp to the task
2294 note Prompt for a note and add it with template `org-log-note-headings'
2296 This option can also be set with on a per-file-basis with
2298 #+STARTUP: nologredeadline
2299 #+STARTUP: logredeadline
2300 #+STARTUP: lognoteredeadline
2302 You can have local logging settings for a subtree by setting the LOGGING
2303 property to one or more of these keywords."
2304 :group 'org-todo
2305 :group 'org-progress
2306 :type '(choice
2307 (const :tag "No logging" nil)
2308 (const :tag "Record timestamp" time)
2309 (const :tag "Record timestamp with note." note)))
2311 (defcustom org-log-note-clock-out nil
2312 "Non-nil means record a note when clocking out of an item.
2313 This can also be configured on a per-file basis by adding one of
2314 the following lines anywhere in the buffer:
2316 #+STARTUP: lognoteclock-out
2317 #+STARTUP: nolognoteclock-out"
2318 :group 'org-todo
2319 :group 'org-progress
2320 :type 'boolean)
2322 (defcustom org-log-done-with-time t
2323 "Non-nil means the CLOSED time stamp will contain date and time.
2324 When nil, only the date will be recorded."
2325 :group 'org-progress
2326 :type 'boolean)
2328 (defcustom org-log-note-headings
2329 '((done . "CLOSING NOTE %t")
2330 (state . "State %-12s from %-12S %t")
2331 (note . "Note taken on %t")
2332 (reschedule . "Rescheduled from %S on %t")
2333 (delschedule . "Not scheduled, was %S on %t")
2334 (redeadline . "New deadline from %S on %t")
2335 (deldeadline . "Removed deadline, was %S on %t")
2336 (refile . "Refiled on %t")
2337 (clock-out . ""))
2338 "Headings for notes added to entries.
2339 The value is an alist, with the car being a symbol indicating the note
2340 context, and the cdr is the heading to be used. The heading may also be the
2341 empty string.
2342 %t in the heading will be replaced by a time stamp.
2343 %T will be an active time stamp instead the default inactive one
2344 %s will be replaced by the new TODO state, in double quotes.
2345 %S will be replaced by the old TODO state, in double quotes.
2346 %u will be replaced by the user name.
2347 %U will be replaced by the full user name.
2349 In fact, it is not a good idea to change the `state' entry, because
2350 agenda log mode depends on the format of these entries."
2351 :group 'org-todo
2352 :group 'org-progress
2353 :type '(list :greedy t
2354 (cons (const :tag "Heading when closing an item" done) string)
2355 (cons (const :tag
2356 "Heading when changing todo state (todo sequence only)"
2357 state) string)
2358 (cons (const :tag "Heading when just taking a note" note) string)
2359 (cons (const :tag "Heading when clocking out" clock-out) string)
2360 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2361 (cons (const :tag "Heading when rescheduling" reschedule) string)
2362 (cons (const :tag "Heading when changing deadline" redeadline) string)
2363 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2364 (cons (const :tag "Heading when refiling" refile) string)))
2366 (unless (assq 'note org-log-note-headings)
2367 (push '(note . "%t") org-log-note-headings))
2369 (defcustom org-log-into-drawer nil
2370 "Non-nil means insert state change notes and time stamps into a drawer.
2371 When nil, state changes notes will be inserted after the headline and
2372 any scheduling and clock lines, but not inside a drawer.
2374 The value of this variable should be the name of the drawer to use.
2375 LOGBOOK is proposed at the default drawer for this purpose, you can
2376 also set this to a string to define the drawer of your choice.
2378 A value of t is also allowed, representing \"LOGBOOK\".
2380 If this variable is set, `org-log-state-notes-insert-after-drawers'
2381 will be ignored.
2383 You can set the property LOG_INTO_DRAWER to overrule this setting for
2384 a subtree."
2385 :group 'org-todo
2386 :group 'org-progress
2387 :type '(choice
2388 (const :tag "Not into a drawer" nil)
2389 (const :tag "LOGBOOK" t)
2390 (string :tag "Other")))
2392 (if (fboundp 'defvaralias)
2393 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2395 (defun org-log-into-drawer ()
2396 "Return the value of `org-log-into-drawer', but let properties overrule.
2397 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2398 used instead of the default value."
2399 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2400 (cond
2401 ((or (not p) (equal p "nil")) org-log-into-drawer)
2402 ((equal p "t") "LOGBOOK")
2403 (t p))))
2405 (defcustom org-log-state-notes-insert-after-drawers nil
2406 "Non-nil means insert state change notes after any drawers in entry.
2407 Only the drawers that *immediately* follow the headline and the
2408 deadline/scheduled line are skipped.
2409 When nil, insert notes right after the heading and perhaps the line
2410 with deadline/scheduling if present.
2412 This variable will have no effect if `org-log-into-drawer' is
2413 set."
2414 :group 'org-todo
2415 :group 'org-progress
2416 :type 'boolean)
2418 (defcustom org-log-states-order-reversed t
2419 "Non-nil means the latest state note will be directly after heading.
2420 When nil, the state change notes will be ordered according to time."
2421 :group 'org-todo
2422 :group 'org-progress
2423 :type 'boolean)
2425 (defcustom org-todo-repeat-to-state nil
2426 "The TODO state to which a repeater should return the repeating task.
2427 By default this is the first task in a TODO sequence, or the previous state
2428 in a TODO_TYP set. But you can specify another task here.
2429 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2430 :group 'org-todo
2431 :type '(choice (const :tag "Head of sequence" nil)
2432 (string :tag "Specific state")))
2434 (defcustom org-log-repeat 'time
2435 "Non-nil means record moving through the DONE state when triggering repeat.
2436 An auto-repeating task is immediately switched back to TODO when
2437 marked DONE. If you are not logging state changes (by adding \"@\"
2438 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2439 record a closing note, there will be no record of the task moving
2440 through DONE. This variable forces taking a note anyway.
2442 nil Don't force a record
2443 time Record a time stamp
2444 note Record a note
2446 This option can also be set with on a per-file-basis with
2448 #+STARTUP: logrepeat
2449 #+STARTUP: lognoterepeat
2450 #+STARTUP: nologrepeat
2452 You can have local logging settings for a subtree by setting the LOGGING
2453 property to one or more of these keywords."
2454 :group 'org-todo
2455 :group 'org-progress
2456 :type '(choice
2457 (const :tag "Don't force a record" nil)
2458 (const :tag "Force recording the DONE state" time)
2459 (const :tag "Force recording a note with the DONE state" note)))
2462 (defgroup org-priorities nil
2463 "Priorities in Org-mode."
2464 :tag "Org Priorities"
2465 :group 'org-todo)
2467 (defcustom org-enable-priority-commands t
2468 "Non-nil means priority commands are active.
2469 When nil, these commands will be disabled, so that you never accidentally
2470 set a priority."
2471 :group 'org-priorities
2472 :type 'boolean)
2474 (defcustom org-highest-priority ?A
2475 "The highest priority of TODO items. A character like ?A, ?B etc.
2476 Must have a smaller ASCII number than `org-lowest-priority'."
2477 :group 'org-priorities
2478 :type 'character)
2480 (defcustom org-lowest-priority ?C
2481 "The lowest priority of TODO items. A character like ?A, ?B etc.
2482 Must have a larger ASCII number than `org-highest-priority'."
2483 :group 'org-priorities
2484 :type 'character)
2486 (defcustom org-default-priority ?B
2487 "The default priority of TODO items.
2488 This is the priority an item get if no explicit priority is given."
2489 :group 'org-priorities
2490 :type 'character)
2492 (defcustom org-priority-start-cycle-with-default t
2493 "Non-nil means start with default priority when starting to cycle.
2494 When this is nil, the first step in the cycle will be (depending on the
2495 command used) one higher or lower that the default priority."
2496 :group 'org-priorities
2497 :type 'boolean)
2499 (defcustom org-get-priority-function nil
2500 "Function to extract the priority from a string.
2501 The string is normally the headline. If this is nil Org computes the
2502 priority from the priority cookie like [#A] in the headline. It returns
2503 an integer, increasing by 1000 for each priority level.
2504 The user can set a different function here, which should take a string
2505 as an argument and return the numeric priority."
2506 :group 'org-priorities
2507 :type 'function)
2509 (defgroup org-time nil
2510 "Options concerning time stamps and deadlines in Org-mode."
2511 :tag "Org Time"
2512 :group 'org)
2514 (defcustom org-insert-labeled-timestamps-at-point nil
2515 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2516 When nil, these labeled time stamps are forces into the second line of an
2517 entry, just after the headline. When scheduling from the global TODO list,
2518 the time stamp will always be forced into the second line."
2519 :group 'org-time
2520 :type 'boolean)
2522 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2523 "Formats for `format-time-string' which are used for time stamps.
2524 It is not recommended to change this constant.")
2526 (defcustom org-time-stamp-rounding-minutes '(0 5)
2527 "Number of minutes to round time stamps to.
2528 These are two values, the first applies when first creating a time stamp.
2529 The second applies when changing it with the commands `S-up' and `S-down'.
2530 When changing the time stamp, this means that it will change in steps
2531 of N minutes, as given by the second value.
2533 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2534 numbers should be factors of 60, so for example 5, 10, 15.
2536 When this is larger than 1, you can still force an exact time stamp by using
2537 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2538 and by using a prefix arg to `S-up/down' to specify the exact number
2539 of minutes to shift."
2540 :group 'org-time
2541 :get '(lambda (var) ; Make sure both elements are there
2542 (if (integerp (default-value var))
2543 (list (default-value var) 5)
2544 (default-value var)))
2545 :type '(list
2546 (integer :tag "when inserting times")
2547 (integer :tag "when modifying times")))
2549 ;; Normalize old customizations of this variable.
2550 (when (integerp org-time-stamp-rounding-minutes)
2551 (setq org-time-stamp-rounding-minutes
2552 (list org-time-stamp-rounding-minutes
2553 org-time-stamp-rounding-minutes)))
2555 (defcustom org-display-custom-times nil
2556 "Non-nil means overlay custom formats over all time stamps.
2557 The formats are defined through the variable `org-time-stamp-custom-formats'.
2558 To turn this on on a per-file basis, insert anywhere in the file:
2559 #+STARTUP: customtime"
2560 :group 'org-time
2561 :set 'set-default
2562 :type 'sexp)
2563 (make-variable-buffer-local 'org-display-custom-times)
2565 (defcustom org-time-stamp-custom-formats
2566 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2567 "Custom formats for time stamps. See `format-time-string' for the syntax.
2568 These are overlayed over the default ISO format if the variable
2569 `org-display-custom-times' is set. Time like %H:%M should be at the
2570 end of the second format. The custom formats are also honored by export
2571 commands, if custom time display is turned on at the time of export."
2572 :group 'org-time
2573 :type 'sexp)
2575 (defun org-time-stamp-format (&optional long inactive)
2576 "Get the right format for a time string."
2577 (let ((f (if long (cdr org-time-stamp-formats)
2578 (car org-time-stamp-formats))))
2579 (if inactive
2580 (concat "[" (substring f 1 -1) "]")
2581 f)))
2583 (defcustom org-time-clocksum-format "%d:%02d"
2584 "The format string used when creating CLOCKSUM lines.
2585 This is also used when org-mode generates a time duration."
2586 :group 'org-time
2587 :type 'string)
2589 (defcustom org-time-clocksum-use-fractional nil
2590 "If non-nil, \\[org-clock-display] uses fractional times.
2591 org-mode generates a time duration."
2592 :group 'org-time
2593 :type 'boolean)
2595 (defcustom org-time-clocksum-fractional-format "%.2f"
2596 "The format string used when creating CLOCKSUM lines, or when
2597 org-mode generates a time duration."
2598 :group 'org-time
2599 :type 'string)
2601 (defcustom org-deadline-warning-days 14
2602 "No. of days before expiration during which a deadline becomes active.
2603 This variable governs the display in sparse trees and in the agenda.
2604 When 0 or negative, it means use this number (the absolute value of it)
2605 even if a deadline has a different individual lead time specified.
2607 Custom commands can set this variable in the options section."
2608 :group 'org-time
2609 :group 'org-agenda-daily/weekly
2610 :type 'integer)
2612 (defcustom org-read-date-prefer-future t
2613 "Non-nil means assume future for incomplete date input from user.
2614 This affects the following situations:
2615 1. The user gives a month but not a year.
2616 For example, if it is April and you enter \"feb 2\", this will be read
2617 as Feb 2, *next* year. \"May 5\", however, will be this year.
2618 2. The user gives a day, but no month.
2619 For example, if today is the 15th, and you enter \"3\", Org-mode will
2620 read this as the third of *next* month. However, if you enter \"17\",
2621 it will be considered as *this* month.
2623 If you set this variable to the symbol `time', then also the following
2624 will work:
2626 3. If the user gives a time, but no day. If the time is before now,
2627 to will be interpreted as tomorrow.
2629 Currently none of this works for ISO week specifications.
2631 When this option is nil, the current day, month and year will always be
2632 used as defaults.
2634 See also `org-agenda-jump-prefer-future'."
2635 :group 'org-time
2636 :type '(choice
2637 (const :tag "Never" nil)
2638 (const :tag "Check month and day" t)
2639 (const :tag "Check month, day, and time" time)))
2641 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2642 "Should the agenda jump command prefer the future for incomplete dates?
2643 The default is to do the same as configured in `org-read-date-prefer-future'.
2644 But you can also set a deviating value here.
2645 This may t or nil, or the symbol `org-read-date-prefer-future'."
2646 :group 'org-agenda
2647 :group 'org-time
2648 :type '(choice
2649 (const :tag "Use org-read-date-prefer-future"
2650 org-read-date-prefer-future)
2651 (const :tag "Never" nil)
2652 (const :tag "Always" t)))
2654 (defcustom org-read-date-display-live t
2655 "Non-nil means display current interpretation of date prompt live.
2656 This display will be in an overlay, in the minibuffer."
2657 :group 'org-time
2658 :type 'boolean)
2660 (defcustom org-read-date-popup-calendar t
2661 "Non-nil means pop up a calendar when prompting for a date.
2662 In the calendar, the date can be selected with mouse-1. However, the
2663 minibuffer will also be active, and you can simply enter the date as well.
2664 When nil, only the minibuffer will be available."
2665 :group 'org-time
2666 :type 'boolean)
2667 (if (fboundp 'defvaralias)
2668 (defvaralias 'org-popup-calendar-for-date-prompt
2669 'org-read-date-popup-calendar))
2671 (defcustom org-read-date-minibuffer-setup-hook nil
2672 "Hook to be used to set up keys for the date/time interface.
2673 Add key definitions to `minibuffer-local-map', which will be a temporary
2674 copy."
2675 :group 'org-time
2676 :type 'hook)
2678 (defcustom org-extend-today-until 0
2679 "The hour when your day really ends. Must be an integer.
2680 This has influence for the following applications:
2681 - When switching the agenda to \"today\". It it is still earlier than
2682 the time given here, the day recognized as TODAY is actually yesterday.
2683 - When a date is read from the user and it is still before the time given
2684 here, the current date and time will be assumed to be yesterday, 23:59.
2685 Also, timestamps inserted in remember templates follow this rule.
2687 IMPORTANT: This is a feature whose implementation is and likely will
2688 remain incomplete. Really, it is only here because past midnight seems to
2689 be the favorite working time of John Wiegley :-)"
2690 :group 'org-time
2691 :type 'integer)
2693 (defcustom org-edit-timestamp-down-means-later nil
2694 "Non-nil means S-down will increase the time in a time stamp.
2695 When nil, S-up will increase."
2696 :group 'org-time
2697 :type 'boolean)
2699 (defcustom org-calendar-follow-timestamp-change t
2700 "Non-nil means make the calendar window follow timestamp changes.
2701 When a timestamp is modified and the calendar window is visible, it will be
2702 moved to the new date."
2703 :group 'org-time
2704 :type 'boolean)
2706 (defgroup org-tags nil
2707 "Options concerning tags in Org-mode."
2708 :tag "Org Tags"
2709 :group 'org)
2711 (defcustom org-tag-alist nil
2712 "List of tags allowed in Org-mode files.
2713 When this list is nil, Org-mode will base TAG input on what is already in the
2714 buffer.
2715 The value of this variable is an alist, the car of each entry must be a
2716 keyword as a string, the cdr may be a character that is used to select
2717 that tag through the fast-tag-selection interface.
2718 See the manual for details."
2719 :group 'org-tags
2720 :type '(repeat
2721 (choice
2722 (cons (string :tag "Tag name")
2723 (character :tag "Access char"))
2724 (list :tag "Start radio group"
2725 (const :startgroup)
2726 (option (string :tag "Group description")))
2727 (list :tag "End radio group"
2728 (const :endgroup)
2729 (option (string :tag "Group description")))
2730 (const :tag "New line" (:newline)))))
2732 (defcustom org-tag-persistent-alist nil
2733 "List of tags that will always appear in all Org-mode files.
2734 This is in addition to any in buffer settings or customizations
2735 of `org-tag-alist'.
2736 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2737 The value of this variable is an alist, the car of each entry must be a
2738 keyword as a string, the cdr may be a character that is used to select
2739 that tag through the fast-tag-selection interface.
2740 See the manual for details.
2741 To disable these tags on a per-file basis, insert anywhere in the file:
2742 #+STARTUP: noptag"
2743 :group 'org-tags
2744 :type '(repeat
2745 (choice
2746 (cons (string :tag "Tag name")
2747 (character :tag "Access char"))
2748 (const :tag "Start radio group" (:startgroup))
2749 (const :tag "End radio group" (:endgroup))
2750 (const :tag "New line" (:newline)))))
2752 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2753 "If non-nil, always offer completion for all tags of all agenda files.
2754 Instead of customizing this variable directly, you might want to
2755 set it locally for capture buffers, because there no list of
2756 tags in that file can be created dynamically (there are none).
2758 (add-hook 'org-capture-mode-hook
2759 (lambda ()
2760 (set (make-local-variable
2761 'org-complete-tags-always-offer-all-agenda-tags)
2762 t)))"
2763 :group 'org-tags
2764 :type 'boolean)
2766 (defvar org-file-tags nil
2767 "List of tags that can be inherited by all entries in the file.
2768 The tags will be inherited if the variable `org-use-tag-inheritance'
2769 says they should be.
2770 This variable is populated from #+FILETAGS lines.")
2772 (defcustom org-use-fast-tag-selection 'auto
2773 "Non-nil means use fast tag selection scheme.
2774 This is a special interface to select and deselect tags with single keys.
2775 When nil, fast selection is never used.
2776 When the symbol `auto', fast selection is used if and only if selection
2777 characters for tags have been configured, either through the variable
2778 `org-tag-alist' or through a #+TAGS line in the buffer.
2779 When t, fast selection is always used and selection keys are assigned
2780 automatically if necessary."
2781 :group 'org-tags
2782 :type '(choice
2783 (const :tag "Always" t)
2784 (const :tag "Never" nil)
2785 (const :tag "When selection characters are configured" 'auto)))
2787 (defcustom org-fast-tag-selection-single-key nil
2788 "Non-nil means fast tag selection exits after first change.
2789 When nil, you have to press RET to exit it.
2790 During fast tag selection, you can toggle this flag with `C-c'.
2791 This variable can also have the value `expert'. In this case, the window
2792 displaying the tags menu is not even shown, until you press C-c again."
2793 :group 'org-tags
2794 :type '(choice
2795 (const :tag "No" nil)
2796 (const :tag "Yes" t)
2797 (const :tag "Expert" expert)))
2799 (defvar org-fast-tag-selection-include-todo nil
2800 "Non-nil means fast tags selection interface will also offer TODO states.
2801 This is an undocumented feature, you should not rely on it.")
2803 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2804 "The column to which tags should be indented in a headline.
2805 If this number is positive, it specifies the column. If it is negative,
2806 it means that the tags should be flushright to that column. For example,
2807 -80 works well for a normal 80 character screen."
2808 :group 'org-tags
2809 :type 'integer)
2811 (defcustom org-auto-align-tags t
2812 "Non-nil means realign tags after pro/demotion of TODO state change.
2813 These operations change the length of a headline and therefore shift
2814 the tags around. With this options turned on, after each such operation
2815 the tags are again aligned to `org-tags-column'."
2816 :group 'org-tags
2817 :type 'boolean)
2819 (defcustom org-use-tag-inheritance t
2820 "Non-nil means tags in levels apply also for sublevels.
2821 When nil, only the tags directly given in a specific line apply there.
2822 This may also be a list of tags that should be inherited, or a regexp that
2823 matches tags that should be inherited. Additional control is possible
2824 with the variable `org-tags-exclude-from-inheritance' which gives an
2825 explicit list of tags to be excluded from inheritance., even if the value of
2826 `org-use-tag-inheritance' would select it for inheritance.
2828 If this option is t, a match early-on in a tree can lead to a large
2829 number of matches in the subtree when constructing the agenda or creating
2830 a sparse tree. If you only want to see the first match in a tree during
2831 a search, check out the variable `org-tags-match-list-sublevels'."
2832 :group 'org-tags
2833 :type '(choice
2834 (const :tag "Not" nil)
2835 (const :tag "Always" t)
2836 (repeat :tag "Specific tags" (string :tag "Tag"))
2837 (regexp :tag "Tags matched by regexp")))
2839 (defcustom org-tags-exclude-from-inheritance nil
2840 "List of tags that should never be inherited.
2841 This is a way to exclude a few tags from inheritance. For way to do
2842 the opposite, to actively allow inheritance for selected tags,
2843 see the variable `org-use-tag-inheritance'."
2844 :group 'org-tags
2845 :type '(repeat (string :tag "Tag")))
2847 (defun org-tag-inherit-p (tag)
2848 "Check if TAG is one that should be inherited."
2849 (cond
2850 ((member tag org-tags-exclude-from-inheritance) nil)
2851 ((eq org-use-tag-inheritance t) t)
2852 ((not org-use-tag-inheritance) nil)
2853 ((stringp org-use-tag-inheritance)
2854 (string-match org-use-tag-inheritance tag))
2855 ((listp org-use-tag-inheritance)
2856 (member tag org-use-tag-inheritance))
2857 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2859 (defcustom org-tags-match-list-sublevels t
2860 "Non-nil means list also sublevels of headlines matching a search.
2861 This variable applies to tags/property searches, and also to stuck
2862 projects because this search is based on a tags match as well.
2864 When set to the symbol `indented', sublevels are indented with
2865 leading dots.
2867 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2868 the sublevels of a headline matching a tag search often also match
2869 the same search. Listing all of them can create very long lists.
2870 Setting this variable to nil causes subtrees of a match to be skipped.
2872 This variable is semi-obsolete and probably should always be true. It
2873 is better to limit inheritance to certain tags using the variables
2874 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2875 :group 'org-tags
2876 :type '(choice
2877 (const :tag "No, don't list them" nil)
2878 (const :tag "Yes, do list them" t)
2879 (const :tag "List them, indented with leading dots" indented)))
2881 (defcustom org-tags-sort-function nil
2882 "When set, tags are sorted using this function as a comparator."
2883 :group 'org-tags
2884 :type '(choice
2885 (const :tag "No sorting" nil)
2886 (const :tag "Alphabetical" string<)
2887 (const :tag "Reverse alphabetical" string>)
2888 (function :tag "Custom function" nil)))
2890 (defvar org-tags-history nil
2891 "History of minibuffer reads for tags.")
2892 (defvar org-last-tags-completion-table nil
2893 "The last used completion table for tags.")
2894 (defvar org-after-tags-change-hook nil
2895 "Hook that is run after the tags in a line have changed.")
2897 (defgroup org-properties nil
2898 "Options concerning properties in Org-mode."
2899 :tag "Org Properties"
2900 :group 'org)
2902 (defcustom org-property-format "%-10s %s"
2903 "How property key/value pairs should be formatted by `indent-line'.
2904 When `indent-line' hits a property definition, it will format the line
2905 according to this format, mainly to make sure that the values are
2906 lined-up with respect to each other."
2907 :group 'org-properties
2908 :type 'string)
2910 (defcustom org-use-property-inheritance nil
2911 "Non-nil means properties apply also for sublevels.
2913 This setting is chiefly used during property searches. Turning it on can
2914 cause significant overhead when doing a search, which is why it is not
2915 on by default.
2917 When nil, only the properties directly given in the current entry count.
2918 When t, every property is inherited. The value may also be a list of
2919 properties that should have inheritance, or a regular expression matching
2920 properties that should be inherited.
2922 However, note that some special properties use inheritance under special
2923 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2924 and the properties ending in \"_ALL\" when they are used as descriptor
2925 for valid values of a property.
2927 Note for programmers:
2928 When querying an entry with `org-entry-get', you can control if inheritance
2929 should be used. By default, `org-entry-get' looks only at the local
2930 properties. You can request inheritance by setting the inherit argument
2931 to t (to force inheritance) or to `selective' (to respect the setting
2932 in this variable)."
2933 :group 'org-properties
2934 :type '(choice
2935 (const :tag "Not" nil)
2936 (const :tag "Always" t)
2937 (repeat :tag "Specific properties" (string :tag "Property"))
2938 (regexp :tag "Properties matched by regexp")))
2940 (defun org-property-inherit-p (property)
2941 "Check if PROPERTY is one that should be inherited."
2942 (cond
2943 ((eq org-use-property-inheritance t) t)
2944 ((not org-use-property-inheritance) nil)
2945 ((stringp org-use-property-inheritance)
2946 (string-match org-use-property-inheritance property))
2947 ((listp org-use-property-inheritance)
2948 (member property org-use-property-inheritance))
2949 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2951 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2952 "The default column format, if no other format has been defined.
2953 This variable can be set on the per-file basis by inserting a line
2955 #+COLUMNS: %25ITEM ....."
2956 :group 'org-properties
2957 :type 'string)
2959 (defcustom org-columns-ellipses ".."
2960 "The ellipses to be used when a field in column view is truncated.
2961 When this is the empty string, as many characters as possible are shown,
2962 but then there will be no visual indication that the field has been truncated.
2963 When this is a string of length N, the last N characters of a truncated
2964 field are replaced by this string. If the column is narrower than the
2965 ellipses string, only part of the ellipses string will be shown."
2966 :group 'org-properties
2967 :type 'string)
2969 (defcustom org-columns-modify-value-for-display-function nil
2970 "Function that modifies values for display in column view.
2971 For example, it can be used to cut out a certain part from a time stamp.
2972 The function must take 2 arguments:
2974 column-title The title of the column (*not* the property name)
2975 value The value that should be modified.
2977 The function should return the value that should be displayed,
2978 or nil if the normal value should be used."
2979 :group 'org-properties
2980 :type 'function)
2982 (defcustom org-effort-property "Effort"
2983 "The property that is being used to keep track of effort estimates.
2984 Effort estimates given in this property need to have the format H:MM."
2985 :group 'org-properties
2986 :group 'org-progress
2987 :type '(string :tag "Property"))
2989 (defconst org-global-properties-fixed
2990 '(("VISIBILITY_ALL" . "folded children content all")
2991 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2992 "List of property/value pairs that can be inherited by any entry.
2994 These are fixed values, for the preset properties. The user variable
2995 that can be used to add to this list is `org-global-properties'.
2997 The entries in this list are cons cells where the car is a property
2998 name and cdr is a string with the value. If the value represents
2999 multiple items like an \"_ALL\" property, separate the items by
3000 spaces.")
3002 (defcustom org-global-properties nil
3003 "List of property/value pairs that can be inherited by any entry.
3005 This list will be combined with the constant `org-global-properties-fixed'.
3007 The entries in this list are cons cells where the car is a property
3008 name and cdr is a string with the value.
3010 You can set buffer-local values for the same purpose in the variable
3011 `org-file-properties' this by adding lines like
3013 #+PROPERTY: NAME VALUE"
3014 :group 'org-properties
3015 :type '(repeat
3016 (cons (string :tag "Property")
3017 (string :tag "Value"))))
3019 (defvar org-file-properties nil
3020 "List of property/value pairs that can be inherited by any entry.
3021 Valid for the current buffer.
3022 This variable is populated from #+PROPERTY lines.")
3023 (make-variable-buffer-local 'org-file-properties)
3025 (defgroup org-agenda nil
3026 "Options concerning agenda views in Org-mode."
3027 :tag "Org Agenda"
3028 :group 'org)
3030 (defvar org-category nil
3031 "Variable used by org files to set a category for agenda display.
3032 Such files should use a file variable to set it, for example
3034 # -*- mode: org; org-category: \"ELisp\"
3036 or contain a special line
3038 #+CATEGORY: ELisp
3040 If the file does not specify a category, then file's base name
3041 is used instead.")
3042 (make-variable-buffer-local 'org-category)
3043 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
3045 (defcustom org-agenda-files nil
3046 "The files to be used for agenda display.
3047 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3048 \\[org-remove-file]. You can also use customize to edit the list.
3050 If an entry is a directory, all files in that directory that are matched by
3051 `org-agenda-file-regexp' will be part of the file list.
3053 If the value of the variable is not a list but a single file name, then
3054 the list of agenda files is actually stored and maintained in that file, one
3055 agenda file per line. In this file paths can be given relative to
3056 `org-directory'. Tilde expansion and environment variable substitution
3057 are also made."
3058 :group 'org-agenda
3059 :type '(choice
3060 (repeat :tag "List of files and directories" file)
3061 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3063 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3064 "Regular expression to match files for `org-agenda-files'.
3065 If any element in the list in that variable contains a directory instead
3066 of a normal file, all files in that directory that are matched by this
3067 regular expression will be included."
3068 :group 'org-agenda
3069 :type 'regexp)
3071 (defcustom org-agenda-text-search-extra-files nil
3072 "List of extra files to be searched by text search commands.
3073 These files will be search in addition to the agenda files by the
3074 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3075 Note that these files will only be searched for text search commands,
3076 not for the other agenda views like todo lists, tag searches or the weekly
3077 agenda. This variable is intended to list notes and possibly archive files
3078 that should also be searched by these two commands.
3079 In fact, if the first element in the list is the symbol `agenda-archives',
3080 than all archive files of all agenda files will be added to the search
3081 scope."
3082 :group 'org-agenda
3083 :type '(set :greedy t
3084 (const :tag "Agenda Archives" agenda-archives)
3085 (repeat :inline t (file))))
3087 (if (fboundp 'defvaralias)
3088 (defvaralias 'org-agenda-multi-occur-extra-files
3089 'org-agenda-text-search-extra-files))
3091 (defcustom org-agenda-skip-unavailable-files nil
3092 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3093 A nil value means to remove them, after a query, from the list."
3094 :group 'org-agenda
3095 :type 'boolean)
3097 (defcustom org-calendar-to-agenda-key [?c]
3098 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3099 The command `org-calendar-goto-agenda' will be bound to this key. The
3100 default is the character `c' because then `c' can be used to switch back and
3101 forth between agenda and calendar."
3102 :group 'org-agenda
3103 :type 'sexp)
3105 (defcustom org-calendar-agenda-action-key [?k]
3106 "The key to be installed in `calendar-mode-map' for agenda-action.
3107 The command `org-agenda-action' will be bound to this key. The
3108 default is the character `k' because we use the same key in the agenda."
3109 :group 'org-agenda
3110 :type 'sexp)
3112 (defcustom org-calendar-insert-diary-entry-key [?i]
3113 "The key to be installed in `calendar-mode-map' for adding diary entries.
3114 This option is irrelevant until `org-agenda-diary-file' has been configured
3115 to point to an Org-mode file. When that is the case, the command
3116 `org-agenda-diary-entry' will be bound to the key given here, by default
3117 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3118 if you want to continue doing this, you need to change this to a different
3119 key."
3120 :group 'org-agenda
3121 :type 'sexp)
3123 (defcustom org-agenda-diary-file 'diary-file
3124 "File to which to add new entries with the `i' key in agenda and calendar.
3125 When this is the symbol `diary-file', the functionality in the Emacs
3126 calendar will be used to add entries to the `diary-file'. But when this
3127 points to a file, `org-agenda-diary-entry' will be used instead."
3128 :group 'org-agenda
3129 :type '(choice
3130 (const :tag "The standard Emacs diary file" diary-file)
3131 (file :tag "Special Org file diary entries")))
3133 (eval-after-load "calendar"
3134 '(progn
3135 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3136 'org-calendar-goto-agenda)
3137 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3138 'org-agenda-action)
3139 (add-hook 'calendar-mode-hook
3140 (lambda ()
3141 (unless (eq org-agenda-diary-file 'diary-file)
3142 (define-key calendar-mode-map
3143 org-calendar-insert-diary-entry-key
3144 'org-agenda-diary-entry))))))
3146 (defgroup org-latex nil
3147 "Options for embedding LaTeX code into Org-mode."
3148 :tag "Org LaTeX"
3149 :group 'org)
3151 (defcustom org-format-latex-options
3152 '(:foreground default :background default :scale 1.0
3153 :html-foreground "Black" :html-background "Transparent"
3154 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3155 "Options for creating images from LaTeX fragments.
3156 This is a property list with the following properties:
3157 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3158 `default' means use the foreground of the default face.
3159 :background the background color, or \"Transparent\".
3160 `default' means use the background of the default face.
3161 :scale a scaling factor for the size of the images, to get more pixels
3162 :html-foreground, :html-background, :html-scale
3163 the same numbers for HTML export.
3164 :matchers a list indicating which matchers should be used to
3165 find LaTeX fragments. Valid members of this list are:
3166 \"begin\" find environments
3167 \"$1\" find single characters surrounded by $.$
3168 \"$\" find math expressions surrounded by $...$
3169 \"$$\" find math expressions surrounded by $$....$$
3170 \"\\(\" find math expressions surrounded by \\(...\\)
3171 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3172 :group 'org-latex
3173 :type 'plist)
3175 (defcustom org-format-latex-signal-error t
3176 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3177 When nil, just push out a message."
3178 :group 'org-latex
3179 :type 'boolean)
3181 (defcustom org-format-latex-header "\\documentclass{article}
3182 \\usepackage[usenames]{color}
3183 \\usepackage{amsmath}
3184 \\usepackage[mathscr]{eucal}
3185 \\pagestyle{empty} % do not remove
3186 \[PACKAGES]
3187 \[DEFAULT-PACKAGES]
3188 % The settings below are copied from fullpage.sty
3189 \\setlength{\\textwidth}{\\paperwidth}
3190 \\addtolength{\\textwidth}{-3cm}
3191 \\setlength{\\oddsidemargin}{1.5cm}
3192 \\addtolength{\\oddsidemargin}{-2.54cm}
3193 \\setlength{\\evensidemargin}{\\oddsidemargin}
3194 \\setlength{\\textheight}{\\paperheight}
3195 \\addtolength{\\textheight}{-\\headheight}
3196 \\addtolength{\\textheight}{-\\headsep}
3197 \\addtolength{\\textheight}{-\\footskip}
3198 \\addtolength{\\textheight}{-3cm}
3199 \\setlength{\\topmargin}{1.5cm}
3200 \\addtolength{\\topmargin}{-2.54cm}"
3201 "The document header used for processing LaTeX fragments.
3202 It is imperative that this header make sure that no page number
3203 appears on the page. The package defined in the variables
3204 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3205 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3206 will be appended."
3207 :group 'org-latex
3208 :type 'string)
3210 (defvar org-format-latex-header-extra nil)
3212 (defun org-set-packages-alist (var val)
3213 "Set the packages alist and make sure it has 3 elements per entry."
3214 (set var (mapcar (lambda (x)
3215 (if (and (consp x) (= (length x) 2))
3216 (list (car x) (nth 1 x) t)
3218 val)))
3220 (defun org-get-packages-alist (var)
3222 "Get the packages alist and make sure it has 3 elements per entry."
3223 (mapcar (lambda (x)
3224 (if (and (consp x) (= (length x) 2))
3225 (list (car x) (nth 1 x) t)
3227 (default-value var)))
3229 ;; The following variables are defined here because is it also used
3230 ;; when formatting latex fragments. Originally it was part of the
3231 ;; LaTeX exporter, which is why the name includes "export".
3232 (defcustom org-export-latex-default-packages-alist
3233 '(("AUTO" "inputenc" t)
3234 ("T1" "fontenc" t)
3235 ("" "fixltx2e" nil)
3236 ("" "graphicx" t)
3237 ("" "longtable" nil)
3238 ("" "float" nil)
3239 ("" "wrapfig" nil)
3240 ("" "soul" t)
3241 ("" "textcomp" t)
3242 ("" "marvosym" t)
3243 ("" "wasysym" t)
3244 ("" "latexsym" t)
3245 ("" "amssymb" t)
3246 ("" "hyperref" nil)
3247 "\\tolerance=1000"
3249 "Alist of default packages to be inserted in the header.
3250 Change this only if one of the packages here causes an incompatibility
3251 with another package you are using.
3252 The packages in this list are needed by one part or another of Org-mode
3253 to function properly.
3255 - inputenc, fontenc: for basic font and character selection
3256 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3257 for interpreting the entities in `org-entities'. You can skip some of these
3258 packages if you don't use any of the symbols in it.
3259 - graphicx: for including images
3260 - float, wrapfig: for figure placement
3261 - longtable: for long tables
3262 - hyperref: for cross references
3264 Therefore you should not modify this variable unless you know what you
3265 are doing. The one reason to change it anyway is that you might be loading
3266 some other package that conflicts with one of the default packages.
3267 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3268 If SNIPPET-FLAG is t, the package also needs to be included when
3269 compiling LaTeX snippets into images for inclusion into HTML."
3270 :group 'org-export-latex
3271 :set 'org-set-packages-alist
3272 :get 'org-get-packages-alist
3273 :type '(repeat
3274 (choice
3275 (list :tag "options/package pair"
3276 (string :tag "options")
3277 (string :tag "package")
3278 (boolean :tag "Snippet"))
3279 (string :tag "A line of LaTeX"))))
3281 (defcustom org-export-latex-packages-alist nil
3282 "Alist of packages to be inserted in every LaTeX header.
3283 These will be inserted after `org-export-latex-default-packages-alist'.
3284 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3285 SNIPPET-FLAG, when t, indicates that this package is also needed when
3286 turning LaTeX snippets into images for inclusion into HTML.
3287 Make sure that you only list packages here which:
3288 - you want in every file
3289 - do not conflict with the default packages in
3290 `org-export-latex-default-packages-alist'
3291 - do not conflict with the setup in `org-format-latex-header'."
3292 :group 'org-export-latex
3293 :set 'org-set-packages-alist
3294 :get 'org-get-packages-alist
3295 :type '(repeat
3296 (choice
3297 (list :tag "options/package pair"
3298 (string :tag "options")
3299 (string :tag "package")
3300 (boolean :tag "Snippet"))
3301 (string :tag "A line of LaTeX"))))
3304 (defgroup org-appearance nil
3305 "Settings for Org-mode appearance."
3306 :tag "Org Appearance"
3307 :group 'org)
3309 (defcustom org-level-color-stars-only nil
3310 "Non-nil means fontify only the stars in each headline.
3311 When nil, the entire headline is fontified.
3312 Changing it requires restart of `font-lock-mode' to become effective
3313 also in regions already fontified."
3314 :group 'org-appearance
3315 :type 'boolean)
3317 (defcustom org-hide-leading-stars nil
3318 "Non-nil means hide the first N-1 stars in a headline.
3319 This works by using the face `org-hide' for these stars. This
3320 face is white for a light background, and black for a dark
3321 background. You may have to customize the face `org-hide' to
3322 make this work.
3323 Changing it requires restart of `font-lock-mode' to become effective
3324 also in regions already fontified.
3325 You may also set this on a per-file basis by adding one of the following
3326 lines to the buffer:
3328 #+STARTUP: hidestars
3329 #+STARTUP: showstars"
3330 :group 'org-appearance
3331 :type 'boolean)
3333 (defcustom org-hidden-keywords nil
3334 "List of symbols corresponding to keywords to be hidden the org buffer.
3335 For example, a value '(title) for this list will make the document's title
3336 appear in the buffer without the initial #+TITLE: keyword."
3337 :group 'org-appearance
3338 :type '(set (const :tag "#+AUTHOR" author)
3339 (const :tag "#+DATE" date)
3340 (const :tag "#+EMAIL" email)
3341 (const :tag "#+TITLE" title)))
3343 (defcustom org-fontify-done-headline nil
3344 "Non-nil means change the face of a headline if it is marked DONE.
3345 Normally, only the TODO/DONE keyword indicates the state of a headline.
3346 When this is non-nil, the headline after the keyword is set to the
3347 `org-headline-done' as an additional indication."
3348 :group 'org-appearance
3349 :type 'boolean)
3351 (defcustom org-fontify-emphasized-text t
3352 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3353 Changing this variable requires a restart of Emacs to take effect."
3354 :group 'org-appearance
3355 :type 'boolean)
3357 (defcustom org-fontify-whole-heading-line nil
3358 "Non-nil means fontify the whole line for headings.
3359 This is useful when setting a background color for the
3360 org-level-* faces."
3361 :group 'org-appearance
3362 :type 'boolean)
3364 (defcustom org-highlight-latex-fragments-and-specials nil
3365 "Non-nil means fontify what is treated specially by the exporters."
3366 :group 'org-appearance
3367 :type 'boolean)
3369 (defcustom org-hide-emphasis-markers nil
3370 "Non-nil mean font-lock should hide the emphasis marker characters."
3371 :group 'org-appearance
3372 :type 'boolean)
3374 (defcustom org-pretty-entities nil
3375 "Non-nil means show entities as UTF8 characters.
3376 When nil, the \\name form remains in the buffer."
3377 :group 'org-appearance
3378 :type 'boolean)
3380 (defcustom org-pretty-entities-include-sub-superscripts t
3381 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3382 :group 'org-appearance
3383 :type 'boolean)
3385 (defvar org-emph-re nil
3386 "Regular expression for matching emphasis.
3387 After a match, the match groups contain these elements:
3388 0 The match of the full regular expression, including the characters
3389 before and after the proper match
3390 1 The character before the proper match, or empty at beginning of line
3391 2 The proper match, including the leading and trailing markers
3392 3 The leading marker like * or /, indicating the type of highlighting
3393 4 The text between the emphasis markers, not including the markers
3394 5 The character after the match, empty at the end of a line")
3395 (defvar org-verbatim-re nil
3396 "Regular expression for matching verbatim text.")
3397 (defvar org-emphasis-regexp-components) ; defined just below
3398 (defvar org-emphasis-alist) ; defined just below
3399 (defun org-set-emph-re (var val)
3400 "Set variable and compute the emphasis regular expression."
3401 (set var val)
3402 (when (and (boundp 'org-emphasis-alist)
3403 (boundp 'org-emphasis-regexp-components)
3404 org-emphasis-alist org-emphasis-regexp-components)
3405 (let* ((e org-emphasis-regexp-components)
3406 (pre (car e))
3407 (post (nth 1 e))
3408 (border (nth 2 e))
3409 (body (nth 3 e))
3410 (nl (nth 4 e))
3411 (body1 (concat body "*?"))
3412 (markers (mapconcat 'car org-emphasis-alist ""))
3413 (vmarkers (mapconcat
3414 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3415 org-emphasis-alist "")))
3416 ;; make sure special characters appear at the right position in the class
3417 (if (string-match "\\^" markers)
3418 (setq markers (concat (replace-match "" t t markers) "^")))
3419 (if (string-match "-" markers)
3420 (setq markers (concat (replace-match "" t t markers) "-")))
3421 (if (string-match "\\^" vmarkers)
3422 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3423 (if (string-match "-" vmarkers)
3424 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3425 (if (> nl 0)
3426 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3427 (int-to-string nl) "\\}")))
3428 ;; Make the regexp
3429 (setq org-emph-re
3430 (concat "\\([" pre "]\\|^\\)"
3431 "\\("
3432 "\\([" markers "]\\)"
3433 "\\("
3434 "[^" border "]\\|"
3435 "[^" border "]"
3436 body1
3437 "[^" border "]"
3438 "\\)"
3439 "\\3\\)"
3440 "\\([" post "]\\|$\\)"))
3441 (setq org-verbatim-re
3442 (concat "\\([" pre "]\\|^\\)"
3443 "\\("
3444 "\\([" vmarkers "]\\)"
3445 "\\("
3446 "[^" border "]\\|"
3447 "[^" border "]"
3448 body1
3449 "[^" border "]"
3450 "\\)"
3451 "\\3\\)"
3452 "\\([" post "]\\|$\\)")))))
3454 (defcustom org-emphasis-regexp-components
3455 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3456 "Components used to build the regular expression for emphasis.
3457 This is a list with five entries. Terminology: In an emphasis string
3458 like \" *strong word* \", we call the initial space PREMATCH, the final
3459 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3460 and \"trong wor\" is the body. The different components in this variable
3461 specify what is allowed/forbidden in each part:
3463 pre Chars allowed as prematch. Beginning of line will be allowed too.
3464 post Chars allowed as postmatch. End of line will be allowed too.
3465 border The chars *forbidden* as border characters.
3466 body-regexp A regexp like \".\" to match a body character. Don't use
3467 non-shy groups here, and don't allow newline here.
3468 newline The maximum number of newlines allowed in an emphasis exp.
3470 Use customize to modify this, or restart Emacs after changing it."
3471 :group 'org-appearance
3472 :set 'org-set-emph-re
3473 :type '(list
3474 (sexp :tag "Allowed chars in pre ")
3475 (sexp :tag "Allowed chars in post ")
3476 (sexp :tag "Forbidden chars in border ")
3477 (sexp :tag "Regexp for body ")
3478 (integer :tag "number of newlines allowed")
3479 (option (boolean :tag "Please ignore this button"))))
3481 (defcustom org-emphasis-alist
3482 `(("*" bold "<b>" "</b>")
3483 ("/" italic "<i>" "</i>")
3484 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3485 ("=" org-code "<code>" "</code>" verbatim)
3486 ("~" org-verbatim "<code>" "</code>" verbatim)
3487 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3488 "<del>" "</del>")
3490 "Special syntax for emphasized text.
3491 Text starting and ending with a special character will be emphasized, for
3492 example *bold*, _underlined_ and /italic/. This variable sets the marker
3493 characters, the face to be used by font-lock for highlighting in Org-mode
3494 Emacs buffers, and the HTML tags to be used for this.
3495 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3496 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3497 Use customize to modify this, or restart Emacs after changing it."
3498 :group 'org-appearance
3499 :set 'org-set-emph-re
3500 :type '(repeat
3501 (list
3502 (string :tag "Marker character")
3503 (choice
3504 (face :tag "Font-lock-face")
3505 (plist :tag "Face property list"))
3506 (string :tag "HTML start tag")
3507 (string :tag "HTML end tag")
3508 (option (const verbatim)))))
3510 (defvar org-protecting-blocks
3511 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3512 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3513 This is needed for font-lock setup.")
3515 ;;; Miscellaneous options
3517 (defgroup org-completion nil
3518 "Completion in Org-mode."
3519 :tag "Org Completion"
3520 :group 'org)
3522 (defcustom org-completion-use-ido nil
3523 "Non-nil means use ido completion wherever possible.
3524 Note that `ido-mode' must be active for this variable to be relevant.
3525 If you decide to turn this variable on, you might well want to turn off
3526 `org-outline-path-complete-in-steps'.
3527 See also `org-completion-use-iswitchb'."
3528 :group 'org-completion
3529 :type 'boolean)
3531 (defcustom org-completion-use-iswitchb nil
3532 "Non-nil means use iswitchb completion wherever possible.
3533 Note that `iswitchb-mode' must be active for this variable to be relevant.
3534 If you decide to turn this variable on, you might well want to turn off
3535 `org-outline-path-complete-in-steps'.
3536 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3537 :group 'org-completion
3538 :type 'boolean)
3540 (defcustom org-completion-fallback-command 'hippie-expand
3541 "The expansion command called by \\[pcomplete] in normal context.
3542 Normal means, no org-mode-specific context."
3543 :group 'org-completion
3544 :type 'function)
3546 ;;; Functions and variables from their packages
3547 ;; Declared here to avoid compiler warnings
3549 ;; XEmacs only
3550 (defvar outline-mode-menu-heading)
3551 (defvar outline-mode-menu-show)
3552 (defvar outline-mode-menu-hide)
3553 (defvar zmacs-regions) ; XEmacs regions
3555 ;; Emacs only
3556 (defvar mark-active)
3558 ;; Various packages
3559 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3560 (declare-function calendar-forward-day "cal-move" (arg))
3561 (declare-function calendar-goto-date "cal-move" (date))
3562 (declare-function calendar-goto-today "cal-move" ())
3563 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3564 (defvar calc-embedded-close-formula)
3565 (defvar calc-embedded-open-formula)
3566 (declare-function cdlatex-tab "ext:cdlatex" ())
3567 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3568 (defvar font-lock-unfontify-region-function)
3569 (declare-function iswitchb-read-buffer "iswitchb"
3570 (prompt &optional default require-match start matches-set))
3571 (defvar iswitchb-temp-buflist)
3572 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3573 (defvar org-agenda-tags-todo-honor-ignore-options)
3574 (declare-function org-agenda-skip "org-agenda" ())
3575 (declare-function
3576 org-format-agenda-item "org-agenda"
3577 (extra txt &optional category tags dotime noprefix remove-re habitp))
3578 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3579 (declare-function org-agenda-change-all-lines "org-agenda"
3580 (newhead hdmarker &optional fixface just-this))
3581 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3582 (declare-function org-agenda-maybe-redo "org-agenda" ())
3583 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3584 (beg end))
3585 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3586 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3587 "org-agenda" (&optional end))
3588 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3589 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3590 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3591 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3592 (declare-function org-indent-mode "org-indent" (&optional arg))
3593 (declare-function parse-time-string "parse-time" (string))
3594 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3595 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3596 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3597 (defvar remember-data-file)
3598 (defvar texmathp-why)
3599 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3600 (declare-function table--at-cell-p "table" (position &optional object at-column))
3602 (defvar w3m-current-url)
3603 (defvar w3m-current-title)
3605 (defvar org-latex-regexps)
3607 ;;; Autoload and prepare some org modules
3609 ;; Some table stuff that needs to be defined here, because it is used
3610 ;; by the functions setting up org-mode or checking for table context.
3612 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3613 "Detect an org-type or table-type table.")
3614 (defconst org-table-line-regexp "^[ \t]*|"
3615 "Detect an org-type table line.")
3616 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3617 "Detect an org-type table line.")
3618 (defconst org-table-hline-regexp "^[ \t]*|-"
3619 "Detect an org-type table hline.")
3620 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3621 "Detect a table-type table hline.")
3622 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3623 "Detect the first line outside a table when searching from within it.
3624 This works for both table types.")
3626 ;; Autoload the functions in org-table.el that are needed by functions here.
3628 (eval-and-compile
3629 (org-autoload "org-table"
3630 '(org-table-align org-table-begin org-table-blank-field
3631 org-table-convert org-table-convert-region org-table-copy-down
3632 org-table-copy-region org-table-create
3633 org-table-create-or-convert-from-region
3634 org-table-create-with-table.el org-table-current-dline
3635 org-table-cut-region org-table-delete-column org-table-edit-field
3636 org-table-edit-formulas org-table-end org-table-eval-formula
3637 org-table-export org-table-field-info
3638 org-table-get-stored-formulas org-table-goto-column
3639 org-table-hline-and-move org-table-import org-table-insert-column
3640 org-table-insert-hline org-table-insert-row org-table-iterate
3641 org-table-justify-field-maybe org-table-kill-row
3642 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3643 org-table-move-column org-table-move-column-left
3644 org-table-move-column-right org-table-move-row
3645 org-table-move-row-down org-table-move-row-up
3646 org-table-next-field org-table-next-row org-table-paste-rectangle
3647 org-table-previous-field org-table-recalculate
3648 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3649 org-table-toggle-coordinate-overlays
3650 org-table-toggle-formula-debugger org-table-wrap-region
3651 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3652 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3653 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3655 (defun org-at-table-p (&optional table-type)
3656 "Return t if the cursor is inside an org-type table.
3657 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3658 (if org-enable-table-editor
3659 (save-excursion
3660 (beginning-of-line 1)
3661 (looking-at (if table-type org-table-any-line-regexp
3662 org-table-line-regexp)))
3663 nil))
3664 (defsubst org-table-p () (org-at-table-p))
3666 (defun org-at-table.el-p ()
3667 "Return t if and only if we are at a table.el table."
3668 (and (org-at-table-p 'any)
3669 (save-excursion
3670 (goto-char (org-table-begin 'any))
3671 (looking-at org-table1-hline-regexp))))
3672 (defun org-table-recognize-table.el ()
3673 "If there is a table.el table nearby, recognize it and move into it."
3674 (if org-table-tab-recognizes-table.el
3675 (if (org-at-table.el-p)
3676 (progn
3677 (beginning-of-line 1)
3678 (if (looking-at org-table-dataline-regexp)
3680 (if (looking-at org-table1-hline-regexp)
3681 (progn
3682 (beginning-of-line 2)
3683 (if (looking-at org-table-any-border-regexp)
3684 (beginning-of-line -1)))))
3685 (if (re-search-forward "|" (org-table-end t) t)
3686 (progn
3687 (require 'table)
3688 (if (table--at-cell-p (point))
3690 (message "recognizing table.el table...")
3691 (table-recognize-table)
3692 (message "recognizing table.el table...done")))
3693 (error "This should not happen"))
3695 nil)
3696 nil))
3698 (defun org-at-table-hline-p ()
3699 "Return t if the cursor is inside a hline in a table."
3700 (if org-enable-table-editor
3701 (save-excursion
3702 (beginning-of-line 1)
3703 (looking-at org-table-hline-regexp))
3704 nil))
3706 (defvar org-table-clean-did-remove-column nil)
3708 (defun org-table-map-tables (function &optional quietly)
3709 "Apply FUNCTION to the start of all tables in the buffer."
3710 (save-excursion
3711 (save-restriction
3712 (widen)
3713 (goto-char (point-min))
3714 (while (re-search-forward org-table-any-line-regexp nil t)
3715 (unless quietly
3716 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3717 (beginning-of-line 1)
3718 (when (looking-at org-table-line-regexp)
3719 (save-excursion (funcall function))
3720 (or (looking-at org-table-line-regexp)
3721 (forward-char 1)))
3722 (re-search-forward org-table-any-border-regexp nil 1))))
3723 (unless quietly (message "Mapping tables: done")))
3725 ;; Declare and autoload functions from org-exp.el & Co
3727 (declare-function org-default-export-plist "org-exp")
3728 (declare-function org-infile-export-plist "org-exp")
3729 (declare-function org-get-current-options "org-exp")
3730 (eval-and-compile
3731 (org-autoload "org-exp"
3732 '(org-export org-export-visible
3733 org-insert-export-options-template
3734 org-table-clean-before-export))
3735 (org-autoload "org-ascii"
3736 '(org-export-as-ascii org-export-ascii-preprocess
3737 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3738 org-export-region-as-ascii))
3739 (org-autoload "org-latex"
3740 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3741 org-replace-region-by-latex org-export-region-as-latex
3742 org-export-as-latex org-export-as-pdf
3743 org-export-as-pdf-and-open))
3744 (org-autoload "org-html"
3745 '(org-export-as-html-and-open
3746 org-export-as-html-batch org-export-as-html-to-buffer
3747 org-replace-region-by-html org-export-region-as-html
3748 org-export-as-html))
3749 (org-autoload "org-docbook"
3750 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3751 org-replace-region-by-docbook org-export-region-as-docbook
3752 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3753 org-export-as-docbook))
3754 (org-autoload "org-icalendar"
3755 '(org-export-icalendar-this-file
3756 org-export-icalendar-all-agenda-files
3757 org-export-icalendar-combine-agenda-files))
3758 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3759 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3761 ;; Declare and autoload functions from org-agenda.el
3763 (eval-and-compile
3764 (org-autoload "org-agenda"
3765 '(org-agenda org-agenda-list org-search-view
3766 org-todo-list org-tags-view org-agenda-list-stuck-projects
3767 org-diary org-agenda-to-appt
3768 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3770 ;; Autoload org-remember
3772 (eval-and-compile
3773 (org-autoload "org-remember"
3774 '(org-remember-insinuate org-remember-annotation
3775 org-remember-apply-template org-remember org-remember-handler)))
3777 (eval-and-compile
3778 (org-autoload "org-capture"
3779 '(org-capture org-capture-insert-template-here
3780 org-capture-import-remember-templates)))
3782 ;; Autoload org-clock.el
3784 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3785 (beg end))
3786 (declare-function org-clock-update-mode-line "org-clock" ())
3787 (declare-function org-resolve-clocks "org-clock"
3788 (&optional also-non-dangling-p prompt last-valid))
3789 (defvar org-clock-start-time)
3790 (defvar org-clock-marker (make-marker)
3791 "Marker recording the last clock-in.")
3792 (defvar org-clock-hd-marker (make-marker)
3793 "Marker recording the last clock-in, but the headline position.")
3794 (defvar org-clock-heading ""
3795 "The heading of the current clock entry.")
3796 (defun org-clock-is-active ()
3797 "Return non-nil if clock is currently running.
3798 The return value is actually the clock marker."
3799 (marker-buffer org-clock-marker))
3801 (eval-and-compile
3802 (org-autoload
3803 "org-clock"
3804 '(org-clock-in org-clock-out org-clock-cancel
3805 org-clock-goto org-clock-sum org-clock-display
3806 org-clock-remove-overlays org-clock-report
3807 org-clocktable-shift org-dblock-write:clocktable
3808 org-get-clocktable org-resolve-clocks)))
3810 (defun org-clock-update-time-maybe ()
3811 "If this is a CLOCK line, update it and return t.
3812 Otherwise, return nil."
3813 (interactive)
3814 (save-excursion
3815 (beginning-of-line 1)
3816 (skip-chars-forward " \t")
3817 (when (looking-at org-clock-string)
3818 (let ((re (concat "[ \t]*" org-clock-string
3819 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3820 "\\([ \t]*=>.*\\)?\\)?"))
3821 ts te h m s neg)
3822 (cond
3823 ((not (looking-at re))
3824 nil)
3825 ((not (match-end 2))
3826 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3827 (> org-clock-marker (point))
3828 (<= org-clock-marker (point-at-eol)))
3829 ;; The clock is running here
3830 (setq org-clock-start-time
3831 (apply 'encode-time
3832 (org-parse-time-string (match-string 1))))
3833 (org-clock-update-mode-line)))
3835 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3836 (end-of-line 1)
3837 (setq ts (match-string 1)
3838 te (match-string 3))
3839 (setq s (- (org-float-time
3840 (apply 'encode-time (org-parse-time-string te)))
3841 (org-float-time
3842 (apply 'encode-time (org-parse-time-string ts))))
3843 neg (< s 0)
3844 s (abs s)
3845 h (floor (/ s 3600))
3846 s (- s (* 3600 h))
3847 m (floor (/ s 60))
3848 s (- s (* 60 s)))
3849 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3850 t))))))
3852 (defun org-check-running-clock ()
3853 "Check if the current buffer contains the running clock.
3854 If yes, offer to stop it and to save the buffer with the changes."
3855 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3856 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3857 (buffer-name))))
3858 (org-clock-out)
3859 (when (y-or-n-p "Save changed buffer?")
3860 (save-buffer))))
3862 (defun org-clocktable-try-shift (dir n)
3863 "Check if this line starts a clock table, if yes, shift the time block."
3864 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3865 (org-clocktable-shift dir n)))
3867 ;; Autoload org-timer.el
3869 (eval-and-compile
3870 (org-autoload
3871 "org-timer"
3872 '(org-timer-start org-timer org-timer-item
3873 org-timer-change-times-in-region
3874 org-timer-set-timer
3875 org-timer-reset-timers
3876 org-timer-show-remaining-time)))
3878 ;; Autoload org-feed.el
3880 (eval-and-compile
3881 (org-autoload
3882 "org-feed"
3883 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3886 ;; Autoload org-indent.el
3888 ;; Define the variable already here, to make sure we have it.
3889 (defvar org-indent-mode nil
3890 "Non-nil if Org-Indent mode is enabled.
3891 Use the command `org-indent-mode' to change this variable.")
3893 (eval-and-compile
3894 (org-autoload
3895 "org-indent"
3896 '(org-indent-mode)))
3898 ;; Autoload org-mobile.el
3900 (eval-and-compile
3901 (org-autoload
3902 "org-mobile"
3903 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3905 ;; Autoload archiving code
3906 ;; The stuff that is needed for cycling and tags has to be defined here.
3908 (defgroup org-archive nil
3909 "Options concerning archiving in Org-mode."
3910 :tag "Org Archive"
3911 :group 'org-structure)
3913 (defcustom org-archive-location "%s_archive::"
3914 "The location where subtrees should be archived.
3916 The value of this variable is a string, consisting of two parts,
3917 separated by a double-colon. The first part is a filename and
3918 the second part is a headline.
3920 When the filename is omitted, archiving happens in the same file.
3921 %s in the filename will be replaced by the current file
3922 name (without the directory part). Archiving to a different file
3923 is useful to keep archived entries from contributing to the
3924 Org-mode Agenda.
3926 The archived entries will be filed as subtrees of the specified
3927 headline. When the headline is omitted, the subtrees are simply
3928 filed away at the end of the file, as top-level entries. Also in
3929 the heading you can use %s to represent the file name, this can be
3930 useful when using the same archive for a number of different files.
3932 Here are a few examples:
3933 \"%s_archive::\"
3934 If the current file is Projects.org, archive in file
3935 Projects.org_archive, as top-level trees. This is the default.
3937 \"::* Archived Tasks\"
3938 Archive in the current file, under the top-level headline
3939 \"* Archived Tasks\".
3941 \"~/org/archive.org::\"
3942 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3944 \"~/org/archive.org::From %s\"
3945 Archive in file ~/org/archive.org (absolute path), under headlines
3946 \"From FILENAME\" where file name is the current file name.
3948 \"basement::** Finished Tasks\"
3949 Archive in file ./basement (relative path), as level 3 trees
3950 below the level 2 heading \"** Finished Tasks\".
3952 You may set this option on a per-file basis by adding to the buffer a
3953 line like
3955 #+ARCHIVE: basement::** Finished Tasks
3957 You may also define it locally for a subtree by setting an ARCHIVE property
3958 in the entry. If such a property is found in an entry, or anywhere up
3959 the hierarchy, it will be used."
3960 :group 'org-archive
3961 :type 'string)
3963 (defcustom org-archive-tag "ARCHIVE"
3964 "The tag that marks a subtree as archived.
3965 An archived subtree does not open during visibility cycling, and does
3966 not contribute to the agenda listings.
3967 After changing this, font-lock must be restarted in the relevant buffers to
3968 get the proper fontification."
3969 :group 'org-archive
3970 :group 'org-keywords
3971 :type 'string)
3973 (defcustom org-agenda-skip-archived-trees t
3974 "Non-nil means the agenda will skip any items located in archived trees.
3975 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3976 variable is no longer recommended, you should leave it at the value t.
3977 Instead, use the key `v' to cycle the archives-mode in the agenda."
3978 :group 'org-archive
3979 :group 'org-agenda-skip
3980 :type 'boolean)
3982 (defcustom org-columns-skip-archived-trees t
3983 "Non-nil means ignore archived trees when creating column view."
3984 :group 'org-archive
3985 :group 'org-properties
3986 :type 'boolean)
3988 (defcustom org-cycle-open-archived-trees nil
3989 "Non-nil means `org-cycle' will open archived trees.
3990 An archived tree is a tree marked with the tag ARCHIVE.
3991 When nil, archived trees will stay folded. You can still open them with
3992 normal outline commands like `show-all', but not with the cycling commands."
3993 :group 'org-archive
3994 :group 'org-cycle
3995 :type 'boolean)
3997 (defcustom org-sparse-tree-open-archived-trees nil
3998 "Non-nil means sparse tree construction shows matches in archived trees.
3999 When nil, matches in these trees are highlighted, but the trees are kept in
4000 collapsed state."
4001 :group 'org-archive
4002 :group 'org-sparse-trees
4003 :type 'boolean)
4005 (defun org-cycle-hide-archived-subtrees (state)
4006 "Re-hide all archived subtrees after a visibility state change."
4007 (when (and (not org-cycle-open-archived-trees)
4008 (not (memq state '(overview folded))))
4009 (save-excursion
4010 (let* ((globalp (memq state '(contents all)))
4011 (beg (if globalp (point-min) (point)))
4012 (end (if globalp (point-max) (org-end-of-subtree t))))
4013 (org-hide-archived-subtrees beg end)
4014 (goto-char beg)
4015 (if (looking-at (concat ".*:" org-archive-tag ":"))
4016 (message "%s" (substitute-command-keys
4017 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4019 (defun org-force-cycle-archived ()
4020 "Cycle subtree even if it is archived."
4021 (interactive)
4022 (setq this-command 'org-cycle)
4023 (let ((org-cycle-open-archived-trees t))
4024 (call-interactively 'org-cycle)))
4026 (defun org-hide-archived-subtrees (beg end)
4027 "Re-hide all archived subtrees after a visibility state change."
4028 (save-excursion
4029 (let* ((re (concat ":" org-archive-tag ":")))
4030 (goto-char beg)
4031 (while (re-search-forward re end t)
4032 (when (org-on-heading-p)
4033 (org-flag-subtree t)
4034 (org-end-of-subtree t))))))
4036 (defun org-flag-subtree (flag)
4037 (save-excursion
4038 (org-back-to-heading t)
4039 (outline-end-of-heading)
4040 (outline-flag-region (point)
4041 (progn (org-end-of-subtree t) (point))
4042 flag)))
4044 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4046 (eval-and-compile
4047 (org-autoload "org-archive"
4048 '(org-add-archive-files org-archive-subtree
4049 org-archive-to-archive-sibling org-toggle-archive-tag
4050 org-archive-subtree-default
4051 org-archive-subtree-default-with-confirmation)))
4053 ;; Autoload Column View Code
4055 (declare-function org-columns-number-to-string "org-colview")
4056 (declare-function org-columns-get-format-and-top-level "org-colview")
4057 (declare-function org-columns-compute "org-colview")
4059 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4060 '(org-columns-number-to-string org-columns-get-format-and-top-level
4061 org-columns-compute org-agenda-columns org-columns-remove-overlays
4062 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4064 ;; Autoload ID code
4066 (declare-function org-id-store-link "org-id")
4067 (declare-function org-id-locations-load "org-id")
4068 (declare-function org-id-locations-save "org-id")
4069 (defvar org-id-track-globally)
4070 (org-autoload "org-id"
4071 '(org-id-get-create org-id-new org-id-copy org-id-get
4072 org-id-get-with-outline-path-completion
4073 org-id-get-with-outline-drilling org-id-store-link
4074 org-id-goto org-id-find org-id-store-link))
4076 ;; Autoload Plotting Code
4078 (org-autoload "org-plot"
4079 '(org-plot/gnuplot))
4081 ;;; Variables for pre-computed regular expressions, all buffer local
4083 (defvar org-drawer-regexp nil
4084 "Matches first line of a hidden block.")
4085 (make-variable-buffer-local 'org-drawer-regexp)
4086 (defvar org-todo-regexp nil
4087 "Matches any of the TODO state keywords.")
4088 (make-variable-buffer-local 'org-todo-regexp)
4089 (defvar org-not-done-regexp nil
4090 "Matches any of the TODO state keywords except the last one.")
4091 (make-variable-buffer-local 'org-not-done-regexp)
4092 (defvar org-not-done-heading-regexp nil
4093 "Matches a TODO headline that is not done.")
4094 (make-variable-buffer-local 'org-not-done-regexp)
4095 (defvar org-todo-line-regexp nil
4096 "Matches a headline and puts TODO state into group 2 if present.")
4097 (make-variable-buffer-local 'org-todo-line-regexp)
4098 (defvar org-complex-heading-regexp nil
4099 "Matches a headline and puts everything into groups:
4100 group 1: the stars
4101 group 2: The todo keyword, maybe
4102 group 3: Priority cookie
4103 group 4: True headline
4104 group 5: Tags")
4105 (make-variable-buffer-local 'org-complex-heading-regexp)
4106 (defvar org-complex-heading-regexp-format nil
4107 "Printf format to make regexp to match an exact headline.
4108 This regexp will match the headline of any node which hase the exact
4109 headline text that is put into the format, but may have any TODO state,
4110 priority and tags.")
4111 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4112 (defvar org-todo-line-tags-regexp nil
4113 "Matches a headline and puts TODO state into group 2 if present.
4114 Also put tags into group 4 if tags are present.")
4115 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4116 (defvar org-nl-done-regexp nil
4117 "Matches newline followed by a headline with the DONE keyword.")
4118 (make-variable-buffer-local 'org-nl-done-regexp)
4119 (defvar org-looking-at-done-regexp nil
4120 "Matches the DONE keyword a point.")
4121 (make-variable-buffer-local 'org-looking-at-done-regexp)
4122 (defvar org-ds-keyword-length 12
4123 "Maximum length of the Deadline and SCHEDULED keywords.")
4124 (make-variable-buffer-local 'org-ds-keyword-length)
4125 (defvar org-deadline-regexp nil
4126 "Matches the DEADLINE keyword.")
4127 (make-variable-buffer-local 'org-deadline-regexp)
4128 (defvar org-deadline-time-regexp nil
4129 "Matches the DEADLINE keyword together with a time stamp.")
4130 (make-variable-buffer-local 'org-deadline-time-regexp)
4131 (defvar org-deadline-line-regexp nil
4132 "Matches the DEADLINE keyword and the rest of the line.")
4133 (make-variable-buffer-local 'org-deadline-line-regexp)
4134 (defvar org-scheduled-regexp nil
4135 "Matches the SCHEDULED keyword.")
4136 (make-variable-buffer-local 'org-scheduled-regexp)
4137 (defvar org-scheduled-time-regexp nil
4138 "Matches the SCHEDULED keyword together with a time stamp.")
4139 (make-variable-buffer-local 'org-scheduled-time-regexp)
4140 (defvar org-closed-time-regexp nil
4141 "Matches the CLOSED keyword together with a time stamp.")
4142 (make-variable-buffer-local 'org-closed-time-regexp)
4144 (defvar org-keyword-time-regexp nil
4145 "Matches any of the 4 keywords, together with the time stamp.")
4146 (make-variable-buffer-local 'org-keyword-time-regexp)
4147 (defvar org-keyword-time-not-clock-regexp nil
4148 "Matches any of the 3 keywords, together with the time stamp.")
4149 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4150 (defvar org-maybe-keyword-time-regexp nil
4151 "Matches a timestamp, possibly preceded by a keyword.")
4152 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4153 (defvar org-planning-or-clock-line-re nil
4154 "Matches a line with planning or clock info.")
4155 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4156 (defvar org-all-time-keywords nil
4157 "List of time keywords.")
4158 (make-variable-buffer-local 'org-all-time-keywords)
4160 (defconst org-plain-time-of-day-regexp
4161 (concat
4162 "\\(\\<[012]?[0-9]"
4163 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4164 "\\(--?"
4165 "\\(\\<[012]?[0-9]"
4166 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4167 "\\)?")
4168 "Regular expression to match a plain time or time range.
4169 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4170 groups carry important information:
4171 0 the full match
4172 1 the first time, range or not
4173 8 the second time, if it is a range.")
4175 (defconst org-plain-time-extension-regexp
4176 (concat
4177 "\\(\\<[012]?[0-9]"
4178 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4179 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4180 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4181 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4182 groups carry important information:
4183 0 the full match
4184 7 hours of duration
4185 9 minutes of duration")
4187 (defconst org-stamp-time-of-day-regexp
4188 (concat
4189 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4190 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4191 "\\(--?"
4192 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4193 "Regular expression to match a timestamp time or time range.
4194 After a match, the following groups carry important information:
4195 0 the full match
4196 1 date plus weekday, for back referencing to make sure both times are on the same day
4197 2 the first time, range or not
4198 4 the second time, if it is a range.")
4200 (defconst org-startup-options
4201 '(("fold" org-startup-folded t)
4202 ("overview" org-startup-folded t)
4203 ("nofold" org-startup-folded nil)
4204 ("showall" org-startup-folded nil)
4205 ("showeverything" org-startup-folded showeverything)
4206 ("content" org-startup-folded content)
4207 ("indent" org-startup-indented t)
4208 ("noindent" org-startup-indented nil)
4209 ("hidestars" org-hide-leading-stars t)
4210 ("showstars" org-hide-leading-stars nil)
4211 ("odd" org-odd-levels-only t)
4212 ("oddeven" org-odd-levels-only nil)
4213 ("align" org-startup-align-all-tables t)
4214 ("noalign" org-startup-align-all-tables nil)
4215 ("inlineimages" org-startup-with-inline-images t)
4216 ("noinlineimages" org-startup-with-inline-images nil)
4217 ("customtime" org-display-custom-times t)
4218 ("logdone" org-log-done time)
4219 ("lognotedone" org-log-done note)
4220 ("nologdone" org-log-done nil)
4221 ("lognoteclock-out" org-log-note-clock-out t)
4222 ("nolognoteclock-out" org-log-note-clock-out nil)
4223 ("logrepeat" org-log-repeat state)
4224 ("lognoterepeat" org-log-repeat note)
4225 ("nologrepeat" org-log-repeat nil)
4226 ("logreschedule" org-log-reschedule time)
4227 ("lognotereschedule" org-log-reschedule note)
4228 ("nologreschedule" org-log-reschedule nil)
4229 ("logredeadline" org-log-redeadline time)
4230 ("lognoteredeadline" org-log-redeadline note)
4231 ("nologredeadline" org-log-redeadline nil)
4232 ("logrefile" org-log-refile time)
4233 ("lognoterefile" org-log-refile note)
4234 ("nologrefile" org-log-refile nil)
4235 ("fninline" org-footnote-define-inline t)
4236 ("nofninline" org-footnote-define-inline nil)
4237 ("fnlocal" org-footnote-section nil)
4238 ("fnauto" org-footnote-auto-label t)
4239 ("fnprompt" org-footnote-auto-label nil)
4240 ("fnconfirm" org-footnote-auto-label confirm)
4241 ("fnplain" org-footnote-auto-label plain)
4242 ("fnadjust" org-footnote-auto-adjust t)
4243 ("nofnadjust" org-footnote-auto-adjust nil)
4244 ("constcgs" constants-unit-system cgs)
4245 ("constSI" constants-unit-system SI)
4246 ("noptag" org-tag-persistent-alist nil)
4247 ("hideblocks" org-hide-block-startup t)
4248 ("nohideblocks" org-hide-block-startup nil)
4249 ("beamer" org-startup-with-beamer-mode t)
4250 ("entitiespretty" org-pretty-entities t)
4251 ("entitiesplain" org-pretty-entities nil))
4252 "Variable associated with STARTUP options for org-mode.
4253 Each element is a list of three items: The startup options as written
4254 in the #+STARTUP line, the corresponding variable, and the value to
4255 set this variable to if the option is found. An optional forth element PUSH
4256 means to push this value onto the list in the variable.")
4258 (defun org-set-regexps-and-options ()
4259 "Precompute regular expressions for current buffer."
4260 (when (org-mode-p)
4261 (org-set-local 'org-todo-kwd-alist nil)
4262 (org-set-local 'org-todo-key-alist nil)
4263 (org-set-local 'org-todo-key-trigger nil)
4264 (org-set-local 'org-todo-keywords-1 nil)
4265 (org-set-local 'org-done-keywords nil)
4266 (org-set-local 'org-todo-heads nil)
4267 (org-set-local 'org-todo-sets nil)
4268 (org-set-local 'org-todo-log-states nil)
4269 (org-set-local 'org-file-properties nil)
4270 (org-set-local 'org-file-tags nil)
4271 (let ((re (org-make-options-regexp
4272 '("CATEGORY" "TODO" "COLUMNS"
4273 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4274 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4275 "OPTIONS")
4276 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4277 (splitre "[ \t]+")
4278 (scripts org-use-sub-superscripts)
4279 kwds kws0 kwsa key log value cat arch tags const links hw dws
4280 tail sep kws1 prio props ftags drawers beamer-p
4281 ext-setup-or-nil setup-contents (start 0))
4282 (save-excursion
4283 (save-restriction
4284 (widen)
4285 (goto-char (point-min))
4286 (while (or (and ext-setup-or-nil
4287 (string-match re ext-setup-or-nil start)
4288 (setq start (match-end 0)))
4289 (and (setq ext-setup-or-nil nil start 0)
4290 (re-search-forward re nil t)))
4291 (setq key (upcase (match-string 1 ext-setup-or-nil))
4292 value (org-match-string-no-properties 2 ext-setup-or-nil))
4293 (if (stringp value) (setq value (org-trim value)))
4294 (cond
4295 ((equal key "CATEGORY")
4296 (setq cat value))
4297 ((member key '("SEQ_TODO" "TODO"))
4298 (push (cons 'sequence (org-split-string value splitre)) kwds))
4299 ((equal key "TYP_TODO")
4300 (push (cons 'type (org-split-string value splitre)) kwds))
4301 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4302 ;; general TODO-like setup
4303 (push (cons (intern (downcase (match-string 1 key)))
4304 (org-split-string value splitre)) kwds))
4305 ((equal key "TAGS")
4306 (setq tags (append tags (if tags '("\\n") nil)
4307 (org-split-string value splitre))))
4308 ((equal key "COLUMNS")
4309 (org-set-local 'org-columns-default-format value))
4310 ((equal key "LINK")
4311 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4312 (push (cons (match-string 1 value)
4313 (org-trim (match-string 2 value)))
4314 links)))
4315 ((equal key "PRIORITIES")
4316 (setq prio (org-split-string value " +")))
4317 ((equal key "PROPERTY")
4318 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4319 (push (cons (match-string 1 value) (match-string 2 value))
4320 props)))
4321 ((equal key "FILETAGS")
4322 (when (string-match "\\S-" value)
4323 (setq ftags
4324 (append
4325 ftags
4326 (apply 'append
4327 (mapcar (lambda (x) (org-split-string x ":"))
4328 (org-split-string value)))))))
4329 ((equal key "DRAWERS")
4330 (setq drawers (org-split-string value splitre)))
4331 ((equal key "CONSTANTS")
4332 (setq const (append const (org-split-string value splitre))))
4333 ((equal key "STARTUP")
4334 (let ((opts (org-split-string value splitre))
4335 l var val)
4336 (while (setq l (pop opts))
4337 (when (setq l (assoc l org-startup-options))
4338 (setq var (nth 1 l) val (nth 2 l))
4339 (if (not (nth 3 l))
4340 (set (make-local-variable var) val)
4341 (if (not (listp (symbol-value var)))
4342 (set (make-local-variable var) nil))
4343 (set (make-local-variable var) (symbol-value var))
4344 (add-to-list var val))))))
4345 ((equal key "ARCHIVE")
4346 (setq arch value)
4347 (remove-text-properties 0 (length arch)
4348 '(face t fontified t) arch))
4349 ((equal key "LATEX_CLASS")
4350 (setq beamer-p (equal value "beamer")))
4351 ((equal key "OPTIONS")
4352 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4353 (setq scripts (read (match-string 2 value)))))
4354 ((equal key "SETUPFILE")
4355 (setq setup-contents (org-file-contents
4356 (expand-file-name
4357 (org-remove-double-quotes value))
4358 'noerror))
4359 (if (not ext-setup-or-nil)
4360 (setq ext-setup-or-nil setup-contents start 0)
4361 (setq ext-setup-or-nil
4362 (concat (substring ext-setup-or-nil 0 start)
4363 "\n" setup-contents "\n"
4364 (substring ext-setup-or-nil start)))))
4365 ))))
4366 (org-set-local 'org-use-sub-superscripts scripts)
4367 (when cat
4368 (org-set-local 'org-category (intern cat))
4369 (push (cons "CATEGORY" cat) props))
4370 (when prio
4371 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4372 (setq prio (mapcar 'string-to-char prio))
4373 (org-set-local 'org-highest-priority (nth 0 prio))
4374 (org-set-local 'org-lowest-priority (nth 1 prio))
4375 (org-set-local 'org-default-priority (nth 2 prio)))
4376 (and props (org-set-local 'org-file-properties (nreverse props)))
4377 (and ftags (org-set-local 'org-file-tags
4378 (mapcar 'org-add-prop-inherited ftags)))
4379 (and drawers (org-set-local 'org-drawers drawers))
4380 (and arch (org-set-local 'org-archive-location arch))
4381 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4382 ;; Process the TODO keywords
4383 (unless kwds
4384 ;; Use the global values as if they had been given locally.
4385 (setq kwds (default-value 'org-todo-keywords))
4386 (if (stringp (car kwds))
4387 (setq kwds (list (cons org-todo-interpretation
4388 (default-value 'org-todo-keywords)))))
4389 (setq kwds (reverse kwds)))
4390 (setq kwds (nreverse kwds))
4391 (let (inter kws kw)
4392 (while (setq kws (pop kwds))
4393 (let ((kws (or
4394 (run-hook-with-args-until-success
4395 'org-todo-setup-filter-hook kws)
4396 kws)))
4397 (setq inter (pop kws) sep (member "|" kws)
4398 kws0 (delete "|" (copy-sequence kws))
4399 kwsa nil
4400 kws1 (mapcar
4401 (lambda (x)
4402 ;; 1 2
4403 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4404 (progn
4405 (setq kw (match-string 1 x)
4406 key (and (match-end 2) (match-string 2 x))
4407 log (org-extract-log-state-settings x))
4408 (push (cons kw (and key (string-to-char key))) kwsa)
4409 (and log (push log org-todo-log-states))
4411 (error "Invalid TODO keyword %s" x)))
4412 kws0)
4413 kwsa (if kwsa (append '((:startgroup))
4414 (nreverse kwsa)
4415 '((:endgroup))))
4416 hw (car kws1)
4417 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4418 tail (list inter hw (car dws) (org-last dws))))
4419 (add-to-list 'org-todo-heads hw 'append)
4420 (push kws1 org-todo-sets)
4421 (setq org-done-keywords (append org-done-keywords dws nil))
4422 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4423 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4424 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4425 (setq org-todo-sets (nreverse org-todo-sets)
4426 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4427 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4428 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4429 ;; Process the constants
4430 (when const
4431 (let (e cst)
4432 (while (setq e (pop const))
4433 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4434 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4435 (setq org-table-formula-constants-local cst)))
4437 ;; Process the tags.
4438 (when tags
4439 (let (e tgs)
4440 (while (setq e (pop tags))
4441 (cond
4442 ((equal e "{") (push '(:startgroup) tgs))
4443 ((equal e "}") (push '(:endgroup) tgs))
4444 ((equal e "\\n") (push '(:newline) tgs))
4445 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4446 (push (cons (match-string 1 e)
4447 (string-to-char (match-string 2 e)))
4448 tgs))
4449 (t (push (list e) tgs))))
4450 (org-set-local 'org-tag-alist nil)
4451 (while (setq e (pop tgs))
4452 (or (and (stringp (car e))
4453 (assoc (car e) org-tag-alist))
4454 (push e org-tag-alist)))))
4456 ;; Compute the regular expressions and other local variables
4457 (if (not org-done-keywords)
4458 (setq org-done-keywords (and org-todo-keywords-1
4459 (list (org-last org-todo-keywords-1)))))
4460 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4461 (length org-scheduled-string)
4462 (length org-clock-string)
4463 (length org-closed-string)))
4464 org-drawer-regexp
4465 (concat "^[ \t]*:\\("
4466 (mapconcat 'regexp-quote org-drawers "\\|")
4467 "\\):[ \t]*$")
4468 org-not-done-keywords
4469 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4470 org-todo-regexp
4471 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4472 "\\|") "\\)\\>")
4473 org-not-done-regexp
4474 (concat "\\<\\("
4475 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4476 "\\)\\>")
4477 org-not-done-heading-regexp
4478 (concat "^\\(\\*+\\)[ \t]+\\("
4479 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4480 "\\)\\>")
4481 org-todo-line-regexp
4482 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4483 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4484 "\\)\\>\\)?[ \t]*\\(.*\\)")
4485 org-complex-heading-regexp
4486 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4487 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4488 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4489 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
4490 org-complex-heading-regexp-format
4491 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4492 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4493 "\\)\\>\\)?"
4494 "\\(?:[ \t]*\\(\\[#.\\]\\)\\)?"
4495 "\\(?:[ \t]*\\(?:\\[[0-9%%/]+\\]\\)\\)?" ;; stats cookie
4496 "[ \t]*\\(%s\\)"
4497 "\\(?:[ \t]*\\(?:\\[[0-9%%/]+\\]\\)\\)?" ;; stats cookie
4498 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?[ \t]*$")
4499 org-nl-done-regexp
4500 (concat "\n\\*+[ \t]+"
4501 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4502 "\\)" "\\>")
4503 org-todo-line-tags-regexp
4504 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4505 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4506 (org-re
4507 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@#%]+:[ \t]*\\)?$\\)"))
4508 org-looking-at-done-regexp
4509 (concat "^" "\\(?:"
4510 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4511 "\\>")
4512 org-deadline-regexp (concat "\\<" org-deadline-string)
4513 org-deadline-time-regexp
4514 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4515 org-deadline-line-regexp
4516 (concat "\\<\\(" org-deadline-string "\\).*")
4517 org-scheduled-regexp
4518 (concat "\\<" org-scheduled-string)
4519 org-scheduled-time-regexp
4520 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4521 org-closed-time-regexp
4522 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4523 org-keyword-time-regexp
4524 (concat "\\<\\(" org-scheduled-string
4525 "\\|" org-deadline-string
4526 "\\|" org-closed-string
4527 "\\|" org-clock-string "\\)"
4528 " *[[<]\\([^]>]+\\)[]>]")
4529 org-keyword-time-not-clock-regexp
4530 (concat "\\<\\(" org-scheduled-string
4531 "\\|" org-deadline-string
4532 "\\|" org-closed-string
4533 "\\)"
4534 " *[[<]\\([^]>]+\\)[]>]")
4535 org-maybe-keyword-time-regexp
4536 (concat "\\(\\<\\(" org-scheduled-string
4537 "\\|" org-deadline-string
4538 "\\|" org-closed-string
4539 "\\|" org-clock-string "\\)\\)?"
4540 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4541 org-planning-or-clock-line-re
4542 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4543 "\\|" org-deadline-string
4544 "\\|" org-closed-string "\\|" org-clock-string
4545 "\\)\\>\\)")
4546 org-all-time-keywords
4547 (mapcar (lambda (w) (substring w 0 -1))
4548 (list org-scheduled-string org-deadline-string
4549 org-clock-string org-closed-string))
4551 (org-compute-latex-and-specials-regexp)
4552 (org-set-font-lock-defaults))))
4554 (defun org-file-contents (file &optional noerror)
4555 "Return the contents of FILE, as a string."
4556 (if (or (not file)
4557 (not (file-readable-p file)))
4558 (if noerror
4559 (progn
4560 (message "Cannot read file \"%s\"" file)
4561 (ding) (sit-for 2)
4563 (error "Cannot read file \"%s\"" file))
4564 (with-temp-buffer
4565 (insert-file-contents file)
4566 (buffer-string))))
4568 (defun org-extract-log-state-settings (x)
4569 "Extract the log state setting from a TODO keyword string.
4570 This will extract info from a string like \"WAIT(w@/!)\"."
4571 (let (kw key log1 log2)
4572 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4573 (setq kw (match-string 1 x)
4574 key (and (match-end 2) (match-string 2 x))
4575 log1 (and (match-end 3) (match-string 3 x))
4576 log2 (and (match-end 4) (match-string 4 x)))
4577 (and (or log1 log2)
4578 (list kw
4579 (and log1 (if (equal log1 "!") 'time 'note))
4580 (and log2 (if (equal log2 "!") 'time 'note)))))))
4582 (defun org-remove-keyword-keys (list)
4583 "Remove a pair of parenthesis at the end of each string in LIST."
4584 (mapcar (lambda (x)
4585 (if (string-match "(.*)$" x)
4586 (substring x 0 (match-beginning 0))
4588 list))
4590 (defun org-assign-fast-keys (alist)
4591 "Assign fast keys to a keyword-key alist.
4592 Respect keys that are already there."
4593 (let (new e (alt ?0))
4594 (while (setq e (pop alist))
4595 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4596 (cdr e)) ;; Key already assigned.
4597 (push e new)
4598 (let ((clist (string-to-list (downcase (car e))))
4599 (used (append new alist)))
4600 (when (= (car clist) ?@)
4601 (pop clist))
4602 (while (and clist (rassoc (car clist) used))
4603 (pop clist))
4604 (unless clist
4605 (while (rassoc alt used)
4606 (incf alt)))
4607 (push (cons (car e) (or (car clist) alt)) new))))
4608 (nreverse new)))
4610 ;;; Some variables used in various places
4612 (defvar org-window-configuration nil
4613 "Used in various places to store a window configuration.")
4614 (defvar org-selected-window nil
4615 "Used in various places to store a window configuration.")
4616 (defvar org-finish-function nil
4617 "Function to be called when `C-c C-c' is used.
4618 This is for getting out of special buffers like remember.")
4621 ;; FIXME: Occasionally check by commenting these, to make sure
4622 ;; no other functions uses these, forgetting to let-bind them.
4623 (defvar entry)
4624 (defvar last-state)
4625 (defvar date)
4627 ;; Defined somewhere in this file, but used before definition.
4628 (defvar org-entities) ;; defined in org-entities.el
4629 (defvar org-struct-menu)
4630 (defvar org-org-menu)
4631 (defvar org-tbl-menu)
4633 ;;;; Define the Org-mode
4635 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4636 (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"))
4639 ;; We use a before-change function to check if a table might need
4640 ;; an update.
4641 (defvar org-table-may-need-update t
4642 "Indicates that a table might need an update.
4643 This variable is set by `org-before-change-function'.
4644 `org-table-align' sets it back to nil.")
4645 (defun org-before-change-function (beg end)
4646 "Every change indicates that a table might need an update."
4647 (setq org-table-may-need-update t))
4648 (defvar org-mode-map)
4649 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4650 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4651 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4652 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4653 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4654 (defvar org-table-buffer-is-an nil)
4655 (defconst org-outline-regexp "\\*+ ")
4657 ;;;###autoload
4658 (define-derived-mode org-mode outline-mode "Org"
4659 "Outline-based notes management and organizer, alias
4660 \"Carsten's outline-mode for keeping track of everything.\"
4662 Org-mode develops organizational tasks around a NOTES file which
4663 contains information about projects as plain text. Org-mode is
4664 implemented on top of outline-mode, which is ideal to keep the content
4665 of large files well structured. It supports ToDo items, deadlines and
4666 time stamps, which magically appear in the diary listing of the Emacs
4667 calendar. Tables are easily created with a built-in table editor.
4668 Plain text URL-like links connect to websites, emails (VM), Usenet
4669 messages (Gnus), BBDB entries, and any files related to the project.
4670 For printing and sharing of notes, an Org-mode file (or a part of it)
4671 can be exported as a structured ASCII or HTML file.
4673 The following commands are available:
4675 \\{org-mode-map}"
4677 ;; Get rid of Outline menus, they are not needed
4678 ;; Need to do this here because define-derived-mode sets up
4679 ;; the keymap so late. Still, it is a waste to call this each time
4680 ;; we switch another buffer into org-mode.
4681 (if (featurep 'xemacs)
4682 (when (boundp 'outline-mode-menu-heading)
4683 ;; Assume this is Greg's port, it uses easymenu
4684 (easy-menu-remove outline-mode-menu-heading)
4685 (easy-menu-remove outline-mode-menu-show)
4686 (easy-menu-remove outline-mode-menu-hide))
4687 (define-key org-mode-map [menu-bar headings] 'undefined)
4688 (define-key org-mode-map [menu-bar hide] 'undefined)
4689 (define-key org-mode-map [menu-bar show] 'undefined))
4691 (org-load-modules-maybe)
4692 (easy-menu-add org-org-menu)
4693 (easy-menu-add org-tbl-menu)
4694 (org-install-agenda-files-menu)
4695 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4696 (add-to-invisibility-spec '(org-cwidth))
4697 (add-to-invisibility-spec '(org-hide-block . t))
4698 (when (featurep 'xemacs)
4699 (org-set-local 'line-move-ignore-invisible t))
4700 (org-set-local 'outline-regexp org-outline-regexp)
4701 (org-set-local 'outline-level 'org-outline-level)
4702 (when (and org-ellipsis
4703 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4704 (fboundp 'make-glyph-code))
4705 (unless org-display-table
4706 (setq org-display-table (make-display-table)))
4707 (set-display-table-slot
4708 org-display-table 4
4709 (vconcat (mapcar
4710 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4711 org-ellipsis)))
4712 (if (stringp org-ellipsis) org-ellipsis "..."))))
4713 (setq buffer-display-table org-display-table))
4714 (org-set-regexps-and-options)
4715 (when (and org-tag-faces (not org-tags-special-faces-re))
4716 ;; tag faces set outside customize.... force initialization.
4717 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4718 ;; Calc embedded
4719 (org-set-local 'calc-embedded-open-mode "# ")
4720 (modify-syntax-entry ?@ "w")
4721 (if org-startup-truncated (setq truncate-lines t))
4722 (org-set-local 'font-lock-unfontify-region-function
4723 'org-unfontify-region)
4724 ;; Activate before-change-function
4725 (org-set-local 'org-table-may-need-update t)
4726 (org-add-hook 'before-change-functions 'org-before-change-function nil
4727 'local)
4728 ;; Check for running clock before killing a buffer
4729 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4730 ;; Paragraphs and auto-filling
4731 (org-set-autofill-regexps)
4732 (setq indent-line-function 'org-indent-line-function)
4733 (org-update-radio-target-regexp)
4734 ;; Beginning/end of defun
4735 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
4736 (org-set-local 'end-of-defun-function 'org-end-of-defun)
4737 ;; Next error for sparse trees
4738 (org-set-local 'next-error-function 'org-occur-next-match)
4739 ;; Make sure dependence stuff works reliably, even for users who set it
4740 ;; too late :-(
4741 (if org-enforce-todo-dependencies
4742 (add-hook 'org-blocker-hook
4743 'org-block-todo-from-children-or-siblings-or-parent)
4744 (remove-hook 'org-blocker-hook
4745 'org-block-todo-from-children-or-siblings-or-parent))
4746 (if org-enforce-todo-checkbox-dependencies
4747 (add-hook 'org-blocker-hook
4748 'org-block-todo-from-checkboxes)
4749 (remove-hook 'org-blocker-hook
4750 'org-block-todo-from-checkboxes))
4752 ;; Comment characters
4753 (org-set-local 'comment-start "#")
4754 (org-set-local 'comment-padding " ")
4756 ;; Align options lines
4757 (org-set-local
4758 'align-mode-rules-list
4759 '((org-in-buffer-settings
4760 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4761 (modes . '(org-mode)))))
4763 ;; Imenu
4764 (org-set-local 'imenu-create-index-function
4765 'org-imenu-get-tree)
4767 ;; Make isearch reveal context
4768 (if (or (featurep 'xemacs)
4769 (not (boundp 'outline-isearch-open-invisible-function)))
4770 ;; Emacs 21 and XEmacs make use of the hook
4771 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4772 ;; Emacs 22 deals with this through a special variable
4773 (org-set-local 'outline-isearch-open-invisible-function
4774 (lambda (&rest ignore) (org-show-context 'isearch))))
4776 ;; Turn on org-beamer-mode?
4777 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4779 ;; Setup the pcomplete hooks
4780 (set (make-local-variable 'pcomplete-command-completion-function)
4781 'org-pcomplete-initial)
4782 (set (make-local-variable 'pcomplete-command-name-function)
4783 'org-command-at-point)
4784 (set (make-local-variable 'pcomplete-default-completion-function)
4785 'ignore)
4786 (set (make-local-variable 'pcomplete-parse-arguments-function)
4787 'org-parse-arguments)
4788 (set (make-local-variable 'pcomplete-termination-string) "")
4790 ;; If empty file that did not turn on org-mode automatically, make it to.
4791 (if (and org-insert-mode-line-in-empty-file
4792 (interactive-p)
4793 (= (point-min) (point-max)))
4794 (insert "# -*- mode: org -*-\n\n"))
4795 (unless org-inhibit-startup
4796 (when org-startup-align-all-tables
4797 (let ((bmp (buffer-modified-p)))
4798 (org-table-map-tables 'org-table-align 'quietly)
4799 (set-buffer-modified-p bmp)))
4800 (when org-startup-with-inline-images
4801 (org-display-inline-images))
4802 (when org-startup-indented
4803 (require 'org-indent)
4804 (org-indent-mode 1))
4805 (unless org-inhibit-startup-visibility-stuff
4806 (org-set-startup-visibility))))
4808 (when (fboundp 'abbrev-table-put)
4809 (abbrev-table-put org-mode-abbrev-table
4810 :parents (list text-mode-abbrev-table)))
4812 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4814 (defun org-current-time ()
4815 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4816 (if (> (car org-time-stamp-rounding-minutes) 1)
4817 (let ((r (car org-time-stamp-rounding-minutes))
4818 (time (decode-time)))
4819 (apply 'encode-time
4820 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4821 (nthcdr 2 time))))
4822 (current-time)))
4824 (defun org-today ()
4825 "Return today date, considering `org-extend-today-until'."
4826 (time-to-days
4827 (time-subtract (current-time)
4828 (list 0 (* 3600 org-extend-today-until) 0))))
4830 ;;;; Font-Lock stuff, including the activators
4832 (defvar org-mouse-map (make-sparse-keymap))
4833 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
4834 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
4835 (when org-mouse-1-follows-link
4836 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4837 (when org-tab-follows-link
4838 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4839 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4841 (require 'font-lock)
4843 (defconst org-non-link-chars "]\t\n\r<>")
4844 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4845 "shell" "elisp" "doi" "message"))
4846 (defvar org-link-types-re nil
4847 "Matches a link that has a url-like prefix like \"http:\"")
4848 (defvar org-link-re-with-space nil
4849 "Matches a link with spaces, optional angular brackets around it.")
4850 (defvar org-link-re-with-space2 nil
4851 "Matches a link with spaces, optional angular brackets around it.")
4852 (defvar org-link-re-with-space3 nil
4853 "Matches a link with spaces, only for internal part in bracket links.")
4854 (defvar org-angle-link-re nil
4855 "Matches link with angular brackets, spaces are allowed.")
4856 (defvar org-plain-link-re nil
4857 "Matches plain link, without spaces.")
4858 (defvar org-bracket-link-regexp nil
4859 "Matches a link in double brackets.")
4860 (defvar org-bracket-link-analytic-regexp nil
4861 "Regular expression used to analyze links.
4862 Here is what the match groups contain after a match:
4863 1: http:
4864 2: http
4865 3: path
4866 4: [desc]
4867 5: desc")
4868 (defvar org-bracket-link-analytic-regexp++ nil
4869 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
4870 (defvar org-any-link-re nil
4871 "Regular expression matching any link.")
4873 (defcustom org-match-sexp-depth 3
4874 "Number of stacked braces for sub/superscript matching.
4875 This has to be set before loading org.el to be effective."
4876 :group 'org-export-translation ; ??????????????????????????/
4877 :type 'integer)
4879 (defun org-create-multibrace-regexp (left right n)
4880 "Create a regular expression which will match a balanced sexp.
4881 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
4882 as single character strings.
4883 The regexp returned will match the entire expression including the
4884 delimiters. It will also define a single group which contains the
4885 match except for the outermost delimiters. The maximum depth of
4886 stacked delimiters is N. Escaping delimiters is not possible."
4887 (let* ((nothing (concat "[^" left right "]*?"))
4888 (or "\\|")
4889 (re nothing)
4890 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
4891 (while (> n 1)
4892 (setq n (1- n)
4893 re (concat re or next)
4894 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
4895 (concat left "\\(" re "\\)" right)))
4897 (defvar org-match-substring-regexp
4898 (concat
4899 "\\([^\\]\\)\\([_^]\\)\\("
4900 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
4901 "\\|"
4902 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
4903 "\\|"
4904 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
4905 "The regular expression matching a sub- or superscript.")
4907 (defvar org-match-substring-with-braces-regexp
4908 (concat
4909 "\\([^\\]\\)\\([_^]\\)\\("
4910 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
4911 "\\)")
4912 "The regular expression matching a sub- or superscript, forcing braces.")
4914 (defun org-make-link-regexps ()
4915 "Update the link regular expressions.
4916 This should be called after the variable `org-link-types' has changed."
4917 (setq org-link-types-re
4918 (concat
4919 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
4920 org-link-re-with-space
4921 (concat
4922 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4923 "\\([^" org-non-link-chars " ]"
4924 "[^" org-non-link-chars "]*"
4925 "[^" org-non-link-chars " ]\\)>?")
4926 org-link-re-with-space2
4927 (concat
4928 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4929 "\\([^" org-non-link-chars " ]"
4930 "[^\t\n\r]*"
4931 "[^" org-non-link-chars " ]\\)>?")
4932 org-link-re-with-space3
4933 (concat
4934 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4935 "\\([^" org-non-link-chars " ]"
4936 "[^\t\n\r]*\\)")
4937 org-angle-link-re
4938 (concat
4939 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4940 "\\([^" org-non-link-chars " ]"
4941 "[^" org-non-link-chars "]*"
4942 "\\)>")
4943 org-plain-link-re
4944 (concat
4945 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4946 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4947 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4948 org-bracket-link-regexp
4949 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4950 org-bracket-link-analytic-regexp
4951 (concat
4952 "\\[\\["
4953 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
4954 "\\([^]]+\\)"
4955 "\\]"
4956 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4957 "\\]")
4958 org-bracket-link-analytic-regexp++
4959 (concat
4960 "\\[\\["
4961 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4962 "\\([^]]+\\)"
4963 "\\]"
4964 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4965 "\\]")
4966 org-any-link-re
4967 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4968 org-angle-link-re "\\)\\|\\("
4969 org-plain-link-re "\\)")))
4971 (org-make-link-regexps)
4973 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4974 "Regular expression for fast time stamp matching.")
4975 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4976 "Regular expression for fast time stamp matching.")
4977 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4978 "Regular expression matching time strings for analysis.
4979 This one does not require the space after the date, so it can be used
4980 on a string that terminates immediately after the date.")
4981 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4982 "Regular expression matching time strings for analysis.")
4983 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4984 "Regular expression matching time stamps, with groups.")
4985 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4986 "Regular expression matching time stamps (also [..]), with groups.")
4987 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4988 "Regular expression matching a time stamp range.")
4989 (defconst org-tr-regexp-both
4990 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4991 "Regular expression matching a time stamp range.")
4992 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4993 org-ts-regexp "\\)?")
4994 "Regular expression matching a time stamp or time stamp range.")
4995 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4996 org-ts-regexp-both "\\)?")
4997 "Regular expression matching a time stamp or time stamp range.
4998 The time stamps may be either active or inactive.")
5000 (defvar org-emph-face nil)
5002 (defun org-do-emphasis-faces (limit)
5003 "Run through the buffer and add overlays to links."
5004 (let (rtn a)
5005 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5006 (if (not (= (char-after (match-beginning 3))
5007 (char-after (match-beginning 4))))
5008 (progn
5009 (setq rtn t)
5010 (setq a (assoc (match-string 3) org-emphasis-alist))
5011 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5012 'face
5013 (nth 1 a))
5014 (and (nth 4 a)
5015 (org-remove-flyspell-overlays-in
5016 (match-beginning 0) (match-end 0)))
5017 (add-text-properties (match-beginning 2) (match-end 2)
5018 '(font-lock-multiline t org-emphasis t))
5019 (when org-hide-emphasis-markers
5020 (add-text-properties (match-end 4) (match-beginning 5)
5021 '(invisible org-link))
5022 (add-text-properties (match-beginning 3) (match-end 3)
5023 '(invisible org-link)))))
5024 (backward-char 1))
5025 rtn))
5027 (defun org-emphasize (&optional char)
5028 "Insert or change an emphasis, i.e. a font like bold or italic.
5029 If there is an active region, change that region to a new emphasis.
5030 If there is no region, just insert the marker characters and position
5031 the cursor between them.
5032 CHAR should be either the marker character, or the first character of the
5033 HTML tag associated with that emphasis. If CHAR is a space, the means
5034 to remove the emphasis of the selected region.
5035 If char is not given (for example in an interactive call) it
5036 will be prompted for."
5037 (interactive)
5038 (let ((eal org-emphasis-alist) e det
5039 (erc org-emphasis-regexp-components)
5040 (prompt "")
5041 (string "") beg end move tag c s)
5042 (if (org-region-active-p)
5043 (setq beg (region-beginning) end (region-end)
5044 string (buffer-substring beg end))
5045 (setq move t))
5047 (while (setq e (pop eal))
5048 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5049 c (aref tag 0))
5050 (push (cons c (string-to-char (car e))) det)
5051 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5052 (substring tag 1)))))
5053 (setq det (nreverse det))
5054 (unless char
5055 (message "%s" (concat "Emphasis marker or tag:" prompt))
5056 (setq char (read-char-exclusive)))
5057 (setq char (or (cdr (assoc char det)) char))
5058 (if (equal char ?\ )
5059 (setq s "" move nil)
5060 (unless (assoc (char-to-string char) org-emphasis-alist)
5061 (error "No such emphasis marker: \"%c\"" char))
5062 (setq s (char-to-string char)))
5063 (while (and (> (length string) 1)
5064 (equal (substring string 0 1) (substring string -1))
5065 (assoc (substring string 0 1) org-emphasis-alist))
5066 (setq string (substring string 1 -1)))
5067 (setq string (concat s string s))
5068 (if beg (delete-region beg end))
5069 (unless (or (bolp)
5070 (string-match (concat "[" (nth 0 erc) "\n]")
5071 (char-to-string (char-before (point)))))
5072 (insert " "))
5073 (unless (or (eobp)
5074 (string-match (concat "[" (nth 1 erc) "\n]")
5075 (char-to-string (char-after (point)))))
5076 (insert " ") (backward-char 1))
5077 (insert string)
5078 (and move (backward-char 1))))
5080 (defconst org-nonsticky-props
5081 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5083 (defsubst org-rear-nonsticky-at (pos)
5084 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5086 (defun org-activate-plain-links (limit)
5087 "Run through the buffer and add overlays to links."
5088 (catch 'exit
5089 (let (f)
5090 (if (re-search-forward org-plain-link-re limit t)
5091 (progn
5092 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5093 (setq f (get-text-property (match-beginning 0) 'face))
5094 (if (or (eq f 'org-tag)
5095 (and (listp f) (memq 'org-tag f)))
5097 (add-text-properties (match-beginning 0) (match-end 0)
5098 (list 'mouse-face 'highlight
5099 'face 'org-link
5100 'keymap org-mouse-map))
5101 (org-rear-nonsticky-at (match-end 0)))
5102 t)))))
5104 (defun org-activate-code (limit)
5105 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
5106 (progn
5107 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5108 (remove-text-properties (match-beginning 0) (match-end 0)
5109 '(display t invisible t intangible t))
5110 t)))
5112 (defcustom org-src-fontify-natively nil
5113 "When non-nil, fontify code in code blocks."
5114 :type 'boolean
5115 :group 'org-appearance
5116 :group 'org-babel)
5118 (defun org-fontify-meta-lines-and-blocks (limit)
5119 "Fontify #+ lines and blocks, in the correct ways."
5120 (let ((case-fold-search t))
5121 (if (re-search-forward
5122 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5123 limit t)
5124 (let ((beg (match-beginning 0))
5125 (block-start (match-end 0))
5126 (block-end nil)
5127 (lang (match-string 7))
5128 (beg1 (line-beginning-position 2))
5129 (dc1 (downcase (match-string 2)))
5130 (dc3 (downcase (match-string 3)))
5131 end end1 quoting block-type)
5132 (cond
5133 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5134 ;; a single line of backend-specific content
5135 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5136 (remove-text-properties (match-beginning 0) (match-end 0)
5137 '(display t invisible t intangible t))
5138 (add-text-properties (match-beginning 1) (match-end 3)
5139 '(font-lock-fontified t face org-meta-line))
5140 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5141 '(font-lock-fontified t face org-block))
5142 ; for backend-specific code
5144 ((and (match-end 4) (equal dc3 "begin"))
5145 ;; Truly a block
5146 (setq block-type (downcase (match-string 5))
5147 quoting (member block-type org-protecting-blocks))
5148 (when (re-search-forward
5149 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5150 nil t) ;; on purpose, we look further than LIMIT
5151 (setq end (match-end 0) end1 (1- (match-beginning 0)))
5152 (setq block-end (match-beginning 0))
5153 (when quoting
5154 (remove-text-properties beg end
5155 '(display t invisible t intangible t)))
5156 (add-text-properties
5157 beg end
5158 '(font-lock-fontified t font-lock-multiline t))
5159 (add-text-properties beg beg1 '(face org-meta-line))
5160 (add-text-properties end1 (+ end 1) '(face org-meta-line))
5161 ; for end_src
5162 (cond
5163 ((and lang org-src-fontify-natively)
5164 (org-src-font-lock-fontify-block lang block-start block-end)
5165 (overlay-put (make-overlay beg1 block-end)
5166 'face 'org-block-background))
5167 (quoting
5168 (add-text-properties beg1 (+ end1 1) '(face org-block)))
5169 ; end of source block
5170 ((not org-fontify-quote-and-verse-blocks))
5171 ((string= block-type "quote")
5172 (add-text-properties beg1 (1+ end1) '(face org-quote)))
5173 ((string= block-type "verse")
5174 (add-text-properties beg1 (1+ end1) '(face org-verse))))
5175 (add-text-properties beg beg1 '(face org-block-begin-line))
5176 (add-text-properties (1+ end) (1+ end1) '(face org-block-end-line))
5178 ((member dc1 '("title:" "author:" "email:" "date:"))
5179 (add-text-properties
5180 beg (match-end 3)
5181 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5182 '(font-lock-fontified t invisible t)
5183 '(font-lock-fontified t face org-document-info-keyword)))
5184 (add-text-properties
5185 (match-beginning 6) (match-end 6)
5186 (if (string-equal dc1 "title:")
5187 '(font-lock-fontified t face org-document-title)
5188 '(font-lock-fontified t face org-document-info))))
5189 ((not (member (char-after beg) '(?\ ?\t)))
5190 ;; just any other in-buffer setting, but not indented
5191 (add-text-properties
5192 beg (1+ (match-end 0))
5193 '(font-lock-fontified t face org-meta-line))
5195 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5196 "orgtbl:" "tblfm:" "tblname:" "result:"
5197 "results:" "source:" "srcname:" "call:"))
5198 (and (match-end 4) (equal dc3 "attr")))
5199 (add-text-properties
5200 beg (match-end 0)
5201 '(font-lock-fontified t face org-meta-line))
5203 ((member dc3 '(" " ""))
5204 (add-text-properties
5205 beg (match-end 0)
5206 '(font-lock-fontified t face font-lock-comment-face)))
5207 (t nil))))))
5209 (defun org-activate-angle-links (limit)
5210 "Run through the buffer and add overlays to links."
5211 (if (re-search-forward org-angle-link-re limit t)
5212 (progn
5213 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5214 (add-text-properties (match-beginning 0) (match-end 0)
5215 (list 'mouse-face 'highlight
5216 'keymap org-mouse-map))
5217 (org-rear-nonsticky-at (match-end 0))
5218 t)))
5220 (defun org-activate-footnote-links (limit)
5221 "Run through the buffer and add overlays to links."
5222 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
5223 limit t)
5224 (progn
5225 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5226 (add-text-properties (match-beginning 2) (match-end 2)
5227 (list 'mouse-face 'highlight
5228 'keymap org-mouse-map
5229 'help-echo
5230 (if (= (point-at-bol) (match-beginning 2))
5231 "Footnote definition"
5232 "Footnote reference")
5234 (org-rear-nonsticky-at (match-end 2))
5235 t)))
5237 (defun org-activate-bracket-links (limit)
5238 "Run through the buffer and add overlays to bracketed links."
5239 (if (re-search-forward org-bracket-link-regexp limit t)
5240 (let* ((help (concat "LINK: "
5241 (org-match-string-no-properties 1)))
5242 ;; FIXME: above we should remove the escapes.
5243 ;; but that requires another match, protecting match data,
5244 ;; a lot of overhead for font-lock.
5245 (ip (org-maybe-intangible
5246 (list 'invisible 'org-link
5247 'keymap org-mouse-map 'mouse-face 'highlight
5248 'font-lock-multiline t 'help-echo help)))
5249 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5250 'font-lock-multiline t 'help-echo help)))
5251 ;; We need to remove the invisible property here. Table narrowing
5252 ;; may have made some of this invisible.
5253 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5254 (remove-text-properties (match-beginning 0) (match-end 0)
5255 '(invisible nil))
5256 (if (match-end 3)
5257 (progn
5258 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5259 (org-rear-nonsticky-at (match-beginning 3))
5260 (add-text-properties (match-beginning 3) (match-end 3) vp)
5261 (org-rear-nonsticky-at (match-end 3))
5262 (add-text-properties (match-end 3) (match-end 0) ip)
5263 (org-rear-nonsticky-at (match-end 0)))
5264 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5265 (org-rear-nonsticky-at (match-beginning 1))
5266 (add-text-properties (match-beginning 1) (match-end 1) vp)
5267 (org-rear-nonsticky-at (match-end 1))
5268 (add-text-properties (match-end 1) (match-end 0) ip)
5269 (org-rear-nonsticky-at (match-end 0)))
5270 t)))
5272 (defun org-activate-dates (limit)
5273 "Run through the buffer and add overlays to dates."
5274 (if (re-search-forward org-tsr-regexp-both limit t)
5275 (progn
5276 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5277 (add-text-properties (match-beginning 0) (match-end 0)
5278 (list 'mouse-face 'highlight
5279 'keymap org-mouse-map))
5280 (org-rear-nonsticky-at (match-end 0))
5281 (when org-display-custom-times
5282 (if (match-end 3)
5283 (org-display-custom-time (match-beginning 3) (match-end 3)))
5284 (org-display-custom-time (match-beginning 1) (match-end 1)))
5285 t)))
5287 (defvar org-target-link-regexp nil
5288 "Regular expression matching radio targets in plain text.")
5289 (make-variable-buffer-local 'org-target-link-regexp)
5290 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5291 "Regular expression matching a link target.")
5292 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5293 "Regular expression matching a radio target.")
5294 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5295 "Regular expression matching any target.")
5297 (defun org-activate-target-links (limit)
5298 "Run through the buffer and add overlays to target matches."
5299 (when org-target-link-regexp
5300 (let ((case-fold-search t))
5301 (if (re-search-forward org-target-link-regexp limit t)
5302 (progn
5303 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5304 (add-text-properties (match-beginning 0) (match-end 0)
5305 (list 'mouse-face 'highlight
5306 'keymap org-mouse-map
5307 'help-echo "Radio target link"
5308 'org-linked-text t))
5309 (org-rear-nonsticky-at (match-end 0))
5310 t)))))
5312 (defun org-update-radio-target-regexp ()
5313 "Find all radio targets in this file and update the regular expression."
5314 (interactive)
5315 (when (memq 'radio org-activate-links)
5316 (setq org-target-link-regexp
5317 (org-make-target-link-regexp (org-all-targets 'radio)))
5318 (org-restart-font-lock)))
5320 (defun org-hide-wide-columns (limit)
5321 (let (s e)
5322 (setq s (text-property-any (point) (or limit (point-max))
5323 'org-cwidth t))
5324 (when s
5325 (setq e (next-single-property-change s 'org-cwidth))
5326 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5327 (goto-char e)
5328 t)))
5330 (defvar org-latex-and-specials-regexp nil
5331 "Regular expression for highlighting export special stuff.")
5332 (defvar org-match-substring-regexp)
5333 (defvar org-match-substring-with-braces-regexp)
5335 ;; This should be with the exporter code, but we also use if for font-locking
5336 (defconst org-export-html-special-string-regexps
5337 '(("\\\\-" . "&shy;")
5338 ("---\\([^-]\\)" . "&mdash;\\1")
5339 ("--\\([^-]\\)" . "&ndash;\\1")
5340 ("\\.\\.\\." . "&hellip;"))
5341 "Regular expressions for special string conversion.")
5344 (defun org-compute-latex-and-specials-regexp ()
5345 "Compute regular expression for stuff treated specially by exporters."
5346 (if (not org-highlight-latex-fragments-and-specials)
5347 (org-set-local 'org-latex-and-specials-regexp nil)
5348 (require 'org-exp)
5349 (let*
5350 ((matchers (plist-get org-format-latex-options :matchers))
5351 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5352 org-latex-regexps)))
5353 (org-export-allow-BIND nil)
5354 (options (org-combine-plists (org-default-export-plist)
5355 (org-infile-export-plist)))
5356 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5357 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5358 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5359 (org-export-html-expand (plist-get options :expand-quoted-html))
5360 (org-export-with-special-strings (plist-get options :special-strings))
5361 (re-sub
5362 (cond
5363 ((equal org-export-with-sub-superscripts '{})
5364 (list org-match-substring-with-braces-regexp))
5365 (org-export-with-sub-superscripts
5366 (list org-match-substring-regexp))
5367 (t nil)))
5368 (re-latex
5369 (if org-export-with-LaTeX-fragments
5370 (mapcar (lambda (x) (nth 1 x)) latexs)))
5371 (re-macros
5372 (if org-export-with-TeX-macros
5373 (list (concat "\\\\"
5374 (regexp-opt
5375 (append
5377 (delq nil
5378 (mapcar 'car-safe
5379 (append org-entities-user
5380 org-entities)))
5381 (if (boundp 'org-latex-entities)
5382 (mapcar (lambda (x)
5383 (or (car-safe x) x))
5384 org-latex-entities)
5385 nil))
5386 'words))) ; FIXME
5388 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5389 (re-special (if org-export-with-special-strings
5390 (mapcar (lambda (x) (car x))
5391 org-export-html-special-string-regexps)))
5392 (re-rest
5393 (delq nil
5394 (list
5395 (if org-export-html-expand "@<[^>\n]+>")
5396 ))))
5397 (org-set-local
5398 'org-latex-and-specials-regexp
5399 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5400 re-rest) "\\|")))))
5402 (defun org-do-latex-and-special-faces (limit)
5403 "Run through the buffer and add overlays to links."
5404 (when org-latex-and-specials-regexp
5405 (let (rtn d)
5406 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5407 limit t))
5408 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5409 'face))
5410 '(org-code org-verbatim underline)))
5411 (progn
5412 (setq rtn t
5413 d (cond ((member (char-after (1+ (match-beginning 0)))
5414 '(?_ ?^)) 1)
5415 (t 0)))
5416 (font-lock-prepend-text-property
5417 (+ d (match-beginning 0)) (match-end 0)
5418 'face 'org-latex-and-export-specials)
5419 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5420 '(font-lock-multiline t)))))
5421 rtn)))
5423 (defun org-restart-font-lock ()
5424 "Restart `font-lock-mode', to force refontification."
5425 (when (and (boundp 'font-lock-mode) font-lock-mode)
5426 (font-lock-mode -1)
5427 (font-lock-mode 1)))
5429 (defun org-all-targets (&optional radio)
5430 "Return a list of all targets in this file.
5431 With optional argument RADIO, only find radio targets."
5432 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5433 rtn)
5434 (save-excursion
5435 (goto-char (point-min))
5436 (while (re-search-forward re nil t)
5437 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5438 rtn)))
5440 (defun org-make-target-link-regexp (targets)
5441 "Make regular expression matching all strings in TARGETS.
5442 The regular expression finds the targets also if there is a line break
5443 between words."
5444 (and targets
5445 (concat
5446 "\\<\\("
5447 (mapconcat
5448 (lambda (x)
5449 (setq x (regexp-quote x))
5450 (while (string-match " +" x)
5451 (setq x (replace-match "\\s-+" t t x)))
5453 targets
5454 "\\|")
5455 "\\)\\>")))
5457 (defun org-activate-tags (limit)
5458 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5459 (progn
5460 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5461 (add-text-properties (match-beginning 1) (match-end 1)
5462 (list 'mouse-face 'highlight
5463 'keymap org-mouse-map))
5464 (org-rear-nonsticky-at (match-end 1))
5465 t)))
5467 (defun org-outline-level ()
5468 "Compute the outline level of the heading at point.
5469 This function assumes that the cursor is at the beginning of a line matched
5470 by `outline-regexp'. Otherwise it returns garbage.
5471 If this is called at a normal headline, the level is the number of stars.
5472 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5473 (save-excursion
5474 (looking-at outline-regexp)
5475 (1- (- (match-end 0) (match-beginning 0)))))
5477 (defvar org-font-lock-keywords nil)
5479 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5480 "Regular expression matching a property line.")
5482 (defvar org-font-lock-hook nil
5483 "Functions to be called for special font lock stuff.")
5485 (defvar org-font-lock-set-keywords-hook nil
5486 "Functions that can manipulate `org-font-lock-extra-keywords'.
5487 This is calles after `org-font-lock-extra-keywords' is defined, but before
5488 it is installed to be used by font lock. This can be useful if something
5489 needs to be inserted at a specific position in the font-lock sequence.")
5491 (defun org-font-lock-hook (limit)
5492 (run-hook-with-args 'org-font-lock-hook limit))
5494 (defun org-set-font-lock-defaults ()
5495 (let* ((em org-fontify-emphasized-text)
5496 (lk org-activate-links)
5497 (org-font-lock-extra-keywords
5498 (list
5499 ;; Call the hook
5500 '(org-font-lock-hook)
5501 ;; Headlines
5502 `(,(if org-fontify-whole-heading-line
5503 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5504 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5505 (1 (org-get-level-face 1))
5506 (2 (org-get-level-face 2))
5507 (3 (org-get-level-face 3)))
5508 ;; Table lines
5509 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5510 (1 'org-table t))
5511 ;; Table internals
5512 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5513 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5514 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5515 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5516 ;; Drawers
5517 (list org-drawer-regexp '(0 'org-special-keyword t))
5518 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5519 ;; Properties
5520 (list org-property-re
5521 '(1 'org-special-keyword t)
5522 '(3 'org-property-value t))
5523 ;; Links
5524 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5525 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5526 (if (memq 'plain lk) '(org-activate-plain-links))
5527 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5528 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5529 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5530 (if (memq 'footnote lk) '(org-activate-footnote-links
5531 (2 'org-footnote t)))
5532 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5533 '(org-hide-wide-columns (0 nil append))
5534 ;; TODO lines
5535 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
5536 '(1 (org-get-todo-face 1) t))
5537 ;; DONE
5538 (if org-fontify-done-headline
5539 (list (concat "^[*]+ +\\<\\("
5540 (mapconcat 'regexp-quote org-done-keywords "\\|")
5541 "\\)\\(.*\\)")
5542 '(2 'org-headline-done t))
5543 nil)
5544 ;; Priorities
5545 '(org-font-lock-add-priority-faces)
5546 ;; Tags
5547 '(org-font-lock-add-tag-faces)
5548 ;; Special keywords
5549 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5550 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5551 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5552 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5553 ;; Emphasis
5554 (if em
5555 (if (featurep 'xemacs)
5556 '(org-do-emphasis-faces (0 nil append))
5557 '(org-do-emphasis-faces)))
5558 ;; Checkboxes
5559 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5560 1 'org-checkbox prepend)
5561 (if (cdr (assq 'checkbox org-list-automatic-rules))
5562 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5563 (0 (org-get-checkbox-statistics-face) t)))
5564 ;; Description list items
5565 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\(.*? ::\\)"
5566 2 'bold prepend)
5567 ;; ARCHIVEd headings
5568 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5569 '(1 'org-archived prepend))
5570 ;; Specials
5571 '(org-do-latex-and-special-faces)
5572 '(org-fontify-entities)
5573 '(org-raise-scripts)
5574 ;; Code
5575 '(org-activate-code (1 'org-code t))
5576 ;; COMMENT
5577 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5578 "\\|" org-quote-string "\\)\\>")
5579 '(1 'org-special-keyword t))
5580 '("^#.*" (0 'font-lock-comment-face t))
5581 ;; Blocks and meta lines
5582 '(org-fontify-meta-lines-and-blocks)
5584 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5585 (run-hooks 'org-font-lock-set-keywords-hook)
5586 ;; Now set the full font-lock-keywords
5587 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5588 (org-set-local 'font-lock-defaults
5589 '(org-font-lock-keywords t nil nil backward-paragraph))
5590 (kill-local-variable 'font-lock-keywords) nil))
5592 (defun org-toggle-pretty-entities ()
5593 "Toggle the composition display of entities as UTF8 characters."
5594 (interactive)
5595 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5596 (org-restart-font-lock)
5597 (if org-pretty-entities
5598 (message "Entities are displayed as UTF8 characers")
5599 (save-restriction
5600 (widen)
5601 (org-decompose-region (point-min) (point-max))
5602 (message "Entities are displayed plain"))))
5604 (defun org-fontify-entities (limit)
5605 "Find an entity to fontify."
5606 (let (ee)
5607 (when org-pretty-entities
5608 (catch 'match
5609 (while (re-search-forward
5610 "\\\\\\([a-zA-Z][a-zA-Z0-9]*\\)\\($\\|[^[:alnum:]\n]\\)"
5611 limit t)
5612 (if (and (not (org-in-indented-comment-line))
5613 (setq ee (org-entity-get (match-string 1)))
5614 (= (length (nth 6 ee)) 1))
5615 (progn
5616 (add-text-properties
5617 (match-beginning 0) (match-end 1)
5618 (list 'font-lock-fontified t))
5619 (compose-region (match-beginning 0) (match-end 1)
5620 (nth 6 ee) nil)
5621 (backward-char 1)
5622 (throw 'match t))))
5623 nil))))
5625 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5626 "Fontify string S like in Org-mode."
5627 (with-temp-buffer
5628 (insert s)
5629 (let ((org-odd-levels-only odd-levels))
5630 (org-mode)
5631 (font-lock-fontify-buffer)
5632 (buffer-string))))
5634 (defvar org-m nil)
5635 (defvar org-l nil)
5636 (defvar org-f nil)
5637 (defun org-get-level-face (n)
5638 "Get the right face for match N in font-lock matching of headlines."
5639 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5640 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5641 (if org-cycle-level-faces
5642 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5643 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5644 (cond
5645 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5646 ((eq n 2) org-f)
5647 (t (if org-level-color-stars-only nil org-f))))
5650 (defun org-get-todo-face (kwd)
5651 "Get the right face for a TODO keyword KWD.
5652 If KWD is a number, get the corresponding match group."
5653 (if (numberp kwd) (setq kwd (match-string kwd)))
5654 (or (org-face-from-face-or-color
5655 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5656 (and (member kwd org-done-keywords) 'org-done)
5657 'org-todo))
5659 (defun org-face-from-face-or-color (context inherit face-or-color)
5660 "Create a face list that inherits INHERIT, but sets the foreground color.
5661 When FACE-OR-COLOR is not a string, just return it."
5662 (if (stringp face-or-color)
5663 (list :inherit inherit
5664 (cdr (assoc context org-faces-easy-properties))
5665 face-or-color)
5666 face-or-color))
5668 (defun org-font-lock-add-tag-faces (limit)
5669 "Add the special tag faces."
5670 (when (and org-tag-faces org-tags-special-faces-re)
5671 (while (re-search-forward org-tags-special-faces-re limit t)
5672 (add-text-properties (match-beginning 1) (match-end 1)
5673 (list 'face (org-get-tag-face 1)
5674 'font-lock-fontified t))
5675 (backward-char 1))))
5677 (defun org-font-lock-add-priority-faces (limit)
5678 "Add the special priority faces."
5679 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5680 (add-text-properties
5681 (match-beginning 0) (match-end 0)
5682 (list 'face (or (org-face-from-face-or-color
5683 'priority 'org-special-keyword
5684 (cdr (assoc (char-after (match-beginning 1))
5685 org-priority-faces)))
5686 'org-special-keyword)
5687 'font-lock-fontified t))))
5689 (defun org-get-tag-face (kwd)
5690 "Get the right face for a TODO keyword KWD.
5691 If KWD is a number, get the corresponding match group."
5692 (if (numberp kwd) (setq kwd (match-string kwd)))
5693 (or (org-face-from-face-or-color
5694 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5695 'org-tag))
5697 (defun org-unfontify-region (beg end &optional maybe_loudly)
5698 "Remove fontification and activation overlays from links."
5699 (font-lock-default-unfontify-region beg end)
5700 (let* ((buffer-undo-list t)
5701 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5702 (inhibit-modification-hooks t)
5703 deactivate-mark buffer-file-name buffer-file-truename)
5704 (org-decompose-region beg end)
5705 (remove-text-properties
5706 beg end
5707 (if org-indent-mode
5708 ;; also remove line-prefix and wrap-prefix properties
5709 '(mouse-face t keymap t org-linked-text t
5710 invisible t intangible t
5711 line-prefix t wrap-prefix t
5712 org-no-flyspell t org-emphasis t)
5713 '(mouse-face t keymap t org-linked-text t
5714 invisible t intangible t
5715 org-no-flyspell t org-emphasis t)))
5716 (org-remove-font-lock-display-properties beg end)))
5718 (defconst org-script-display '(((raise -0.3) (height 0.7))
5719 ((raise 0.3) (height 0.7))
5720 ((raise -0.5))
5721 ((raise 0.5)))
5722 "Display properties for showing superscripts and subscripts.")
5724 (defun org-remove-font-lock-display-properties (beg end)
5725 "Remove specific display properties that have been added by font lock.
5726 The will remove the raise properties that are used to show superscripts
5727 and subscripts."
5728 (let (next prop)
5729 (while (< beg end)
5730 (setq next (next-single-property-change beg 'display nil end)
5731 prop (get-text-property beg 'display))
5732 (if (member prop org-script-display)
5733 (put-text-property beg next 'display nil))
5734 (setq beg next))))
5736 (defun org-raise-scripts (limit)
5737 "Add raise properties to sub/superscripts."
5738 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
5739 (if (re-search-forward
5740 (if (eq org-use-sub-superscripts t)
5741 org-match-substring-regexp
5742 org-match-substring-with-braces-regexp)
5743 limit t)
5744 (let* ((pos (point)) table-p comment-p
5745 (mpos (match-beginning 3))
5746 (emph-p (get-text-property mpos 'org-emphasis))
5747 (link-p (get-text-property mpos 'mouse-face))
5748 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
5749 (goto-char (point-at-bol))
5750 (setq table-p (org-looking-at-p org-table-dataline-regexp)
5751 comment-p (org-looking-at-p "[ \t]*#"))
5752 (goto-char pos)
5753 ;; FIXME: Should we go back one character here, for a_b^c
5754 ;; (goto-char (1- pos)) ;????????????????????
5755 (if (or comment-p emph-p link-p keyw-p)
5757 (put-text-property (match-beginning 3) (match-end 0)
5758 'display
5759 (if (equal (char-after (match-beginning 2)) ?^)
5760 (nth (if table-p 3 1) org-script-display)
5761 (nth (if table-p 2 0) org-script-display)))
5762 (add-text-properties (match-beginning 2) (match-end 2)
5763 (list 'invisible t
5764 'org-dwidth t 'org-dwidth-n 1))
5765 (if (and (eq (char-after (match-beginning 3)) ?{)
5766 (eq (char-before (match-end 3)) ?}))
5767 (progn
5768 (add-text-properties
5769 (match-beginning 3) (1+ (match-beginning 3))
5770 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
5771 (add-text-properties
5772 (1- (match-end 3)) (match-end 3)
5773 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
5774 t)))))
5776 ;;;; Visibility cycling, including org-goto and indirect buffer
5778 ;;; Cycling
5780 (defvar org-cycle-global-status nil)
5781 (make-variable-buffer-local 'org-cycle-global-status)
5782 (defvar org-cycle-subtree-status nil)
5783 (make-variable-buffer-local 'org-cycle-subtree-status)
5785 ;;;###autoload
5787 (defvar org-inlinetask-min-level)
5789 (defun org-cycle (&optional arg)
5790 "TAB-action and visibility cycling for Org-mode.
5792 This is the command invoked in Org-mode by the TAB key. Its main purpose
5793 is outline visibility cycling, but it also invokes other actions
5794 in special contexts.
5796 - When this function is called with a prefix argument, rotate the entire
5797 buffer through 3 states (global cycling)
5798 1. OVERVIEW: Show only top-level headlines.
5799 2. CONTENTS: Show all headlines of all levels, but no body text.
5800 3. SHOW ALL: Show everything.
5801 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5802 determined by the variable `org-startup-folded', and by any VISIBILITY
5803 properties in the buffer.
5804 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5805 including any drawers.
5807 - When inside a table, re-align the table and move to the next field.
5809 - When point is at the beginning of a headline, rotate the subtree started
5810 by this line through 3 different states (local cycling)
5811 1. FOLDED: Only the main headline is shown.
5812 2. CHILDREN: The main headline and the direct children are shown.
5813 From this state, you can move to one of the children
5814 and zoom in further.
5815 3. SUBTREE: Show the entire subtree, including body text.
5816 If there is no subtree, switch directly from CHILDREN to FOLDED.
5818 - When point is at the beginning of an empty headline and the variable
5819 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5820 of the headline by demoting and promoting it to likely levels. This
5821 speeds up creation document structure by pressing TAB once or several
5822 times right after creating a new headline.
5824 - When there is a numeric prefix, go up to a heading with level ARG, do
5825 a `show-subtree' and return to the previous cursor position. If ARG
5826 is negative, go up that many levels.
5828 - When point is not at the beginning of a headline, execute the global
5829 binding for TAB, which is re-indenting the line. See the option
5830 `org-cycle-emulate-tab' for details.
5832 - Special case: if point is at the beginning of the buffer and there is
5833 no headline in line 1, this function will act as if called with prefix arg
5834 (C-u TAB, same as S-TAB) also when called without prefix arg.
5835 But only if also the variable `org-cycle-global-at-bob' is t."
5836 (interactive "P")
5837 (org-load-modules-maybe)
5838 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5839 (and org-cycle-level-after-item/entry-creation
5840 (or (org-cycle-level)
5841 (org-cycle-item-indentation))))
5842 (let* ((limit-level
5843 (or org-cycle-max-level
5844 (and (boundp 'org-inlinetask-min-level)
5845 org-inlinetask-min-level
5846 (1- org-inlinetask-min-level))))
5847 (nstars (and limit-level
5848 (if org-odd-levels-only
5849 (and limit-level (1- (* limit-level 2)))
5850 limit-level)))
5851 (outline-regexp
5852 (if (not (org-mode-p))
5853 outline-regexp
5854 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
5855 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
5856 (not (looking-at outline-regexp))))
5857 (org-cycle-hook
5858 (if bob-special
5859 (delq 'org-optimize-window-after-visibility-change
5860 (copy-sequence org-cycle-hook))
5861 org-cycle-hook))
5862 (pos (point)))
5864 (if (or bob-special (equal arg '(4)))
5865 ;; special case: use global cycling
5866 (setq arg t))
5868 (cond
5870 ((equal arg '(16))
5871 (setq last-command 'dummy)
5872 (org-set-startup-visibility)
5873 (message "Startup visibility, plus VISIBILITY properties"))
5875 ((equal arg '(64))
5876 (show-all)
5877 (message "Entire buffer visible, including drawers"))
5879 ;; Table: enter it or move to the next field.
5880 ((org-at-table-p 'any)
5881 (if (org-at-table.el-p)
5882 (message "Use C-c ' to edit table.el tables")
5883 (if arg (org-table-edit-field t)
5884 (org-table-justify-field-maybe)
5885 (call-interactively 'org-table-next-field))))
5887 ((run-hook-with-args-until-success
5888 'org-tab-after-check-for-table-hook))
5890 ;; Global cycling: delegate to `org-cycle-internal-global'.
5891 ((eq arg t) (org-cycle-internal-global))
5893 ;; Drawers: delegate to `org-flag-drawer'.
5894 ((and org-drawers org-drawer-regexp
5895 (save-excursion
5896 (beginning-of-line 1)
5897 (looking-at org-drawer-regexp)))
5898 (org-flag-drawer ; toggle block visibility
5899 (not (get-char-property (match-end 0) 'invisible))))
5901 ;; Show-subtree, ARG levels up from here.
5902 ((integerp arg)
5903 (save-excursion
5904 (org-back-to-heading)
5905 (outline-up-heading (if (< arg 0) (- arg)
5906 (- (funcall outline-level) arg)))
5907 (org-show-subtree)))
5909 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
5910 ((and (featurep 'org-inlinetask)
5911 (org-inlinetask-at-task-p)
5912 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5913 (org-inlinetask-toggle-visibility))
5915 ;; At an item/headline: delegate to `org-cycle-internal-local'.
5916 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
5917 (save-excursion (beginning-of-line 1)
5918 (looking-at outline-regexp)))
5919 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5920 (org-cycle-internal-local))
5922 ;; From there: TAB emulation and template completion.
5923 (buffer-read-only (org-back-to-heading))
5925 ((run-hook-with-args-until-success
5926 'org-tab-after-check-for-cycling-hook))
5928 ((org-try-structure-completion))
5930 ((org-try-cdlatex-tab))
5932 ((run-hook-with-args-until-success
5933 'org-tab-before-tab-emulation-hook))
5935 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5936 (or (not (bolp))
5937 (not (looking-at outline-regexp))))
5938 (call-interactively (global-key-binding "\t")))
5940 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5941 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5942 (or (and (eq org-cycle-emulate-tab 'white)
5943 (= (match-end 0) (point-at-eol)))
5944 (and (eq org-cycle-emulate-tab 'whitestart)
5945 (>= (match-end 0) pos))))
5947 (eq org-cycle-emulate-tab t))
5948 (call-interactively (global-key-binding "\t")))
5950 (t (save-excursion
5951 (org-back-to-heading)
5952 (org-cycle)))))))
5954 (defun org-cycle-internal-global ()
5955 "Do the global cycling action."
5956 (cond
5957 ((and (eq last-command this-command)
5958 (eq org-cycle-global-status 'overview))
5959 ;; We just created the overview - now do table of contents
5960 ;; This can be slow in very large buffers, so indicate action
5961 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5962 (message "CONTENTS...")
5963 (org-content)
5964 (message "CONTENTS...done")
5965 (setq org-cycle-global-status 'contents)
5966 (run-hook-with-args 'org-cycle-hook 'contents))
5968 ((and (eq last-command this-command)
5969 (eq org-cycle-global-status 'contents))
5970 ;; We just showed the table of contents - now show everything
5971 (run-hook-with-args 'org-pre-cycle-hook 'all)
5972 (show-all)
5973 (message "SHOW ALL")
5974 (setq org-cycle-global-status 'all)
5975 (run-hook-with-args 'org-cycle-hook 'all))
5978 ;; Default action: go to overview
5979 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5980 (org-overview)
5981 (message "OVERVIEW")
5982 (setq org-cycle-global-status 'overview)
5983 (run-hook-with-args 'org-cycle-hook 'overview))))
5985 (defun org-cycle-internal-local ()
5986 "Do the local cycling action."
5987 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
5988 ;; First, determine end of headline (EOH), end of subtree or item
5989 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
5990 (save-excursion
5991 (if (org-at-item-p)
5992 (progn
5993 (beginning-of-line)
5994 (setq struct (org-list-struct))
5995 (setq eoh (point-at-eol))
5996 (setq eos (org-list-get-item-end-before-blank (point) struct))
5997 (setq has-children (org-list-has-child-p (point) struct)))
5998 (org-back-to-heading)
5999 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6000 (setq eos (save-excursion
6001 (org-end-of-subtree t)
6002 (unless (eobp)
6003 (skip-chars-forward " \t\n"))
6004 (if (eobp) (point) (1- (point)))))
6005 (setq has-children
6006 (or (save-excursion
6007 (let ((level (funcall outline-level)))
6008 (outline-next-heading)
6009 (and (org-at-heading-p t)
6010 (> (funcall outline-level) level))))
6011 (save-excursion
6012 (org-list-search-forward (org-item-beginning-re) eos t)))))
6013 ;; Determine end invisible part of buffer (EOL)
6014 (beginning-of-line 2)
6015 ;; XEmacs doesn't have `next-single-char-property-change'
6016 (if (featurep 'xemacs)
6017 (while (and (not (eobp)) ;; this is like `next-line'
6018 (get-char-property (1- (point)) 'invisible))
6019 (beginning-of-line 2))
6020 (while (and (not (eobp)) ;; this is like `next-line'
6021 (get-char-property (1- (point)) 'invisible))
6022 (goto-char (next-single-char-property-change (point) 'invisible))
6023 (and (eolp) (beginning-of-line 2))))
6024 (setq eol (point)))
6025 ;; Find out what to do next and set `this-command'
6026 (cond
6027 ((= eos eoh)
6028 ;; Nothing is hidden behind this heading
6029 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6030 (message "EMPTY ENTRY")
6031 (setq org-cycle-subtree-status nil)
6032 (save-excursion
6033 (goto-char eos)
6034 (outline-next-heading)
6035 (if (outline-invisible-p) (org-flag-heading nil))))
6036 ((and (or (>= eol eos)
6037 (not (string-match "\\S-" (buffer-substring eol eos))))
6038 (or has-children
6039 (not (setq children-skipped
6040 org-cycle-skip-children-state-if-no-children))))
6041 ;; Entire subtree is hidden in one line: children view
6042 (run-hook-with-args 'org-pre-cycle-hook 'children)
6043 (if (org-at-item-p)
6044 (org-list-set-item-visibility (point-at-bol) struct 'children)
6045 (org-show-entry)
6046 (show-children)
6047 ;; Fold every list in subtree to top-level items.
6048 (when (eq org-cycle-include-plain-lists 'integrate)
6049 (save-excursion
6050 (org-back-to-heading)
6051 (while (org-list-search-forward (org-item-beginning-re) eos t)
6052 (beginning-of-line 1)
6053 (let* ((struct (org-list-struct))
6054 (prevs (org-list-prevs-alist struct))
6055 (end (org-list-get-bottom-point struct)))
6056 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6057 (org-list-get-all-items (point) struct prevs))
6058 (goto-char end))))))
6059 (message "CHILDREN")
6060 (save-excursion
6061 (goto-char eos)
6062 (outline-next-heading)
6063 (if (outline-invisible-p) (org-flag-heading nil)))
6064 (setq org-cycle-subtree-status 'children)
6065 (run-hook-with-args 'org-cycle-hook 'children))
6066 ((or children-skipped
6067 (and (eq last-command this-command)
6068 (eq org-cycle-subtree-status 'children)))
6069 ;; We just showed the children, or no children are there,
6070 ;; now show everything.
6071 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6072 (outline-flag-region eoh eos nil)
6073 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6074 (setq org-cycle-subtree-status 'subtree)
6075 (run-hook-with-args 'org-cycle-hook 'subtree))
6077 ;; Default action: hide the subtree.
6078 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6079 (outline-flag-region eoh eos t)
6080 (message "FOLDED")
6081 (setq org-cycle-subtree-status 'folded)
6082 (run-hook-with-args 'org-cycle-hook 'folded)))))
6084 ;;;###autoload
6085 (defun org-global-cycle (&optional arg)
6086 "Cycle the global visibility. For details see `org-cycle'.
6087 With \\[universal-argument] prefix arg, switch to startup visibility.
6088 With a numeric prefix, show all headlines up to that level."
6089 (interactive "P")
6090 (let ((org-cycle-include-plain-lists
6091 (if (org-mode-p) org-cycle-include-plain-lists nil)))
6092 (cond
6093 ((integerp arg)
6094 (show-all)
6095 (hide-sublevels arg)
6096 (setq org-cycle-global-status 'contents))
6097 ((equal arg '(4))
6098 (org-set-startup-visibility)
6099 (message "Startup visibility, plus VISIBILITY properties."))
6101 (org-cycle '(4))))))
6103 (defun org-set-startup-visibility ()
6104 "Set the visibility required by startup options and properties."
6105 (cond
6106 ((eq org-startup-folded t)
6107 (org-cycle '(4)))
6108 ((eq org-startup-folded 'content)
6109 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6110 (org-cycle '(4)) (org-cycle '(4)))))
6111 (unless (eq org-startup-folded 'showeverything)
6112 (if org-hide-block-startup (org-hide-block-all))
6113 (org-set-visibility-according-to-property 'no-cleanup)
6114 (org-cycle-hide-archived-subtrees 'all)
6115 (org-cycle-hide-drawers 'all)
6116 (org-cycle-show-empty-lines t)))
6118 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6119 "Switch subtree visibilities according to :VISIBILITY: property."
6120 (interactive)
6121 (let (org-show-entry-below state)
6122 (save-excursion
6123 (goto-char (point-min))
6124 (while (re-search-forward
6125 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6126 nil t)
6127 (setq state (match-string 1))
6128 (save-excursion
6129 (org-back-to-heading t)
6130 (hide-subtree)
6131 (org-reveal)
6132 (cond
6133 ((equal state '("fold" "folded"))
6134 (hide-subtree))
6135 ((equal state "children")
6136 (org-show-hidden-entry)
6137 (show-children))
6138 ((equal state "content")
6139 (save-excursion
6140 (save-restriction
6141 (org-narrow-to-subtree)
6142 (org-content))))
6143 ((member state '("all" "showall"))
6144 (show-subtree)))))
6145 (unless no-cleanup
6146 (org-cycle-hide-archived-subtrees 'all)
6147 (org-cycle-hide-drawers 'all)
6148 (org-cycle-show-empty-lines 'all)))))
6150 (defun org-overview ()
6151 "Switch to overview mode, showing only top-level headlines.
6152 Really, this shows all headlines with level equal or greater than the level
6153 of the first headline in the buffer. This is important, because if the
6154 first headline is not level one, then (hide-sublevels 1) gives confusing
6155 results."
6156 (interactive)
6157 (let ((level (save-excursion
6158 (goto-char (point-min))
6159 (if (re-search-forward (concat "^" outline-regexp) nil t)
6160 (progn
6161 (goto-char (match-beginning 0))
6162 (funcall outline-level))))))
6163 (and level (hide-sublevels level))))
6165 (defun org-content (&optional arg)
6166 "Show all headlines in the buffer, like a table of contents.
6167 With numerical argument N, show content up to level N."
6168 (interactive "P")
6169 (save-excursion
6170 ;; Visit all headings and show their offspring
6171 (and (integerp arg) (org-overview))
6172 (goto-char (point-max))
6173 (catch 'exit
6174 (while (and (progn (condition-case nil
6175 (outline-previous-visible-heading 1)
6176 (error (goto-char (point-min))))
6178 (looking-at outline-regexp))
6179 (if (integerp arg)
6180 (show-children (1- arg))
6181 (show-branches))
6182 (if (bobp) (throw 'exit nil))))))
6185 (defun org-optimize-window-after-visibility-change (state)
6186 "Adjust the window after a change in outline visibility.
6187 This function is the default value of the hook `org-cycle-hook'."
6188 (when (get-buffer-window (current-buffer))
6189 (cond
6190 ((eq state 'content) nil)
6191 ((eq state 'all) nil)
6192 ((eq state 'folded) nil)
6193 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6194 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6196 (defun org-remove-empty-overlays-at (pos)
6197 "Remove outline overlays that do not contain non-white stuff."
6198 (mapc
6199 (lambda (o)
6200 (and (eq 'outline (overlay-get o 'invisible))
6201 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6202 (overlay-end o))))
6203 (delete-overlay o)))
6204 (overlays-at pos)))
6206 (defun org-clean-visibility-after-subtree-move ()
6207 "Fix visibility issues after moving a subtree."
6208 ;; First, find a reasonable region to look at:
6209 ;; Start two siblings above, end three below
6210 (let* ((beg (save-excursion
6211 (and (org-get-last-sibling)
6212 (org-get-last-sibling))
6213 (point)))
6214 (end (save-excursion
6215 (and (org-get-next-sibling)
6216 (org-get-next-sibling)
6217 (org-get-next-sibling))
6218 (if (org-at-heading-p)
6219 (point-at-eol)
6220 (point))))
6221 (level (looking-at "\\*+"))
6222 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6223 (save-excursion
6224 (save-restriction
6225 (narrow-to-region beg end)
6226 (when re
6227 ;; Properly fold already folded siblings
6228 (goto-char (point-min))
6229 (while (re-search-forward re nil t)
6230 (if (and (not (outline-invisible-p))
6231 (save-excursion
6232 (goto-char (point-at-eol)) (outline-invisible-p)))
6233 (hide-entry))))
6234 (org-cycle-show-empty-lines 'overview)
6235 (org-cycle-hide-drawers 'overview)))))
6237 (defun org-cycle-show-empty-lines (state)
6238 "Show empty lines above all visible headlines.
6239 The region to be covered depends on STATE when called through
6240 `org-cycle-hook'. Lisp program can use t for STATE to get the
6241 entire buffer covered. Note that an empty line is only shown if there
6242 are at least `org-cycle-separator-lines' empty lines before the headline."
6243 (when (not (= org-cycle-separator-lines 0))
6244 (save-excursion
6245 (let* ((n (abs org-cycle-separator-lines))
6246 (re (cond
6247 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6248 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6249 (t (let ((ns (number-to-string (- n 2))))
6250 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6251 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6252 beg end b e)
6253 (cond
6254 ((memq state '(overview contents t))
6255 (setq beg (point-min) end (point-max)))
6256 ((memq state '(children folded))
6257 (setq beg (point) end (progn (org-end-of-subtree t t)
6258 (beginning-of-line 2)
6259 (point)))))
6260 (when beg
6261 (goto-char beg)
6262 (while (re-search-forward re end t)
6263 (unless (get-char-property (match-end 1) 'invisible)
6264 (setq e (match-end 1))
6265 (if (< org-cycle-separator-lines 0)
6266 (setq b (save-excursion
6267 (goto-char (match-beginning 0))
6268 (org-back-over-empty-lines)
6269 (if (save-excursion
6270 (goto-char (max (point-min) (1- (point))))
6271 (org-on-heading-p))
6272 (1- (point))
6273 (point))))
6274 (setq b (match-beginning 1)))
6275 (outline-flag-region b e nil)))))))
6276 ;; Never hide empty lines at the end of the file.
6277 (save-excursion
6278 (goto-char (point-max))
6279 (outline-previous-heading)
6280 (outline-end-of-heading)
6281 (if (and (looking-at "[ \t\n]+")
6282 (= (match-end 0) (point-max)))
6283 (outline-flag-region (point) (match-end 0) nil))))
6285 (defun org-show-empty-lines-in-parent ()
6286 "Move to the parent and re-show empty lines before visible headlines."
6287 (save-excursion
6288 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6289 (org-cycle-show-empty-lines context))))
6291 (defun org-files-list ()
6292 "Return `org-agenda-files' list, plus all open org-mode files.
6293 This is useful for operations that need to scan all of a user's
6294 open and agenda-wise Org files."
6295 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6296 (dolist (buf (buffer-list))
6297 (with-current-buffer buf
6298 (if (and (org-mode-p) (buffer-file-name))
6299 (let ((file (expand-file-name (buffer-file-name))))
6300 (unless (member file files)
6301 (push file files))))))
6302 files))
6304 (defsubst org-entry-beginning-position ()
6305 "Return the beginning position of the current entry."
6306 (save-excursion (outline-back-to-heading t) (point)))
6308 (defsubst org-entry-end-position ()
6309 "Return the end position of the current entry."
6310 (save-excursion (outline-next-heading) (point)))
6312 (defun org-cycle-hide-drawers (state)
6313 "Re-hide all drawers after a visibility state change."
6314 (when (and (org-mode-p)
6315 (not (memq state '(overview folded contents))))
6316 (save-excursion
6317 (let* ((globalp (memq state '(contents all)))
6318 (beg (if globalp (point-min) (point)))
6319 (end (if globalp (point-max)
6320 (if (eq state 'children)
6321 (save-excursion (outline-next-heading) (point))
6322 (org-end-of-subtree t)))))
6323 (goto-char beg)
6324 (while (re-search-forward org-drawer-regexp end t)
6325 (org-flag-drawer t))))))
6327 (defun org-flag-drawer (flag)
6328 (save-excursion
6329 (beginning-of-line 1)
6330 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6331 (let ((b (match-end 0))
6332 (outline-regexp org-outline-regexp))
6333 (if (re-search-forward
6334 "^[ \t]*:END:"
6335 (save-excursion (outline-next-heading) (point)) t)
6336 (outline-flag-region b (point-at-eol) flag)
6337 (error ":END: line missing at position %s" b))))))
6339 (defun org-subtree-end-visible-p ()
6340 "Is the end of the current subtree visible?"
6341 (pos-visible-in-window-p
6342 (save-excursion (org-end-of-subtree t) (point))))
6344 (defun org-first-headline-recenter (&optional N)
6345 "Move cursor to the first headline and recenter the headline.
6346 Optional argument N means put the headline into the Nth line of the window."
6347 (goto-char (point-min))
6348 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
6349 (beginning-of-line)
6350 (recenter (prefix-numeric-value N))))
6352 ;;; Saving and restoring visibility
6354 (defun org-outline-overlay-data (&optional use-markers)
6355 "Return a list of the locations of all outline overlays.
6356 These are overlays with the `invisible' property value `outline'.
6357 The return value is a list of cons cells, with start and stop
6358 positions for each overlay.
6359 If USE-MARKERS is set, return the positions as markers."
6360 (let (beg end)
6361 (save-excursion
6362 (save-restriction
6363 (widen)
6364 (delq nil
6365 (mapcar (lambda (o)
6366 (when (eq (overlay-get o 'invisible) 'outline)
6367 (setq beg (overlay-start o)
6368 end (overlay-end o))
6369 (and beg end (> end beg)
6370 (if use-markers
6371 (cons (move-marker (make-marker) beg)
6372 (move-marker (make-marker) end))
6373 (cons beg end)))))
6374 (overlays-in (point-min) (point-max))))))))
6376 (defun org-set-outline-overlay-data (data)
6377 "Create visibility overlays for all positions in DATA.
6378 DATA should have been made by `org-outline-overlay-data'."
6379 (let (o)
6380 (save-excursion
6381 (save-restriction
6382 (widen)
6383 (show-all)
6384 (mapc (lambda (c)
6385 (setq o (make-overlay (car c) (cdr c)))
6386 (overlay-put o 'invisible 'outline))
6387 data)))))
6389 ;;; Folding of blocks
6391 (defconst org-block-regexp
6392 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
6393 "Regular expression for hiding blocks.")
6395 (defvar org-hide-block-overlays nil
6396 "Overlays hiding blocks.")
6397 (make-variable-buffer-local 'org-hide-block-overlays)
6399 (defun org-block-map (function &optional start end)
6400 "Call FUNCTION at the head of all source blocks in the current buffer.
6401 Optional arguments START and END can be used to limit the range."
6402 (let ((start (or start (point-min)))
6403 (end (or end (point-max))))
6404 (save-excursion
6405 (goto-char start)
6406 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6407 (save-excursion
6408 (save-match-data
6409 (goto-char (match-beginning 0))
6410 (funcall function)))))))
6412 (defun org-hide-block-toggle-all ()
6413 "Toggle the visibility of all blocks in the current buffer."
6414 (org-block-map #'org-hide-block-toggle))
6416 (defun org-hide-block-all ()
6417 "Fold all blocks in the current buffer."
6418 (interactive)
6419 (org-show-block-all)
6420 (org-block-map #'org-hide-block-toggle-maybe))
6422 (defun org-show-block-all ()
6423 "Unfold all blocks in the current buffer."
6424 (interactive)
6425 (mapc 'delete-overlay org-hide-block-overlays)
6426 (setq org-hide-block-overlays nil))
6428 (defun org-hide-block-toggle-maybe ()
6429 "Toggle visibility of block at point."
6430 (interactive)
6431 (let ((case-fold-search t))
6432 (if (save-excursion
6433 (beginning-of-line 1)
6434 (looking-at org-block-regexp))
6435 (progn (org-hide-block-toggle)
6436 t) ;; to signal that we took action
6437 nil))) ;; to signal that we did not
6439 (defun org-hide-block-toggle (&optional force)
6440 "Toggle the visibility of the current block."
6441 (interactive)
6442 (save-excursion
6443 (beginning-of-line)
6444 (if (re-search-forward org-block-regexp nil t)
6445 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6446 (end (match-end 0)) ;; end of entire body
6448 (if (memq t (mapcar (lambda (overlay)
6449 (eq (overlay-get overlay 'invisible)
6450 'org-hide-block))
6451 (overlays-at start)))
6452 (if (or (not force) (eq force 'off))
6453 (mapc (lambda (ov)
6454 (when (member ov org-hide-block-overlays)
6455 (setq org-hide-block-overlays
6456 (delq ov org-hide-block-overlays)))
6457 (when (eq (overlay-get ov 'invisible)
6458 'org-hide-block)
6459 (delete-overlay ov)))
6460 (overlays-at start)))
6461 (setq ov (make-overlay start end))
6462 (overlay-put ov 'invisible 'org-hide-block)
6463 ;; make the block accessible to isearch
6464 (overlay-put
6465 ov 'isearch-open-invisible
6466 (lambda (ov)
6467 (when (member ov org-hide-block-overlays)
6468 (setq org-hide-block-overlays
6469 (delq ov org-hide-block-overlays)))
6470 (when (eq (overlay-get ov 'invisible)
6471 'org-hide-block)
6472 (delete-overlay ov))))
6473 (push ov org-hide-block-overlays)))
6474 (error "Not looking at a source block"))))
6476 ;; org-tab-after-check-for-cycling-hook
6477 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6478 ;; Remove overlays when changing major mode
6479 (add-hook 'org-mode-hook
6480 (lambda () (org-add-hook 'change-major-mode-hook
6481 'org-show-block-all 'append 'local)))
6483 ;;; Org-goto
6485 (defvar org-goto-window-configuration nil)
6486 (defvar org-goto-marker nil)
6487 (defvar org-goto-map
6488 (let ((map (make-sparse-keymap)))
6489 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6490 (while (setq cmd (pop cmds))
6491 (substitute-key-definition cmd cmd map global-map)))
6492 (suppress-keymap map)
6493 (org-defkey map "\C-m" 'org-goto-ret)
6494 (org-defkey map [(return)] 'org-goto-ret)
6495 (org-defkey map [(left)] 'org-goto-left)
6496 (org-defkey map [(right)] 'org-goto-right)
6497 (org-defkey map [(control ?g)] 'org-goto-quit)
6498 (org-defkey map "\C-i" 'org-cycle)
6499 (org-defkey map [(tab)] 'org-cycle)
6500 (org-defkey map [(down)] 'outline-next-visible-heading)
6501 (org-defkey map [(up)] 'outline-previous-visible-heading)
6502 (if org-goto-auto-isearch
6503 (if (fboundp 'define-key-after)
6504 (define-key-after map [t] 'org-goto-local-auto-isearch)
6505 nil)
6506 (org-defkey map "q" 'org-goto-quit)
6507 (org-defkey map "n" 'outline-next-visible-heading)
6508 (org-defkey map "p" 'outline-previous-visible-heading)
6509 (org-defkey map "f" 'outline-forward-same-level)
6510 (org-defkey map "b" 'outline-backward-same-level)
6511 (org-defkey map "u" 'outline-up-heading))
6512 (org-defkey map "/" 'org-occur)
6513 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6514 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6515 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6516 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6517 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6518 map))
6520 (defconst org-goto-help
6521 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6522 RET=jump to location [Q]uit and return to previous location
6523 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6525 (defvar org-goto-start-pos) ; dynamically scoped parameter
6527 ;; FIXME: Docstring does not mention both interfaces
6528 (defun org-goto (&optional alternative-interface)
6529 "Look up a different location in the current file, keeping current visibility.
6531 When you want look-up or go to a different location in a document, the
6532 fastest way is often to fold the entire buffer and then dive into the tree.
6533 This method has the disadvantage, that the previous location will be folded,
6534 which may not be what you want.
6536 This command works around this by showing a copy of the current buffer
6537 in an indirect buffer, in overview mode. You can dive into the tree in
6538 that copy, use org-occur and incremental search to find a location.
6539 When pressing RET or `Q', the command returns to the original buffer in
6540 which the visibility is still unchanged. After RET is will also jump to
6541 the location selected in the indirect buffer and expose the
6542 the headline hierarchy above."
6543 (interactive "P")
6544 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6545 (org-refile-use-outline-path t)
6546 (org-refile-target-verify-function nil)
6547 (interface
6548 (if (not alternative-interface)
6549 org-goto-interface
6550 (if (eq org-goto-interface 'outline)
6551 'outline-path-completion
6552 'outline)))
6553 (org-goto-start-pos (point))
6554 (selected-point
6555 (if (eq interface 'outline)
6556 (car (org-get-location (current-buffer) org-goto-help))
6557 (let ((pa (org-refile-get-location "Goto")))
6558 (org-refile-check-position pa)
6559 (nth 3 pa)))))
6560 (if selected-point
6561 (progn
6562 (org-mark-ring-push org-goto-start-pos)
6563 (goto-char selected-point)
6564 (if (or (outline-invisible-p) (org-invisible-p2))
6565 (org-show-context 'org-goto)))
6566 (message "Quit"))))
6568 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6569 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6570 (defvar org-goto-local-auto-isearch-map) ; defined below
6572 (defun org-get-location (buf help)
6573 "Let the user select a location in the Org-mode buffer BUF.
6574 This function uses a recursive edit. It returns the selected position
6575 or nil."
6576 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6577 (isearch-hide-immediately nil)
6578 (isearch-search-fun-function
6579 (lambda () 'org-goto-local-search-headings))
6580 (org-goto-selected-point org-goto-exit-command)
6581 (pop-up-frames nil)
6582 (special-display-buffer-names nil)
6583 (special-display-regexps nil)
6584 (special-display-function nil))
6585 (save-excursion
6586 (save-window-excursion
6587 (delete-other-windows)
6588 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6589 (switch-to-buffer
6590 (condition-case nil
6591 (make-indirect-buffer (current-buffer) "*org-goto*")
6592 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6593 (with-output-to-temp-buffer "*Help*"
6594 (princ help))
6595 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6596 (setq buffer-read-only nil)
6597 (let ((org-startup-truncated t)
6598 (org-startup-folded nil)
6599 (org-startup-align-all-tables nil))
6600 (org-mode)
6601 (org-overview))
6602 (setq buffer-read-only t)
6603 (if (and (boundp 'org-goto-start-pos)
6604 (integer-or-marker-p org-goto-start-pos))
6605 (let ((org-show-hierarchy-above t)
6606 (org-show-siblings t)
6607 (org-show-following-heading t))
6608 (goto-char org-goto-start-pos)
6609 (and (outline-invisible-p) (org-show-context)))
6610 (goto-char (point-min)))
6611 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6612 (message "Select location and press RET")
6613 (use-local-map org-goto-map)
6614 (recursive-edit)
6616 (kill-buffer "*org-goto*")
6617 (cons org-goto-selected-point org-goto-exit-command)))
6619 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6620 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6621 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6622 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6624 (defun org-goto-local-search-headings (string bound noerror)
6625 "Search and make sure that any matches are in headlines."
6626 (catch 'return
6627 (while (if isearch-forward
6628 (search-forward string bound noerror)
6629 (search-backward string bound noerror))
6630 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6631 (and (member :headline context)
6632 (not (member :tags context))))
6633 (throw 'return (point))))))
6635 (defun org-goto-local-auto-isearch ()
6636 "Start isearch."
6637 (interactive)
6638 (goto-char (point-min))
6639 (let ((keys (this-command-keys)))
6640 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6641 (isearch-mode t)
6642 (isearch-process-search-char (string-to-char keys)))))
6644 (defun org-goto-ret (&optional arg)
6645 "Finish `org-goto' by going to the new location."
6646 (interactive "P")
6647 (setq org-goto-selected-point (point)
6648 org-goto-exit-command 'return)
6649 (throw 'exit nil))
6651 (defun org-goto-left ()
6652 "Finish `org-goto' by going to the new location."
6653 (interactive)
6654 (if (org-on-heading-p)
6655 (progn
6656 (beginning-of-line 1)
6657 (setq org-goto-selected-point (point)
6658 org-goto-exit-command 'left)
6659 (throw 'exit nil))
6660 (error "Not on a heading")))
6662 (defun org-goto-right ()
6663 "Finish `org-goto' by going to the new location."
6664 (interactive)
6665 (if (org-on-heading-p)
6666 (progn
6667 (setq org-goto-selected-point (point)
6668 org-goto-exit-command 'right)
6669 (throw 'exit nil))
6670 (error "Not on a heading")))
6672 (defun org-goto-quit ()
6673 "Finish `org-goto' without cursor motion."
6674 (interactive)
6675 (setq org-goto-selected-point nil)
6676 (setq org-goto-exit-command 'quit)
6677 (throw 'exit nil))
6679 ;;; Indirect buffer display of subtrees
6681 (defvar org-indirect-dedicated-frame nil
6682 "This is the frame being used for indirect tree display.")
6683 (defvar org-last-indirect-buffer nil)
6685 (defun org-tree-to-indirect-buffer (&optional arg)
6686 "Create indirect buffer and narrow it to current subtree.
6687 With numerical prefix ARG, go up to this level and then take that tree.
6688 If ARG is negative, go up that many levels.
6689 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6690 indirect buffer previously made with this command, to avoid proliferation of
6691 indirect buffers. However, when you call the command with a \
6692 \\[universal-argument] prefix, or
6693 when `org-indirect-buffer-display' is `new-frame', the last buffer
6694 is kept so that you can work with several indirect buffers at the same time.
6695 If `org-indirect-buffer-display' is `dedicated-frame', the \
6696 \\[universal-argument] prefix also
6697 requests that a new frame be made for the new buffer, so that the dedicated
6698 frame is not changed."
6699 (interactive "P")
6700 (let ((cbuf (current-buffer))
6701 (cwin (selected-window))
6702 (pos (point))
6703 beg end level heading ibuf)
6704 (save-excursion
6705 (org-back-to-heading t)
6706 (when (numberp arg)
6707 (setq level (org-outline-level))
6708 (if (< arg 0) (setq arg (+ level arg)))
6709 (while (> (setq level (org-outline-level)) arg)
6710 (outline-up-heading 1 t)))
6711 (setq beg (point)
6712 heading (org-get-heading))
6713 (org-end-of-subtree t t)
6714 (if (org-on-heading-p) (backward-char 1))
6715 (setq end (point)))
6716 (if (and (buffer-live-p org-last-indirect-buffer)
6717 (not (eq org-indirect-buffer-display 'new-frame))
6718 (not arg))
6719 (kill-buffer org-last-indirect-buffer))
6720 (setq ibuf (org-get-indirect-buffer cbuf)
6721 org-last-indirect-buffer ibuf)
6722 (cond
6723 ((or (eq org-indirect-buffer-display 'new-frame)
6724 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6725 (select-frame (make-frame))
6726 (delete-other-windows)
6727 (switch-to-buffer ibuf)
6728 (org-set-frame-title heading))
6729 ((eq org-indirect-buffer-display 'dedicated-frame)
6730 (raise-frame
6731 (select-frame (or (and org-indirect-dedicated-frame
6732 (frame-live-p org-indirect-dedicated-frame)
6733 org-indirect-dedicated-frame)
6734 (setq org-indirect-dedicated-frame (make-frame)))))
6735 (delete-other-windows)
6736 (switch-to-buffer ibuf)
6737 (org-set-frame-title (concat "Indirect: " heading)))
6738 ((eq org-indirect-buffer-display 'current-window)
6739 (switch-to-buffer ibuf))
6740 ((eq org-indirect-buffer-display 'other-window)
6741 (pop-to-buffer ibuf))
6742 (t (error "Invalid value")))
6743 (if (featurep 'xemacs)
6744 (save-excursion (org-mode) (turn-on-font-lock)))
6745 (narrow-to-region beg end)
6746 (show-all)
6747 (goto-char pos)
6748 (and (window-live-p cwin) (select-window cwin))))
6750 (defun org-get-indirect-buffer (&optional buffer)
6751 (setq buffer (or buffer (current-buffer)))
6752 (let ((n 1) (base (buffer-name buffer)) bname)
6753 (while (buffer-live-p
6754 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6755 (setq n (1+ n)))
6756 (condition-case nil
6757 (make-indirect-buffer buffer bname 'clone)
6758 (error (make-indirect-buffer buffer bname)))))
6760 (defun org-set-frame-title (title)
6761 "Set the title of the current frame to the string TITLE."
6762 ;; FIXME: how to name a single frame in XEmacs???
6763 (unless (featurep 'xemacs)
6764 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6766 ;;;; Structure editing
6768 ;;; Inserting headlines
6770 (defun org-previous-line-empty-p ()
6771 (save-excursion
6772 (and (not (bobp))
6773 (or (beginning-of-line 0) t)
6774 (save-match-data
6775 (looking-at "[ \t]*$")))))
6777 (defun org-insert-heading (&optional force-heading invisible-ok)
6778 "Insert a new heading or item with same depth at point.
6779 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6780 If point is at the beginning of a headline, insert a sibling before the
6781 current headline. If point is not at the beginning, split the line,
6782 create the new headline with the text in the current line after point
6783 \(but see also the variable `org-M-RET-may-split-line').
6785 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6786 This is important for non-interactive uses of the command."
6787 (interactive "P")
6788 (if (or (= (buffer-size) 0)
6789 (and (not (save-excursion
6790 (and (ignore-errors (org-back-to-heading invisible-ok))
6791 (org-on-heading-p))))
6792 (not (org-in-item-p))))
6793 (progn
6794 (insert "\n* ")
6795 (run-hooks 'org-insert-heading-hook))
6796 (when (or force-heading (not (org-insert-item)))
6797 (let* ((empty-line-p nil)
6798 (level nil)
6799 (on-heading (org-on-heading-p))
6800 (head (save-excursion
6801 (condition-case nil
6802 (progn
6803 (org-back-to-heading invisible-ok)
6804 (when (and (not on-heading)
6805 (featurep 'org-inlinetask)
6806 (integerp org-inlinetask-min-level)
6807 (>= (length (match-string 0))
6808 org-inlinetask-min-level))
6809 ;; Find a heading level before the inline task
6810 (while (and (setq level (org-up-heading-safe))
6811 (>= level org-inlinetask-min-level)))
6812 (if (org-on-heading-p)
6813 (org-back-to-heading invisible-ok)
6814 (error "This should not happen")))
6815 (setq empty-line-p (org-previous-line-empty-p))
6816 (match-string 0))
6817 (error "*"))))
6818 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6819 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6820 pos hide-previous previous-pos)
6821 (cond
6822 ((and (org-on-heading-p) (bolp)
6823 (or (bobp)
6824 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
6825 ;; insert before the current line
6826 (open-line (if blank 2 1)))
6827 ((and (bolp)
6828 (not org-insert-heading-respect-content)
6829 (or (bobp)
6830 (save-excursion
6831 (backward-char 1) (not (outline-invisible-p)))))
6832 ;; insert right here
6833 nil)
6835 ;; somewhere in the line
6836 (save-excursion
6837 (setq previous-pos (point-at-bol))
6838 (end-of-line)
6839 (setq hide-previous (outline-invisible-p)))
6840 (and org-insert-heading-respect-content (org-show-subtree))
6841 (let ((split
6842 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6843 (save-excursion
6844 (let ((p (point)))
6845 (goto-char (point-at-bol))
6846 (and (looking-at org-complex-heading-regexp)
6847 (> p (match-beginning 4)))))))
6848 tags pos)
6849 (cond
6850 (org-insert-heading-respect-content
6851 (org-end-of-subtree nil t)
6852 (when (featurep 'org-inlinetask)
6853 (while (and (not (eobp))
6854 (looking-at "\\(\\*+\\)[ \t]+")
6855 (>= (length (match-string 1))
6856 org-inlinetask-min-level))
6857 (org-end-of-subtree nil t)))
6858 (or (bolp) (newline))
6859 (or (org-previous-line-empty-p)
6860 (and blank (newline)))
6861 (open-line 1))
6862 ((org-on-heading-p)
6863 (when hide-previous
6864 (show-children)
6865 (org-show-entry))
6866 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
6867 (setq tags (and (match-end 2) (match-string 2)))
6868 (and (match-end 1)
6869 (delete-region (match-beginning 1) (match-end 1)))
6870 (setq pos (point-at-bol))
6871 (or split (end-of-line 1))
6872 (delete-horizontal-space)
6873 (if (string-match "\\`\\*+\\'"
6874 (buffer-substring (point-at-bol) (point)))
6875 (insert " "))
6876 (newline (if blank 2 1))
6877 (when tags
6878 (save-excursion
6879 (goto-char pos)
6880 (end-of-line 1)
6881 (insert " " tags)
6882 (org-set-tags nil 'align))))
6884 (or split (end-of-line 1))
6885 (newline (if blank 2 1)))))))
6886 (insert head) (just-one-space)
6887 (setq pos (point))
6888 (end-of-line 1)
6889 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6890 (when (and org-insert-heading-respect-content hide-previous)
6891 (save-excursion
6892 (goto-char previous-pos)
6893 (hide-subtree)))
6894 (run-hooks 'org-insert-heading-hook)))))
6896 (defun org-get-heading (&optional no-tags)
6897 "Return the heading of the current entry, without the stars."
6898 (save-excursion
6899 (org-back-to-heading t)
6900 (if (looking-at
6901 (if no-tags
6902 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@#%]+:[ \t]*\\)?$")
6903 "\\*+[ \t]+\\([^\r\n]*\\)"))
6904 (match-string 1) "")))
6906 (defun org-heading-components ()
6907 "Return the components of the current heading.
6908 This is a list with the following elements:
6909 - the level as an integer
6910 - the reduced level, different if `org-odd-levels-only' is set.
6911 - the TODO keyword, or nil
6912 - the priority character, like ?A, or nil if no priority is given
6913 - the headline text itself, or the tags string if no headline text
6914 - the tags string, or nil."
6915 (save-excursion
6916 (org-back-to-heading t)
6917 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6918 (list (length (match-string 1))
6919 (org-reduced-level (length (match-string 1)))
6920 (org-match-string-no-properties 2)
6921 (and (match-end 3) (aref (match-string 3) 2))
6922 (org-match-string-no-properties 4)
6923 (org-match-string-no-properties 5)))))
6925 (defun org-get-entry ()
6926 "Get the entry text, after heading, entire subtree."
6927 (save-excursion
6928 (org-back-to-heading t)
6929 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6931 (defun org-insert-heading-after-current ()
6932 "Insert a new heading with same level as current, after current subtree."
6933 (interactive)
6934 (org-back-to-heading)
6935 (org-insert-heading)
6936 (org-move-subtree-down)
6937 (end-of-line 1))
6939 (defun org-insert-heading-respect-content ()
6940 (interactive)
6941 (let ((org-insert-heading-respect-content t))
6942 (org-insert-heading t)))
6944 (defun org-insert-todo-heading-respect-content (&optional force-state)
6945 (interactive "P")
6946 (let ((org-insert-heading-respect-content t))
6947 (org-insert-todo-heading force-state t)))
6949 (defun org-insert-todo-heading (arg &optional force-heading)
6950 "Insert a new heading with the same level and TODO state as current heading.
6951 If the heading has no TODO state, or if the state is DONE, use the first
6952 state (TODO by default). Also with prefix arg, force first state."
6953 (interactive "P")
6954 (when (or force-heading (not (org-insert-item 'checkbox)))
6955 (org-insert-heading force-heading)
6956 (save-excursion
6957 (org-back-to-heading)
6958 (outline-previous-heading)
6959 (looking-at org-todo-line-regexp))
6960 (let*
6961 ((new-mark-x
6962 (if (or arg
6963 (not (match-beginning 2))
6964 (member (match-string 2) org-done-keywords))
6965 (car org-todo-keywords-1)
6966 (match-string 2)))
6967 (new-mark
6969 (run-hook-with-args-until-success
6970 'org-todo-get-default-hook new-mark-x nil)
6971 new-mark-x)))
6972 (beginning-of-line 1)
6973 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6974 (if org-treat-insert-todo-heading-as-state-change
6975 (org-todo new-mark)
6976 (insert new-mark " "))))
6977 (when org-provide-todo-statistics
6978 (org-update-parent-todo-statistics))))
6980 (defun org-insert-subheading (arg)
6981 "Insert a new subheading and demote it.
6982 Works for outline headings and for plain lists alike."
6983 (interactive "P")
6984 (org-insert-heading arg)
6985 (cond
6986 ((org-on-heading-p) (org-do-demote))
6987 ((org-at-item-p) (org-indent-item))))
6989 (defun org-insert-todo-subheading (arg)
6990 "Insert a new subheading with TODO keyword or checkbox and demote it.
6991 Works for outline headings and for plain lists alike."
6992 (interactive "P")
6993 (org-insert-todo-heading arg)
6994 (cond
6995 ((org-on-heading-p) (org-do-demote))
6996 ((org-at-item-p) (org-indent-item))))
6998 ;;; Promotion and Demotion
7000 (defvar org-after-demote-entry-hook nil
7001 "Hook run after an entry has been demoted.
7002 The cursor will be at the beginning of the entry.
7003 When a subtree is being demoted, the hook will be called for each node.")
7005 (defvar org-after-promote-entry-hook nil
7006 "Hook run after an entry has been promoted.
7007 The cursor will be at the beginning of the entry.
7008 When a subtree is being promoted, the hook will be called for each node.")
7010 (defun org-promote-subtree ()
7011 "Promote the entire subtree.
7012 See also `org-promote'."
7013 (interactive)
7014 (save-excursion
7015 (org-with-limited-levels (org-map-tree 'org-promote)))
7016 (org-fix-position-after-promote))
7018 (defun org-demote-subtree ()
7019 "Demote the entire subtree. See `org-demote'.
7020 See also `org-promote'."
7021 (interactive)
7022 (save-excursion
7023 (org-with-limited-levels (org-map-tree 'org-demote)))
7024 (org-fix-position-after-promote))
7027 (defun org-do-promote ()
7028 "Promote the current heading higher up the tree.
7029 If the region is active in `transient-mark-mode', promote all headings
7030 in the region."
7031 (interactive)
7032 (save-excursion
7033 (if (org-region-active-p)
7034 (org-map-region 'org-promote (region-beginning) (region-end))
7035 (org-promote)))
7036 (org-fix-position-after-promote))
7038 (defun org-do-demote ()
7039 "Demote the current heading lower down the tree.
7040 If the region is active in `transient-mark-mode', demote all headings
7041 in the region."
7042 (interactive)
7043 (save-excursion
7044 (if (org-region-active-p)
7045 (org-map-region 'org-demote (region-beginning) (region-end))
7046 (org-demote)))
7047 (org-fix-position-after-promote))
7049 (defun org-fix-position-after-promote ()
7050 "Make sure that after pro/demotion cursor position is right."
7051 (let ((pos (point)))
7052 (when (save-excursion
7053 (beginning-of-line 1)
7054 (looking-at org-todo-line-regexp)
7055 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7056 (cond ((eobp) (insert " "))
7057 ((eolp) (insert " "))
7058 ((equal (char-after) ?\ ) (forward-char 1))))))
7060 (defun org-current-level ()
7061 "Return the level of the current entry, or nil if before the first headline.
7062 The level is the number of stars at the beginning of the headline."
7063 (save-excursion
7064 (org-with-limited-levels
7065 (ignore-errors
7066 (org-back-to-heading t)
7067 (funcall outline-level)))))
7069 (defun org-get-previous-line-level ()
7070 "Return the outline depth of the last headline before the current line.
7071 Returns 0 for the first headline in the buffer, and nil if before the
7072 first headline."
7073 (let ((current-level (org-current-level))
7074 (prev-level (when (> (line-number-at-pos) 1)
7075 (save-excursion
7076 (beginning-of-line 0)
7077 (org-current-level)))))
7078 (cond ((null current-level) nil) ; Before first headline
7079 ((null prev-level) 0) ; At first headline
7080 (prev-level))))
7082 (defun org-reduced-level (l)
7083 "Compute the effective level of a heading.
7084 This takes into account the setting of `org-odd-levels-only'."
7085 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
7087 (defun org-level-increment ()
7088 "Return the number of stars that will be added or removed at a
7089 time to headlines when structure editing, based on the value of
7090 `org-odd-levels-only'."
7091 (if org-odd-levels-only 2 1))
7093 (defun org-get-valid-level (level &optional change)
7094 "Rectify a level change under the influence of `org-odd-levels-only'
7095 LEVEL is a current level, CHANGE is by how much the level should be
7096 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7097 even level numbers will become the next higher odd number."
7098 (if org-odd-levels-only
7099 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7100 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7101 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7102 (max 1 (+ level (or change 0)))))
7104 (if (boundp 'define-obsolete-function-alias)
7105 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7106 (define-obsolete-function-alias 'org-get-legal-level
7107 'org-get-valid-level)
7108 (define-obsolete-function-alias 'org-get-legal-level
7109 'org-get-valid-level "23.1")))
7111 (defun org-promote ()
7112 "Promote the current heading higher up the tree.
7113 If the region is active in `transient-mark-mode', promote all headings
7114 in the region."
7115 (org-back-to-heading t)
7116 (let* ((level (save-match-data (funcall outline-level)))
7117 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7118 (diff (abs (- level (length up-head) -1))))
7119 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7120 (replace-match up-head nil t)
7121 ;; Fixup tag positioning
7122 (and org-auto-align-tags (org-set-tags nil t))
7123 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7124 (run-hooks 'org-after-promote-entry-hook)))
7126 (defun org-demote ()
7127 "Demote the current heading lower down the tree.
7128 If the region is active in `transient-mark-mode', demote all headings
7129 in the region."
7130 (org-back-to-heading t)
7131 (let* ((level (save-match-data (funcall outline-level)))
7132 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7133 (diff (abs (- level (length down-head) -1))))
7134 (replace-match down-head nil t)
7135 ;; Fixup tag positioning
7136 (and org-auto-align-tags (org-set-tags nil t))
7137 (if org-adapt-indentation (org-fixup-indentation diff))
7138 (run-hooks 'org-after-demote-entry-hook)))
7140 (defun org-cycle-level ()
7141 "Cycle the level of an empty headline through possible states.
7142 This goes first to child, then to parent, level, then up the hierarchy.
7143 After top level, it switches back to sibling level."
7144 (interactive)
7145 (let ((org-adapt-indentation nil))
7146 (when (org-point-at-end-of-empty-headline)
7147 (setq this-command 'org-cycle-level) ; Only needed for caching
7148 (let ((cur-level (org-current-level))
7149 (prev-level (org-get-previous-line-level)))
7150 (cond
7151 ;; If first headline in file, promote to top-level.
7152 ((= prev-level 0)
7153 (loop repeat (/ (- cur-level 1) (org-level-increment))
7154 do (org-do-promote)))
7155 ;; If same level as prev, demote one.
7156 ((= prev-level cur-level)
7157 (org-do-demote))
7158 ;; If parent is top-level, promote to top level if not already.
7159 ((= prev-level 1)
7160 (loop repeat (/ (- cur-level 1) (org-level-increment))
7161 do (org-do-promote)))
7162 ;; If top-level, return to prev-level.
7163 ((= cur-level 1)
7164 (loop repeat (/ (- prev-level 1) (org-level-increment))
7165 do (org-do-demote)))
7166 ;; If less than prev-level, promote one.
7167 ((< cur-level prev-level)
7168 (org-do-promote))
7169 ;; If deeper than prev-level, promote until higher than
7170 ;; prev-level.
7171 ((> cur-level prev-level)
7172 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7173 do (org-do-promote))))
7174 t))))
7176 (defun org-map-tree (fun)
7177 "Call FUN for every heading underneath the current one."
7178 (org-back-to-heading)
7179 (let ((level (funcall outline-level)))
7180 (save-excursion
7181 (funcall fun)
7182 (while (and (progn
7183 (outline-next-heading)
7184 (> (funcall outline-level) level))
7185 (not (eobp)))
7186 (funcall fun)))))
7188 (defun org-map-region (fun beg end)
7189 "Call FUN for every heading between BEG and END."
7190 (let ((org-ignore-region t))
7191 (save-excursion
7192 (setq end (copy-marker end))
7193 (goto-char beg)
7194 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
7195 (< (point) end))
7196 (funcall fun))
7197 (while (and (progn
7198 (outline-next-heading)
7199 (< (point) end))
7200 (not (eobp)))
7201 (funcall fun)))))
7203 (defun org-fixup-indentation (diff)
7204 "Change the indentation in the current entry by DIFF.
7205 However, if any line in the current entry has no indentation, or if it
7206 would end up with no indentation after the change, nothing at all is done."
7207 (save-excursion
7208 (let ((end (save-excursion (outline-next-heading)
7209 (point-marker)))
7210 (prohibit (if (> diff 0)
7211 "^\\S-"
7212 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7213 col)
7214 (unless (save-excursion (end-of-line 1)
7215 (re-search-forward prohibit end t))
7216 (while (and (< (point) end)
7217 (re-search-forward "^[ \t]+" end t))
7218 (goto-char (match-end 0))
7219 (setq col (current-column))
7220 (if (< diff 0) (replace-match ""))
7221 (org-indent-to-column (+ diff col))))
7222 (move-marker end nil))))
7224 (defun org-convert-to-odd-levels ()
7225 "Convert an org-mode file with all levels allowed to one with odd levels.
7226 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7227 level 5 etc."
7228 (interactive)
7229 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7230 (let ((outline-regexp org-outline-regexp)
7231 (outline-level 'org-outline-level)
7232 (org-odd-levels-only nil) n)
7233 (save-excursion
7234 (goto-char (point-min))
7235 (while (re-search-forward "^\\*\\*+ " nil t)
7236 (setq n (- (length (match-string 0)) 2))
7237 (while (>= (setq n (1- n)) 0)
7238 (org-demote))
7239 (end-of-line 1))))))
7241 (defun org-convert-to-oddeven-levels ()
7242 "Convert an org-mode file with only odd levels to one with odd/even levels.
7243 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7244 file contains a section with an even level, conversion would
7245 destroy the structure of the file. An error is signaled in this
7246 case."
7247 (interactive)
7248 (goto-char (point-min))
7249 ;; First check if there are no even levels
7250 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7251 (org-show-context t)
7252 (error "Not all levels are odd in this file. Conversion not possible"))
7253 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7254 (let ((outline-regexp org-outline-regexp)
7255 (outline-level 'org-outline-level)
7256 (org-odd-levels-only nil) n)
7257 (save-excursion
7258 (goto-char (point-min))
7259 (while (re-search-forward "^\\*\\*+ " nil t)
7260 (setq n (/ (1- (length (match-string 0))) 2))
7261 (while (>= (setq n (1- n)) 0)
7262 (org-promote))
7263 (end-of-line 1))))))
7265 (defun org-tr-level (n)
7266 "Make N odd if required."
7267 (if org-odd-levels-only (1+ (/ n 2)) n))
7269 ;;; Vertical tree motion, cutting and pasting of subtrees
7271 (defun org-move-subtree-up (&optional arg)
7272 "Move the current subtree up past ARG headlines of the same level."
7273 (interactive "p")
7274 (org-move-subtree-down (- (prefix-numeric-value arg))))
7276 (defun org-move-subtree-down (&optional arg)
7277 "Move the current subtree down past ARG headlines of the same level."
7278 (interactive "p")
7279 (setq arg (prefix-numeric-value arg))
7280 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7281 'org-get-last-sibling))
7282 (ins-point (make-marker))
7283 (cnt (abs arg))
7284 (col (current-column))
7285 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7286 ;; Select the tree
7287 (org-back-to-heading)
7288 (setq beg0 (point))
7289 (save-excursion
7290 (setq ne-beg (org-back-over-empty-lines))
7291 (setq beg (point)))
7292 (save-match-data
7293 (save-excursion (outline-end-of-heading)
7294 (setq folded (outline-invisible-p)))
7295 (outline-end-of-subtree))
7296 (outline-next-heading)
7297 (setq ne-end (org-back-over-empty-lines))
7298 (setq end (point))
7299 (goto-char beg0)
7300 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7301 ;; include less whitespace
7302 (save-excursion
7303 (goto-char beg)
7304 (forward-line (- ne-beg ne-end))
7305 (setq beg (point))))
7306 ;; Find insertion point, with error handling
7307 (while (> cnt 0)
7308 (or (and (funcall movfunc) (looking-at outline-regexp))
7309 (progn (goto-char beg0)
7310 (error "Cannot move past superior level or buffer limit")))
7311 (setq cnt (1- cnt)))
7312 (if (> arg 0)
7313 ;; Moving forward - still need to move over subtree
7314 (progn (org-end-of-subtree t t)
7315 (save-excursion
7316 (org-back-over-empty-lines)
7317 (or (bolp) (newline)))))
7318 (setq ne-ins (org-back-over-empty-lines))
7319 (move-marker ins-point (point))
7320 (setq txt (buffer-substring beg end))
7321 (org-save-markers-in-region beg end)
7322 (delete-region beg end)
7323 (org-remove-empty-overlays-at beg)
7324 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7325 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7326 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7327 (let ((bbb (point)))
7328 (insert-before-markers txt)
7329 (org-reinstall-markers-in-region bbb)
7330 (move-marker ins-point bbb))
7331 (or (bolp) (insert "\n"))
7332 (setq ins-end (point))
7333 (goto-char ins-point)
7334 (org-skip-whitespace)
7335 (when (and (< arg 0)
7336 (org-first-sibling-p)
7337 (> ne-ins ne-beg))
7338 ;; Move whitespace back to beginning
7339 (save-excursion
7340 (goto-char ins-end)
7341 (let ((kill-whole-line t))
7342 (kill-line (- ne-ins ne-beg)) (point)))
7343 (insert (make-string (- ne-ins ne-beg) ?\n)))
7344 (move-marker ins-point nil)
7345 (if folded
7346 (hide-subtree)
7347 (org-show-entry)
7348 (show-children)
7349 (org-cycle-hide-drawers 'children))
7350 (org-clean-visibility-after-subtree-move)
7351 ;; move back to the initial column we were at
7352 (move-to-column col)))
7354 (defvar org-subtree-clip ""
7355 "Clipboard for cut and paste of subtrees.
7356 This is actually only a copy of the kill, because we use the normal kill
7357 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7359 (defvar org-subtree-clip-folded nil
7360 "Was the last copied subtree folded?
7361 This is used to fold the tree back after pasting.")
7363 (defun org-cut-subtree (&optional n)
7364 "Cut the current subtree into the clipboard.
7365 With prefix arg N, cut this many sequential subtrees.
7366 This is a short-hand for marking the subtree and then cutting it."
7367 (interactive "p")
7368 (org-copy-subtree n 'cut))
7370 (defun org-copy-subtree (&optional n cut force-store-markers)
7371 "Cut the current subtree into the clipboard.
7372 With prefix arg N, cut this many sequential subtrees.
7373 This is a short-hand for marking the subtree and then copying it.
7374 If CUT is non-nil, actually cut the subtree.
7375 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7376 of some markers in the region, even if CUT is non-nil. This is
7377 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7378 (interactive "p")
7379 (let (beg end folded (beg0 (point)))
7380 (if (interactive-p)
7381 (org-back-to-heading nil) ; take what looks like a subtree
7382 (org-back-to-heading t)) ; take what is really there
7383 (org-back-over-empty-lines)
7384 (setq beg (point))
7385 (skip-chars-forward " \t\r\n")
7386 (save-match-data
7387 (save-excursion (outline-end-of-heading)
7388 (setq folded (outline-invisible-p)))
7389 (condition-case nil
7390 (org-forward-same-level (1- n) t)
7391 (error nil))
7392 (org-end-of-subtree t t))
7393 (org-back-over-empty-lines)
7394 (setq end (point))
7395 (goto-char beg0)
7396 (when (> end beg)
7397 (setq org-subtree-clip-folded folded)
7398 (when (or cut force-store-markers)
7399 (org-save-markers-in-region beg end))
7400 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7401 (setq org-subtree-clip (current-kill 0))
7402 (message "%s: Subtree(s) with %d characters"
7403 (if cut "Cut" "Copied")
7404 (length org-subtree-clip)))))
7406 (defun org-paste-subtree (&optional level tree for-yank)
7407 "Paste the clipboard as a subtree, with modification of headline level.
7408 The entire subtree is promoted or demoted in order to match a new headline
7409 level.
7411 If the cursor is at the beginning of a headline, the same level as
7412 that headline is used to paste the tree
7414 If not, the new level is derived from the *visible* headings
7415 before and after the insertion point, and taken to be the inferior headline
7416 level of the two. So if the previous visible heading is level 3 and the
7417 next is level 4 (or vice versa), level 4 will be used for insertion.
7418 This makes sure that the subtree remains an independent subtree and does
7419 not swallow low level entries.
7421 You can also force a different level, either by using a numeric prefix
7422 argument, or by inserting the heading marker by hand. For example, if the
7423 cursor is after \"*****\", then the tree will be shifted to level 5.
7425 If optional TREE is given, use this text instead of the kill ring.
7427 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7428 move back over whitespace before inserting, and move point to the end of
7429 the inserted text when done."
7430 (interactive "P")
7431 (setq tree (or tree (and kill-ring (current-kill 0))))
7432 (unless (org-kill-is-subtree-p tree)
7433 (error "%s"
7434 (substitute-command-keys
7435 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7436 (let* ((visp (not (outline-invisible-p)))
7437 (txt tree)
7438 (^re (concat "^\\(" outline-regexp "\\)"))
7439 (re (concat "\\(" outline-regexp "\\)"))
7440 (^re_ (concat "\\(\\*+\\)[ \t]*"))
7442 (old-level (if (string-match ^re txt)
7443 (- (match-end 0) (match-beginning 0) 1)
7444 -1))
7445 (force-level (cond (level (prefix-numeric-value level))
7446 ((and (looking-at "[ \t]*$")
7447 (string-match
7448 ^re_ (buffer-substring
7449 (point-at-bol) (point))))
7450 (- (match-end 1) (match-beginning 1)))
7451 ((and (bolp)
7452 (looking-at org-outline-regexp))
7453 (- (match-end 0) (point) 1))
7454 (t nil)))
7455 (previous-level (save-excursion
7456 (condition-case nil
7457 (progn
7458 (outline-previous-visible-heading 1)
7459 (if (looking-at re)
7460 (- (match-end 0) (match-beginning 0) 1)
7462 (error 1))))
7463 (next-level (save-excursion
7464 (condition-case nil
7465 (progn
7466 (or (looking-at outline-regexp)
7467 (outline-next-visible-heading 1))
7468 (if (looking-at re)
7469 (- (match-end 0) (match-beginning 0) 1)
7471 (error 1))))
7472 (new-level (or force-level (max previous-level next-level)))
7473 (shift (if (or (= old-level -1)
7474 (= new-level -1)
7475 (= old-level new-level))
7477 (- new-level old-level)))
7478 (delta (if (> shift 0) -1 1))
7479 (func (if (> shift 0) 'org-demote 'org-promote))
7480 (org-odd-levels-only nil)
7481 beg end newend)
7482 ;; Remove the forced level indicator
7483 (if force-level
7484 (delete-region (point-at-bol) (point)))
7485 ;; Paste
7486 (beginning-of-line 1)
7487 (unless for-yank (org-back-over-empty-lines))
7488 (setq beg (point))
7489 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7490 (insert-before-markers txt)
7491 (unless (string-match "\n\\'" txt) (insert "\n"))
7492 (setq newend (point))
7493 (org-reinstall-markers-in-region beg)
7494 (setq end (point))
7495 (goto-char beg)
7496 (skip-chars-forward " \t\n\r")
7497 (setq beg (point))
7498 (if (and (outline-invisible-p) visp)
7499 (save-excursion (outline-show-heading)))
7500 ;; Shift if necessary
7501 (unless (= shift 0)
7502 (save-restriction
7503 (narrow-to-region beg end)
7504 (while (not (= shift 0))
7505 (org-map-region func (point-min) (point-max))
7506 (setq shift (+ delta shift)))
7507 (goto-char (point-min))
7508 (setq newend (point-max))))
7509 (when (or (interactive-p) for-yank)
7510 (message "Clipboard pasted as level %d subtree" new-level))
7511 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7512 kill-ring
7513 (eq org-subtree-clip (current-kill 0))
7514 org-subtree-clip-folded)
7515 ;; The tree was folded before it was killed/copied
7516 (hide-subtree))
7517 (and for-yank (goto-char newend))))
7519 (defun org-kill-is-subtree-p (&optional txt)
7520 "Check if the current kill is an outline subtree, or a set of trees.
7521 Returns nil if kill does not start with a headline, or if the first
7522 headline level is not the largest headline level in the tree.
7523 So this will actually accept several entries of equal levels as well,
7524 which is OK for `org-paste-subtree'.
7525 If optional TXT is given, check this string instead of the current kill."
7526 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7527 (start-level (and kill
7528 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
7529 org-outline-regexp "\\)")
7530 kill)
7531 (- (match-end 2) (match-beginning 2) 1)))
7532 (re (concat "^" org-outline-regexp))
7533 (start (1+ (or (match-beginning 2) -1))))
7534 (if (not start-level)
7535 (progn
7536 nil) ;; does not even start with a heading
7537 (catch 'exit
7538 (while (setq start (string-match re kill (1+ start)))
7539 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7540 (throw 'exit nil)))
7541 t))))
7543 (defvar org-markers-to-move nil
7544 "Markers that should be moved with a cut-and-paste operation.
7545 Those markers are stored together with their positions relative to
7546 the start of the region.")
7548 (defun org-save-markers-in-region (beg end)
7549 "Check markers in region.
7550 If these markers are between BEG and END, record their position relative
7551 to BEG, so that after moving the block of text, we can put the markers back
7552 into place.
7553 This function gets called just before an entry or tree gets cut from the
7554 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7555 called immediately, to move the markers with the entries."
7556 (setq org-markers-to-move nil)
7557 (when (featurep 'org-clock)
7558 (org-clock-save-markers-for-cut-and-paste beg end))
7559 (when (featurep 'org-agenda)
7560 (org-agenda-save-markers-for-cut-and-paste beg end)))
7562 (defun org-check-and-save-marker (marker beg end)
7563 "Check if MARKER is between BEG and END.
7564 If yes, remember the marker and the distance to BEG."
7565 (when (and (marker-buffer marker)
7566 (equal (marker-buffer marker) (current-buffer)))
7567 (if (and (>= marker beg) (< marker end))
7568 (push (cons marker (- marker beg)) org-markers-to-move))))
7570 (defun org-reinstall-markers-in-region (beg)
7571 "Move all remembered markers to their position relative to BEG."
7572 (mapc (lambda (x)
7573 (move-marker (car x) (+ beg (cdr x))))
7574 org-markers-to-move)
7575 (setq org-markers-to-move nil))
7577 (defun org-narrow-to-subtree ()
7578 "Narrow buffer to the current subtree."
7579 (interactive)
7580 (save-excursion
7581 (save-match-data
7582 (org-with-limited-levels
7583 (narrow-to-region
7584 (progn (org-back-to-heading t) (point))
7585 (progn (org-end-of-subtree t t)
7586 (if (and (org-on-heading-p) (not (eobp))) (backward-char 1))
7587 (point)))))))
7589 (defun org-narrow-to-block ()
7590 "Narrow buffer to the current block."
7591 (interactive)
7592 (let ((bstart "^[ \t]*#\\+begin")
7593 (bend "[ \t]*#\\+end")
7594 (case-fold-search t) ;; allow #+BEGIN
7595 b_start b_end)
7596 (if (org-in-regexps-block-p bstart bend)
7597 (progn
7598 (save-excursion (re-search-backward bstart nil t)
7599 (setq b_start (match-beginning 0)))
7600 (save-excursion (re-search-forward bend nil t)
7601 (setq b_end (match-end 0)))
7602 (narrow-to-region b_start b_end))
7603 (error "Not in a block"))))
7605 (eval-when-compile
7606 (defvar org-property-drawer-re))
7608 (defvar org-property-start-re) ;; defined below
7609 (defun org-clone-subtree-with-time-shift (n &optional shift)
7610 "Clone the task (subtree) at point N times.
7611 The clones will be inserted as siblings.
7613 In interactive use, the user will be prompted for the number of
7614 clones to be produced, and for a time SHIFT, which may be a
7615 repeater as used in time stamps, for example `+3d'.
7617 When a valid repeater is given and the entry contains any time
7618 stamps, the clones will become a sequence in time, with time
7619 stamps in the subtree shifted for each clone produced. If SHIFT
7620 is nil or the empty string, time stamps will be left alone. The
7621 ID property of the original subtree is removed.
7623 If the original subtree did contain time stamps with a repeater,
7624 the following will happen:
7625 - the repeater will be removed in each clone
7626 - an additional clone will be produced, with the current, unshifted
7627 date(s) in the entry.
7628 - the original entry will be placed *after* all the clones, with
7629 repeater intact.
7630 - the start days in the repeater in the original entry will be shifted
7631 to past the last clone.
7632 I this way you can spell out a number of instances of a repeating task,
7633 and still retain the repeater to cover future instances of the task."
7634 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7635 (let (beg end template task idprop
7636 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7637 (if (not (and (integerp n) (> n 0)))
7638 (error "Invalid number of replications %s" n))
7639 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7640 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7641 shift)))
7642 (error "Invalid shift specification %s" shift))
7643 (when doshift
7644 (setq shift-n (string-to-number (match-string 1 shift))
7645 shift-what (cdr (assoc (match-string 2 shift)
7646 '(("d" . day) ("w" . week)
7647 ("m" . month) ("y" . year))))))
7648 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7649 (setq nmin 1 nmax n)
7650 (org-back-to-heading t)
7651 (setq beg (point))
7652 (setq idprop (org-entry-get nil "ID"))
7653 (org-end-of-subtree t t)
7654 (or (bolp) (insert "\n"))
7655 (setq end (point))
7656 (setq template (buffer-substring beg end))
7657 (when (and doshift
7658 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7659 (delete-region beg end)
7660 (setq end beg)
7661 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7662 (goto-char end)
7663 (loop for n from nmin to nmax do
7664 ;; prepare clone
7665 (with-temp-buffer
7666 (insert template)
7667 (org-mode)
7668 (goto-char (point-min))
7669 (and idprop (if org-clone-delete-id
7670 (org-entry-delete nil "ID")
7671 (org-id-get-create t)))
7672 (while (re-search-forward org-property-start-re nil t)
7673 (org-remove-empty-drawer-at "PROPERTIES" (point)))
7674 (goto-char (point-min))
7675 (when doshift
7676 (while (re-search-forward org-ts-regexp-both nil t)
7677 (org-timestamp-change (* n shift-n) shift-what))
7678 (unless (= n n-no-remove)
7679 (goto-char (point-min))
7680 (while (re-search-forward org-ts-regexp nil t)
7681 (save-excursion
7682 (goto-char (match-beginning 0))
7683 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7684 (delete-region (match-beginning 1) (match-end 1)))))))
7685 (setq task (buffer-string)))
7686 (insert task))
7687 (goto-char beg)))
7689 ;;; Outline Sorting
7691 (defun org-sort (with-case)
7692 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
7693 Optional argument WITH-CASE means sort case-sensitively.
7694 With a double prefix argument, also remove duplicate entries."
7695 (interactive "P")
7696 (cond
7697 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
7698 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
7700 (org-call-with-arg 'org-sort-entries with-case))))
7702 (defun org-sort-remove-invisible (s)
7703 (remove-text-properties 0 (length s) org-rm-props s)
7704 (while (string-match org-bracket-link-regexp s)
7705 (setq s (replace-match (if (match-end 2)
7706 (match-string 3 s)
7707 (match-string 1 s)) t t s)))
7710 (defvar org-priority-regexp) ; defined later in the file
7712 (defvar org-after-sorting-entries-or-items-hook nil
7713 "Hook that is run after a bunch of entries or items have been sorted.
7714 When children are sorted, the cursor is in the parent line when this
7715 hook gets called. When a region or a plain list is sorted, the cursor
7716 will be in the first entry of the sorted region/list.")
7718 (defun org-sort-entries
7719 (&optional with-case sorting-type getkey-func compare-func property)
7720 "Sort entries on a certain level of an outline tree.
7721 If there is an active region, the entries in the region are sorted.
7722 Else, if the cursor is before the first entry, sort the top-level items.
7723 Else, the children of the entry at point are sorted.
7725 Sorting can be alphabetically, numerically, by date/time as given by
7726 a time stamp, by a property or by priority.
7728 The command prompts for the sorting type unless it has been given to the
7729 function through the SORTING-TYPE argument, which needs to be a character,
7730 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7731 precise meaning of each character:
7733 n Numerically, by converting the beginning of the entry/item to a number.
7734 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7735 t By date/time, either the first active time stamp in the entry, or, if
7736 none exist, by the first inactive one.
7737 s By the scheduled date/time.
7738 d By deadline date/time.
7739 c By creation time, which is assumed to be the first inactive time stamp
7740 at the beginning of a line.
7741 p By priority according to the cookie.
7742 r By the value of a property.
7744 Capital letters will reverse the sort order.
7746 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7747 called with point at the beginning of the record. It must return either
7748 a string or a number that should serve as the sorting key for that record.
7750 Comparing entries ignores case by default. However, with an optional argument
7751 WITH-CASE, the sorting considers case as well."
7752 (interactive "P")
7753 (let ((case-func (if with-case 'identity 'downcase))
7754 start beg end stars re re2
7755 txt what tmp)
7756 ;; Find beginning and end of region to sort
7757 (cond
7758 ((org-region-active-p)
7759 ;; we will sort the region
7760 (setq end (region-end)
7761 what "region")
7762 (goto-char (region-beginning))
7763 (if (not (org-on-heading-p)) (outline-next-heading))
7764 (setq start (point)))
7765 ((or (org-on-heading-p)
7766 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7767 ;; we will sort the children of the current headline
7768 (org-back-to-heading)
7769 (setq start (point)
7770 end (progn (org-end-of-subtree t t)
7771 (or (bolp) (insert "\n"))
7772 (org-back-over-empty-lines)
7773 (point))
7774 what "children")
7775 (goto-char start)
7776 (show-subtree)
7777 (outline-next-heading))
7779 ;; we will sort the top-level entries in this file
7780 (goto-char (point-min))
7781 (or (org-on-heading-p) (outline-next-heading))
7782 (setq start (point))
7783 (goto-char (point-max))
7784 (beginning-of-line 1)
7785 (when (looking-at ".*?\\S-")
7786 ;; File ends in a non-white line
7787 (end-of-line 1)
7788 (insert "\n"))
7789 (setq end (point-max))
7790 (setq what "top-level")
7791 (goto-char start)
7792 (show-all)))
7794 (setq beg (point))
7795 (if (>= beg end) (error "Nothing to sort"))
7797 (looking-at "\\(\\*+\\)")
7798 (setq stars (match-string 1)
7799 re (concat "^" (regexp-quote stars) " +")
7800 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
7801 txt (buffer-substring beg end))
7802 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7803 (if (and (not (equal stars "*")) (string-match re2 txt))
7804 (error "Region to sort contains a level above the first entry"))
7806 (unless sorting-type
7807 (message
7808 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7809 [t]ime [s]cheduled [d]eadline [c]reated
7810 A/N/T/S/D/C/P/O/F means reversed:"
7811 what)
7812 (setq sorting-type (read-char-exclusive))
7814 (and (= (downcase sorting-type) ?f)
7815 (setq getkey-func
7816 (org-icompleting-read "Sort using function: "
7817 obarray 'fboundp t nil nil))
7818 (setq getkey-func (intern getkey-func)))
7820 (and (= (downcase sorting-type) ?r)
7821 (setq property
7822 (org-icompleting-read "Property: "
7823 (mapcar 'list (org-buffer-property-keys t))
7824 nil t))))
7826 (message "Sorting entries...")
7828 (save-restriction
7829 (narrow-to-region start end)
7830 (let ((dcst (downcase sorting-type))
7831 (case-fold-search nil)
7832 (now (current-time)))
7833 (sort-subr
7834 (/= dcst sorting-type)
7835 ;; This function moves to the beginning character of the "record" to
7836 ;; be sorted.
7837 (lambda nil
7838 (if (re-search-forward re nil t)
7839 (goto-char (match-beginning 0))
7840 (goto-char (point-max))))
7841 ;; This function moves to the last character of the "record" being
7842 ;; sorted.
7843 (lambda nil
7844 (save-match-data
7845 (condition-case nil
7846 (outline-forward-same-level 1)
7847 (error
7848 (goto-char (point-max))))))
7849 ;; This function returns the value that gets sorted against.
7850 (lambda nil
7851 (cond
7852 ((= dcst ?n)
7853 (if (looking-at org-complex-heading-regexp)
7854 (string-to-number (match-string 4))
7855 nil))
7856 ((= dcst ?a)
7857 (if (looking-at org-complex-heading-regexp)
7858 (funcall case-func (match-string 4))
7859 nil))
7860 ((= dcst ?t)
7861 (let ((end (save-excursion (outline-next-heading) (point))))
7862 (if (or (re-search-forward org-ts-regexp end t)
7863 (re-search-forward org-ts-regexp-both end t))
7864 (org-time-string-to-seconds (match-string 0))
7865 (org-float-time now))))
7866 ((= dcst ?c)
7867 (let ((end (save-excursion (outline-next-heading) (point))))
7868 (if (re-search-forward
7869 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7870 end t)
7871 (org-time-string-to-seconds (match-string 0))
7872 (org-float-time now))))
7873 ((= dcst ?s)
7874 (let ((end (save-excursion (outline-next-heading) (point))))
7875 (if (re-search-forward org-scheduled-time-regexp end t)
7876 (org-time-string-to-seconds (match-string 1))
7877 (org-float-time now))))
7878 ((= dcst ?d)
7879 (let ((end (save-excursion (outline-next-heading) (point))))
7880 (if (re-search-forward org-deadline-time-regexp end t)
7881 (org-time-string-to-seconds (match-string 1))
7882 (org-float-time now))))
7883 ((= dcst ?p)
7884 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7885 (string-to-char (match-string 2))
7886 org-default-priority))
7887 ((= dcst ?r)
7888 (or (org-entry-get nil property) ""))
7889 ((= dcst ?o)
7890 (if (looking-at org-complex-heading-regexp)
7891 (- 9999 (length (member (match-string 2)
7892 org-todo-keywords-1)))))
7893 ((= dcst ?f)
7894 (if getkey-func
7895 (progn
7896 (setq tmp (funcall getkey-func))
7897 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7898 tmp)
7899 (error "Invalid key function `%s'" getkey-func)))
7900 (t (error "Invalid sorting type `%c'" sorting-type))))
7902 (cond
7903 ((= dcst ?a) 'string<)
7904 ((= dcst ?f) compare-func)
7905 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7906 (t nil)))))
7907 (run-hooks 'org-after-sorting-entries-or-items-hook)
7908 (message "Sorting entries...done")))
7910 (defun org-do-sort (table what &optional with-case sorting-type)
7911 "Sort TABLE of WHAT according to SORTING-TYPE.
7912 The user will be prompted for the SORTING-TYPE if the call to this
7913 function does not specify it. WHAT is only for the prompt, to indicate
7914 what is being sorted. The sorting key will be extracted from
7915 the car of the elements of the table.
7916 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7917 (unless sorting-type
7918 (message
7919 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7920 what)
7921 (setq sorting-type (read-char-exclusive)))
7922 (let ((dcst (downcase sorting-type))
7923 extractfun comparefun)
7924 ;; Define the appropriate functions
7925 (cond
7926 ((= dcst ?n)
7927 (setq extractfun 'string-to-number
7928 comparefun (if (= dcst sorting-type) '< '>)))
7929 ((= dcst ?a)
7930 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7931 (lambda(x) (downcase (org-sort-remove-invisible x))))
7932 comparefun (if (= dcst sorting-type)
7933 'string<
7934 (lambda (a b) (and (not (string< a b))
7935 (not (string= a b)))))))
7936 ((= dcst ?t)
7937 (setq extractfun
7938 (lambda (x)
7939 (if (or (string-match org-ts-regexp x)
7940 (string-match org-ts-regexp-both x))
7941 (org-float-time
7942 (org-time-string-to-time (match-string 0 x)))
7944 comparefun (if (= dcst sorting-type) '< '>)))
7945 (t (error "Invalid sorting type `%c'" sorting-type)))
7947 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7948 table)
7949 (lambda (a b) (funcall comparefun (car a) (car b))))))
7952 ;;; The orgstruct minor mode
7954 ;; Define a minor mode which can be used in other modes in order to
7955 ;; integrate the org-mode structure editing commands.
7957 ;; This is really a hack, because the org-mode structure commands use
7958 ;; keys which normally belong to the major mode. Here is how it
7959 ;; works: The minor mode defines all the keys necessary to operate the
7960 ;; structure commands, but wraps the commands into a function which
7961 ;; tests if the cursor is currently at a headline or a plain list
7962 ;; item. If that is the case, the structure command is used,
7963 ;; temporarily setting many Org-mode variables like regular
7964 ;; expressions for filling etc. However, when any of those keys is
7965 ;; used at a different location, function uses `key-binding' to look
7966 ;; up if the key has an associated command in another currently active
7967 ;; keymap (minor modes, major mode, global), and executes that
7968 ;; command. There might be problems if any of the keys is otherwise
7969 ;; used as a prefix key.
7971 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7972 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7973 ;; addresses this by checking explicitly for both bindings.
7975 (defvar orgstruct-mode-map (make-sparse-keymap)
7976 "Keymap for the minor `orgstruct-mode'.")
7978 (defvar org-local-vars nil
7979 "List of local variables, for use by `orgstruct-mode'.")
7981 ;;;###autoload
7982 (define-minor-mode orgstruct-mode
7983 "Toggle the minor mode `orgstruct-mode'.
7984 This mode is for using Org-mode structure commands in other
7985 modes. The following keys behave as if Org-mode were active, if
7986 the cursor is on a headline, or on a plain list item (both as
7987 defined by Org-mode).
7989 M-up Move entry/item up
7990 M-down Move entry/item down
7991 M-left Promote
7992 M-right Demote
7993 M-S-up Move entry/item up
7994 M-S-down Move entry/item down
7995 M-S-left Promote subtree
7996 M-S-right Demote subtree
7997 M-q Fill paragraph and items like in Org-mode
7998 C-c ^ Sort entries
7999 C-c - Cycle list bullet
8000 TAB Cycle item visibility
8001 M-RET Insert new heading/item
8002 S-M-RET Insert new TODO heading / Checkbox item
8003 C-c C-c Set tags / toggle checkbox"
8004 nil " OrgStruct" nil
8005 (org-load-modules-maybe)
8006 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8008 ;;;###autoload
8009 (defun turn-on-orgstruct ()
8010 "Unconditionally turn on `orgstruct-mode'."
8011 (orgstruct-mode 1))
8013 (defun orgstruct++-mode (&optional arg)
8014 "Toggle `orgstruct-mode', the enhanced version of it.
8015 In addition to setting orgstruct-mode, this also exports all indentation
8016 and autofilling variables from org-mode into the buffer. It will also
8017 recognize item context in multiline items.
8018 Note that turning off orgstruct-mode will *not* remove the
8019 indentation/paragraph settings. This can only be done by refreshing the
8020 major mode, for example with \\[normal-mode]."
8021 (interactive "P")
8022 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8023 (if (< arg 1)
8024 (orgstruct-mode -1)
8025 (orgstruct-mode 1)
8026 (let (var val)
8027 (mapc
8028 (lambda (x)
8029 (when (string-match
8030 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8031 (symbol-name (car x)))
8032 (setq var (car x) val (nth 1 x))
8033 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8034 org-local-vars)
8035 (org-set-local 'orgstruct-is-++ t))))
8037 (defvar orgstruct-is-++ nil
8038 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8039 (make-variable-buffer-local 'orgstruct-is-++)
8041 ;;;###autoload
8042 (defun turn-on-orgstruct++ ()
8043 "Unconditionally turn on `orgstruct++-mode'."
8044 (orgstruct++-mode 1))
8046 (defun orgstruct-error ()
8047 "Error when there is no default binding for a structure key."
8048 (interactive)
8049 (error "This key has no function outside structure elements"))
8051 (defun orgstruct-setup ()
8052 "Setup orgstruct keymaps."
8053 (let ((nfunc 0)
8054 (bindings
8055 (list
8056 '([(meta up)] org-metaup)
8057 '([(meta down)] org-metadown)
8058 '([(meta left)] org-metaleft)
8059 '([(meta right)] org-metaright)
8060 '([(meta shift up)] org-shiftmetaup)
8061 '([(meta shift down)] org-shiftmetadown)
8062 '([(meta shift left)] org-shiftmetaleft)
8063 '([(meta shift right)] org-shiftmetaright)
8064 '([?\e (up)] org-metaup)
8065 '([?\e (down)] org-metadown)
8066 '([?\e (left)] org-metaleft)
8067 '([?\e (right)] org-metaright)
8068 '([?\e (shift up)] org-shiftmetaup)
8069 '([?\e (shift down)] org-shiftmetadown)
8070 '([?\e (shift left)] org-shiftmetaleft)
8071 '([?\e (shift right)] org-shiftmetaright)
8072 '([(shift up)] org-shiftup)
8073 '([(shift down)] org-shiftdown)
8074 '([(shift left)] org-shiftleft)
8075 '([(shift right)] org-shiftright)
8076 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8077 '("\M-q" fill-paragraph)
8078 '("\C-c^" org-sort)
8079 '("\C-c-" org-cycle-list-bullet)))
8080 elt key fun cmd)
8081 (while (setq elt (pop bindings))
8082 (setq nfunc (1+ nfunc))
8083 (setq key (org-key (car elt))
8084 fun (nth 1 elt)
8085 cmd (orgstruct-make-binding fun nfunc key))
8086 (org-defkey orgstruct-mode-map key cmd))
8088 ;; Special treatment needed for TAB and RET
8089 (org-defkey orgstruct-mode-map [(tab)]
8090 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8091 (org-defkey orgstruct-mode-map "\C-i"
8092 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8094 (org-defkey orgstruct-mode-map "\M-\C-m"
8095 (orgstruct-make-binding 'org-insert-heading 105
8096 "\M-\C-m" [(meta return)]))
8097 (org-defkey orgstruct-mode-map [(meta return)]
8098 (orgstruct-make-binding 'org-insert-heading 106
8099 [(meta return)] "\M-\C-m"))
8101 (org-defkey orgstruct-mode-map [(shift meta return)]
8102 (orgstruct-make-binding 'org-insert-todo-heading 107
8103 [(meta return)] "\M-\C-m"))
8105 (org-defkey orgstruct-mode-map "\e\C-m"
8106 (orgstruct-make-binding 'org-insert-heading 108
8107 "\e\C-m" [?\e (return)]))
8108 (org-defkey orgstruct-mode-map [?\e (return)]
8109 (orgstruct-make-binding 'org-insert-heading 109
8110 [?\e (return)] "\e\C-m"))
8111 (org-defkey orgstruct-mode-map [?\e (shift return)]
8112 (orgstruct-make-binding 'org-insert-todo-heading 110
8113 [?\e (return)] "\e\C-m"))
8115 (unless org-local-vars
8116 (setq org-local-vars (org-get-local-variables)))
8120 (defun orgstruct-make-binding (fun n &rest keys)
8121 "Create a function for binding in the structure minor mode.
8122 FUN is the command to call inside a table. N is used to create a unique
8123 command name. KEYS are keys that should be checked in for a command
8124 to execute outside of tables."
8125 (eval
8126 (list 'defun
8127 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8128 '(arg)
8129 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8130 "Outside of structure, run the binding of `"
8131 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8132 "'.")
8133 '(interactive "p")
8134 (list 'if
8135 `(org-context-p 'headline 'item
8136 (and orgstruct-is-++
8137 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8138 'item-body))
8139 (list 'org-run-like-in-org-mode (list 'quote fun))
8140 (list 'let '(orgstruct-mode)
8141 (list 'call-interactively
8142 (append '(or)
8143 (mapcar (lambda (k)
8144 (list 'key-binding k))
8145 keys)
8146 '('orgstruct-error))))))))
8148 (defun org-context-p (&rest contexts)
8149 "Check if local context is any of CONTEXTS.
8150 Possible values in the list of contexts are `table', `headline', and `item'."
8151 (let ((pos (point)))
8152 (goto-char (point-at-bol))
8153 (prog1 (or (and (memq 'table contexts)
8154 (looking-at "[ \t]*|"))
8155 (and (memq 'headline contexts)
8156 ;;????????? (looking-at "\\*+"))
8157 (looking-at outline-regexp))
8158 (and (memq 'item contexts)
8159 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8160 (and (memq 'item-body contexts)
8161 (org-in-item-p)))
8162 (goto-char pos))))
8164 (defun org-get-local-variables ()
8165 "Return a list of all local variables in an org-mode buffer."
8166 (let (varlist)
8167 (with-current-buffer (get-buffer-create "*Org tmp*")
8168 (erase-buffer)
8169 (org-mode)
8170 (setq varlist (buffer-local-variables)))
8171 (kill-buffer "*Org tmp*")
8172 (delq nil
8173 (mapcar
8174 (lambda (x)
8175 (setq x
8176 (if (symbolp x)
8177 (list x)
8178 (list (car x) (list 'quote (cdr x)))))
8179 (if (string-match
8180 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8181 (symbol-name (car x)))
8182 x nil))
8183 varlist))))
8185 (defun org-clone-local-variables (from-buffer &optional regexp)
8186 "Clone local variables from FROM-BUFFER.
8187 Optional argument REGEXP selects variables to clone."
8188 (mapc
8189 (lambda (pair)
8190 (and (symbolp (car pair))
8191 (or (null regexp)
8192 (string-match regexp (symbol-name (car pair))))
8193 (set (make-local-variable (car pair))
8194 (cdr pair))))
8195 (buffer-local-variables from-buffer)))
8197 ;;;###autoload
8198 (defun org-run-like-in-org-mode (cmd)
8199 "Run a command, pretending that the current buffer is in Org-mode.
8200 This will temporarily bind local variables that are typically bound in
8201 Org-mode to the values they have in Org-mode, and then interactively
8202 call CMD."
8203 (org-load-modules-maybe)
8204 (unless org-local-vars
8205 (setq org-local-vars (org-get-local-variables)))
8206 (eval (list 'let org-local-vars
8207 (list 'call-interactively (list 'quote cmd)))))
8209 ;;;; Archiving
8211 (defun org-get-category (&optional pos force-refresh)
8212 "Get the category applying to position POS."
8213 (if force-refresh (org-refresh-category-properties))
8214 (let ((pos (or pos (point))))
8215 (or (get-text-property pos 'org-category)
8216 (progn (org-refresh-category-properties)
8217 (get-text-property pos 'org-category)))))
8219 (defun org-refresh-category-properties ()
8220 "Refresh category text properties in the buffer."
8221 (let ((def-cat (cond
8222 ((null org-category)
8223 (if buffer-file-name
8224 (file-name-sans-extension
8225 (file-name-nondirectory buffer-file-name))
8226 "???"))
8227 ((symbolp org-category) (symbol-name org-category))
8228 (t org-category)))
8229 beg end cat pos optionp)
8230 (org-unmodified
8231 (save-excursion
8232 (save-restriction
8233 (widen)
8234 (goto-char (point-min))
8235 (put-text-property (point) (point-max) 'org-category def-cat)
8236 (while (re-search-forward
8237 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8238 (setq pos (match-end 0)
8239 optionp (equal (char-after (match-beginning 0)) ?#)
8240 cat (org-trim (match-string 2)))
8241 (if optionp
8242 (setq beg (point-at-bol) end (point-max))
8243 (org-back-to-heading t)
8244 (setq beg (point) end (org-end-of-subtree t t)))
8245 (put-text-property beg end 'org-category cat)
8246 (goto-char pos)))))))
8249 ;;;; Link Stuff
8251 ;;; Link abbreviations
8253 (defun org-link-expand-abbrev (link)
8254 "Apply replacements as defined in `org-link-abbrev-alist."
8255 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8256 (let* ((key (match-string 1 link))
8257 (as (or (assoc key org-link-abbrev-alist-local)
8258 (assoc key org-link-abbrev-alist)))
8259 (tag (and (match-end 2) (match-string 3 link)))
8260 rpl)
8261 (if (not as)
8262 link
8263 (setq rpl (cdr as))
8264 (cond
8265 ((symbolp rpl) (funcall rpl tag))
8266 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8267 ((string-match "%h" rpl)
8268 (replace-match (url-hexify-string (or tag "")) t t rpl))
8269 (t (concat rpl tag)))))
8270 link))
8272 ;;; Storing and inserting links
8274 (defvar org-insert-link-history nil
8275 "Minibuffer history for links inserted with `org-insert-link'.")
8277 (defvar org-stored-links nil
8278 "Contains the links stored with `org-store-link'.")
8280 (defvar org-store-link-plist nil
8281 "Plist with info about the most recently link created with `org-store-link'.")
8283 (defvar org-link-protocols nil
8284 "Link protocols added to Org-mode using `org-add-link-type'.")
8286 (defvar org-store-link-functions nil
8287 "List of functions that are called to create and store a link.
8288 Each function will be called in turn until one returns a non-nil
8289 value. Each function should check if it is responsible for creating
8290 this link (for example by looking at the major mode).
8291 If not, it must exit and return nil.
8292 If yes, it should return a non-nil value after a calling
8293 `org-store-link-props' with a list of properties and values.
8294 Special properties are:
8296 :type The link prefix, like \"http\". This must be given.
8297 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8298 This is obligatory as well.
8299 :description Optional default description for the second pair
8300 of brackets in an Org-mode link. The user can still change
8301 this when inserting this link into an Org-mode buffer.
8303 In addition to these, any additional properties can be specified
8304 and then used in remember templates.")
8306 (defun org-add-link-type (type &optional follow export)
8307 "Add TYPE to the list of `org-link-types'.
8308 Re-compute all regular expressions depending on `org-link-types'
8310 FOLLOW and EXPORT are two functions.
8312 FOLLOW should take the link path as the single argument and do whatever
8313 is necessary to follow the link, for example find a file or display
8314 a mail message.
8316 EXPORT should format the link path for export to one of the export formats.
8317 It should be a function accepting three arguments:
8319 path the path of the link, the text after the prefix (like \"http:\")
8320 desc the description of the link, if any, or a description added by
8321 org-export-normalize-links if there is none
8322 format the export format, a symbol like `html' or `latex' or `ascii'..
8324 The function may use the FORMAT information to return different values
8325 depending on the format. The return value will be put literally into
8326 the exported file. If the return value is nil, this means Org should
8327 do what it normally does with links which do not have EXPORT defined.
8329 Org-mode has a built-in default for exporting links. If you are happy with
8330 this default, there is no need to define an export function for the link
8331 type. For a simple example of an export function, see `org-bbdb.el'."
8332 (add-to-list 'org-link-types type t)
8333 (org-make-link-regexps)
8334 (if (assoc type org-link-protocols)
8335 (setcdr (assoc type org-link-protocols) (list follow export))
8336 (push (list type follow export) org-link-protocols)))
8338 (defvar org-agenda-buffer-name)
8340 ;;;###autoload
8341 (defun org-store-link (arg)
8342 "\\<org-mode-map>Store an org-link to the current location.
8343 This link is added to `org-stored-links' and can later be inserted
8344 into an org-buffer with \\[org-insert-link].
8346 For some link types, a prefix arg is interpreted:
8347 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8348 For file links, arg negates `org-context-in-file-links'."
8349 (interactive "P")
8350 (org-load-modules-maybe)
8351 (setq org-store-link-plist nil) ; reset
8352 (org-with-limited-levels
8353 (let (link cpltxt desc description search txt custom-id agenda-link)
8354 (cond
8356 ((run-hook-with-args-until-success 'org-store-link-functions)
8357 (setq link (plist-get org-store-link-plist :link)
8358 desc (or (plist-get org-store-link-plist :description) link)))
8360 ((equal (buffer-name) "*Org Edit Src Example*")
8361 (let (label gc)
8362 (while (or (not label)
8363 (save-excursion
8364 (save-restriction
8365 (widen)
8366 (goto-char (point-min))
8367 (re-search-forward
8368 (regexp-quote (format org-coderef-label-format label))
8369 nil t))))
8370 (when label (message "Label exists already") (sit-for 2))
8371 (setq label (read-string "Code line label: " label)))
8372 (end-of-line 1)
8373 (setq link (format org-coderef-label-format label))
8374 (setq gc (- 79 (length link)))
8375 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8376 (insert link)
8377 (setq link (concat "(" label ")") desc nil)))
8379 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8380 ;; We are in the agenda, link to referenced location
8381 (let ((m (or (get-text-property (point) 'org-hd-marker)
8382 (get-text-property (point) 'org-marker))))
8383 (when m
8384 (org-with-point-at m
8385 (setq agenda-link
8386 (if (interactive-p)
8387 (call-interactively 'org-store-link)
8388 (org-store-link nil)))))))
8390 ((eq major-mode 'calendar-mode)
8391 (let ((cd (calendar-cursor-to-date)))
8392 (setq link
8393 (format-time-string
8394 (car org-time-stamp-formats)
8395 (apply 'encode-time
8396 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8397 nil nil nil))))
8398 (org-store-link-props :type "calendar" :date cd)))
8400 ((eq major-mode 'w3-mode)
8401 (setq cpltxt (if (and (buffer-name)
8402 (not (string-match "Untitled" (buffer-name))))
8403 (buffer-name)
8404 (url-view-url t))
8405 link (org-make-link (url-view-url t)))
8406 (org-store-link-props :type "w3" :url (url-view-url t)))
8408 ((eq major-mode 'w3m-mode)
8409 (setq cpltxt (or w3m-current-title w3m-current-url)
8410 link (org-make-link w3m-current-url))
8411 (org-store-link-props :type "w3m" :url (url-view-url t)))
8413 ((setq search (run-hook-with-args-until-success
8414 'org-create-file-search-functions))
8415 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8416 "::" search))
8417 (setq cpltxt (or description link)))
8419 ((eq major-mode 'image-mode)
8420 (setq cpltxt (concat "file:"
8421 (abbreviate-file-name buffer-file-name))
8422 link (org-make-link cpltxt))
8423 (org-store-link-props :type "image" :file buffer-file-name))
8425 ((eq major-mode 'dired-mode)
8426 ;; link to the file in the current line
8427 (let ((file (dired-get-filename nil t)))
8428 (setq file (if file
8429 (abbreviate-file-name
8430 (expand-file-name (dired-get-filename nil t)))
8431 ;; otherwise, no file so use current directory.
8432 default-directory))
8433 (setq cpltxt (concat "file:" file)
8434 link (org-make-link cpltxt))))
8436 ((and (buffer-file-name (buffer-base-buffer)) (org-mode-p))
8437 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8438 (cond
8439 ((org-in-regexp "<<\\(.*?\\)>>")
8440 (setq cpltxt
8441 (concat "file:"
8442 (abbreviate-file-name
8443 (buffer-file-name (buffer-base-buffer)))
8444 "::" (match-string 1))
8445 link (org-make-link cpltxt)))
8446 ((and (featurep 'org-id)
8447 (or (eq org-link-to-org-use-id t)
8448 (and (eq org-link-to-org-use-id 'create-if-interactive)
8449 (interactive-p))
8450 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
8451 (interactive-p)
8452 (not custom-id))
8453 (and org-link-to-org-use-id
8454 (org-entry-get nil "ID"))))
8455 ;; We can make a link using the ID.
8456 (setq link (condition-case nil
8457 (prog1 (org-id-store-link)
8458 (setq desc (plist-get org-store-link-plist
8459 :description)))
8460 (error
8461 ;; probably before first headline, link to file only
8462 (concat "file:"
8463 (abbreviate-file-name
8464 (buffer-file-name (buffer-base-buffer))))))))
8466 ;; Just link to current headline
8467 (setq cpltxt (concat "file:"
8468 (abbreviate-file-name
8469 (buffer-file-name (buffer-base-buffer)))))
8470 ;; Add a context search string
8471 (when (org-xor org-context-in-file-links arg)
8472 (setq txt (cond
8473 ((org-on-heading-p) nil)
8474 ((org-region-active-p)
8475 (buffer-substring (region-beginning) (region-end)))
8476 (t nil)))
8477 (when (or (null txt) (string-match "\\S-" txt))
8478 (setq cpltxt
8479 (concat cpltxt "::"
8480 (condition-case nil
8481 (org-make-org-heading-search-string txt)
8482 (error "")))
8483 desc (or (nth 4 (ignore-errors
8484 (org-heading-components))) "NONE"))))
8485 (if (string-match "::\\'" cpltxt)
8486 (setq cpltxt (substring cpltxt 0 -2)))
8487 (setq link (org-make-link cpltxt)))))
8489 ((buffer-file-name (buffer-base-buffer))
8490 ;; Just link to this file here.
8491 (setq cpltxt (concat "file:"
8492 (abbreviate-file-name
8493 (buffer-file-name (buffer-base-buffer)))))
8494 ;; Add a context string
8495 (when (org-xor org-context-in-file-links arg)
8496 (setq txt (if (org-region-active-p)
8497 (buffer-substring (region-beginning) (region-end))
8498 (buffer-substring (point-at-bol) (point-at-eol))))
8499 ;; Only use search option if there is some text.
8500 (when (string-match "\\S-" txt)
8501 (setq cpltxt
8502 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8503 desc "NONE")))
8504 (setq link (org-make-link cpltxt)))
8506 ((interactive-p)
8507 (error "Cannot link to a buffer which is not visiting a file"))
8509 (t (setq link nil)))
8511 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8512 (setq link (or link cpltxt)
8513 desc (or desc cpltxt))
8514 (if (equal desc "NONE") (setq desc nil))
8516 (if (and (or (interactive-p) executing-kbd-macro) link)
8517 (progn
8518 (setq org-stored-links
8519 (cons (list link desc) org-stored-links))
8520 (message "Stored: %s" (or desc link))
8521 (when custom-id
8522 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8523 "::#" custom-id))
8524 (setq org-stored-links
8525 (cons (list link desc) org-stored-links))))
8526 (or agenda-link (and link (org-make-link-string link desc)))))))
8528 (defun org-store-link-props (&rest plist)
8529 "Store link properties, extract names and addresses."
8530 (let (x adr)
8531 (when (setq x (plist-get plist :from))
8532 (setq adr (mail-extract-address-components x))
8533 (setq plist (plist-put plist :fromname (car adr)))
8534 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8535 (when (setq x (plist-get plist :to))
8536 (setq adr (mail-extract-address-components x))
8537 (setq plist (plist-put plist :toname (car adr)))
8538 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8539 (let ((from (plist-get plist :from))
8540 (to (plist-get plist :to)))
8541 (when (and from to org-from-is-user-regexp)
8542 (setq plist
8543 (plist-put plist :fromto
8544 (if (string-match org-from-is-user-regexp from)
8545 (concat "to %t")
8546 (concat "from %f"))))))
8547 (setq org-store-link-plist plist))
8549 (defun org-add-link-props (&rest plist)
8550 "Add these properties to the link property list."
8551 (let (key value)
8552 (while plist
8553 (setq key (pop plist) value (pop plist))
8554 (setq org-store-link-plist
8555 (plist-put org-store-link-plist key value)))))
8557 (defun org-email-link-description (&optional fmt)
8558 "Return the description part of an email link.
8559 This takes information from `org-store-link-plist' and formats it
8560 according to FMT (default from `org-email-link-description-format')."
8561 (setq fmt (or fmt org-email-link-description-format))
8562 (let* ((p org-store-link-plist)
8563 (to (plist-get p :toaddress))
8564 (from (plist-get p :fromaddress))
8565 (table
8566 (list
8567 (cons "%c" (plist-get p :fromto))
8568 (cons "%F" (plist-get p :from))
8569 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8570 (cons "%T" (plist-get p :to))
8571 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8572 (cons "%s" (plist-get p :subject))
8573 (cons "%d" (plist-get p :date))
8574 (cons "%m" (plist-get p :message-id)))))
8575 (when (string-match "%c" fmt)
8576 ;; Check if the user wrote this message
8577 (if (and org-from-is-user-regexp from to
8578 (save-match-data (string-match org-from-is-user-regexp from)))
8579 (setq fmt (replace-match "to %t" t t fmt))
8580 (setq fmt (replace-match "from %f" t t fmt))))
8581 (org-replace-escapes fmt table)))
8583 (defun org-make-org-heading-search-string (&optional string heading)
8584 "Make search string for STRING or current headline."
8585 (interactive)
8586 (let ((s (or string (org-get-heading)))
8587 (lines org-context-in-file-links))
8588 (unless (and string (not heading))
8589 ;; We are using a headline, clean up garbage in there.
8590 (if (string-match org-todo-regexp s)
8591 (setq s (replace-match "" t t s)))
8592 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8593 (setq s (replace-match "" t t s)))
8594 (setq s (org-trim s))
8595 (if (string-match (concat "^\\(" org-quote-string "\\|"
8596 org-comment-string "\\)") s)
8597 (setq s (replace-match "" t t s)))
8598 (while (string-match org-ts-regexp s)
8599 (setq s (replace-match "" t t s))))
8600 (or string (setq s (concat "*" s))) ; Add * for headlines
8601 (when (and string (integerp lines) (> lines 0))
8602 (let ((slines (org-split-string s "\n")))
8603 (when (< lines (length slines))
8604 (setq s (mapconcat
8605 'identity
8606 (reverse (nthcdr (- (length slines) lines)
8607 (reverse slines))) "\n")))))
8608 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8610 (defun org-make-link (&rest strings)
8611 "Concatenate STRINGS."
8612 (apply 'concat strings))
8614 (defun org-make-link-string (link &optional description)
8615 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8616 (unless (string-match "\\S-" link)
8617 (error "Empty link"))
8618 (when (and description
8619 (stringp description)
8620 (not (string-match "\\S-" description)))
8621 (setq description nil))
8622 (when (stringp description)
8623 ;; Remove brackets from the description, they are fatal.
8624 (while (string-match "\\[" description)
8625 (setq description (replace-match "{" t t description)))
8626 (while (string-match "\\]" description)
8627 (setq description (replace-match "}" t t description))))
8628 (when (equal (org-link-escape link) description)
8629 ;; No description needed, it is identical
8630 (setq description nil))
8631 (when (and (not description)
8632 (not (equal link (org-link-escape link))))
8633 (setq description (org-extract-attributes link)))
8634 (setq link (if (string-match org-link-types-re link)
8635 (concat (match-string 1 link)
8636 (org-link-escape (substring link (match-end 1))))
8637 (org-link-escape link)))
8638 (concat "[[" link "]"
8639 (if description (concat "[" description "]") "")
8640 "]"))
8642 (defconst org-link-escape-chars
8643 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8644 "List of characters that should be escaped in link.
8645 This is the list that is used for internal purposes.")
8647 (defvar org-url-encoding-use-url-hexify nil)
8649 (defconst org-link-escape-chars-browser
8650 '(?\ )
8651 "List of escapes for characters that are problematic in links.
8652 This is the list that is used before handing over to the browser.")
8654 (defun org-link-escape (text &optional table merge)
8655 "Return percent escaped representation of TEXT.
8656 TEXT is a string with the text to escape.
8657 Optional argument TABLE is a list with characters that should be
8658 escaped. When nil, `org-link-escape-chars' is used.
8659 If optional argument MERGE is set, merge TABLE into
8660 `org-link-escape-chars'."
8661 (if (and org-url-encoding-use-url-hexify (not table))
8662 (url-hexify-string text)
8663 (cond
8664 ((and table merge)
8665 (mapc (lambda (defchr)
8666 (unless (member defchr table)
8667 (setq table (cons defchr table)))) org-link-escape-chars))
8668 ((null table)
8669 (setq table org-link-escape-chars)))
8670 (mapconcat
8671 (lambda (char)
8672 (if (or (member char table)
8673 (< char 32) (= char 37) (> char 126))
8674 (mapconcat (lambda (sequence-element)
8675 (format "%%%.2X" sequence-element))
8676 (or (encode-coding-char char 'utf-8)
8677 (error "Unable to percent escape character: %s"
8678 (char-to-string char))) "")
8679 (char-to-string char))) text "")))
8681 (defun org-link-unescape (str)
8682 "Unhex hexified unicode strings as returned from the JavaScript function
8683 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
8684 (unless (and (null str) (string= "" str))
8685 (let ((pos 0) (case-fold-search t) unhexed)
8686 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
8687 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
8688 (setq str (replace-match unhexed t t str))
8689 (setq pos (+ pos (length unhexed))))))
8690 str)
8692 (defun org-link-unescape-compound (hex)
8693 "Unhexify unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
8694 Note: this function also decodes single byte encodings like
8695 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
8696 (save-match-data
8697 (let* ((bytes (cdr (split-string hex "%")))
8698 (ret "")
8699 (eat 0)
8700 (sum 0))
8701 (while bytes
8702 (let* ((val (string-to-number (pop bytes) 16))
8703 (shift-xor
8704 (if (= 0 eat)
8705 (cond
8706 ((>= val 252) (cons 6 252))
8707 ((>= val 248) (cons 5 248))
8708 ((>= val 240) (cons 4 240))
8709 ((>= val 224) (cons 3 224))
8710 ((>= val 192) (cons 2 192))
8711 (t (cons 0 0)))
8712 (cons 6 128))))
8713 (if (>= val 192) (setq eat (car shift-xor)))
8714 (setq val (logxor val (cdr shift-xor)))
8715 (setq sum (+ (lsh sum (car shift-xor)) val))
8716 (if (> eat 0) (setq eat (- eat 1)))
8717 (cond
8718 ((= 0 eat) ;multi byte
8719 (setq ret (concat ret (org-char-to-string sum)))
8720 (setq sum 0))
8721 ((not bytes) ; single byte(s)
8722 (setq ret (org-link-unescape-single-byte-sequence hex))))
8723 )) ;; end (while bytes
8724 ret )))
8726 (defun org-link-unescape-single-byte-sequence (hex)
8727 "Unhexify hex-encoded single byte character sequences."
8728 (mapconcat (lambda (byte)
8729 (char-to-string (string-to-number byte 16)))
8730 (cdr (split-string hex "%")) ""))
8732 (defun org-xor (a b)
8733 "Exclusive or."
8734 (if a (not b) b))
8736 (defun org-fixup-message-id-for-http (s)
8737 "Replace special characters in a message id, so it can be used in an http query."
8738 (when (string-match "%" s)
8739 (setq s (mapconcat (lambda (c)
8740 (if (eq c ?%)
8741 "%25"
8742 (char-to-string c)))
8743 s "")))
8744 (while (string-match "<" s)
8745 (setq s (replace-match "%3C" t t s)))
8746 (while (string-match ">" s)
8747 (setq s (replace-match "%3E" t t s)))
8748 (while (string-match "@" s)
8749 (setq s (replace-match "%40" t t s)))
8752 ;;;###autoload
8753 (defun org-insert-link-global ()
8754 "Insert a link like Org-mode does.
8755 This command can be called in any mode to insert a link in Org-mode syntax."
8756 (interactive)
8757 (org-load-modules-maybe)
8758 (org-run-like-in-org-mode 'org-insert-link))
8760 (defun org-insert-link (&optional complete-file link-location)
8761 "Insert a link. At the prompt, enter the link.
8763 Completion can be used to insert any of the link protocol prefixes like
8764 http or ftp in use.
8766 The history can be used to select a link previously stored with
8767 `org-store-link'. When the empty string is entered (i.e. if you just
8768 press RET at the prompt), the link defaults to the most recently
8769 stored link. As SPC triggers completion in the minibuffer, you need to
8770 use M-SPC or C-q SPC to force the insertion of a space character.
8772 You will also be prompted for a description, and if one is given, it will
8773 be displayed in the buffer instead of the link.
8775 If there is already a link at point, this command will allow you to edit link
8776 and description parts.
8778 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
8779 be selected using completion. The path to the file will be relative to the
8780 current directory if the file is in the current directory or a subdirectory.
8781 Otherwise, the link will be the absolute path as completed in the minibuffer
8782 \(i.e. normally ~/path/to/file). You can configure this behavior using the
8783 option `org-link-file-path-type'.
8785 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
8786 the current directory or below.
8788 With three \\[universal-argument] prefixes, negate the meaning of
8789 `org-keep-stored-link-after-insertion'.
8791 If `org-make-link-description-function' is non-nil, this function will be
8792 called with the link target, and the result will be the default
8793 link description.
8795 If the LINK-LOCATION parameter is non-nil, this value will be
8796 used as the link location instead of reading one interactively."
8797 (interactive "P")
8798 (let* ((wcf (current-window-configuration))
8799 (region (if (org-region-active-p)
8800 (buffer-substring (region-beginning) (region-end))))
8801 (remove (and region (list (region-beginning) (region-end))))
8802 (desc region)
8803 tmphist ; byte-compile incorrectly complains about this
8804 (link link-location)
8805 entry file all-prefixes)
8806 (cond
8807 (link-location) ; specified by arg, just use it.
8808 ((org-in-regexp org-bracket-link-regexp 1)
8809 ;; We do have a link at point, and we are going to edit it.
8810 (setq remove (list (match-beginning 0) (match-end 0)))
8811 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8812 (setq link (read-string "Link: "
8813 (org-link-unescape
8814 (org-match-string-no-properties 1)))))
8815 ((or (org-in-regexp org-angle-link-re)
8816 (org-in-regexp org-plain-link-re))
8817 ;; Convert to bracket link
8818 (setq remove (list (match-beginning 0) (match-end 0))
8819 link (read-string "Link: "
8820 (org-remove-angle-brackets (match-string 0)))))
8821 ((member complete-file '((4) (16)))
8822 ;; Completing read for file names.
8823 (setq link (org-file-complete-link complete-file)))
8825 ;; Read link, with completion for stored links.
8826 (with-output-to-temp-buffer "*Org Links*"
8827 (princ "Insert a link.
8828 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8829 (when org-stored-links
8830 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8831 (princ (mapconcat
8832 (lambda (x)
8833 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8834 (reverse org-stored-links) "\n"))))
8835 (let ((cw (selected-window)))
8836 (select-window (get-buffer-window "*Org Links*" 'visible))
8837 (setq truncate-lines t)
8838 (unless (pos-visible-in-window-p (point-max))
8839 (org-fit-window-to-buffer))
8840 (and (window-live-p cw) (select-window cw)))
8841 ;; Fake a link history, containing the stored links.
8842 (setq tmphist (append (mapcar 'car org-stored-links)
8843 org-insert-link-history))
8844 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8845 (mapcar 'car org-link-abbrev-alist)
8846 org-link-types))
8847 (unwind-protect
8848 (progn
8849 (setq link
8850 (let ((org-completion-use-ido nil)
8851 (org-completion-use-iswitchb nil))
8852 (org-completing-read
8853 "Link: "
8854 (append
8855 (mapcar (lambda (x) (list (concat x ":")))
8856 all-prefixes)
8857 (mapcar 'car org-stored-links))
8858 nil nil nil
8859 'tmphist
8860 (car (car org-stored-links)))))
8861 (if (not (string-match "\\S-" link))
8862 (error "No link selected"))
8863 (if (or (member link all-prefixes)
8864 (and (equal ":" (substring link -1))
8865 (member (substring link 0 -1) all-prefixes)
8866 (setq link (substring link 0 -1))))
8867 (setq link (org-link-try-special-completion link))))
8868 (set-window-configuration wcf)
8869 (kill-buffer "*Org Links*"))
8870 (setq entry (assoc link org-stored-links))
8871 (or entry (push link org-insert-link-history))
8872 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8873 (not org-keep-stored-link-after-insertion))
8874 (setq org-stored-links (delq (assoc link org-stored-links)
8875 org-stored-links)))
8876 (setq desc (or desc (nth 1 entry)))))
8878 (if (string-match org-plain-link-re link)
8879 ;; URL-like link, normalize the use of angular brackets.
8880 (setq link (org-make-link (org-remove-angle-brackets link))))
8882 ;; Check if we are linking to the current file with a search option
8883 ;; If yes, simplify the link by using only the search option.
8884 (when (and buffer-file-name
8885 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8886 (let* ((path (match-string 1 link))
8887 (case-fold-search nil)
8888 (search (match-string 2 link)))
8889 (save-match-data
8890 (if (equal (file-truename buffer-file-name) (file-truename path))
8891 ;; We are linking to this same file, with a search option
8892 (setq link search)))))
8894 ;; Check if we can/should use a relative path. If yes, simplify the link
8895 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8896 (let* ((type (match-string 1 link))
8897 (path (match-string 2 link))
8898 (origpath path)
8899 (case-fold-search nil))
8900 (cond
8901 ((or (eq org-link-file-path-type 'absolute)
8902 (equal complete-file '(16)))
8903 (setq path (abbreviate-file-name (expand-file-name path))))
8904 ((eq org-link-file-path-type 'noabbrev)
8905 (setq path (expand-file-name path)))
8906 ((eq org-link-file-path-type 'relative)
8907 (setq path (file-relative-name path)))
8909 (save-match-data
8910 (if (string-match (concat "^" (regexp-quote
8911 (expand-file-name
8912 (file-name-as-directory
8913 default-directory))))
8914 (expand-file-name path))
8915 ;; We are linking a file with relative path name.
8916 (setq path (substring (expand-file-name path)
8917 (match-end 0)))
8918 (setq path (abbreviate-file-name (expand-file-name path)))))))
8919 (setq link (concat type path))
8920 (if (equal desc origpath)
8921 (setq desc path))))
8923 (if org-make-link-description-function
8924 (setq desc (funcall org-make-link-description-function link desc)))
8926 (setq desc (read-string "Description: " desc))
8927 (unless (string-match "\\S-" desc) (setq desc nil))
8928 (if remove (apply 'delete-region remove))
8929 (insert (org-make-link-string link desc))))
8931 (defun org-link-try-special-completion (type)
8932 "If there is completion support for link type TYPE, offer it."
8933 (let ((fun (intern (concat "org-" type "-complete-link"))))
8934 (if (functionp fun)
8935 (funcall fun)
8936 (read-string "Link (no completion support): " (concat type ":")))))
8938 (defun org-file-complete-link (&optional arg)
8939 "Create a file link using completion."
8940 (let (file link)
8941 (setq file (read-file-name "File: "))
8942 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8943 (pwd1 (file-name-as-directory (abbreviate-file-name
8944 (expand-file-name ".")))))
8945 (cond
8946 ((equal arg '(16))
8947 (setq link (org-make-link
8948 "file:"
8949 (abbreviate-file-name (expand-file-name file)))))
8950 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8951 (setq link (org-make-link "file:" (match-string 1 file))))
8952 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8953 (expand-file-name file))
8954 (setq link (org-make-link
8955 "file:" (match-string 1 (expand-file-name file)))))
8956 (t (setq link (org-make-link "file:" file)))))
8957 link))
8959 (defun org-completing-read (&rest args)
8960 "Completing-read with SPACE being a normal character."
8961 (let ((minibuffer-local-completion-map
8962 (copy-keymap minibuffer-local-completion-map)))
8963 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8964 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8965 (apply 'org-icompleting-read args)))
8967 (defun org-completing-read-no-i (&rest args)
8968 (let (org-completion-use-ido org-completion-use-iswitchb)
8969 (apply 'org-completing-read args)))
8971 (defun org-iswitchb-completing-read (prompt choices &rest args)
8972 "Use iswitch as a completing-read replacement to choose from choices.
8973 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8974 from."
8975 (let* ((iswitchb-use-virtual-buffers nil)
8976 (iswitchb-make-buflist-hook
8977 (lambda ()
8978 (setq iswitchb-temp-buflist choices))))
8979 (iswitchb-read-buffer prompt)))
8981 (defun org-icompleting-read (&rest args)
8982 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8983 (org-without-partial-completion
8984 (if (and org-completion-use-ido
8985 (fboundp 'ido-completing-read)
8986 (boundp 'ido-mode) ido-mode
8987 (listp (second args)))
8988 (let ((ido-enter-matching-directory nil))
8989 (apply 'ido-completing-read (concat (car args))
8990 (if (consp (car (nth 1 args)))
8991 (mapcar (lambda (x) (car x)) (nth 1 args))
8992 (nth 1 args))
8993 (cddr args)))
8994 (if (and org-completion-use-iswitchb
8995 (boundp 'iswitchb-mode) iswitchb-mode
8996 (listp (second args)))
8997 (apply 'org-iswitchb-completing-read (concat (car args))
8998 (if (consp (car (nth 1 args)))
8999 (mapcar (lambda (x) (car x)) (nth 1 args))
9000 (nth 1 args))
9001 (cddr args))
9002 (apply 'completing-read args)))))
9004 (defun org-extract-attributes (s)
9005 "Extract the attributes cookie from a string and set as text property."
9006 (let (a attr (start 0) key value)
9007 (save-match-data
9008 (when (string-match "{{\\([^}]+\\)}}$" s)
9009 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9010 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9011 (setq key (match-string 1 a) value (match-string 2 a)
9012 start (match-end 0)
9013 attr (plist-put attr (intern key) value))))
9014 (org-add-props s nil 'org-attr attr))
9017 (defun org-extract-attributes-from-string (tag)
9018 (let (key value attr)
9019 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9020 (setq key (match-string 1 tag) value (match-string 2 tag)
9021 tag (replace-match "" t t tag)
9022 attr (plist-put attr (intern key) value)))
9023 (cons tag attr)))
9025 (defun org-attributes-to-string (plist)
9026 "Format a property list into an HTML attribute list."
9027 (let ((s "") key value)
9028 (while plist
9029 (setq key (pop plist) value (pop plist))
9030 (and value
9031 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9034 ;;; Opening/following a link
9036 (defvar org-link-search-failed nil)
9038 (defvar org-open-link-functions nil
9039 "Hook for functions finding a plain text link.
9040 These functions must take a single argument, the link content.
9041 They will be called for links that look like [[link text][description]]
9042 when LINK TEXT does not have a protocol like \"http:\" and does not look
9043 like a filename (e.g. \"./blue.png\").
9045 These functions will be called *before* Org attempts to resolve the
9046 link by doing text searches in the current buffer - so if you want a
9047 link \"[[target]]\" to still find \"<<target>>\", your function should
9048 handle this as a special case.
9050 When the function does handle the link, it must return a non-nil value.
9051 If it decides that it is not responsible for this link, it must return
9052 nil to indicate that that Org-mode can continue with other options
9053 like exact and fuzzy text search.")
9055 (defun org-next-link ()
9056 "Move forward to the next link.
9057 If the link is in hidden text, expose it."
9058 (interactive)
9059 (when (and org-link-search-failed (eq this-command last-command))
9060 (goto-char (point-min))
9061 (message "Link search wrapped back to beginning of buffer"))
9062 (setq org-link-search-failed nil)
9063 (let* ((pos (point))
9064 (ct (org-context))
9065 (a (assoc :link ct)))
9066 (if a (goto-char (nth 2 a)))
9067 (if (re-search-forward org-any-link-re nil t)
9068 (progn
9069 (goto-char (match-beginning 0))
9070 (if (outline-invisible-p) (org-show-context)))
9071 (goto-char pos)
9072 (setq org-link-search-failed t)
9073 (error "No further link found"))))
9075 (defun org-previous-link ()
9076 "Move backward to the previous link.
9077 If the link is in hidden text, expose it."
9078 (interactive)
9079 (when (and org-link-search-failed (eq this-command last-command))
9080 (goto-char (point-max))
9081 (message "Link search wrapped back to end of buffer"))
9082 (setq org-link-search-failed nil)
9083 (let* ((pos (point))
9084 (ct (org-context))
9085 (a (assoc :link ct)))
9086 (if a (goto-char (nth 1 a)))
9087 (if (re-search-backward org-any-link-re nil t)
9088 (progn
9089 (goto-char (match-beginning 0))
9090 (if (outline-invisible-p) (org-show-context)))
9091 (goto-char pos)
9092 (setq org-link-search-failed t)
9093 (error "No further link found"))))
9095 (defun org-translate-link (s)
9096 "Translate a link string if a translation function has been defined."
9097 (if (and org-link-translation-function
9098 (fboundp org-link-translation-function)
9099 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9100 (progn
9101 (setq s (funcall org-link-translation-function
9102 (match-string 1) (match-string 2)))
9103 (concat (car s) ":" (cdr s)))
9106 (defun org-translate-link-from-planner (type path)
9107 "Translate a link from Emacs Planner syntax so that Org can follow it.
9108 This is still an experimental function, your mileage may vary."
9109 (cond
9110 ((member type '("http" "https" "news" "ftp"))
9111 ;; standard Internet links are the same.
9112 nil)
9113 ((and (equal type "irc") (string-match "^//" path))
9114 ;; Planner has two / at the beginning of an irc link, we have 1.
9115 ;; We should have zero, actually....
9116 (setq path (substring path 1)))
9117 ((and (equal type "lisp") (string-match "^/" path))
9118 ;; Planner has a slash, we do not.
9119 (setq type "elisp" path (substring path 1)))
9120 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9121 ;; A typical message link. Planner has the id after the final slash,
9122 ;; we separate it with a hash mark
9123 (setq path (concat (match-string 1 path) "#"
9124 (org-remove-angle-brackets (match-string 2 path)))))
9126 (cons type path))
9128 (defun org-find-file-at-mouse (ev)
9129 "Open file link or URL at mouse."
9130 (interactive "e")
9131 (mouse-set-point ev)
9132 (org-open-at-point 'in-emacs))
9134 (defun org-open-at-mouse (ev)
9135 "Open file link or URL at mouse."
9136 (interactive "e")
9137 (mouse-set-point ev)
9138 (if (eq major-mode 'org-agenda-mode)
9139 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9140 (org-open-at-point))
9142 (defvar org-window-config-before-follow-link nil
9143 "The window configuration before following a link.
9144 This is saved in case the need arises to restore it.")
9146 (defvar org-open-link-marker (make-marker)
9147 "Marker pointing to the location where `org-open-at-point; was called.")
9149 ;;;###autoload
9150 (defun org-open-at-point-global ()
9151 "Follow a link like Org-mode does.
9152 This command can be called in any mode to follow a link that has
9153 Org-mode syntax."
9154 (interactive)
9155 (org-run-like-in-org-mode 'org-open-at-point))
9157 ;;;###autoload
9158 (defun org-open-link-from-string (s &optional arg reference-buffer)
9159 "Open a link in the string S, as if it was in Org-mode."
9160 (interactive "sLink: \nP")
9161 (let ((reference-buffer (or reference-buffer (current-buffer))))
9162 (with-temp-buffer
9163 (let ((org-inhibit-startup t))
9164 (org-mode)
9165 (insert s)
9166 (goto-char (point-min))
9167 (when reference-buffer
9168 (setq org-link-abbrev-alist-local
9169 (with-current-buffer reference-buffer
9170 org-link-abbrev-alist-local)))
9171 (org-open-at-point arg reference-buffer)))))
9173 (defvar org-open-at-point-functions nil
9174 "Hook that is run when following a link at point.
9176 Functions in this hook must return t if they identify and follow
9177 a link at point. If they don't find anything interesting at point,
9178 they must return nil.")
9180 (defun org-open-at-point (&optional arg reference-buffer)
9181 "Open link at or after point.
9182 If there is no link at point, this function will search forward up to
9183 the end of the current line.
9184 Normally, files will be opened by an appropriate application. If the
9185 optional prefix argument ARG is non-nil, Emacs will visit the file.
9186 With a double prefix argument, try to open outside of Emacs, in the
9187 application the system uses for this file type."
9188 (interactive "P")
9189 ;; if in a code block, then open the block's results
9190 (unless (call-interactively #'org-babel-open-src-block-result)
9191 (org-load-modules-maybe)
9192 (move-marker org-open-link-marker (point))
9193 (setq org-window-config-before-follow-link (current-window-configuration))
9194 (org-remove-occur-highlights nil nil t)
9195 (cond
9196 ((and (org-on-heading-p)
9197 (not (org-in-regexp
9198 (concat org-plain-link-re "\\|"
9199 org-bracket-link-regexp "\\|"
9200 org-angle-link-re "\\|"
9201 "[ \t]:[^ \t\n]+:[ \t]*$")))
9202 (not (get-text-property (point) 'org-linked-text)))
9203 (or (org-offer-links-in-entry arg)
9204 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9205 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9206 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9207 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9208 (not (org-in-regexp org-bracket-link-regexp)))
9209 (org-footnote-action))
9211 (let (type path link line search (pos (point)))
9212 (catch 'match
9213 (save-excursion
9214 (skip-chars-forward "^]\n\r")
9215 (when (org-in-regexp org-bracket-link-regexp 1)
9216 (setq link (org-extract-attributes
9217 (org-link-unescape (org-match-string-no-properties 1))))
9218 (while (string-match " *\n *" link)
9219 (setq link (replace-match " " t t link)))
9220 (setq link (org-link-expand-abbrev link))
9221 (cond
9222 ((or (file-name-absolute-p link)
9223 (string-match "^\\.\\.?/" link))
9224 (setq type "file" path link))
9225 ((string-match org-link-re-with-space3 link)
9226 (setq type (match-string 1 link) path (match-string 2 link)))
9227 (t (setq type "thisfile" path link)))
9228 (throw 'match t)))
9230 (when (get-text-property (point) 'org-linked-text)
9231 (setq type "thisfile"
9232 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9233 (1+ (point)) (point))
9234 path (buffer-substring
9235 (or (previous-single-property-change pos 'org-linked-text)
9236 (point-min))
9237 (or (next-single-property-change pos 'org-linked-text)
9238 (point-max))))
9239 (throw 'match t))
9241 (save-excursion
9242 (when (or (org-in-regexp org-angle-link-re)
9243 (org-in-regexp org-plain-link-re))
9244 (setq type (match-string 1) path (match-string 2))
9245 (throw 'match t)))
9246 (save-excursion
9247 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9248 (setq type "tags"
9249 path (match-string 1))
9250 (while (string-match ":" path)
9251 (setq path (replace-match "+" t t path)))
9252 (throw 'match t)))
9253 (when (org-in-regexp "<\\([^><\n]+\\)>")
9254 (setq type "tree-match"
9255 path (match-string 1))
9256 (throw 'match t)))
9257 (unless path
9258 (error "No link found"))
9260 ;; switch back to reference buffer
9261 ;; needed when if called in a temporary buffer through
9262 ;; org-open-link-from-string
9263 (with-current-buffer (or reference-buffer (current-buffer))
9265 ;; Remove any trailing spaces in path
9266 (if (string-match " +\\'" path)
9267 (setq path (replace-match "" t t path)))
9268 (if (and org-link-translation-function
9269 (fboundp org-link-translation-function))
9270 ;; Check if we need to translate the link
9271 (let ((tmp (funcall org-link-translation-function type path)))
9272 (setq type (car tmp) path (cdr tmp))))
9274 (cond
9276 ((assoc type org-link-protocols)
9277 (funcall (nth 1 (assoc type org-link-protocols)) path))
9279 ((equal type "mailto")
9280 (let ((cmd (car org-link-mailto-program))
9281 (args (cdr org-link-mailto-program)) args1
9282 (address path) (subject "") a)
9283 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9284 (setq address (match-string 1 path)
9285 subject (org-link-escape (match-string 2 path))))
9286 (while args
9287 (cond
9288 ((not (stringp (car args))) (push (pop args) args1))
9289 (t (setq a (pop args))
9290 (if (string-match "%a" a)
9291 (setq a (replace-match address t t a)))
9292 (if (string-match "%s" a)
9293 (setq a (replace-match subject t t a)))
9294 (push a args1))))
9295 (apply cmd (nreverse args1))))
9297 ((member type '("http" "https" "ftp" "news"))
9298 (browse-url (concat type ":" (org-link-escape
9299 path org-link-escape-chars-browser))))
9301 ((string= type "doi")
9302 (browse-url (concat "http://dx.doi.org/"
9303 (org-link-escape
9304 path org-link-escape-chars-browser))))
9306 ((member type '("message"))
9307 (browse-url (concat type ":" path)))
9309 ((string= type "tags")
9310 (org-tags-view arg path))
9312 ((string= type "tree-match")
9313 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9315 ((string= type "file")
9316 (if (string-match "::\\([0-9]+\\)\\'" path)
9317 (setq line (string-to-number (match-string 1 path))
9318 path (substring path 0 (match-beginning 0)))
9319 (if (string-match "::\\(.+\\)\\'" path)
9320 (setq search (match-string 1 path)
9321 path (substring path 0 (match-beginning 0)))))
9322 (if (string-match "[*?{]" (file-name-nondirectory path))
9323 (dired path)
9324 (org-open-file path arg line search)))
9326 ((string= type "shell")
9327 (let ((cmd path))
9328 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9329 (string-match org-confirm-shell-link-not-regexp cmd))
9330 (not org-confirm-shell-link-function)
9331 (funcall org-confirm-shell-link-function
9332 (format "Execute \"%s\" in shell? "
9333 (org-add-props cmd nil
9334 'face 'org-warning))))
9335 (progn
9336 (message "Executing %s" cmd)
9337 (shell-command cmd))
9338 (error "Abort"))))
9340 ((string= type "elisp")
9341 (let ((cmd path))
9342 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9343 (string-match org-confirm-elisp-link-not-regexp cmd))
9344 (not org-confirm-elisp-link-function)
9345 (funcall org-confirm-elisp-link-function
9346 (format "Execute \"%s\" as elisp? "
9347 (org-add-props cmd nil
9348 'face 'org-warning))))
9349 (message "%s => %s" cmd
9350 (if (equal (string-to-char cmd) ?\()
9351 (eval (read cmd))
9352 (call-interactively (read cmd))))
9353 (error "Abort"))))
9355 ((and (string= type "thisfile")
9356 (run-hook-with-args-until-success
9357 'org-open-link-functions path)))
9359 ((string= type "thisfile")
9360 (if arg
9361 (switch-to-buffer-other-window
9362 (org-get-buffer-for-internal-link (current-buffer)))
9363 (org-mark-ring-push))
9364 (let ((cmd `(org-link-search
9365 ,path
9366 ,(cond ((equal arg '(4)) ''occur)
9367 ((equal arg '(16)) ''org-occur)
9368 (t nil))
9369 ,pos)))
9370 (condition-case nil (eval cmd)
9371 (error (progn (widen) (eval cmd))))))
9374 (browse-url-at-point)))))))
9375 (move-marker org-open-link-marker nil)
9376 (run-hook-with-args 'org-follow-link-hook)))
9378 (defun org-offer-links-in-entry (&optional nth zero)
9379 "Offer links in the current entry and follow the selected link.
9380 If there is only one link, follow it immediately as well.
9381 If NTH is an integer, immediately pick the NTH link found.
9382 If ZERO is a string, check also this string for a link, and if
9383 there is one, offer it as link number zero."
9384 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9385 "\\(" org-angle-link-re "\\)\\|"
9386 "\\(" org-plain-link-re "\\)"))
9387 (cnt ?0)
9388 (in-emacs (if (integerp nth) nil nth))
9389 have-zero end links link c)
9390 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9391 (push (match-string 0 zero) links)
9392 (setq cnt (1- cnt) have-zero t))
9393 (save-excursion
9394 (org-back-to-heading t)
9395 (setq end (save-excursion (outline-next-heading) (point)))
9396 (while (re-search-forward re end t)
9397 (push (match-string 0) links))
9398 (setq links (org-uniquify (reverse links))))
9400 (cond
9401 ((null links)
9402 (message "No links"))
9403 ((equal (length links) 1)
9404 (setq link (list (car links))))
9405 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9406 (setq link (nth (if have-zero nth (1- nth)) links)))
9407 (t ; we have to select a link
9408 (save-excursion
9409 (save-window-excursion
9410 (delete-other-windows)
9411 (with-output-to-temp-buffer "*Select Link*"
9412 (mapc (lambda (l)
9413 (if (not (string-match org-bracket-link-regexp l))
9414 (princ (format "[%c] %s\n" (incf cnt)
9415 (org-remove-angle-brackets l)))
9416 (if (match-end 3)
9417 (princ (format "[%c] %s (%s)\n" (incf cnt)
9418 (match-string 3 l) (match-string 1 l)))
9419 (princ (format "[%c] %s\n" (incf cnt)
9420 (match-string 1 l))))))
9421 links))
9422 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9423 (message "Select link to open, RET to open all:")
9424 (setq c (read-char-exclusive))
9425 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9426 (when (equal c ?q) (error "Abort"))
9427 (if (equal c ?\C-m)
9428 (setq link links)
9429 (setq nth (- c ?0))
9430 (if have-zero (setq nth (1+ nth)))
9431 (unless (and (integerp nth) (>= (length links) nth))
9432 (error "Invalid link selection"))
9433 (setq link (list (nth (1- nth) links))))))
9434 (if link
9435 (let ((buf (current-buffer)))
9436 (dolist (l link)
9437 (org-open-link-from-string l in-emacs buf))
9439 nil)))
9441 ;; Add special file links that specify the way of opening
9443 (org-add-link-type "file+sys" 'org-open-file-with-system)
9444 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9445 (defun org-open-file-with-system (path)
9446 "Open file at PATH using the system way of opening it."
9447 (org-open-file path 'system))
9448 (defun org-open-file-with-emacs (path)
9449 "Open file at PATH in Emacs."
9450 (org-open-file path 'emacs))
9451 (defun org-remove-file-link-modifiers ()
9452 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9453 (goto-char (point-min))
9454 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9455 (org-if-unprotected
9456 (replace-match "file:" t t))))
9457 (eval-after-load "org-exp"
9458 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9459 'org-remove-file-link-modifiers))
9461 ;;;; Time estimates
9463 (defun org-get-effort (&optional pom)
9464 "Get the effort estimate for the current entry."
9465 (org-entry-get pom org-effort-property))
9467 ;;; File search
9469 (defvar org-create-file-search-functions nil
9470 "List of functions to construct the right search string for a file link.
9471 These functions are called in turn with point at the location to
9472 which the link should point.
9474 A function in the hook should first test if it would like to
9475 handle this file type, for example by checking the `major-mode'
9476 or the file extension. If it decides not to handle this file, it
9477 should just return nil to give other functions a chance. If it
9478 does handle the file, it must return the search string to be used
9479 when following the link. The search string will be part of the
9480 file link, given after a double colon, and `org-open-at-point'
9481 will automatically search for it. If special measures must be
9482 taken to make the search successful, another function should be
9483 added to the companion hook `org-execute-file-search-functions',
9484 which see.
9486 A function in this hook may also use `setq' to set the variable
9487 `description' to provide a suggestion for the descriptive text to
9488 be used for this link when it gets inserted into an Org-mode
9489 buffer with \\[org-insert-link].")
9491 (defvar org-execute-file-search-functions nil
9492 "List of functions to execute a file search triggered by a link.
9494 Functions added to this hook must accept a single argument, the
9495 search string that was part of the file link, the part after the
9496 double colon. The function must first check if it would like to
9497 handle this search, for example by checking the `major-mode' or
9498 the file extension. If it decides not to handle this search, it
9499 should just return nil to give other functions a chance. If it
9500 does handle the search, it must return a non-nil value to keep
9501 other functions from trying.
9503 Each function can access the current prefix argument through the
9504 variable `current-prefix-argument'. Note that a single prefix is
9505 used to force opening a link in Emacs, so it may be good to only
9506 use a numeric or double prefix to guide the search function.
9508 In case this is needed, a function in this hook can also restore
9509 the window configuration before `org-open-at-point' was called using:
9511 (set-window-configuration org-window-config-before-follow-link)")
9513 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9514 (defun org-link-search (s &optional type avoid-pos)
9515 "Search for a link search option.
9516 If S is surrounded by forward slashes, it is interpreted as a
9517 regular expression. In org-mode files, this will create an `org-occur'
9518 sparse tree. In ordinary files, `occur' will be used to list matches.
9519 If the current buffer is in `dired-mode', grep will be used to search
9520 in all files. If AVOID-POS is given, ignore matches near that position."
9521 (let ((case-fold-search t)
9522 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9523 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9524 (append '(("") (" ") ("\t") ("\n"))
9525 org-emphasis-alist)
9526 "\\|") "\\)"))
9527 (pos (point))
9528 (pre nil) (post nil)
9529 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9530 (cond
9531 ;; First check if there are any special search functions
9532 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9533 ;; Now try the builtin stuff
9534 ((and (equal (string-to-char s0) ?#)
9535 (> (length s0) 1)
9536 (save-excursion
9537 (goto-char (point-min))
9538 (and
9539 (re-search-forward
9540 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9541 (setq type 'dedicated
9542 pos (match-beginning 0))))
9543 ;; There is an exact target for this
9544 (goto-char pos)
9545 (org-back-to-heading t)))
9546 ((save-excursion
9547 (goto-char (point-min))
9548 (and
9549 (re-search-forward
9550 (concat "<<" (regexp-quote s0) ">>") nil t)
9551 (setq type 'dedicated
9552 pos (match-beginning 0))))
9553 ;; There is an exact target for this
9554 (goto-char pos))
9555 ((and (string-match "^(\\(.*\\))$" s0)
9556 (save-excursion
9557 (goto-char (point-min))
9558 (and
9559 (re-search-forward
9560 (concat "[^[]" (regexp-quote
9561 (format org-coderef-label-format
9562 (match-string 1 s0))))
9563 nil t)
9564 (setq type 'dedicated
9565 pos (1+ (match-beginning 0))))))
9566 ;; There is a coderef target for this
9567 (goto-char pos))
9568 ((string-match "^/\\(.*\\)/$" s)
9569 ;; A regular expression
9570 (cond
9571 ((org-mode-p)
9572 (org-occur (match-string 1 s)))
9573 ;;((eq major-mode 'dired-mode)
9574 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9575 (t (org-do-occur (match-string 1 s)))))
9576 ((and (org-mode-p) org-link-search-must-match-exact-headline)
9577 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9578 (goto-char (point-min))
9579 (cond
9580 ((let (case-fold-search)
9581 (re-search-forward (format org-complex-heading-regexp-format
9582 (regexp-quote s))
9583 nil t))
9584 ;; OK, found a match
9585 (setq type 'dedicated)
9586 (goto-char (match-beginning 0)))
9587 ((and (not org-link-search-inhibit-query)
9588 (eq org-link-search-must-match-exact-headline 'query-to-create)
9589 (y-or-n-p "No match - create this as a new heading? "))
9590 (goto-char (point-max))
9591 (or (bolp) (newline))
9592 (insert "* " s "\n")
9593 (beginning-of-line 0))
9595 (goto-char pos)
9596 (error "No match"))))
9598 ;; A normal search string
9599 (when (equal (string-to-char s) ?*)
9600 ;; Anchor on headlines, post may include tags.
9601 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9602 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9603 s (substring s 1)))
9604 (remove-text-properties
9605 0 (length s)
9606 '(face nil mouse-face nil keymap nil fontified nil) s)
9607 ;; Make a series of regular expressions to find a match
9608 (setq words (org-split-string s "[ \n\r\t]+")
9610 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9611 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9612 "\\)" markers)
9613 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9614 re2a (concat "[ \t\r\n]" re2a_)
9615 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9616 re4 (concat "[^a-zA-Z_]" re4_)
9618 re1 (concat pre re2 post)
9619 re3 (concat pre (if pre re4_ re4) post)
9620 re5 (concat pre ".*" re4)
9621 re2 (concat pre re2)
9622 re2a (concat pre (if pre re2a_ re2a))
9623 re4 (concat pre (if pre re4_ re4))
9624 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9625 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9626 re5 "\\)"
9628 (cond
9629 ((eq type 'org-occur) (org-occur reall))
9630 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9631 (t (goto-char (point-min))
9632 (setq type 'fuzzy)
9633 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9634 (org-search-not-self 1 re1 nil t)
9635 (org-search-not-self 1 re2 nil t)
9636 (org-search-not-self 1 re2a nil t)
9637 (org-search-not-self 1 re3 nil t)
9638 (org-search-not-self 1 re4 nil t)
9639 (org-search-not-self 1 re5 nil t)
9641 (goto-char (match-beginning 1))
9642 (goto-char pos)
9643 (error "No match"))))))
9644 (and (org-mode-p) (org-show-context 'link-search))
9645 type))
9647 (defun org-search-not-self (group &rest args)
9648 "Execute `re-search-forward', but only accept matches that do not
9649 enclose the position of `org-open-link-marker'."
9650 (let ((m org-open-link-marker))
9651 (catch 'exit
9652 (while (apply 're-search-forward args)
9653 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9654 (goto-char (match-end group))
9655 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9656 (> (match-beginning 0) (marker-position m))
9657 (< (match-end 0) (marker-position m)))
9658 (save-match-data
9659 (or (not (org-in-regexp
9660 org-bracket-link-analytic-regexp 1))
9661 (not (match-end 4)) ; no description
9662 (and (<= (match-beginning 4) (point))
9663 (>= (match-end 4) (point))))))
9664 (throw 'exit (point))))))))
9666 (defun org-get-buffer-for-internal-link (buffer)
9667 "Return a buffer to be used for displaying the link target of internal links."
9668 (cond
9669 ((not org-display-internal-link-with-indirect-buffer)
9670 buffer)
9671 ((string-match "(Clone)$" (buffer-name buffer))
9672 (message "Buffer is already a clone, not making another one")
9673 ;; we also do not modify visibility in this case
9674 buffer)
9675 (t ; make a new indirect buffer for displaying the link
9676 (let* ((bn (buffer-name buffer))
9677 (ibn (concat bn "(Clone)"))
9678 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9679 (with-current-buffer ib (org-overview))
9680 ib))))
9682 (defun org-do-occur (regexp &optional cleanup)
9683 "Call the Emacs command `occur'.
9684 If CLEANUP is non-nil, remove the printout of the regular expression
9685 in the *Occur* buffer. This is useful if the regex is long and not useful
9686 to read."
9687 (occur regexp)
9688 (when cleanup
9689 (let ((cwin (selected-window)) win beg end)
9690 (when (setq win (get-buffer-window "*Occur*"))
9691 (select-window win))
9692 (goto-char (point-min))
9693 (when (re-search-forward "match[a-z]+" nil t)
9694 (setq beg (match-end 0))
9695 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9696 (setq end (1- (match-beginning 0)))))
9697 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9698 (goto-char (point-min))
9699 (select-window cwin))))
9701 ;;; The mark ring for links jumps
9703 (defvar org-mark-ring nil
9704 "Mark ring for positions before jumps in Org-mode.")
9705 (defvar org-mark-ring-last-goto nil
9706 "Last position in the mark ring used to go back.")
9707 ;; Fill and close the ring
9708 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9709 (loop for i from 1 to org-mark-ring-length do
9710 (push (make-marker) org-mark-ring))
9711 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9712 org-mark-ring)
9714 (defun org-mark-ring-push (&optional pos buffer)
9715 "Put the current position or POS into the mark ring and rotate it."
9716 (interactive)
9717 (setq pos (or pos (point)))
9718 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9719 (move-marker (car org-mark-ring)
9720 (or pos (point))
9721 (or buffer (current-buffer)))
9722 (message "%s"
9723 (substitute-command-keys
9724 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9726 (defun org-mark-ring-goto (&optional n)
9727 "Jump to the previous position in the mark ring.
9728 With prefix arg N, jump back that many stored positions. When
9729 called several times in succession, walk through the entire ring.
9730 Org-mode commands jumping to a different position in the current file,
9731 or to another Org-mode file, automatically push the old position
9732 onto the ring."
9733 (interactive "p")
9734 (let (p m)
9735 (if (eq last-command this-command)
9736 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9737 (setq p org-mark-ring))
9738 (setq org-mark-ring-last-goto p)
9739 (setq m (car p))
9740 (switch-to-buffer (marker-buffer m))
9741 (goto-char m)
9742 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9744 (defun org-remove-angle-brackets (s)
9745 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9746 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9748 (defun org-add-angle-brackets (s)
9749 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9750 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9752 (defun org-remove-double-quotes (s)
9753 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9754 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
9757 ;;; Following specific links
9759 (defun org-follow-timestamp-link ()
9760 (cond
9761 ((org-at-date-range-p t)
9762 (let ((org-agenda-start-on-weekday)
9763 (t1 (match-string 1))
9764 (t2 (match-string 2)))
9765 (setq t1 (time-to-days (org-time-string-to-time t1))
9766 t2 (time-to-days (org-time-string-to-time t2)))
9767 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9768 ((org-at-timestamp-p t)
9769 (org-agenda-list nil (time-to-days (org-time-string-to-time
9770 (substring (match-string 1) 0 10)))
9772 (t (error "This should not happen"))))
9775 ;;; Following file links
9776 (defvar org-wait nil)
9777 (defun org-open-file (path &optional in-emacs line search)
9778 "Open the file at PATH.
9779 First, this expands any special file name abbreviations. Then the
9780 configuration variable `org-file-apps' is checked if it contains an
9781 entry for this file type, and if yes, the corresponding command is launched.
9783 If no application is found, Emacs simply visits the file.
9785 With optional prefix argument IN-EMACS, Emacs will visit the file.
9786 With a double \\[universal-argument] \\[universal-argument] \
9787 prefix arg, Org tries to avoid opening in Emacs
9788 and to use an external application to visit the file.
9790 Optional LINE specifies a line to go to, optional SEARCH a string
9791 to search for. If LINE or SEARCH is given, the file will be
9792 opened in Emacs, unless an entry from org-file-apps that makes
9793 use of groups in a regexp matches.
9794 If the file does not exist, an error is thrown."
9795 (let* ((file (if (equal path "")
9796 buffer-file-name
9797 (substitute-in-file-name (expand-file-name path))))
9798 (file-apps (append org-file-apps (org-default-apps)))
9799 (apps (org-remove-if
9800 'org-file-apps-entry-match-against-dlink-p file-apps))
9801 (apps-dlink (org-remove-if-not
9802 'org-file-apps-entry-match-against-dlink-p file-apps))
9803 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9804 (dirp (if remp nil (file-directory-p file)))
9805 (file (if (and dirp org-open-directory-means-index-dot-org)
9806 (concat (file-name-as-directory file) "index.org")
9807 file))
9808 (a-m-a-p (assq 'auto-mode apps))
9809 (dfile (downcase file))
9810 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
9811 (link (cond ((and (eq line nil)
9812 (eq search nil))
9813 file)
9814 (line
9815 (concat file "::" (number-to-string line)))
9816 (search
9817 (concat file "::" search))))
9818 (dlink (downcase link))
9819 (old-buffer (current-buffer))
9820 (old-pos (point))
9821 (old-mode major-mode)
9822 ext cmd link-match-data)
9823 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9824 (setq ext (match-string 1 dfile))
9825 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9826 (setq ext (match-string 1 dfile))))
9827 (cond
9828 ((member in-emacs '((16) system))
9829 (setq cmd (cdr (assoc 'system apps))))
9830 (in-emacs (setq cmd 'emacs))
9832 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9833 (and dirp (cdr (assoc 'directory apps)))
9834 ; first, try matching against apps-dlink
9835 ; if we get a match here, store the match data for later
9836 (let ((match (assoc-default dlink apps-dlink
9837 'string-match)))
9838 (if match
9839 (progn (setq link-match-data (match-data))
9840 match)
9841 (progn (setq in-emacs (or in-emacs line search))
9842 nil))) ; if we have no match in apps-dlink,
9843 ; always open the file in emacs if line or search
9844 ; is given (for backwards compatibility)
9845 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
9846 'string-match)
9847 (cdr (assoc ext apps))
9848 (cdr (assoc t apps))))))
9849 (when (eq cmd 'system)
9850 (setq cmd (cdr (assoc 'system apps))))
9851 (when (eq cmd 'default)
9852 (setq cmd (cdr (assoc t apps))))
9853 (when (eq cmd 'mailcap)
9854 (require 'mailcap)
9855 (mailcap-parse-mailcaps)
9856 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9857 (command (mailcap-mime-info mime-type)))
9858 (if (stringp command)
9859 (setq cmd command)
9860 (setq cmd 'emacs))))
9861 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
9862 (not (file-exists-p file))
9863 (not org-open-non-existing-files))
9864 (error "No such file: %s" file))
9865 (cond
9866 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9867 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9868 (while (string-match "['\"]%s['\"]" cmd)
9869 (setq cmd (replace-match "%s" t t cmd)))
9870 (while (string-match "%s" cmd)
9871 (setq cmd (replace-match
9872 (save-match-data
9873 (shell-quote-argument
9874 (convert-standard-filename file)))
9875 t t cmd)))
9877 ;; Replace "%1", "%2" etc. in command with group matches from regex
9878 (save-match-data
9879 (let ((match-index 1)
9880 (number-of-groups (- (/ (length link-match-data) 2) 1)))
9881 (set-match-data link-match-data)
9882 (while (<= match-index number-of-groups)
9883 (let ((regex (concat "%" (number-to-string match-index)))
9884 (replace-with (match-string match-index dlink)))
9885 (while (string-match regex cmd)
9886 (setq cmd (replace-match replace-with t t cmd))))
9887 (setq match-index (+ match-index 1)))))
9889 (save-window-excursion
9890 (start-process-shell-command cmd nil cmd)
9891 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9893 ((or (stringp cmd)
9894 (eq cmd 'emacs))
9895 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9896 (widen)
9897 (if line (org-goto-line line)
9898 (if search (org-link-search search))))
9899 ((consp cmd)
9900 (let ((file (convert-standard-filename file)))
9901 (save-match-data
9902 (set-match-data link-match-data)
9903 (eval cmd))))
9904 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9905 (and (org-mode-p) (eq old-mode 'org-mode)
9906 (or (not (equal old-buffer (current-buffer)))
9907 (not (equal old-pos (point))))
9908 (org-mark-ring-push old-pos old-buffer))))
9910 (defun org-file-apps-entry-match-against-dlink-p (entry)
9911 "This function returns non-nil if `entry' uses a regular
9912 expression which should be matched against the whole link by
9913 org-open-file.
9915 It assumes that is the case when the entry uses a regular
9916 expression which has at least one grouping construct and the
9917 action is either a lisp form or a command string containing
9918 '%1', i.e. using at least one subexpression match as a
9919 parameter."
9920 (let ((selector (car entry))
9921 (action (cdr entry)))
9922 (if (stringp selector)
9923 (and (> (regexp-opt-depth selector) 0)
9924 (or (and (stringp action)
9925 (string-match "%[0-9]" action))
9926 (consp action)))
9927 nil)))
9929 (defun org-default-apps ()
9930 "Return the default applications for this operating system."
9931 (cond
9932 ((eq system-type 'darwin)
9933 org-file-apps-defaults-macosx)
9934 ((eq system-type 'windows-nt)
9935 org-file-apps-defaults-windowsnt)
9936 (t org-file-apps-defaults-gnu)))
9938 (defun org-apps-regexp-alist (list &optional add-auto-mode)
9939 "Convert extensions to regular expressions in the cars of LIST.
9940 Also, weed out any non-string entries, because the return value is used
9941 only for regexp matching.
9942 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
9943 point to the symbol `emacs', indicating that the file should
9944 be opened in Emacs."
9945 (append
9946 (delq nil
9947 (mapcar (lambda (x)
9948 (if (not (stringp (car x)))
9950 (if (string-match "\\W" (car x))
9952 (cons (concat "\\." (car x) "\\'") (cdr x)))))
9953 list))
9954 (if add-auto-mode
9955 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
9957 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
9958 (defun org-file-remote-p (file)
9959 "Test whether FILE specifies a location on a remote system.
9960 Return non-nil if the location is indeed remote.
9962 For example, the filename \"/user@host:/foo\" specifies a location
9963 on the system \"/user@host:\"."
9964 (cond ((fboundp 'file-remote-p)
9965 (file-remote-p file))
9966 ((fboundp 'tramp-handle-file-remote-p)
9967 (tramp-handle-file-remote-p file))
9968 ((and (boundp 'ange-ftp-name-format)
9969 (string-match (car ange-ftp-name-format) file))
9971 (t nil)))
9974 ;;;; Refiling
9976 (defun org-get-org-file ()
9977 "Read a filename, with default directory `org-directory'."
9978 (let ((default (or org-default-notes-file remember-data-file)))
9979 (read-file-name (format "File name [%s]: " default)
9980 (file-name-as-directory org-directory)
9981 default)))
9983 (defun org-notes-order-reversed-p ()
9984 "Check if the current file should receive notes in reversed order."
9985 (cond
9986 ((not org-reverse-note-order) nil)
9987 ((eq t org-reverse-note-order) t)
9988 ((not (listp org-reverse-note-order)) nil)
9989 (t (catch 'exit
9990 (let ((all org-reverse-note-order)
9991 entry)
9992 (while (setq entry (pop all))
9993 (if (string-match (car entry) buffer-file-name)
9994 (throw 'exit (cdr entry))))
9995 nil)))))
9997 (defvar org-refile-target-table nil
9998 "The list of refile targets, created by `org-refile'.")
10000 (defvar org-agenda-new-buffers nil
10001 "Buffers created to visit agenda files.")
10003 (defvar org-refile-cache nil
10004 "Cache for refile targets.")
10006 (defvar org-refile-markers nil
10007 "All the markers used for caching refile locations.")
10009 (defun org-refile-marker (pos)
10010 "Get a new refile marker, but only if caching is in use."
10011 (if (not org-refile-use-cache)
10013 (let ((m (make-marker)))
10014 (move-marker m pos)
10015 (push m org-refile-markers)
10016 m)))
10018 (defun org-refile-cache-clear ()
10019 "Clear the refile cache and disable all the markers."
10020 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10021 (setq org-refile-markers nil)
10022 (setq org-refile-cache nil)
10023 (message "Refile cache has been cleared"))
10025 (defun org-refile-cache-check-set (set)
10026 "Check if all the markers in the cache still have live buffers."
10027 (let (marker)
10028 (catch 'exit
10029 (while (and set (setq marker (nth 3 (pop set))))
10030 ;; if org-refile-use-outline-path is 'file, marker may be nil
10031 (when (and marker (null (marker-buffer marker)))
10032 (message "not found") (sit-for 3)
10033 (throw 'exit nil)))
10034 t)))
10036 (defun org-refile-cache-put (set &rest identifiers)
10037 "Push the refile targets SET into the cache, under IDENTIFIERS."
10038 (let* ((key (sha1 (prin1-to-string identifiers)))
10039 (entry (assoc key org-refile-cache)))
10040 (if entry
10041 (setcdr entry set)
10042 (push (cons key set) org-refile-cache))))
10044 (defun org-refile-cache-get (&rest identifiers)
10045 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10046 (cond
10047 ((not org-refile-cache) nil)
10048 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10050 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10051 org-refile-cache))))
10052 (and set (org-refile-cache-check-set set) set)))))
10054 (defun org-refile-get-targets (&optional default-buffer)
10055 "Produce a table with refile targets."
10056 (let ((case-fold-search nil)
10057 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10058 (entries (or org-refile-targets '((nil . (:level . 1)))))
10059 targets tgs txt re files f desc descre fast-path-p level pos0)
10060 (message "Getting targets...")
10061 (with-current-buffer (or default-buffer (current-buffer))
10062 (while (setq entry (pop entries))
10063 (setq files (car entry) desc (cdr entry))
10064 (setq fast-path-p nil)
10065 (cond
10066 ((null files) (setq files (list (current-buffer))))
10067 ((eq files 'org-agenda-files)
10068 (setq files (org-agenda-files 'unrestricted)))
10069 ((and (symbolp files) (fboundp files))
10070 (setq files (funcall files)))
10071 ((and (symbolp files) (boundp files))
10072 (setq files (symbol-value files))))
10073 (if (stringp files) (setq files (list files)))
10074 (cond
10075 ((eq (car desc) :tag)
10076 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10077 ((eq (car desc) :todo)
10078 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10079 ((eq (car desc) :regexp)
10080 (setq descre (cdr desc)))
10081 ((eq (car desc) :level)
10082 (setq descre (concat "^\\*\\{" (number-to-string
10083 (if org-odd-levels-only
10084 (1- (* 2 (cdr desc)))
10085 (cdr desc)))
10086 "\\}[ \t]")))
10087 ((eq (car desc) :maxlevel)
10088 (setq fast-path-p t)
10089 (setq descre (concat "^\\*\\{1," (number-to-string
10090 (if org-odd-levels-only
10091 (1- (* 2 (cdr desc)))
10092 (cdr desc)))
10093 "\\}[ \t]")))
10094 (t (error "Bad refiling target description %s" desc)))
10095 (while (setq f (pop files))
10096 (with-current-buffer
10097 (if (bufferp f) f (org-get-agenda-file-buffer f))
10099 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10100 (progn
10101 (if (bufferp f) (setq f (buffer-file-name
10102 (buffer-base-buffer f))))
10103 (setq f (and f (expand-file-name f)))
10104 (if (eq org-refile-use-outline-path 'file)
10105 (push (list (file-name-nondirectory f) f nil nil) tgs))
10106 (save-excursion
10107 (save-restriction
10108 (widen)
10109 (goto-char (point-min))
10110 (while (re-search-forward descre nil t)
10111 (goto-char (setq pos0 (point-at-bol)))
10112 (catch 'next
10113 (when org-refile-target-verify-function
10114 (save-match-data
10115 (or (funcall org-refile-target-verify-function)
10116 (throw 'next t))))
10117 (when (looking-at org-complex-heading-regexp)
10118 (setq level (org-reduced-level
10119 (- (match-end 1) (match-beginning 1)))
10120 txt (org-link-display-format (match-string 4))
10121 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10122 re (format org-complex-heading-regexp-format
10123 (regexp-quote (match-string 4))))
10124 (when org-refile-use-outline-path
10125 (setq txt (mapconcat
10126 'org-protect-slash
10127 (append
10128 (if (eq org-refile-use-outline-path
10129 'file)
10130 (list (file-name-nondirectory
10131 (buffer-file-name
10132 (buffer-base-buffer))))
10133 (if (eq org-refile-use-outline-path
10134 'full-file-path)
10135 (list (buffer-file-name
10136 (buffer-base-buffer)))))
10137 (org-get-outline-path fast-path-p
10138 level txt)
10139 (list txt))
10140 "/")))
10141 (push (list txt f re (org-refile-marker (point)))
10142 tgs)))
10143 (when (= (point) pos0)
10144 ;; verification function has not moved point
10145 (goto-char (point-at-eol))))))))
10146 (when org-refile-use-cache
10147 (org-refile-cache-put tgs (buffer-file-name) descre))
10148 (setq targets (append tgs targets))
10149 ))))
10150 (message "Getting targets...done")
10151 (nreverse targets)))
10153 (defun org-protect-slash (s)
10154 (while (string-match "/" s)
10155 (setq s (replace-match "\\" t t s)))
10158 (defvar org-olpa (make-vector 20 nil))
10160 (defun org-get-outline-path (&optional fastp level heading)
10161 "Return the outline path to the current entry, as a list.
10163 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10164 routine which makes outline path derivations for an entire file,
10165 avoiding backtracing. Refile target collection makes use of that."
10166 (if fastp
10167 (progn
10168 (if (> level 19)
10169 (error "Outline path failure, more than 19 levels"))
10170 (loop for i from level upto 19 do
10171 (aset org-olpa i nil))
10172 (prog1
10173 (delq nil (append org-olpa nil))
10174 (aset org-olpa level heading)))
10175 (let (rtn case-fold-search)
10176 (save-excursion
10177 (save-restriction
10178 (widen)
10179 (while (org-up-heading-safe)
10180 (when (looking-at org-complex-heading-regexp)
10181 (push (org-match-string-no-properties 4) rtn)))
10182 rtn)))))
10184 (defun org-format-outline-path (path &optional width prefix)
10185 "Format the outline path PATH for display.
10186 Width is the maximum number of characters that is available.
10187 Prefix is a prefix to be included in the returned string,
10188 such as the file name."
10189 (setq width (or width 79))
10190 (if prefix (setq width (- width (length prefix))))
10191 (if (not path)
10192 (or prefix "")
10193 (let* ((nsteps (length path))
10194 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10195 (maxwidth (if (<= total-width width)
10196 10000 ;; everything fits
10197 ;; we need to shorten the level headings
10198 (/ (- width nsteps) nsteps)))
10199 (org-odd-levels-only nil)
10200 (n 0)
10201 (total (1+ (length prefix))))
10202 (setq maxwidth (max maxwidth 10))
10203 (concat prefix
10204 (mapconcat
10205 (lambda (h)
10206 (setq n (1+ n))
10207 (if (and (= n nsteps) (< maxwidth 10000))
10208 (setq maxwidth (- total-width total)))
10209 (if (< (length h) maxwidth)
10210 (progn (setq total (+ total (length h) 1)) h)
10211 (setq h (substring h 0 (- maxwidth 2))
10212 total (+ total maxwidth 1))
10213 (if (string-match "[ \t]+\\'" h)
10214 (setq h (substring h 0 (match-beginning 0))))
10215 (setq h (concat h "..")))
10216 (org-add-props h nil 'face
10217 (nth (% (1- n) org-n-level-faces)
10218 org-level-faces))
10220 path "/")))))
10222 (defun org-display-outline-path (&optional file current)
10223 "Display the current outline path in the echo area."
10224 (interactive "P")
10225 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10226 (case-fold-search nil)
10227 (path (and (org-mode-p) (org-get-outline-path))))
10228 (if current (setq path (append path
10229 (save-excursion
10230 (org-back-to-heading t)
10231 (if (looking-at org-complex-heading-regexp)
10232 (list (match-string 4)))))))
10233 (message "%s"
10234 (org-format-outline-path
10235 path
10236 (1- (frame-width))
10237 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10239 (defvar org-refile-history nil
10240 "History for refiling operations.")
10242 (defvar org-after-refile-insert-hook nil
10243 "Hook run after `org-refile' has inserted its stuff at the new location.
10244 Note that this is still *before* the stuff will be removed from
10245 the *old* location.")
10247 (defvar org-capture-last-stored-marker)
10248 (defun org-refile (&optional goto default-buffer rfloc)
10249 "Move the entry at point to another heading.
10250 The list of target headings is compiled using the information in
10251 `org-refile-targets', which see. This list is created before each use
10252 and will therefore always be up-to-date.
10254 At the target location, the entry is filed as a subitem of the target heading.
10255 Depending on `org-reverse-note-order', the new subitem will either be the
10256 first or the last subitem.
10258 If there is an active region, all entries in that region will be moved.
10259 However, the region must fulfill the requirement that the first heading
10260 is the first one sets the top-level of the moved text - at most siblings
10261 below it are allowed.
10263 With prefix arg GOTO, the command will only visit the target location,
10264 not actually move anything.
10265 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10266 go to the location where the last refiling
10267 operation has put the subtree.
10268 With a prefix argument of `2', refile to the running clock.
10270 RFLOC can be a refile location obtained in a different way.
10272 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10274 If you are using target caching (see `org-refile-use-cache'),
10275 You have to clear the target cache in order to find new targets.
10276 This can be done with a 0 prefix: `C-0 C-c C-w'"
10277 (interactive "P")
10278 (if (member goto '(0 (64)))
10279 (org-refile-cache-clear)
10280 (let* ((cbuf (current-buffer))
10281 (regionp (org-region-active-p))
10282 (region-start (and regionp (region-beginning)))
10283 (region-end (and regionp (region-end)))
10284 (region-length (and regionp (- region-end region-start)))
10285 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10286 pos it nbuf file re level reversed)
10287 (setq last-command nil)
10288 (when regionp
10289 (goto-char region-start)
10290 (or (bolp) (goto-char (point-at-bol)))
10291 (setq region-start (point))
10292 (unless (org-kill-is-subtree-p
10293 (buffer-substring region-start region-end))
10294 (error "The region is not a (sequence of) subtree(s)")))
10295 (if (equal goto '(16))
10296 (org-refile-goto-last-stored)
10297 (when (or
10298 (and (equal goto 2)
10299 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10300 (prog1
10301 (setq it (list (or org-clock-heading "running clock")
10302 (buffer-file-name
10303 (marker-buffer org-clock-hd-marker))
10305 (marker-position org-clock-hd-marker)))
10306 (setq goto nil)))
10307 (setq it (or rfloc
10308 (save-excursion
10309 (org-refile-get-location
10310 (if goto "Goto" "Refile to") default-buffer
10311 org-refile-allow-creating-parent-nodes)))))
10312 (setq file (nth 1 it)
10313 re (nth 2 it)
10314 pos (nth 3 it))
10315 (if (and (not goto)
10317 (equal (buffer-file-name) file)
10318 (if regionp
10319 (and (>= pos region-start)
10320 (<= pos region-end))
10321 (and (>= pos (point))
10322 (< pos (save-excursion
10323 (org-end-of-subtree t t))))))
10324 (error "Cannot refile to position inside the tree or region"))
10326 (setq nbuf (or (find-buffer-visiting file)
10327 (find-file-noselect file)))
10328 (if goto
10329 (progn
10330 (switch-to-buffer nbuf)
10331 (goto-char pos)
10332 (org-show-context 'org-goto))
10333 (if regionp
10334 (progn
10335 (org-kill-new (buffer-substring region-start region-end))
10336 (org-save-markers-in-region region-start region-end))
10337 (org-copy-subtree 1 nil t))
10338 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10339 (find-file-noselect file)))
10340 (setq reversed (org-notes-order-reversed-p))
10341 (save-excursion
10342 (save-restriction
10343 (widen)
10344 (if pos
10345 (progn
10346 (goto-char pos)
10347 (looking-at outline-regexp)
10348 (setq level (org-get-valid-level (funcall outline-level) 1))
10349 (goto-char
10350 (if reversed
10351 (or (outline-next-heading) (point-max))
10352 (or (save-excursion (org-get-next-sibling))
10353 (org-end-of-subtree t t)
10354 (point-max)))))
10355 (setq level 1)
10356 (if (not reversed)
10357 (goto-char (point-max))
10358 (goto-char (point-min))
10359 (or (outline-next-heading) (goto-char (point-max)))))
10360 (if (not (bolp)) (newline))
10361 (org-paste-subtree level)
10362 (when org-log-refile
10363 (org-add-log-setup 'refile nil nil 'findpos
10364 org-log-refile)
10365 (unless (eq org-log-refile 'note)
10366 (save-excursion (org-add-log-note))))
10367 (and org-auto-align-tags (org-set-tags nil t))
10368 (bookmark-set "org-refile-last-stored")
10369 ;; If we are refiling for capture, make sure that the
10370 ;; last-capture pointers point here
10371 (when (org-bound-and-true-p org-refile-for-capture)
10372 (bookmark-set "org-capture-last-stored-marker")
10373 (move-marker org-capture-last-stored-marker (point)))
10374 (if (fboundp 'deactivate-mark) (deactivate-mark))
10375 (run-hooks 'org-after-refile-insert-hook))))
10376 (if regionp
10377 (delete-region (point) (+ (point) region-length))
10378 (org-cut-subtree))
10379 (when (featurep 'org-inlinetask)
10380 (org-inlinetask-remove-END-maybe))
10381 (setq org-markers-to-move nil)
10382 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10384 (defun org-refile-goto-last-stored ()
10385 "Go to the location where the last refile was stored."
10386 (interactive)
10387 (bookmark-jump "org-refile-last-stored")
10388 (message "This is the location of the last refile"))
10390 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
10391 "Prompt the user for a refile location, using PROMPT.
10392 PROMPT should not be suffixed with a colon and a space, because
10393 this function appends the default value from
10394 `org-refile-history' automatically, if that is not empty."
10395 (let ((org-refile-targets org-refile-targets)
10396 (org-refile-use-outline-path org-refile-use-outline-path))
10397 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
10398 (unless org-refile-target-table
10399 (error "No refile targets"))
10400 (let* ((prompt (concat prompt
10401 (and (car org-refile-history)
10402 (concat " (default " (car org-refile-history) ")"))
10403 ": "))
10404 (cbuf (current-buffer))
10405 (partial-completion-mode nil)
10406 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10407 (cfunc (if (and org-refile-use-outline-path
10408 org-outline-path-complete-in-steps)
10409 'org-olpath-completing-read
10410 'org-icompleting-read))
10411 (extra (if org-refile-use-outline-path "/" ""))
10412 (filename (and cfn (expand-file-name cfn)))
10413 (tbl (mapcar
10414 (lambda (x)
10415 (if (and (not (member org-refile-use-outline-path
10416 '(file full-file-path)))
10417 (not (equal filename (nth 1 x))))
10418 (cons (concat (car x) extra " ("
10419 (file-name-nondirectory (nth 1 x)) ")")
10420 (cdr x))
10421 (cons (concat (car x) extra) (cdr x))))
10422 org-refile-target-table))
10423 (completion-ignore-case t)
10424 pa answ parent-target child parent old-hist)
10425 (setq old-hist org-refile-history)
10426 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10427 nil 'org-refile-history (car org-refile-history)))
10428 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10429 (org-refile-check-position pa)
10430 (if pa
10431 (progn
10432 (when (or (not org-refile-history)
10433 (not (eq old-hist org-refile-history))
10434 (not (equal (car pa) (car org-refile-history))))
10435 (setq org-refile-history
10436 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10437 org-refile-history
10438 (cdr org-refile-history))))
10439 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10440 (pop org-refile-history)))
10442 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10443 (progn
10444 (setq parent (match-string 1 answ)
10445 child (match-string 2 answ))
10446 (setq parent-target (or (assoc parent tbl)
10447 (assoc (concat parent "/") tbl)))
10448 (when (and parent-target
10449 (or (eq new-nodes t)
10450 (and (eq new-nodes 'confirm)
10451 (y-or-n-p (format "Create new node \"%s\"? "
10452 child)))))
10453 (org-refile-new-child parent-target child)))
10454 (error "Invalid target location")))))
10456 (defun org-refile-check-position (refile-pointer)
10457 "Check if the refile pointer matches the readline to which it points."
10458 (let* ((file (nth 1 refile-pointer))
10459 (re (nth 2 refile-pointer))
10460 (pos (nth 3 refile-pointer))
10461 buffer)
10462 (when (org-string-nw-p re)
10463 (setq buffer (if (markerp pos)
10464 (marker-buffer pos)
10465 (or (find-buffer-visiting file)
10466 (find-file-noselect file))))
10467 (with-current-buffer buffer
10468 (save-excursion
10469 (save-restriction
10470 (widen)
10471 (goto-char pos)
10472 (beginning-of-line 1)
10473 (unless (org-looking-at-p re)
10474 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10476 (defun org-refile-new-child (parent-target child)
10477 "Use refile target PARENT-TARGET to add new CHILD below it."
10478 (unless parent-target
10479 (error "Cannot find parent for new node"))
10480 (let ((file (nth 1 parent-target))
10481 (pos (nth 3 parent-target))
10482 level)
10483 (with-current-buffer (or (find-buffer-visiting file)
10484 (find-file-noselect file))
10485 (save-excursion
10486 (save-restriction
10487 (widen)
10488 (if pos
10489 (goto-char pos)
10490 (goto-char (point-max))
10491 (if (not (bolp)) (newline)))
10492 (when (looking-at outline-regexp)
10493 (setq level (funcall outline-level))
10494 (org-end-of-subtree t t))
10495 (org-back-over-empty-lines)
10496 (insert "\n" (make-string
10497 (if pos (org-get-valid-level level 1) 1) ?*)
10498 " " child "\n")
10499 (beginning-of-line 0)
10500 (list (concat (car parent-target) "/" child) file "" (point)))))))
10502 (defun org-olpath-completing-read (prompt collection &rest args)
10503 "Read an outline path like a file name."
10504 (let ((thetable collection)
10505 (org-completion-use-ido nil) ; does not work with ido.
10506 (org-completion-use-iswitchb nil)) ; or iswitchb
10507 (apply
10508 'org-icompleting-read prompt
10509 (lambda (string predicate &optional flag)
10510 (let (rtn r f (l (length string)))
10511 (cond
10512 ((eq flag nil)
10513 ;; try completion
10514 (try-completion string thetable))
10515 ((eq flag t)
10516 ;; all-completions
10517 (setq rtn (all-completions string thetable predicate))
10518 (mapcar
10519 (lambda (x)
10520 (setq r (substring x l))
10521 (if (string-match " ([^)]*)$" x)
10522 (setq f (match-string 0 x))
10523 (setq f ""))
10524 (if (string-match "/" r)
10525 (concat string (substring r 0 (match-end 0)) f)
10527 rtn))
10528 ((eq flag 'lambda)
10529 ;; exact match?
10530 (assoc string thetable)))
10532 args)))
10534 ;;;; Dynamic blocks
10536 (defun org-find-dblock (name)
10537 "Find the first dynamic block with name NAME in the buffer.
10538 If not found, stay at current position and return nil."
10539 (let (pos)
10540 (save-excursion
10541 (goto-char (point-min))
10542 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
10543 nil t)
10544 (match-beginning 0))))
10545 (if pos (goto-char pos))
10546 pos))
10548 (defconst org-dblock-start-re
10549 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10550 "Matches the start line of a dynamic block, with parameters.")
10552 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10553 "Matches the end of a dynamic block.")
10555 (defun org-create-dblock (plist)
10556 "Create a dynamic block section, with parameters taken from PLIST.
10557 PLIST must contain a :name entry which is used as name of the block."
10558 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10559 (end-of-line 1)
10560 (newline))
10561 (let ((col (current-column))
10562 (name (plist-get plist :name)))
10563 (insert "#+BEGIN: " name)
10564 (while plist
10565 (if (eq (car plist) :name)
10566 (setq plist (cddr plist))
10567 (insert " " (prin1-to-string (pop plist)))))
10568 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10569 (beginning-of-line -2)))
10571 (defun org-prepare-dblock ()
10572 "Prepare dynamic block for refresh.
10573 This empties the block, puts the cursor at the insert position and returns
10574 the property list including an extra property :name with the block name."
10575 (unless (looking-at org-dblock-start-re)
10576 (error "Not at a dynamic block"))
10577 (let* ((begdel (1+ (match-end 0)))
10578 (name (org-no-properties (match-string 1)))
10579 (params (append (list :name name)
10580 (read (concat "(" (match-string 3) ")")))))
10581 (save-excursion
10582 (beginning-of-line 1)
10583 (skip-chars-forward " \t")
10584 (setq params (plist-put params :indentation-column (current-column))))
10585 (unless (re-search-forward org-dblock-end-re nil t)
10586 (error "Dynamic block not terminated"))
10587 (setq params
10588 (append params
10589 (list :content (buffer-substring
10590 begdel (match-beginning 0)))))
10591 (delete-region begdel (match-beginning 0))
10592 (goto-char begdel)
10593 (open-line 1)
10594 params))
10596 (defun org-map-dblocks (&optional command)
10597 "Apply COMMAND to all dynamic blocks in the current buffer.
10598 If COMMAND is not given, use `org-update-dblock'."
10599 (let ((cmd (or command 'org-update-dblock)))
10600 (save-excursion
10601 (goto-char (point-min))
10602 (while (re-search-forward org-dblock-start-re nil t)
10603 (goto-char (match-beginning 0))
10604 (save-excursion
10605 (condition-case nil
10606 (funcall cmd)
10607 (error (message "Error during update of dynamic block"))))
10608 (unless (re-search-forward org-dblock-end-re nil t)
10609 (error "Dynamic block not terminated"))))))
10611 (defun org-dblock-update (&optional arg)
10612 "User command for updating dynamic blocks.
10613 Update the dynamic block at point. With prefix ARG, update all dynamic
10614 blocks in the buffer."
10615 (interactive "P")
10616 (if arg
10617 (org-update-all-dblocks)
10618 (or (looking-at org-dblock-start-re)
10619 (org-beginning-of-dblock))
10620 (org-update-dblock)))
10622 (defun org-update-dblock ()
10623 "Update the dynamic block at point.
10624 This means to empty the block, parse for parameters and then call
10625 the correct writing function."
10626 (interactive)
10627 (save-window-excursion
10628 (let* ((pos (point))
10629 (line (org-current-line))
10630 (params (org-prepare-dblock))
10631 (name (plist-get params :name))
10632 (indent (plist-get params :indentation-column))
10633 (cmd (intern (concat "org-dblock-write:" name))))
10634 (message "Updating dynamic block `%s' at line %d..." name line)
10635 (funcall cmd params)
10636 (message "Updating dynamic block `%s' at line %d...done" name line)
10637 (goto-char pos)
10638 (when (and indent (> indent 0))
10639 (setq indent (make-string indent ?\ ))
10640 (save-excursion
10641 (org-beginning-of-dblock)
10642 (forward-line 1)
10643 (while (not (looking-at org-dblock-end-re))
10644 (insert indent)
10645 (beginning-of-line 2))
10646 (when (looking-at org-dblock-end-re)
10647 (and (looking-at "[ \t]+")
10648 (replace-match ""))
10649 (insert indent)))))))
10651 (defun org-beginning-of-dblock ()
10652 "Find the beginning of the dynamic block at point.
10653 Error if there is no such block at point."
10654 (let ((pos (point))
10655 beg)
10656 (end-of-line 1)
10657 (if (and (re-search-backward org-dblock-start-re nil t)
10658 (setq beg (match-beginning 0))
10659 (re-search-forward org-dblock-end-re nil t)
10660 (> (match-end 0) pos))
10661 (goto-char beg)
10662 (goto-char pos)
10663 (error "Not in a dynamic block"))))
10665 (defun org-update-all-dblocks ()
10666 "Update all dynamic blocks in the buffer.
10667 This function can be used in a hook."
10668 (interactive)
10669 (when (org-mode-p)
10670 (org-map-dblocks 'org-update-dblock)))
10673 ;;;; Completion
10675 (defconst org-additional-option-like-keywords
10676 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
10677 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
10678 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
10679 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
10680 "BEGIN:" "END:"
10681 "ORGTBL" "TBLFM:" "TBLNAME:"
10682 "BEGIN_EXAMPLE" "END_EXAMPLE"
10683 "BEGIN_QUOTE" "END_QUOTE"
10684 "BEGIN_VERSE" "END_VERSE"
10685 "BEGIN_CENTER" "END_CENTER"
10686 "BEGIN_SRC" "END_SRC"
10687 "BEGIN_RESULT" "END_RESULT"
10688 "SOURCE:" "SRCNAME:" "FUNCTION:"
10689 "RESULTS:"
10690 "HEADER:" "HEADERS:"
10691 "BABEL:"
10692 "CATEGORY:" "COLUMNS:" "PROPERTY:"
10693 "CAPTION:" "LABEL:"
10694 "SETUPFILE:"
10695 "INCLUDE:"
10696 "BIND:"
10697 "MACRO:"))
10699 (defcustom org-structure-template-alist
10701 ("s" "#+begin_src ?\n\n#+end_src"
10702 "<src lang=\"?\">\n\n</src>")
10703 ("e" "#+begin_example\n?\n#+end_example"
10704 "<example>\n?\n</example>")
10705 ("q" "#+begin_quote\n?\n#+end_quote"
10706 "<quote>\n?\n</quote>")
10707 ("v" "#+begin_verse\n?\n#+end_verse"
10708 "<verse>\n?\n/verse>")
10709 ("c" "#+begin_center\n?\n#+end_center"
10710 "<center>\n?\n/center>")
10711 ("l" "#+begin_latex\n?\n#+end_latex"
10712 "<literal style=\"latex\">\n?\n</literal>")
10713 ("L" "#+latex: "
10714 "<literal style=\"latex\">?</literal>")
10715 ("h" "#+begin_html\n?\n#+end_html"
10716 "<literal style=\"html\">\n?\n</literal>")
10717 ("H" "#+html: "
10718 "<literal style=\"html\">?</literal>")
10719 ("a" "#+begin_ascii\n?\n#+end_ascii")
10720 ("A" "#+ascii: ")
10721 ("i" "#+include %file ?"
10722 "<include file=%file markup=\"?\">")
10724 "Structure completion elements.
10725 This is a list of abbreviation keys and values. The value gets inserted
10726 if you type `<' followed by the key and then press the completion key,
10727 usually `M-TAB'. %file will be replaced by a file name after prompting
10728 for the file using completion.
10729 There are two templates for each key, the first uses the original Org syntax,
10730 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
10731 the default when the /org-mtags.el/ module has been loaded. See also the
10732 variable `org-mtags-prefer-muse-templates'.
10733 This is an experimental feature, it is undecided if it is going to stay in."
10734 :group 'org-completion
10735 :type '(repeat
10736 (string :tag "Key")
10737 (string :tag "Template")
10738 (string :tag "Muse Template")))
10740 (defun org-try-structure-completion ()
10741 "Try to complete a structure template before point.
10742 This looks for strings like \"<e\" on an otherwise empty line and
10743 expands them."
10744 (let ((l (buffer-substring (point-at-bol) (point)))
10746 (when (and (looking-at "[ \t]*$")
10747 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
10748 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
10749 (org-complete-expand-structure-template (+ -1 (point-at-bol)
10750 (match-beginning 1)) a)
10751 t)))
10753 (defun org-complete-expand-structure-template (start cell)
10754 "Expand a structure template."
10755 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
10756 (rpl (nth (if musep 2 1) cell))
10757 (ind ""))
10758 (delete-region start (point))
10759 (when (string-match "\\`#\\+" rpl)
10760 (cond
10761 ((bolp))
10762 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
10763 (setq ind (buffer-substring (point-at-bol) (point))))
10764 (t (newline))))
10765 (setq start (point))
10766 (if (string-match "%file" rpl)
10767 (setq rpl (replace-match
10768 (concat
10769 "\""
10770 (save-match-data
10771 (abbreviate-file-name (read-file-name "Include file: ")))
10772 "\"")
10773 t t rpl)))
10774 (setq rpl (mapconcat 'identity (split-string rpl "\n")
10775 (concat "\n" ind)))
10776 (insert rpl)
10777 (if (re-search-backward "\\?" start t) (delete-char 1))))
10779 ;;;; TODO, DEADLINE, Comments
10781 (defun org-toggle-comment ()
10782 "Change the COMMENT state of an entry."
10783 (interactive)
10784 (save-excursion
10785 (org-back-to-heading)
10786 (let (case-fold-search)
10787 (if (looking-at (concat outline-regexp
10788 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10789 (replace-match "" t t nil 1)
10790 (if (looking-at outline-regexp)
10791 (progn
10792 (goto-char (match-end 0))
10793 (insert org-comment-string " ")))))))
10795 (defvar org-last-todo-state-is-todo nil
10796 "This is non-nil when the last TODO state change led to a TODO state.
10797 If the last change removed the TODO tag or switched to DONE, then
10798 this is nil.")
10800 (defvar org-setting-tags nil) ; dynamically skipped
10802 (defvar org-todo-setup-filter-hook nil
10803 "Hook for functions that pre-filter todo specs.
10804 Each function takes a todo spec and returns either nil or the spec
10805 transformed into canonical form." )
10807 (defvar org-todo-get-default-hook nil
10808 "Hook for functions that get a default item for todo.
10809 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
10810 nil or a string to be used for the todo mark." )
10812 (defvar org-agenda-headline-snapshot-before-repeat)
10814 (defun org-todo (&optional arg)
10815 "Change the TODO state of an item.
10816 The state of an item is given by a keyword at the start of the heading,
10817 like
10818 *** TODO Write paper
10819 *** DONE Call mom
10821 The different keywords are specified in the variable `org-todo-keywords'.
10822 By default the available states are \"TODO\" and \"DONE\".
10823 So for this example: when the item starts with TODO, it is changed to DONE.
10824 When it starts with DONE, the DONE is removed. And when neither TODO nor
10825 DONE are present, add TODO at the beginning of the heading.
10827 With \\[universal-argument] prefix arg, use completion to determine the new \
10828 state.
10829 With numeric prefix arg, switch to that state.
10830 With a double \\[universal-argument] prefix, switch to the next set of TODO \
10831 keywords (nextset).
10832 With a triple \\[universal-argument] prefix, circumvent any state blocking.
10834 For calling through lisp, arg is also interpreted in the following way:
10835 'none -> empty state
10836 \"\"(empty string) -> switch to empty state
10837 'done -> switch to DONE
10838 'nextset -> switch to the next set of keywords
10839 'previousset -> switch to the previous set of keywords
10840 \"WAITING\" -> switch to the specified keyword, but only if it
10841 really is a member of `org-todo-keywords'."
10842 (interactive "P")
10843 (if (equal arg '(16)) (setq arg 'nextset))
10844 (let ((org-blocker-hook org-blocker-hook)
10845 (case-fold-search nil))
10846 (when (equal arg '(64))
10847 (setq arg nil org-blocker-hook nil))
10848 (when (and org-blocker-hook
10849 (or org-inhibit-blocking
10850 (org-entry-get nil "NOBLOCKING")))
10851 (setq org-blocker-hook nil))
10852 (save-excursion
10853 (catch 'exit
10854 (org-back-to-heading t)
10855 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
10856 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
10857 (looking-at " *"))
10858 (let* ((match-data (match-data))
10859 (startpos (point-at-bol))
10860 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
10861 (org-log-done org-log-done)
10862 (org-log-repeat org-log-repeat)
10863 (org-todo-log-states org-todo-log-states)
10864 (this (match-string 1))
10865 (hl-pos (match-beginning 0))
10866 (head (org-get-todo-sequence-head this))
10867 (ass (assoc head org-todo-kwd-alist))
10868 (interpret (nth 1 ass))
10869 (done-word (nth 3 ass))
10870 (final-done-word (nth 4 ass))
10871 (last-state (or this ""))
10872 (completion-ignore-case t)
10873 (member (member this org-todo-keywords-1))
10874 (tail (cdr member))
10875 (state (cond
10876 ((and org-todo-key-trigger
10877 (or (and (equal arg '(4))
10878 (eq org-use-fast-todo-selection 'prefix))
10879 (and (not arg) org-use-fast-todo-selection
10880 (not (eq org-use-fast-todo-selection
10881 'prefix)))))
10882 ;; Use fast selection
10883 (org-fast-todo-selection))
10884 ((and (equal arg '(4))
10885 (or (not org-use-fast-todo-selection)
10886 (not org-todo-key-trigger)))
10887 ;; Read a state with completion
10888 (org-icompleting-read
10889 "State: " (mapcar (lambda(x) (list x))
10890 org-todo-keywords-1)
10891 nil t))
10892 ((eq arg 'right)
10893 (if this
10894 (if tail (car tail) nil)
10895 (car org-todo-keywords-1)))
10896 ((eq arg 'left)
10897 (if (equal member org-todo-keywords-1)
10899 (if this
10900 (nth (- (length org-todo-keywords-1)
10901 (length tail) 2)
10902 org-todo-keywords-1)
10903 (org-last org-todo-keywords-1))))
10904 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10905 (setq arg nil))) ; hack to fall back to cycling
10906 (arg
10907 ;; user or caller requests a specific state
10908 (cond
10909 ((equal arg "") nil)
10910 ((eq arg 'none) nil)
10911 ((eq arg 'done) (or done-word (car org-done-keywords)))
10912 ((eq arg 'nextset)
10913 (or (car (cdr (member head org-todo-heads)))
10914 (car org-todo-heads)))
10915 ((eq arg 'previousset)
10916 (let ((org-todo-heads (reverse org-todo-heads)))
10917 (or (car (cdr (member head org-todo-heads)))
10918 (car org-todo-heads))))
10919 ((car (member arg org-todo-keywords-1)))
10920 ((stringp arg)
10921 (error "State `%s' not valid in this file" arg))
10922 ((nth (1- (prefix-numeric-value arg))
10923 org-todo-keywords-1))))
10924 ((null member) (or head (car org-todo-keywords-1)))
10925 ((equal this final-done-word) nil) ;; -> make empty
10926 ((null tail) nil) ;; -> first entry
10927 ((memq interpret '(type priority))
10928 (if (eq this-command last-command)
10929 (car tail)
10930 (if (> (length tail) 0)
10931 (or done-word (car org-done-keywords))
10932 nil)))
10934 (car tail))))
10935 (state (or
10936 (run-hook-with-args-until-success
10937 'org-todo-get-default-hook state last-state)
10938 state))
10939 (next (if state (concat " " state " ") " "))
10940 (change-plist (list :type 'todo-state-change :from this :to state
10941 :position startpos))
10942 dolog now-done-p)
10943 (when org-blocker-hook
10944 (setq org-last-todo-state-is-todo
10945 (not (member this org-done-keywords)))
10946 (unless (save-excursion
10947 (save-match-data
10948 (org-with-wide-buffer
10949 (run-hook-with-args-until-failure
10950 'org-blocker-hook change-plist))))
10951 (if (interactive-p)
10952 (error "TODO state change from %s to %s blocked" this state)
10953 ;; fail silently
10954 (message "TODO state change from %s to %s blocked" this state)
10955 (throw 'exit nil))))
10956 (store-match-data match-data)
10957 (replace-match next t t)
10958 (unless (pos-visible-in-window-p hl-pos)
10959 (message "TODO state changed to %s" (org-trim next)))
10960 (unless head
10961 (setq head (org-get-todo-sequence-head state)
10962 ass (assoc head org-todo-kwd-alist)
10963 interpret (nth 1 ass)
10964 done-word (nth 3 ass)
10965 final-done-word (nth 4 ass)))
10966 (when (memq arg '(nextset previousset))
10967 (message "Keyword-Set %d/%d: %s"
10968 (- (length org-todo-sets) -1
10969 (length (memq (assoc state org-todo-sets) org-todo-sets)))
10970 (length org-todo-sets)
10971 (mapconcat 'identity (assoc state org-todo-sets) " ")))
10972 (setq org-last-todo-state-is-todo
10973 (not (member state org-done-keywords)))
10974 (setq now-done-p (and (member state org-done-keywords)
10975 (not (member this org-done-keywords))))
10976 (and logging (org-local-logging logging))
10977 (when (and (or org-todo-log-states org-log-done)
10978 (not (eq org-inhibit-logging t))
10979 (not (memq arg '(nextset previousset))))
10980 ;; we need to look at recording a time and note
10981 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
10982 (nth 2 (assoc this org-todo-log-states))))
10983 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
10984 (setq dolog 'time))
10985 (when (and state
10986 (member state org-not-done-keywords)
10987 (not (member this org-not-done-keywords)))
10988 ;; This is now a todo state and was not one before
10989 ;; If there was a CLOSED time stamp, get rid of it.
10990 (org-add-planning-info nil nil 'closed))
10991 (when (and now-done-p org-log-done)
10992 ;; It is now done, and it was not done before
10993 (org-add-planning-info 'closed (org-current-time))
10994 (if (and (not dolog) (eq 'note org-log-done))
10995 (org-add-log-setup 'done state this 'findpos 'note)))
10996 (when (and state dolog)
10997 ;; This is a non-nil state, and we need to log it
10998 (org-add-log-setup 'state state this 'findpos dolog)))
10999 ;; Fixup tag positioning
11000 (org-todo-trigger-tag-changes state)
11001 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11002 (when org-provide-todo-statistics
11003 (org-update-parent-todo-statistics))
11004 (run-hooks 'org-after-todo-state-change-hook)
11005 (if (and arg (not (member state org-done-keywords)))
11006 (setq head (org-get-todo-sequence-head state)))
11007 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11008 ;; Do we need to trigger a repeat?
11009 (when now-done-p
11010 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11011 ;; This is for the agenda, take a snapshot of the headline.
11012 (save-match-data
11013 (setq org-agenda-headline-snapshot-before-repeat
11014 (org-get-heading))))
11015 (org-auto-repeat-maybe state))
11016 ;; Fixup cursor location if close to the keyword
11017 (if (and (outline-on-heading-p)
11018 (not (bolp))
11019 (save-excursion (beginning-of-line 1)
11020 (looking-at org-todo-line-regexp))
11021 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11022 (progn
11023 (goto-char (or (match-end 2) (match-end 1)))
11024 (and (looking-at " ") (just-one-space))))
11025 (when org-trigger-hook
11026 (save-excursion
11027 (run-hook-with-args 'org-trigger-hook change-plist))))))))
11029 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11030 "Block turning an entry into a TODO, using the hierarchy.
11031 This checks whether the current task should be blocked from state
11032 changes. Such blocking occurs when:
11034 1. The task has children which are not all in a completed state.
11036 2. A task has a parent with the property :ORDERED:, and there
11037 are siblings prior to the current task with incomplete
11038 status.
11040 3. The parent of the task is blocked because it has siblings that should
11041 be done first, or is child of a block grandparent TODO entry."
11043 (if (not org-enforce-todo-dependencies)
11044 t ; if locally turned off don't block
11045 (catch 'dont-block
11046 ;; If this is not a todo state change, or if this entry is already DONE,
11047 ;; do not block
11048 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11049 (member (plist-get change-plist :from)
11050 (cons 'done org-done-keywords))
11051 (member (plist-get change-plist :to)
11052 (cons 'todo org-not-done-keywords))
11053 (not (plist-get change-plist :to)))
11054 (throw 'dont-block t))
11055 ;; If this task has children, and any are undone, it's blocked
11056 (save-excursion
11057 (org-back-to-heading t)
11058 (let ((this-level (funcall outline-level)))
11059 (outline-next-heading)
11060 (let ((child-level (funcall outline-level)))
11061 (while (and (not (eobp))
11062 (> child-level this-level))
11063 ;; this todo has children, check whether they are all
11064 ;; completed
11065 (if (and (not (org-entry-is-done-p))
11066 (org-entry-is-todo-p))
11067 (throw 'dont-block nil))
11068 (outline-next-heading)
11069 (setq child-level (funcall outline-level))))))
11070 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11071 ;; any previous siblings are undone, it's blocked
11072 (save-excursion
11073 (org-back-to-heading t)
11074 (let* ((pos (point))
11075 (parent-pos (and (org-up-heading-safe) (point))))
11076 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11077 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11078 (forward-line 1)
11079 (re-search-forward org-not-done-heading-regexp pos t))
11080 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11081 ;; Search further up the hierarchy, to see if an anchestor is blocked
11082 (while t
11083 (goto-char parent-pos)
11084 (if (not (looking-at org-not-done-heading-regexp))
11085 (throw 'dont-block t)) ; do not block, parent is not a TODO
11086 (setq pos (point))
11087 (setq parent-pos (and (org-up-heading-safe) (point)))
11088 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11089 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11090 (forward-line 1)
11091 (re-search-forward org-not-done-heading-regexp pos t))
11092 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11094 (defcustom org-track-ordered-property-with-tag nil
11095 "Should the ORDERED property also be shown as a tag?
11096 The ORDERED property decides if an entry should require subtasks to be
11097 completed in sequence. Since a property is not very visible, setting
11098 this option means that toggling the ORDERED property with the command
11099 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11100 not relevant for the behavior, but it makes things more visible.
11102 Note that toggling the tag with tags commands will not change the property
11103 and therefore not influence behavior!
11105 This can be t, meaning the tag ORDERED should be used, It can also be a
11106 string to select a different tag for this task."
11107 :group 'org-todo
11108 :type '(choice
11109 (const :tag "No tracking" nil)
11110 (const :tag "Track with ORDERED tag" t)
11111 (string :tag "Use other tag")))
11113 (defun org-toggle-ordered-property ()
11114 "Toggle the ORDERED property of the current entry.
11115 For better visibility, you can track the value of this property with a tag.
11116 See variable `org-track-ordered-property-with-tag'."
11117 (interactive)
11118 (let* ((t1 org-track-ordered-property-with-tag)
11119 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11120 (save-excursion
11121 (org-back-to-heading)
11122 (if (org-entry-get nil "ORDERED")
11123 (progn
11124 (org-delete-property "ORDERED")
11125 (and tag (org-toggle-tag tag 'off))
11126 (message "Subtasks can be completed in arbitrary order"))
11127 (org-entry-put nil "ORDERED" "t")
11128 (and tag (org-toggle-tag tag 'on))
11129 (message "Subtasks must be completed in sequence")))))
11131 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11132 (defun org-block-todo-from-checkboxes (change-plist)
11133 "Block turning an entry into a TODO, using checkboxes.
11134 This checks whether the current task should be blocked from state
11135 changes because there are unchecked boxes in this entry."
11136 (if (not org-enforce-todo-checkbox-dependencies)
11137 t ; if locally turned off don't block
11138 (catch 'dont-block
11139 ;; If this is not a todo state change, or if this entry is already DONE,
11140 ;; do not block
11141 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11142 (member (plist-get change-plist :from)
11143 (cons 'done org-done-keywords))
11144 (member (plist-get change-plist :to)
11145 (cons 'todo org-not-done-keywords))
11146 (not (plist-get change-plist :to)))
11147 (throw 'dont-block t))
11148 ;; If this task has checkboxes that are not checked, it's blocked
11149 (save-excursion
11150 (org-back-to-heading t)
11151 (let ((beg (point)) end)
11152 (outline-next-heading)
11153 (setq end (point))
11154 (goto-char beg)
11155 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
11156 end t)
11157 (progn
11158 (if (boundp 'org-blocked-by-checkboxes)
11159 (setq org-blocked-by-checkboxes t))
11160 (throw 'dont-block nil)))))
11161 t))) ; do not block
11163 (defun org-entry-blocked-p ()
11164 "Is the current entry blocked?"
11165 (if (org-entry-get nil "NOBLOCKING")
11166 nil ;; Never block this entry
11167 (not
11168 (run-hook-with-args-until-failure
11169 'org-blocker-hook
11170 (list :type 'todo-state-change
11171 :position (point)
11172 :from 'todo
11173 :to 'done)))))
11175 (defun org-update-statistics-cookies (all)
11176 "Update the statistics cookie, either from TODO or from checkboxes.
11177 This should be called with the cursor in a line with a statistics cookie."
11178 (interactive "P")
11179 (if all
11180 (progn
11181 (org-update-checkbox-count 'all)
11182 (org-map-entries 'org-update-parent-todo-statistics))
11183 (if (not (org-on-heading-p))
11184 (org-update-checkbox-count)
11185 (let ((pos (move-marker (make-marker) (point)))
11186 end l1 l2)
11187 (ignore-errors (org-back-to-heading t))
11188 (if (not (org-on-heading-p))
11189 (org-update-checkbox-count)
11190 (setq l1 (org-outline-level))
11191 (setq end (save-excursion
11192 (outline-next-heading)
11193 (if (org-on-heading-p) (setq l2 (org-outline-level)))
11194 (point)))
11195 (if (and (save-excursion
11196 (re-search-forward
11197 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11198 (not (save-excursion (re-search-forward
11199 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11200 (org-update-checkbox-count)
11201 (if (and l2 (> l2 l1))
11202 (progn
11203 (goto-char end)
11204 (org-update-parent-todo-statistics))
11205 (goto-char pos)
11206 (beginning-of-line 1)
11207 (while (re-search-forward
11208 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11209 (point-at-eol) t)
11210 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11211 (goto-char pos)
11212 (move-marker pos nil)))))
11214 (defvar org-entry-property-inherited-from) ;; defined below
11215 (defun org-update-parent-todo-statistics ()
11216 "Update any statistics cookie in the parent of the current headline.
11217 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11218 the entire subtree and this will travel up the hierarchy and update
11219 statistics everywhere."
11220 (interactive)
11221 (let* ((lim 0) prop
11222 (recursive (or (not org-hierarchical-todo-statistics)
11223 (string-match
11224 "\\<recursive\\>"
11225 (or (setq prop (org-entry-get
11226 nil "COOKIE_DATA" 'inherit)) ""))))
11227 (lim (or (and prop (marker-position
11228 org-entry-property-inherited-from))
11229 lim))
11230 (first t)
11231 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11232 level ltoggle l1 new ndel
11233 (cnt-all 0) (cnt-done 0) is-percent kwd
11234 checkbox-beg ov ovs ove cookie-present)
11235 (catch 'exit
11236 (save-excursion
11237 (beginning-of-line 1)
11238 (if (org-at-heading-p)
11239 (setq ltoggle (funcall outline-level))
11240 (error "This should not happen"))
11241 (while (and (setq level (org-up-heading-safe))
11242 (or recursive first)
11243 (>= (point) lim))
11244 (setq first nil cookie-present nil)
11245 (unless (and level
11246 (not (string-match
11247 "\\<checkbox\\>"
11248 (downcase
11249 (or (org-entry-get
11250 nil "COOKIE_DATA")
11251 "")))))
11252 (throw 'exit nil))
11253 (while (re-search-forward box-re (point-at-eol) t)
11254 (setq cnt-all 0 cnt-done 0 cookie-present t)
11255 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11256 (save-match-data
11257 (unless (outline-next-heading) (throw 'exit nil))
11258 (while (and (looking-at org-complex-heading-regexp)
11259 (> (setq l1 (length (match-string 1))) level))
11260 (setq kwd (and (or recursive (= l1 ltoggle))
11261 (match-string 2)))
11262 (if (or (eq org-provide-todo-statistics 'all-headlines)
11263 (and (listp org-provide-todo-statistics)
11264 (or (member kwd org-provide-todo-statistics)
11265 (member kwd org-done-keywords))))
11266 (setq cnt-all (1+ cnt-all))
11267 (if (eq org-provide-todo-statistics t)
11268 (and kwd (setq cnt-all (1+ cnt-all)))))
11269 (and (member kwd org-done-keywords)
11270 (setq cnt-done (1+ cnt-done)))
11271 (outline-next-heading)))
11272 (setq new
11273 (if is-percent
11274 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11275 (format "[%d/%d]" cnt-done cnt-all))
11276 ndel (- (match-end 0) checkbox-beg))
11277 ;; handle overlays when updating cookie from column view
11278 (when (setq ov (car (overlays-at checkbox-beg)))
11279 (setq ovs (overlay-start ov) ove (overlay-end ov))
11280 (delete-overlay ov))
11281 (goto-char checkbox-beg)
11282 (insert new)
11283 (delete-region (point) (+ (point) ndel))
11284 (when ov (move-overlay ov ovs ove)))
11285 (when cookie-present
11286 (run-hook-with-args 'org-after-todo-statistics-hook
11287 cnt-done (- cnt-all cnt-done))))))
11288 (run-hooks 'org-todo-statistics-hook)))
11290 (defvar org-after-todo-statistics-hook nil
11291 "Hook that is called after a TODO statistics cookie has been updated.
11292 Each function is called with two arguments: the number of not-done entries
11293 and the number of done entries.
11295 For example, the following function, when added to this hook, will switch
11296 an entry to DONE when all children are done, and back to TODO when new
11297 entries are set to a TODO status. Note that this hook is only called
11298 when there is a statistics cookie in the headline!
11300 (defun org-summary-todo (n-done n-not-done)
11301 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11302 (let (org-log-done org-log-states) ; turn off logging
11303 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11306 (defvar org-todo-statistics-hook nil
11307 "Hook that is run whenever Org thinks TODO statistics should be updated.
11308 This hook runs even if there is no statistics cookie present, in which case
11309 `org-after-todo-statistics-hook' would not run.")
11311 (defun org-todo-trigger-tag-changes (state)
11312 "Apply the changes defined in `org-todo-state-tags-triggers'."
11313 (let ((l org-todo-state-tags-triggers)
11314 changes)
11315 (when (or (not state) (equal state ""))
11316 (setq changes (append changes (cdr (assoc "" l)))))
11317 (when (and (stringp state) (> (length state) 0))
11318 (setq changes (append changes (cdr (assoc state l)))))
11319 (when (member state org-not-done-keywords)
11320 (setq changes (append changes (cdr (assoc 'todo l)))))
11321 (when (member state org-done-keywords)
11322 (setq changes (append changes (cdr (assoc 'done l)))))
11323 (dolist (c changes)
11324 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11326 (defun org-local-logging (value)
11327 "Get logging settings from a property VALUE."
11328 (let* (words w a)
11329 ;; directly set the variables, they are already local.
11330 (setq org-log-done nil
11331 org-log-repeat nil
11332 org-todo-log-states nil)
11333 (setq words (org-split-string value))
11334 (while (setq w (pop words))
11335 (cond
11336 ((setq a (assoc w org-startup-options))
11337 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11338 (set (nth 1 a) (nth 2 a))))
11339 ((setq a (org-extract-log-state-settings w))
11340 (and (member (car a) org-todo-keywords-1)
11341 (push a org-todo-log-states)))))))
11343 (defun org-get-todo-sequence-head (kwd)
11344 "Return the head of the TODO sequence to which KWD belongs.
11345 If KWD is not set, check if there is a text property remembering the
11346 right sequence."
11347 (let (p)
11348 (cond
11349 ((not kwd)
11350 (or (get-text-property (point-at-bol) 'org-todo-head)
11351 (progn
11352 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11353 nil (point-at-eol)))
11354 (get-text-property p 'org-todo-head))))
11355 ((not (member kwd org-todo-keywords-1))
11356 (car org-todo-keywords-1))
11357 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11359 (defun org-fast-todo-selection ()
11360 "Fast TODO keyword selection with single keys.
11361 Returns the new TODO keyword, or nil if no state change should occur."
11362 (let* ((fulltable org-todo-key-alist)
11363 (done-keywords org-done-keywords) ;; needed for the faces.
11364 (maxlen (apply 'max (mapcar
11365 (lambda (x)
11366 (if (stringp (car x)) (string-width (car x)) 0))
11367 fulltable)))
11368 (expert nil)
11369 (fwidth (+ maxlen 3 1 3))
11370 (ncol (/ (- (window-width) 4) fwidth))
11371 tg cnt e c tbl
11372 groups ingroup)
11373 (save-excursion
11374 (save-window-excursion
11375 (if expert
11376 (set-buffer (get-buffer-create " *Org todo*"))
11377 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11378 (erase-buffer)
11379 (org-set-local 'org-done-keywords done-keywords)
11380 (setq tbl fulltable cnt 0)
11381 (while (setq e (pop tbl))
11382 (cond
11383 ((equal e '(:startgroup))
11384 (push '() groups) (setq ingroup t)
11385 (when (not (= cnt 0))
11386 (setq cnt 0)
11387 (insert "\n"))
11388 (insert "{ "))
11389 ((equal e '(:endgroup))
11390 (setq ingroup nil cnt 0)
11391 (insert "}\n"))
11392 ((equal e '(:newline))
11393 (when (not (= cnt 0))
11394 (setq cnt 0)
11395 (insert "\n")
11396 (setq e (car tbl))
11397 (while (equal (car tbl) '(:newline))
11398 (insert "\n")
11399 (setq tbl (cdr tbl)))))
11401 (setq tg (car e) c (cdr e))
11402 (if ingroup (push tg (car groups)))
11403 (setq tg (org-add-props tg nil 'face
11404 (org-get-todo-face tg)))
11405 (if (and (= cnt 0) (not ingroup)) (insert " "))
11406 (insert "[" c "] " tg (make-string
11407 (- fwidth 4 (length tg)) ?\ ))
11408 (when (= (setq cnt (1+ cnt)) ncol)
11409 (insert "\n")
11410 (if ingroup (insert " "))
11411 (setq cnt 0)))))
11412 (insert "\n")
11413 (goto-char (point-min))
11414 (if (not expert) (org-fit-window-to-buffer))
11415 (message "[a-z..]:Set [SPC]:clear")
11416 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11417 (cond
11418 ((or (= c ?\C-g)
11419 (and (= c ?q) (not (rassoc c fulltable))))
11420 (setq quit-flag t))
11421 ((= c ?\ ) nil)
11422 ((setq e (rassoc c fulltable) tg (car e))
11424 (t (setq quit-flag t)))))))
11426 (defun org-entry-is-todo-p ()
11427 (member (org-get-todo-state) org-not-done-keywords))
11429 (defun org-entry-is-done-p ()
11430 (member (org-get-todo-state) org-done-keywords))
11432 (defun org-get-todo-state ()
11433 (save-excursion
11434 (org-back-to-heading t)
11435 (and (looking-at org-todo-line-regexp)
11436 (match-end 2)
11437 (match-string 2))))
11439 (defun org-at-date-range-p (&optional inactive-ok)
11440 "Is the cursor inside a date range?"
11441 (interactive)
11442 (save-excursion
11443 (catch 'exit
11444 (let ((pos (point)))
11445 (skip-chars-backward "^[<\r\n")
11446 (skip-chars-backward "<[")
11447 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11448 (>= (match-end 0) pos)
11449 (throw 'exit t))
11450 (skip-chars-backward "^<[\r\n")
11451 (skip-chars-backward "<[")
11452 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11453 (>= (match-end 0) pos)
11454 (throw 'exit t)))
11455 nil)))
11457 (defun org-get-repeat (&optional tagline)
11458 "Check if there is a deadline/schedule with repeater in this entry."
11459 (save-match-data
11460 (save-excursion
11461 (org-back-to-heading t)
11462 (and (re-search-forward (if tagline
11463 (concat tagline "\\s-*" org-repeat-re)
11464 org-repeat-re)
11465 (org-entry-end-position) t)
11466 (match-string-no-properties 1)))))
11468 (defvar org-last-changed-timestamp)
11469 (defvar org-last-inserted-timestamp)
11470 (defvar org-log-post-message)
11471 (defvar org-log-note-purpose)
11472 (defvar org-log-note-how)
11473 (defvar org-log-note-extra)
11474 (defun org-auto-repeat-maybe (done-word)
11475 "Check if the current headline contains a repeated deadline/schedule.
11476 If yes, set TODO state back to what it was and change the base date
11477 of repeating deadline/scheduled time stamps to new date.
11478 This function is run automatically after each state change to a DONE state."
11479 ;; last-state is dynamically scoped into this function
11480 (let* ((repeat (org-get-repeat))
11481 (aa (assoc last-state org-todo-kwd-alist))
11482 (interpret (nth 1 aa))
11483 (head (nth 2 aa))
11484 (whata '(("d" . day) ("m" . month) ("y" . year)))
11485 (msg "Entry repeats: ")
11486 (org-log-done nil)
11487 (org-todo-log-states nil)
11488 re type n what ts time to-state)
11489 (when repeat
11490 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11491 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11492 org-todo-repeat-to-state))
11493 (unless (and to-state (member to-state org-todo-keywords-1))
11494 (setq to-state (if (eq interpret 'type) last-state head)))
11495 (org-todo to-state)
11496 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11497 (org-entry-put nil "LAST_REPEAT" (format-time-string
11498 (org-time-stamp-format t t))))
11499 (when org-log-repeat
11500 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11501 (memq 'org-add-log-note post-command-hook))
11502 ;; OK, we are already setup for some record
11503 (if (eq org-log-repeat 'note)
11504 ;; make sure we take a note, not only a time stamp
11505 (setq org-log-note-how 'note))
11506 ;; Set up for taking a record
11507 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11508 last-state
11509 'findpos org-log-repeat)))
11510 (org-back-to-heading t)
11511 (org-add-planning-info nil nil 'closed)
11512 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11513 org-deadline-time-regexp "\\)\\|\\("
11514 org-ts-regexp "\\)"))
11515 (while (re-search-forward
11516 re (save-excursion (outline-next-heading) (point)) t)
11517 (setq type (if (match-end 1) org-scheduled-string
11518 (if (match-end 3) org-deadline-string "Plain:"))
11519 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11520 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11521 (setq n (string-to-number (match-string 2 ts))
11522 what (match-string 3 ts))
11523 (if (equal what "w") (setq n (* n 7) what "d"))
11524 ;; Preparation, see if we need to modify the start date for the change
11525 (when (match-end 1)
11526 (setq time (save-match-data (org-time-string-to-time ts)))
11527 (cond
11528 ((equal (match-string 1 ts) ".")
11529 ;; Shift starting date to today
11530 (org-timestamp-change
11531 (- (time-to-days (current-time)) (time-to-days time))
11532 'day))
11533 ((equal (match-string 1 ts) "+")
11534 (let ((nshiftmax 10) (nshift 0))
11535 (while (or (= nshift 0)
11536 (<= (time-to-days time)
11537 (time-to-days (current-time))))
11538 (when (= (incf nshift) nshiftmax)
11539 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11540 (error "Abort")))
11541 (org-timestamp-change n (cdr (assoc what whata)))
11542 (org-at-timestamp-p t)
11543 (setq ts (match-string 1))
11544 (setq time (save-match-data (org-time-string-to-time ts)))))
11545 (org-timestamp-change (- n) (cdr (assoc what whata)))
11546 ;; rematch, so that we have everything in place for the real shift
11547 (org-at-timestamp-p t)
11548 (setq ts (match-string 1))
11549 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11550 (org-timestamp-change n (cdr (assoc what whata)))
11551 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11552 (setq org-log-post-message msg)
11553 (message "%s" msg))))
11555 (defun org-show-todo-tree (arg)
11556 "Make a compact tree which shows all headlines marked with TODO.
11557 The tree will show the lines where the regexp matches, and all higher
11558 headlines above the match.
11559 With a \\[universal-argument] prefix, prompt for a regexp to match.
11560 With a numeric prefix N, construct a sparse tree for the Nth element
11561 of `org-todo-keywords-1'."
11562 (interactive "P")
11563 (let ((case-fold-search nil)
11564 (kwd-re
11565 (cond ((null arg) org-not-done-regexp)
11566 ((equal arg '(4))
11567 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11568 (mapcar 'list org-todo-keywords-1))))
11569 (concat "\\("
11570 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11571 "\\)\\>")))
11572 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11573 (regexp-quote (nth (1- (prefix-numeric-value arg))
11574 org-todo-keywords-1)))
11575 (t (error "Invalid prefix argument: %s" arg)))))
11576 (message "%d TODO entries found"
11577 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
11579 (defun org-deadline (&optional remove time)
11580 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11581 With argument REMOVE, remove any deadline from the item.
11582 When TIME is set, it should be an internal time specification, and the
11583 scheduling will use the corresponding date."
11584 (interactive "P")
11585 (let* ((old-date (org-entry-get nil "DEADLINE"))
11586 (repeater (and old-date
11587 (string-match
11588 "\\([.+]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11589 old-date)
11590 (match-string 1 old-date))))
11591 (if remove
11592 (progn
11593 (when (and old-date org-log-redeadline)
11594 (org-add-log-setup 'deldeadline nil old-date 'findpos
11595 org-log-redeadline))
11596 (org-remove-timestamp-with-keyword org-deadline-string)
11597 (message "Item no longer has a deadline."))
11598 (org-add-planning-info 'deadline time 'closed)
11599 (when (and old-date org-log-redeadline
11600 (not (equal old-date
11601 (substring org-last-inserted-timestamp 1 -1))))
11602 (org-add-log-setup 'redeadline nil old-date 'findpos
11603 org-log-redeadline))
11604 (when repeater
11605 (save-excursion
11606 (org-back-to-heading t)
11607 (when (re-search-forward (concat org-deadline-string " "
11608 org-last-inserted-timestamp)
11609 (save-excursion
11610 (outline-next-heading) (point)) t)
11611 (goto-char (1- (match-end 0)))
11612 (insert " " repeater)
11613 (setq org-last-inserted-timestamp
11614 (concat (substring org-last-inserted-timestamp 0 -1)
11615 " " repeater
11616 (substring org-last-inserted-timestamp -1))))))
11617 (message "Deadline on %s" org-last-inserted-timestamp))))
11619 (defun org-schedule (&optional remove time)
11620 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11621 With argument REMOVE, remove any scheduling date from the item.
11622 When TIME is set, it should be an internal time specification, and the
11623 scheduling will use the corresponding date."
11624 (interactive "P")
11625 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11626 (repeater (and old-date
11627 (string-match
11628 "\\([.+]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11629 old-date)
11630 (match-string 1 old-date))))
11631 (if remove
11632 (progn
11633 (when (and old-date org-log-reschedule)
11634 (org-add-log-setup 'delschedule nil old-date 'findpos
11635 org-log-reschedule))
11636 (org-remove-timestamp-with-keyword org-scheduled-string)
11637 (message "Item is no longer scheduled."))
11638 (org-add-planning-info 'scheduled time 'closed)
11639 (when (and old-date org-log-reschedule
11640 (not (equal old-date
11641 (substring org-last-inserted-timestamp 1 -1))))
11642 (org-add-log-setup 'reschedule nil old-date 'findpos
11643 org-log-reschedule))
11644 (when repeater
11645 (save-excursion
11646 (org-back-to-heading t)
11647 (when (re-search-forward (concat org-scheduled-string " "
11648 org-last-inserted-timestamp)
11649 (save-excursion
11650 (outline-next-heading) (point)) t)
11651 (goto-char (1- (match-end 0)))
11652 (insert " " repeater)
11653 (setq org-last-inserted-timestamp
11654 (concat (substring org-last-inserted-timestamp 0 -1)
11655 " " repeater
11656 (substring org-last-inserted-timestamp -1))))))
11657 (message "Scheduled to %s" org-last-inserted-timestamp))))
11659 (defun org-get-scheduled-time (pom &optional inherit)
11660 "Get the scheduled time as a time tuple, of a format suitable
11661 for calling org-schedule with, or if there is no scheduling,
11662 returns nil."
11663 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
11664 (when time
11665 (apply 'encode-time (org-parse-time-string time)))))
11667 (defun org-get-deadline-time (pom &optional inherit)
11668 "Get the deadline as a time tuple, of a format suitable for
11669 calling org-deadline with, or if there is no scheduling, returns
11670 nil."
11671 (let ((time (org-entry-get pom "DEADLINE" inherit)))
11672 (when time
11673 (apply 'encode-time (org-parse-time-string time)))))
11675 (defun org-remove-timestamp-with-keyword (keyword)
11676 "Remove all time stamps with KEYWORD in the current entry."
11677 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
11678 beg)
11679 (save-excursion
11680 (org-back-to-heading t)
11681 (setq beg (point))
11682 (outline-next-heading)
11683 (while (re-search-backward re beg t)
11684 (replace-match "")
11685 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
11686 (equal (char-before) ?\ ))
11687 (backward-delete-char 1)
11688 (if (string-match "^[ \t]*$" (buffer-substring
11689 (point-at-bol) (point-at-eol)))
11690 (delete-region (point-at-bol)
11691 (min (point-max) (1+ (point-at-eol))))))))))
11693 (defun org-add-planning-info (what &optional time &rest remove)
11694 "Insert new timestamp with keyword in the line directly after the headline.
11695 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11696 If non is given, the user is prompted for a date.
11697 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11698 be removed."
11699 (interactive)
11700 (let (org-time-was-given org-end-time-was-given ts
11701 end default-time default-input)
11703 (catch 'exit
11704 (when (and (not time) (memq what '(scheduled deadline)))
11705 ;; Try to get a default date/time from existing timestamp
11706 (save-excursion
11707 (org-back-to-heading t)
11708 (setq end (save-excursion (outline-next-heading) (point)))
11709 (when (re-search-forward (if (eq what 'scheduled)
11710 org-scheduled-time-regexp
11711 org-deadline-time-regexp)
11712 end t)
11713 (setq ts (match-string 1)
11714 default-time
11715 (apply 'encode-time (org-parse-time-string ts))
11716 default-input (and ts (org-get-compact-tod ts))))))
11717 (when what
11718 ;; If necessary, get the time from the user
11719 (setq time (or time (org-read-date nil 'to-time nil nil
11720 default-time default-input))))
11722 (when (and org-insert-labeled-timestamps-at-point
11723 (member what '(scheduled deadline)))
11724 (insert
11725 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11726 (org-insert-time-stamp time org-time-was-given
11727 nil nil nil (list org-end-time-was-given))
11728 (setq what nil))
11729 (save-excursion
11730 (save-restriction
11731 (let (col list elt ts buffer-invisibility-spec)
11732 (org-back-to-heading t)
11733 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11734 (goto-char (match-end 1))
11735 (setq col (current-column))
11736 (goto-char (match-end 0))
11737 (if (eobp) (insert "\n") (forward-char 1))
11738 (when (and (not what)
11739 (not (looking-at
11740 (concat "[ \t]*"
11741 org-keyword-time-not-clock-regexp))))
11742 ;; Nothing to add, nothing to remove...... :-)
11743 (throw 'exit nil))
11744 (if (and (not (looking-at outline-regexp))
11745 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11746 "[^\r\n]*"))
11747 (not (equal (match-string 1) org-clock-string)))
11748 (narrow-to-region (match-beginning 0) (match-end 0))
11749 (insert-before-markers "\n")
11750 (backward-char 1)
11751 (narrow-to-region (point) (point))
11752 (and org-adapt-indentation (org-indent-to-column col)))
11753 ;; Check if we have to remove something.
11754 (setq list (cons what remove))
11755 (while list
11756 (setq elt (pop list))
11757 (goto-char (point-min))
11758 (when (or (and (eq elt 'scheduled)
11759 (re-search-forward org-scheduled-time-regexp nil t))
11760 (and (eq elt 'deadline)
11761 (re-search-forward org-deadline-time-regexp nil t))
11762 (and (eq elt 'closed)
11763 (re-search-forward org-closed-time-regexp nil t)))
11764 (replace-match "")
11765 (if (looking-at "--+<[^>]+>") (replace-match ""))
11766 (skip-chars-backward " ")
11767 (if (looking-at " +") (replace-match ""))))
11768 (goto-char (point-max))
11769 (and org-adapt-indentation (bolp) (org-indent-to-column col))
11770 (when what
11771 (insert
11772 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
11773 (cond ((eq what 'scheduled) org-scheduled-string)
11774 ((eq what 'deadline) org-deadline-string)
11775 ((eq what 'closed) org-closed-string))
11776 " ")
11777 (setq ts (org-insert-time-stamp
11778 time
11779 (or org-time-was-given
11780 (and (eq what 'closed) org-log-done-with-time))
11781 (eq what 'closed)
11782 nil nil (list org-end-time-was-given)))
11783 (end-of-line 1))
11784 (goto-char (point-min))
11785 (widen)
11786 (if (and (looking-at "[ \t]*\n")
11787 (equal (char-before) ?\n))
11788 (delete-region (1- (point)) (point-at-eol)))
11789 ts))))))
11791 (defvar org-log-note-marker (make-marker))
11792 (defvar org-log-note-purpose nil)
11793 (defvar org-log-note-state nil)
11794 (defvar org-log-note-previous-state nil)
11795 (defvar org-log-note-how nil)
11796 (defvar org-log-note-extra nil)
11797 (defvar org-log-note-window-configuration nil)
11798 (defvar org-log-note-return-to (make-marker))
11799 (defvar org-log-post-message nil
11800 "Message to be displayed after a log note has been stored.
11801 The auto-repeater uses this.")
11803 (defun org-add-note ()
11804 "Add a note to the current entry.
11805 This is done in the same way as adding a state change note."
11806 (interactive)
11807 (org-add-log-setup 'note nil nil 'findpos nil))
11809 (defvar org-property-end-re)
11810 (defun org-add-log-setup (&optional purpose state prev-state
11811 findpos how extra)
11812 "Set up the post command hook to take a note.
11813 If this is about to TODO state change, the new state is expected in STATE.
11814 When FINDPOS is non-nil, find the correct position for the note in
11815 the current entry. If not, assume that it can be inserted at point.
11816 HOW is an indicator what kind of note should be created.
11817 EXTRA is additional text that will be inserted into the notes buffer."
11818 (let* ((org-log-into-drawer (org-log-into-drawer))
11819 (drawer (cond ((stringp org-log-into-drawer)
11820 org-log-into-drawer)
11821 (org-log-into-drawer "LOGBOOK")
11822 (t nil))))
11823 (save-restriction
11824 (save-excursion
11825 (when findpos
11826 (org-back-to-heading t)
11827 (narrow-to-region (point) (save-excursion
11828 (outline-next-heading) (point)))
11829 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11830 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11831 "[^\r\n]*\\)?"))
11832 (goto-char (match-end 0))
11833 (cond
11834 (drawer
11835 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
11836 nil t)
11837 (progn
11838 (goto-char (match-end 0))
11839 (or org-log-states-order-reversed
11840 (and (re-search-forward org-property-end-re nil t)
11841 (goto-char (1- (match-beginning 0))))))
11842 (insert "\n:" drawer ":\n:END:")
11843 (beginning-of-line 0)
11844 (org-indent-line-function)
11845 (beginning-of-line 2)
11846 (org-indent-line-function)
11847 (end-of-line 0)))
11848 ((and org-log-state-notes-insert-after-drawers
11849 (save-excursion
11850 (forward-line) (looking-at org-drawer-regexp)))
11851 (forward-line)
11852 (while (looking-at org-drawer-regexp)
11853 (goto-char (match-end 0))
11854 (re-search-forward org-property-end-re (point-max) t)
11855 (forward-line))
11856 (forward-line -1)))
11857 (unless org-log-states-order-reversed
11858 (and (= (char-after) ?\n) (forward-char 1))
11859 (org-skip-over-state-notes)
11860 (skip-chars-backward " \t\n\r")))
11861 (move-marker org-log-note-marker (point))
11862 (setq org-log-note-purpose purpose
11863 org-log-note-state state
11864 org-log-note-previous-state prev-state
11865 org-log-note-how how
11866 org-log-note-extra extra)
11867 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
11869 (defun org-skip-over-state-notes ()
11870 "Skip past the list of State notes in an entry."
11871 (if (looking-at "\n[ \t]*- State") (forward-char 1))
11872 (when (ignore-errors (goto-char (org-in-item-p)))
11873 (let* ((struct (org-list-struct))
11874 (prevs (org-list-prevs-alist struct)))
11875 (while (looking-at "[ \t]*- State")
11876 (goto-char (or (org-list-get-next-item (point) struct prevs)
11877 (org-list-get-item-end (point) struct)))))))
11879 (defun org-add-log-note (&optional purpose)
11880 "Pop up a window for taking a note, and add this note later at point."
11881 (remove-hook 'post-command-hook 'org-add-log-note)
11882 (setq org-log-note-window-configuration (current-window-configuration))
11883 (delete-other-windows)
11884 (move-marker org-log-note-return-to (point))
11885 (switch-to-buffer (marker-buffer org-log-note-marker))
11886 (goto-char org-log-note-marker)
11887 (org-switch-to-buffer-other-window "*Org Note*")
11888 (erase-buffer)
11889 (if (memq org-log-note-how '(time state))
11890 (let (current-prefix-arg) (org-store-log-note))
11891 (let ((org-inhibit-startup t)) (org-mode))
11892 (insert (format "# Insert note for %s.
11893 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
11894 (cond
11895 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11896 ((eq org-log-note-purpose 'done) "closed todo item")
11897 ((eq org-log-note-purpose 'state)
11898 (format "state change from \"%s\" to \"%s\""
11899 (or org-log-note-previous-state "")
11900 (or org-log-note-state "")))
11901 ((eq org-log-note-purpose 'reschedule)
11902 "rescheduling")
11903 ((eq org-log-note-purpose 'delschedule)
11904 "no longer scheduled")
11905 ((eq org-log-note-purpose 'redeadline)
11906 "changing deadline")
11907 ((eq org-log-note-purpose 'deldeadline)
11908 "removing deadline")
11909 ((eq org-log-note-purpose 'refile)
11910 "refiling")
11911 ((eq org-log-note-purpose 'note)
11912 "this entry")
11913 (t (error "This should not happen")))))
11914 (if org-log-note-extra (insert org-log-note-extra))
11915 (org-set-local 'org-finish-function 'org-store-log-note)))
11917 (defvar org-note-abort nil) ; dynamically scoped
11918 (defun org-store-log-note ()
11919 "Finish taking a log note, and insert it to where it belongs."
11920 (let ((txt (buffer-string))
11921 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11922 lines ind bul)
11923 (kill-buffer (current-buffer))
11924 (while (string-match "\\`#.*\n[ \t\n]*" txt)
11925 (setq txt (replace-match "" t t txt)))
11926 (if (string-match "\\s-+\\'" txt)
11927 (setq txt (replace-match "" t t txt)))
11928 (setq lines (org-split-string txt "\n"))
11929 (when (and note (string-match "\\S-" note))
11930 (setq note
11931 (org-replace-escapes
11932 note
11933 (list (cons "%u" (user-login-name))
11934 (cons "%U" user-full-name)
11935 (cons "%t" (format-time-string
11936 (org-time-stamp-format 'long 'inactive)
11937 (current-time)))
11938 (cons "%T" (format-time-string
11939 (org-time-stamp-format 'long nil)
11940 (current-time)))
11941 (cons "%s" (if org-log-note-state
11942 (concat "\"" org-log-note-state "\"")
11943 ""))
11944 (cons "%S" (if org-log-note-previous-state
11945 (concat "\"" org-log-note-previous-state "\"")
11946 "\"\"")))))
11947 (if lines (setq note (concat note " \\\\")))
11948 (push note lines))
11949 (when (or current-prefix-arg org-note-abort)
11950 (when org-log-into-drawer
11951 (org-remove-empty-drawer-at
11952 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
11953 org-log-note-marker))
11954 (setq lines nil))
11955 (when lines
11956 (with-current-buffer (marker-buffer org-log-note-marker)
11957 (save-excursion
11958 (goto-char org-log-note-marker)
11959 (move-marker org-log-note-marker nil)
11960 (end-of-line 1)
11961 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
11962 (setq ind (save-excursion
11963 (if (ignore-errors (goto-char (org-in-item-p)))
11964 (let ((struct (org-list-struct)))
11965 (org-list-get-ind
11966 (org-list-get-top-point struct) struct))
11967 (skip-chars-backward " \r\t\n")
11968 (cond
11969 ((and (org-at-heading-p)
11970 org-adapt-indentation)
11971 (1+ (org-current-level)))
11972 ((org-at-heading-p) 0)
11973 (t (org-get-indentation))))))
11974 (setq bul (org-list-bullet-string "-"))
11975 (org-indent-line-to ind)
11976 (insert bul (pop lines))
11977 (let ((ind-body (+ (length bul) ind)))
11978 (while lines
11979 (insert "\n")
11980 (org-indent-line-to ind-body)
11981 (insert (pop lines))))
11982 (message "Note stored")
11983 (org-back-to-heading t)
11984 (org-cycle-hide-drawers 'children)))))
11985 (set-window-configuration org-log-note-window-configuration)
11986 (with-current-buffer (marker-buffer org-log-note-return-to)
11987 (goto-char org-log-note-return-to))
11988 (move-marker org-log-note-return-to nil)
11989 (and org-log-post-message (message "%s" org-log-post-message)))
11991 (defun org-remove-empty-drawer-at (drawer pos)
11992 "Remove an empty drawer DRAWER at position POS.
11993 POS may also be a marker."
11994 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
11995 (save-excursion
11996 (save-restriction
11997 (widen)
11998 (goto-char pos)
11999 (if (org-in-regexp
12000 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12001 (replace-match ""))))))
12003 (defun org-sparse-tree (&optional arg)
12004 "Create a sparse tree, prompt for the details.
12005 This command can create sparse trees. You first need to select the type
12006 of match used to create the tree:
12008 t Show all TODO entries.
12009 T Show entries with a specific TODO keyword.
12010 m Show entries selected by a tags/property match.
12011 p Enter a property name and its value (both with completion on existing
12012 names/values) and show entries with that property.
12013 r Show entries matching a regular expression (`/' can be used as well)
12014 d Show deadlines due within `org-deadline-warning-days'.
12015 b Show deadlines and scheduled items before a date.
12016 a Show deadlines and scheduled items after a date."
12017 (interactive "P")
12018 (let (ans kwd value)
12019 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date")
12020 (setq ans (read-char-exclusive))
12021 (cond
12022 ((equal ans ?d)
12023 (call-interactively 'org-check-deadlines))
12024 ((equal ans ?b)
12025 (call-interactively 'org-check-before-date))
12026 ((equal ans ?a)
12027 (call-interactively 'org-check-after-date))
12028 ((equal ans ?t)
12029 (org-show-todo-tree nil))
12030 ((equal ans ?T)
12031 (org-show-todo-tree '(4)))
12032 ((member ans '(?T ?m))
12033 (call-interactively 'org-match-sparse-tree))
12034 ((member ans '(?p ?P))
12035 (setq kwd (org-icompleting-read "Property: "
12036 (mapcar 'list (org-buffer-property-keys))))
12037 (setq value (org-icompleting-read "Value: "
12038 (mapcar 'list (org-property-values kwd))))
12039 (unless (string-match "\\`{.*}\\'" value)
12040 (setq value (concat "\"" value "\"")))
12041 (org-match-sparse-tree arg (concat kwd "=" value)))
12042 ((member ans '(?r ?R ?/))
12043 (call-interactively 'org-occur))
12044 (t (error "No such sparse tree command \"%c\"" ans)))))
12046 (defvar org-occur-highlights nil
12047 "List of overlays used for occur matches.")
12048 (make-variable-buffer-local 'org-occur-highlights)
12049 (defvar org-occur-parameters nil
12050 "Parameters of the active org-occur calls.
12051 This is a list, each call to org-occur pushes as cons cell,
12052 containing the regular expression and the callback, onto the list.
12053 The list can contain several entries if `org-occur' has been called
12054 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12055 will only contain one set of parameters. When the highlights are
12056 removed (for example with `C-c C-c', or with the next edit (depending
12057 on `org-remove-highlights-with-change'), this variable is emptied
12058 as well.")
12059 (make-variable-buffer-local 'org-occur-parameters)
12061 (defun org-occur (regexp &optional keep-previous callback)
12062 "Make a compact tree which shows all matches of REGEXP.
12063 The tree will show the lines where the regexp matches, and all higher
12064 headlines above the match. It will also show the heading after the match,
12065 to make sure editing the matching entry is easy.
12066 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12067 call to `org-occur' will be kept, to allow stacking of calls to this
12068 command.
12069 If CALLBACK is non-nil, it is a function which is called to confirm
12070 that the match should indeed be shown."
12071 (interactive "sRegexp: \nP")
12072 (when (equal regexp "")
12073 (error "Regexp cannot be empty"))
12074 (unless keep-previous
12075 (org-remove-occur-highlights nil nil t))
12076 (push (cons regexp callback) org-occur-parameters)
12077 (let ((cnt 0))
12078 (save-excursion
12079 (goto-char (point-min))
12080 (if (or (not keep-previous) ; do not want to keep
12081 (not org-occur-highlights)) ; no previous matches
12082 ;; hide everything
12083 (org-overview))
12084 (while (re-search-forward regexp nil t)
12085 (when (or (not callback)
12086 (save-match-data (funcall callback)))
12087 (setq cnt (1+ cnt))
12088 (when org-highlight-sparse-tree-matches
12089 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12090 (org-show-context 'occur-tree))))
12091 (when org-remove-highlights-with-change
12092 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12093 nil 'local))
12094 (unless org-sparse-tree-open-archived-trees
12095 (org-hide-archived-subtrees (point-min) (point-max)))
12096 (run-hooks 'org-occur-hook)
12097 (if (interactive-p)
12098 (message "%d match(es) for regexp %s" cnt regexp))
12099 cnt))
12101 (defun org-occur-next-match (&optional n reset)
12102 "Function for `next-error-function' to find sparse tree matches.
12103 N is the number of matches to move, when negative move backwards.
12104 RESET is entirely ignored - this function always goes back to the
12105 starting point when no match is found."
12106 (let* ((limit (if (< n 0) (point-min) (point-max)))
12107 (search-func (if (< n 0)
12108 'previous-single-char-property-change
12109 'next-single-char-property-change))
12110 (n (abs n))
12111 (pos (point))
12113 (catch 'exit
12114 (while (setq p1 (funcall search-func (point) 'org-type))
12115 (when (equal p1 limit)
12116 (goto-char pos)
12117 (error "No more matches"))
12118 (when (equal (get-char-property p1 'org-type) 'org-occur)
12119 (setq n (1- n))
12120 (when (= n 0)
12121 (goto-char p1)
12122 (throw 'exit (point))))
12123 (goto-char p1))
12124 (goto-char p1)
12125 (error "No more matches"))))
12127 (defun org-show-context (&optional key)
12128 "Make sure point and context are visible.
12129 How much context is shown depends upon the variables
12130 `org-show-hierarchy-above', `org-show-following-heading'. and
12131 `org-show-siblings'."
12132 (let ((heading-p (org-on-heading-p t))
12133 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12134 (following-p (org-get-alist-option org-show-following-heading key))
12135 (entry-p (org-get-alist-option org-show-entry-below key))
12136 (siblings-p (org-get-alist-option org-show-siblings key)))
12137 (catch 'exit
12138 ;; Show heading or entry text
12139 (if (and heading-p (not entry-p))
12140 (org-flag-heading nil) ; only show the heading
12141 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12142 (org-show-hidden-entry))) ; show entire entry
12143 (when following-p
12144 ;; Show next sibling, or heading below text
12145 (save-excursion
12146 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12147 (org-flag-heading nil))))
12148 (when siblings-p (org-show-siblings))
12149 (when hierarchy-p
12150 ;; show all higher headings, possibly with siblings
12151 (save-excursion
12152 (while (and (condition-case nil
12153 (progn (org-up-heading-all 1) t)
12154 (error nil))
12155 (not (bobp)))
12156 (org-flag-heading nil)
12157 (when siblings-p (org-show-siblings))))))))
12159 (defvar org-reveal-start-hook nil
12160 "Hook run before revealing a location.")
12162 (defun org-reveal (&optional siblings)
12163 "Show current entry, hierarchy above it, and the following headline.
12164 This can be used to show a consistent set of context around locations
12165 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12166 not t for the search context.
12168 With optional argument SIBLINGS, on each level of the hierarchy all
12169 siblings are shown. This repairs the tree structure to what it would
12170 look like when opened with hierarchical calls to `org-cycle'.
12171 With double optional argument \\[universal-argument] \\[universal-argument], \
12172 go to the parent and show the
12173 entire tree."
12174 (interactive "P")
12175 (run-hooks 'org-reveal-start-hook)
12176 (let ((org-show-hierarchy-above t)
12177 (org-show-following-heading t)
12178 (org-show-siblings (if siblings t org-show-siblings)))
12179 (org-show-context nil))
12180 (when (equal siblings '(16))
12181 (save-excursion
12182 (when (org-up-heading-safe)
12183 (org-show-subtree)
12184 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12186 (defun org-highlight-new-match (beg end)
12187 "Highlight from BEG to END and mark the highlight is an occur headline."
12188 (let ((ov (make-overlay beg end)))
12189 (overlay-put ov 'face 'secondary-selection)
12190 (overlay-put ov 'org-type 'org-occur)
12191 (push ov org-occur-highlights)))
12193 (defun org-remove-occur-highlights (&optional beg end noremove)
12194 "Remove the occur highlights from the buffer.
12195 BEG and END are ignored. If NOREMOVE is nil, remove this function
12196 from the `before-change-functions' in the current buffer."
12197 (interactive)
12198 (unless org-inhibit-highlight-removal
12199 (mapc 'delete-overlay org-occur-highlights)
12200 (setq org-occur-highlights nil)
12201 (setq org-occur-parameters nil)
12202 (unless noremove
12203 (remove-hook 'before-change-functions
12204 'org-remove-occur-highlights 'local))))
12206 ;;;; Priorities
12208 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12209 "Regular expression matching the priority indicator.")
12211 (defvar org-remove-priority-next-time nil)
12213 (defun org-priority-up ()
12214 "Increase the priority of the current item."
12215 (interactive)
12216 (org-priority 'up))
12218 (defun org-priority-down ()
12219 "Decrease the priority of the current item."
12220 (interactive)
12221 (org-priority 'down))
12223 (defun org-priority (&optional action)
12224 "Change the priority of an item by ARG.
12225 ACTION can be `set', `up', `down', or a character."
12226 (interactive)
12227 (unless org-enable-priority-commands
12228 (error "Priority commands are disabled"))
12229 (setq action (or action 'set))
12230 (let (current new news have remove)
12231 (save-excursion
12232 (org-back-to-heading t)
12233 (if (looking-at org-priority-regexp)
12234 (setq current (string-to-char (match-string 2))
12235 have t)
12236 (setq current org-default-priority))
12237 (cond
12238 ((eq action 'remove)
12239 (setq remove t new ?\ ))
12240 ((or (eq action 'set)
12241 (if (featurep 'xemacs) (characterp action) (integerp action)))
12242 (if (not (eq action 'set))
12243 (setq new action)
12244 (message "Priority %c-%c, SPC to remove: "
12245 org-highest-priority org-lowest-priority)
12246 (save-match-data
12247 (setq new (read-char-exclusive))))
12248 (if (and (= (upcase org-highest-priority) org-highest-priority)
12249 (= (upcase org-lowest-priority) org-lowest-priority))
12250 (setq new (upcase new)))
12251 (cond ((equal new ?\ ) (setq remove t))
12252 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12253 (error "Priority must be between `%c' and `%c'"
12254 org-highest-priority org-lowest-priority))))
12255 ((eq action 'up)
12256 (if (and (not have) (eq last-command this-command))
12257 (setq new org-lowest-priority)
12258 (setq new (if (and org-priority-start-cycle-with-default (not have))
12259 org-default-priority (1- current)))))
12260 ((eq action 'down)
12261 (if (and (not have) (eq last-command this-command))
12262 (setq new org-highest-priority)
12263 (setq new (if (and org-priority-start-cycle-with-default (not have))
12264 org-default-priority (1+ current)))))
12265 (t (error "Invalid action")))
12266 (if (or (< (upcase new) org-highest-priority)
12267 (> (upcase new) org-lowest-priority))
12268 (setq remove t))
12269 (setq news (format "%c" new))
12270 (if have
12271 (if remove
12272 (replace-match "" t t nil 1)
12273 (replace-match news t t nil 2))
12274 (if remove
12275 (error "No priority cookie found in line")
12276 (let ((case-fold-search nil))
12277 (looking-at org-todo-line-regexp))
12278 (if (match-end 2)
12279 (progn
12280 (goto-char (match-end 2))
12281 (insert " [#" news "]"))
12282 (goto-char (match-beginning 3))
12283 (insert "[#" news "] "))))
12284 (org-preserve-lc (org-set-tags nil 'align)))
12285 (if remove
12286 (message "Priority removed")
12287 (message "Priority of current item set to %s" news))))
12289 (defun org-get-priority (s)
12290 "Find priority cookie and return priority."
12291 (if (functionp org-get-priority-function)
12292 (funcall org-get-priority-function)
12293 (save-match-data
12294 (if (not (string-match org-priority-regexp s))
12295 (* 1000 (- org-lowest-priority org-default-priority))
12296 (* 1000 (- org-lowest-priority
12297 (string-to-char (match-string 2 s))))))))
12299 ;;;; Tags
12301 (defvar org-agenda-archives-mode)
12302 (defvar org-map-continue-from nil
12303 "Position from where mapping should continue.
12304 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
12306 (defvar org-scanner-tags nil
12307 "The current tag list while the tags scanner is running.")
12308 (defvar org-trust-scanner-tags nil
12309 "Should `org-get-tags-at' use the tags for the scanner.
12310 This is for internal dynamical scoping only.
12311 When this is non-nil, the function `org-get-tags-at' will return the value
12312 of `org-scanner-tags' instead of building the list by itself. This
12313 can lead to large speed-ups when the tags scanner is used in a file with
12314 many entries, and when the list of tags is retrieved, for example to
12315 obtain a list of properties. Building the tags list for each entry in such
12316 a file becomes an N^2 operation - but with this variable set, it scales
12317 as N.")
12319 (defun org-scan-tags (action matcher &optional todo-only)
12320 "Scan headline tags with inheritance and produce output ACTION.
12322 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12323 or `agenda' to produce an entry list for an agenda view. It can also be
12324 a Lisp form or a function that should be called at each matched headline, in
12325 this case the return value is a list of all return values from these calls.
12327 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12328 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12329 only lines with a TODO keyword are included in the output."
12330 (require 'org-agenda)
12331 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
12332 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12333 (org-re
12334 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12335 (props (list 'face 'default
12336 'done-face 'org-agenda-done
12337 'undone-face 'default
12338 'mouse-face 'highlight
12339 'org-not-done-regexp org-not-done-regexp
12340 'org-todo-regexp org-todo-regexp
12341 'help-echo
12342 (format "mouse-2 or RET jump to org file %s"
12343 (abbreviate-file-name
12344 (or (buffer-file-name (buffer-base-buffer))
12345 (buffer-name (buffer-base-buffer)))))))
12346 (case-fold-search nil)
12347 (org-map-continue-from nil)
12348 lspos tags tags-list
12349 (tags-alist (list (cons 0 org-file-tags)))
12350 (llast 0) rtn rtn1 level category i txt
12351 todo marker entry priority)
12352 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12353 (setq action (list 'lambda nil action)))
12354 (save-excursion
12355 (goto-char (point-min))
12356 (when (eq action 'sparse-tree)
12357 (org-overview)
12358 (org-remove-occur-highlights))
12359 (while (re-search-forward re nil t)
12360 (catch :skip
12361 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12362 tags (if (match-end 4) (org-match-string-no-properties 4)))
12363 (goto-char (setq lspos (match-beginning 0)))
12364 (setq level (org-reduced-level (funcall outline-level))
12365 category (org-get-category))
12366 (setq i llast llast level)
12367 ;; remove tag lists from same and sublevels
12368 (while (>= i level)
12369 (when (setq entry (assoc i tags-alist))
12370 (setq tags-alist (delete entry tags-alist)))
12371 (setq i (1- i)))
12372 ;; add the next tags
12373 (when tags
12374 (setq tags (org-split-string tags ":")
12375 tags-alist
12376 (cons (cons level tags) tags-alist)))
12377 ;; compile tags for current headline
12378 (setq tags-list
12379 (if org-use-tag-inheritance
12380 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12381 tags)
12382 org-scanner-tags tags-list)
12383 (when org-use-tag-inheritance
12384 (setcdr (car tags-alist)
12385 (mapcar (lambda (x)
12386 (setq x (copy-sequence x))
12387 (org-add-prop-inherited x))
12388 (cdar tags-alist))))
12389 (when (and tags org-use-tag-inheritance
12390 (or (not (eq t org-use-tag-inheritance))
12391 org-tags-exclude-from-inheritance))
12392 ;; selective inheritance, remove uninherited ones
12393 (setcdr (car tags-alist)
12394 (org-remove-uniherited-tags (cdar tags-alist))))
12395 (when (and (or (not todo-only)
12396 (and (member todo org-not-done-keywords)
12397 (or (not org-agenda-tags-todo-honor-ignore-options)
12398 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12399 (let ((case-fold-search t)) (eval matcher))
12401 (not (member org-archive-tag tags-list))
12402 ;; we have an archive tag, should we use this anyway?
12403 (or (not org-agenda-skip-archived-trees)
12404 (and (eq action 'agenda) org-agenda-archives-mode))))
12405 (unless (eq action 'sparse-tree) (org-agenda-skip))
12407 ;; select this headline
12409 (cond
12410 ((eq action 'sparse-tree)
12411 (and org-highlight-sparse-tree-matches
12412 (org-get-heading) (match-end 0)
12413 (org-highlight-new-match
12414 (match-beginning 0) (match-beginning 1)))
12415 (org-show-context 'tags-tree))
12416 ((eq action 'agenda)
12417 (setq txt (org-format-agenda-item
12419 (concat
12420 (if (eq org-tags-match-list-sublevels 'indented)
12421 (make-string (1- level) ?.) "")
12422 (org-get-heading))
12423 category
12424 tags-list
12426 priority (org-get-priority txt))
12427 (goto-char lspos)
12428 (setq marker (org-agenda-new-marker))
12429 (org-add-props txt props
12430 'org-marker marker 'org-hd-marker marker 'org-category category
12431 'todo-state todo
12432 'priority priority 'type "tagsmatch")
12433 (push txt rtn))
12434 ((functionp action)
12435 (setq org-map-continue-from nil)
12436 (save-excursion
12437 (setq rtn1 (funcall action))
12438 (push rtn1 rtn)))
12439 (t (error "Invalid action")))
12441 ;; if we are to skip sublevels, jump to end of subtree
12442 (unless org-tags-match-list-sublevels
12443 (org-end-of-subtree t)
12444 (backward-char 1))))
12445 ;; Get the correct position from where to continue
12446 (if org-map-continue-from
12447 (goto-char org-map-continue-from)
12448 (and (= (point) lspos) (end-of-line 1)))))
12449 (when (and (eq action 'sparse-tree)
12450 (not org-sparse-tree-open-archived-trees))
12451 (org-hide-archived-subtrees (point-min) (point-max)))
12452 (nreverse rtn)))
12454 (defun org-remove-uniherited-tags (tags)
12455 "Remove all tags that are not inherited from the list TAGS."
12456 (cond
12457 ((eq org-use-tag-inheritance t)
12458 (if org-tags-exclude-from-inheritance
12459 (org-delete-all org-tags-exclude-from-inheritance tags)
12460 tags))
12461 ((not org-use-tag-inheritance) nil)
12462 ((stringp org-use-tag-inheritance)
12463 (delq nil (mapcar
12464 (lambda (x)
12465 (if (and (string-match org-use-tag-inheritance x)
12466 (not (member x org-tags-exclude-from-inheritance)))
12467 x nil))
12468 tags)))
12469 ((listp org-use-tag-inheritance)
12470 (delq nil (mapcar
12471 (lambda (x)
12472 (if (member x org-use-tag-inheritance) x nil))
12473 tags)))))
12475 (defvar todo-only) ;; dynamically scoped
12477 (defun org-match-sparse-tree (&optional todo-only match)
12478 "Create a sparse tree according to tags string MATCH.
12479 MATCH can contain positive and negative selection of tags, like
12480 \"+WORK+URGENT-WITHBOSS\".
12481 If optional argument TODO-ONLY is non-nil, only select lines that are
12482 also TODO lines."
12483 (interactive "P")
12484 (org-prepare-agenda-buffers (list (current-buffer)))
12485 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12487 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12489 (defvar org-cached-props nil)
12490 (defun org-cached-entry-get (pom property)
12491 (if (or (eq t org-use-property-inheritance)
12492 (and (stringp org-use-property-inheritance)
12493 (string-match org-use-property-inheritance property))
12494 (and (listp org-use-property-inheritance)
12495 (member property org-use-property-inheritance)))
12496 ;; Caching is not possible, check it directly
12497 (org-entry-get pom property 'inherit)
12498 ;; Get all properties, so that we can do complicated checks easily
12499 (cdr (assoc property (or org-cached-props
12500 (setq org-cached-props
12501 (org-entry-properties pom)))))))
12503 (defun org-global-tags-completion-table (&optional files)
12504 "Return the list of all tags in all agenda buffer/files.
12505 Optional FILES argument is a list of files to which can be used
12506 instead of the agenda files."
12507 (save-excursion
12508 (org-uniquify
12509 (delq nil
12510 (apply 'append
12511 (mapcar
12512 (lambda (file)
12513 (set-buffer (find-file-noselect file))
12514 (append (org-get-buffer-tags)
12515 (mapcar (lambda (x) (if (stringp (car-safe x))
12516 (list (car-safe x)) nil))
12517 org-tag-alist)))
12518 (if (and files (car files))
12519 files
12520 (org-agenda-files))))))))
12522 (defun org-make-tags-matcher (match)
12523 "Create the TAGS//TODO matcher form for the selection string MATCH."
12524 ;; todo-only is scoped dynamically into this function, and the function
12525 ;; may change it if the matcher asks for it.
12526 (unless match
12527 ;; Get a new match request, with completion
12528 (let ((org-last-tags-completion-table
12529 (org-global-tags-completion-table)))
12530 (setq match (org-completing-read-no-i
12531 "Match: " 'org-tags-completion-function nil nil nil
12532 'org-tags-history))))
12534 ;; Parse the string and create a lisp form
12535 (let ((match0 match)
12536 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
12537 minus tag mm
12538 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12539 orterms term orlist re-p str-p level-p level-op time-p
12540 prop-p pn pv po gv rest)
12541 (if (string-match "/+" match)
12542 ;; match contains also a todo-matching request
12543 (progn
12544 (setq tagsmatch (substring match 0 (match-beginning 0))
12545 todomatch (substring match (match-end 0)))
12546 (if (string-match "^!" todomatch)
12547 (setq todo-only t todomatch (substring todomatch 1)))
12548 (if (string-match "^\\s-*$" todomatch)
12549 (setq todomatch nil)))
12550 ;; only matching tags
12551 (setq tagsmatch match todomatch nil))
12553 ;; Make the tags matcher
12554 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12555 (setq tagsmatcher t)
12556 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12557 (while (setq term (pop orterms))
12558 (while (and (equal (substring term -1) "\\") orterms)
12559 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12560 (while (string-match re term)
12561 (setq rest (substring term (match-end 0))
12562 minus (and (match-end 1)
12563 (equal (match-string 1 term) "-"))
12564 tag (save-match-data (replace-regexp-in-string
12565 "\\\\-" "-"
12566 (match-string 2 term)))
12567 re-p (equal (string-to-char tag) ?{)
12568 level-p (match-end 4)
12569 prop-p (match-end 5)
12570 mm (cond
12571 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12572 (level-p
12573 (setq level-op (org-op-to-function (match-string 3 term)))
12574 `(,level-op level ,(string-to-number
12575 (match-string 4 term))))
12576 (prop-p
12577 (setq pn (match-string 5 term)
12578 po (match-string 6 term)
12579 pv (match-string 7 term)
12580 re-p (equal (string-to-char pv) ?{)
12581 str-p (equal (string-to-char pv) ?\")
12582 time-p (save-match-data
12583 (string-match "^\"[[<].*[]>]\"$" pv))
12584 pv (if (or re-p str-p) (substring pv 1 -1) pv))
12585 (if time-p (setq pv (org-matcher-time pv)))
12586 (setq po (org-op-to-function po (if time-p 'time str-p)))
12587 (cond
12588 ((equal pn "CATEGORY")
12589 (setq gv '(get-text-property (point) 'org-category)))
12590 ((equal pn "TODO")
12591 (setq gv 'todo))
12593 (setq gv `(org-cached-entry-get nil ,pn))))
12594 (if re-p
12595 (if (eq po 'org<>)
12596 `(not (string-match ,pv (or ,gv "")))
12597 `(string-match ,pv (or ,gv "")))
12598 (if str-p
12599 `(,po (or ,gv "") ,pv)
12600 `(,po (string-to-number (or ,gv ""))
12601 ,(string-to-number pv) ))))
12602 (t `(member ,tag tags-list)))
12603 mm (if minus (list 'not mm) mm)
12604 term rest)
12605 (push mm tagsmatcher))
12606 (push (if (> (length tagsmatcher) 1)
12607 (cons 'and tagsmatcher)
12608 (car tagsmatcher))
12609 orlist)
12610 (setq tagsmatcher nil))
12611 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
12612 (setq tagsmatcher
12613 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
12614 ;; Make the todo matcher
12615 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
12616 (setq todomatcher t)
12617 (setq orterms (org-split-string todomatch "|") orlist nil)
12618 (while (setq term (pop orterms))
12619 (while (string-match re term)
12620 (setq minus (and (match-end 1)
12621 (equal (match-string 1 term) "-"))
12622 kwd (match-string 2 term)
12623 re-p (equal (string-to-char kwd) ?{)
12624 term (substring term (match-end 0))
12625 mm (if re-p
12626 `(string-match ,(substring kwd 1 -1) todo)
12627 (list 'equal 'todo kwd))
12628 mm (if minus (list 'not mm) mm))
12629 (push mm todomatcher))
12630 (push (if (> (length todomatcher) 1)
12631 (cons 'and todomatcher)
12632 (car todomatcher))
12633 orlist)
12634 (setq todomatcher nil))
12635 (setq todomatcher (if (> (length orlist) 1)
12636 (cons 'or orlist) (car orlist))))
12638 ;; Return the string and lisp forms of the matcher
12639 (setq matcher (if todomatcher
12640 (list 'and tagsmatcher todomatcher)
12641 tagsmatcher))
12642 (cons match0 matcher)))
12644 (defun org-op-to-function (op &optional stringp)
12645 "Turn an operator into the appropriate function."
12646 (setq op
12647 (cond
12648 ((equal op "<" ) '(< string< org-time<))
12649 ((equal op ">" ) '(> org-string> org-time>))
12650 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
12651 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
12652 ((member op '("=" "==")) '(= string= org-time=))
12653 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
12654 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
12656 (defun org<> (a b) (not (= a b)))
12657 (defun org-string<= (a b) (or (string= a b) (string< a b)))
12658 (defun org-string>= (a b) (not (string< a b)))
12659 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
12660 (defun org-string<> (a b) (not (string= a b)))
12661 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
12662 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
12663 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
12664 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
12665 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
12666 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
12667 (defun org-2ft (s)
12668 "Convert S to a floating point time.
12669 If S is already a number, just return it. If it is a string, parse
12670 it as a time string and apply `float-time' to it. If S is nil, just return 0."
12671 (cond
12672 ((numberp s) s)
12673 ((stringp s)
12674 (condition-case nil
12675 (float-time (apply 'encode-time (org-parse-time-string s)))
12676 (error 0.)))
12677 (t 0.)))
12679 (defun org-time-today ()
12680 "Time in seconds today at 0:00.
12681 Returns the float number of seconds since the beginning of the
12682 epoch to the beginning of today (00:00)."
12683 (float-time (apply 'encode-time
12684 (append '(0 0 0) (nthcdr 3 (decode-time))))))
12686 (defun org-matcher-time (s)
12687 "Interpret a time comparison value."
12688 (save-match-data
12689 (cond
12690 ((string= s "<now>") (float-time))
12691 ((string= s "<today>") (org-time-today))
12692 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
12693 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
12694 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
12695 (+ (org-time-today)
12696 (* (string-to-number (match-string 1 s))
12697 (cdr (assoc (match-string 2 s)
12698 '(("d" . 86400.0) ("w" . 604800.0)
12699 ("m" . 2678400.0) ("y" . 31557600.0)))))))
12700 (t (org-2ft s)))))
12702 (defun org-match-any-p (re list)
12703 "Does re match any element of list?"
12704 (setq list (mapcar (lambda (x) (string-match re x)) list))
12705 (delq nil list))
12707 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
12708 (defvar org-tags-overlay (make-overlay 1 1))
12709 (org-detach-overlay org-tags-overlay)
12711 (defun org-get-local-tags-at (&optional pos)
12712 "Get a list of tags defined in the current headline."
12713 (org-get-tags-at pos 'local))
12715 (defun org-get-local-tags ()
12716 "Get a list of tags defined in the current headline."
12717 (org-get-tags-at nil 'local))
12719 (defun org-get-tags-at (&optional pos local)
12720 "Get a list of all headline tags applicable at POS.
12721 POS defaults to point. If tags are inherited, the list contains
12722 the targets in the same sequence as the headlines appear, i.e.
12723 the tags of the current headline come last.
12724 When LOCAL is non-nil, only return tags from the current headline,
12725 ignore inherited ones."
12726 (interactive)
12727 (if (and org-trust-scanner-tags
12728 (or (not pos) (equal pos (point)))
12729 (not local))
12730 org-scanner-tags
12731 (let (tags ltags lastpos parent)
12732 (save-excursion
12733 (save-restriction
12734 (widen)
12735 (goto-char (or pos (point)))
12736 (save-match-data
12737 (catch 'done
12738 (condition-case nil
12739 (progn
12740 (org-back-to-heading t)
12741 (while (not (equal lastpos (point)))
12742 (setq lastpos (point))
12743 (when (looking-at
12744 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
12745 (setq ltags (org-split-string
12746 (org-match-string-no-properties 1) ":"))
12747 (when parent
12748 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
12749 (setq tags (append
12750 (if parent
12751 (org-remove-uniherited-tags ltags)
12752 ltags)
12753 tags)))
12754 (or org-use-tag-inheritance (throw 'done t))
12755 (if local (throw 'done t))
12756 (or (org-up-heading-safe) (error nil))
12757 (setq parent t)))
12758 (error nil)))))
12759 (append (org-remove-uniherited-tags org-file-tags) tags)))))
12761 (defun org-add-prop-inherited (s)
12762 (add-text-properties 0 (length s) '(inherited t) s)
12765 (defun org-toggle-tag (tag &optional onoff)
12766 "Toggle the tag TAG for the current line.
12767 If ONOFF is `on' or `off', don't toggle but set to this state."
12768 (let (res current)
12769 (save-excursion
12770 (org-back-to-heading t)
12771 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
12772 (point-at-eol) t)
12773 (progn
12774 (setq current (match-string 1))
12775 (replace-match ""))
12776 (setq current ""))
12777 (setq current (nreverse (org-split-string current ":")))
12778 (cond
12779 ((eq onoff 'on)
12780 (setq res t)
12781 (or (member tag current) (push tag current)))
12782 ((eq onoff 'off)
12783 (or (not (member tag current)) (setq current (delete tag current))))
12784 (t (if (member tag current)
12785 (setq current (delete tag current))
12786 (setq res t)
12787 (push tag current))))
12788 (end-of-line 1)
12789 (if current
12790 (progn
12791 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
12792 (org-set-tags nil t))
12793 (delete-horizontal-space))
12794 (run-hooks 'org-after-tags-change-hook))
12795 res))
12797 (defun org-align-tags-here (to-col)
12798 ;; Assumes that this is a headline
12799 (let ((pos (point)) (col (current-column)) ncol tags-l p)
12800 (beginning-of-line 1)
12801 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
12802 (< pos (match-beginning 2)))
12803 (progn
12804 (setq tags-l (- (match-end 2) (match-beginning 2)))
12805 (goto-char (match-beginning 1))
12806 (insert " ")
12807 (delete-region (point) (1+ (match-beginning 2)))
12808 (setq ncol (max (1+ (current-column))
12809 (1+ col)
12810 (if (> to-col 0)
12811 to-col
12812 (- (abs to-col) tags-l))))
12813 (setq p (point))
12814 (insert (make-string (- ncol (current-column)) ?\ ))
12815 (setq ncol (current-column))
12816 (when indent-tabs-mode (tabify p (point-at-eol)))
12817 (org-move-to-column (min ncol col) t))
12818 (goto-char pos))))
12820 (defun org-set-tags-command (&optional arg just-align)
12821 "Call the set-tags command for the current entry."
12822 (interactive "P")
12823 (if (org-on-heading-p)
12824 (org-set-tags arg just-align)
12825 (save-excursion
12826 (org-back-to-heading t)
12827 (org-set-tags arg just-align))))
12829 (defun org-set-tags-to (data)
12830 "Set the tags of the current entry to DATA, replacing the current tags.
12831 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
12832 If DATA is nil or the empty string, any tags will be removed."
12833 (interactive "sTags: ")
12834 (setq data
12835 (cond
12836 ((eq data nil) "")
12837 ((equal data "") "")
12838 ((stringp data)
12839 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
12840 ":"))
12841 ((listp data)
12842 (concat ":" (mapconcat 'identity data ":") ":"))
12843 (t nil)))
12844 (when data
12845 (save-excursion
12846 (org-back-to-heading t)
12847 (when (looking-at org-complex-heading-regexp)
12848 (if (match-end 5)
12849 (progn
12850 (goto-char (match-beginning 5))
12851 (insert data)
12852 (delete-region (point) (point-at-eol))
12853 (org-set-tags nil 'align))
12854 (goto-char (point-at-eol))
12855 (insert " " data)
12856 (org-set-tags nil 'align)))
12857 (beginning-of-line 1)
12858 (if (looking-at ".*?\\([ \t]+\\)$")
12859 (delete-region (match-beginning 1) (match-end 1))))))
12861 (defun org-align-all-tags ()
12862 "Align the tags i all headings."
12863 (interactive)
12864 (save-excursion
12865 (or (ignore-errors (org-back-to-heading t))
12866 (outline-next-heading))
12867 (if (org-on-heading-p)
12868 (org-set-tags t)
12869 (message "No headings"))))
12871 (defvar org-indent-indentation-per-level)
12872 (defun org-set-tags (&optional arg just-align)
12873 "Set the tags for the current headline.
12874 With prefix ARG, realign all tags in headings in the current buffer."
12875 (interactive "P")
12876 (let* ((re (concat "^" outline-regexp))
12877 (current (org-get-tags-string))
12878 (col (current-column))
12879 (org-setting-tags t)
12880 table current-tags inherited-tags ; computed below when needed
12881 tags p0 c0 c1 rpl di tc level)
12882 (if arg
12883 (save-excursion
12884 (goto-char (point-min))
12885 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12886 (while (re-search-forward re nil t)
12887 (org-set-tags nil t)
12888 (end-of-line 1)))
12889 (message "All tags realigned to column %d" org-tags-column))
12890 (if just-align
12891 (setq tags current)
12892 ;; Get a new set of tags from the user
12893 (save-excursion
12894 (setq table (append org-tag-persistent-alist
12895 (or org-tag-alist (org-get-buffer-tags))
12896 (and
12897 org-complete-tags-always-offer-all-agenda-tags
12898 (org-global-tags-completion-table
12899 (org-agenda-files))))
12900 org-last-tags-completion-table table
12901 current-tags (org-split-string current ":")
12902 inherited-tags (nreverse
12903 (nthcdr (length current-tags)
12904 (nreverse (org-get-tags-at))))
12905 tags
12906 (if (or (eq t org-use-fast-tag-selection)
12907 (and org-use-fast-tag-selection
12908 (delq nil (mapcar 'cdr table))))
12909 (org-fast-tag-selection
12910 current-tags inherited-tags table
12911 (if org-fast-tag-selection-include-todo
12912 org-todo-key-alist))
12913 (let ((org-add-colon-after-tag-completion t))
12914 (org-trim
12915 (org-without-partial-completion
12916 (org-icompleting-read "Tags: "
12917 'org-tags-completion-function
12918 nil nil current 'org-tags-history)))))))
12919 (while (string-match "[-+&]+" tags)
12920 ;; No boolean logic, just a list
12921 (setq tags (replace-match ":" t t tags))))
12923 (setq tags (replace-regexp-in-string "[,]" ":" tags))
12925 (if org-tags-sort-function
12926 (setq tags (mapconcat 'identity
12927 (sort (org-split-string
12928 tags (org-re "[^[:alnum:]_@#%]+"))
12929 org-tags-sort-function) ":")))
12931 (if (string-match "\\`[\t ]*\\'" tags)
12932 (setq tags "")
12933 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
12934 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
12936 ;; Insert new tags at the correct column
12937 (beginning-of-line 1)
12938 (setq level (or (and (looking-at org-outline-regexp)
12939 (- (match-end 0) (point) 1))
12941 (cond
12942 ((and (equal current "") (equal tags "")))
12943 ((re-search-forward
12944 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
12945 (point-at-eol) t)
12946 (if (equal tags "")
12947 (setq rpl "")
12948 (goto-char (match-beginning 0))
12949 (setq c0 (current-column)
12950 ;; compute offset for the case of org-indent-mode active
12951 di (if org-indent-mode
12952 (* (1- org-indent-indentation-per-level) (1- level))
12954 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
12955 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
12956 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
12957 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
12958 (replace-match rpl t t)
12959 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
12960 tags)
12961 (t (error "Tags alignment failed")))
12962 (org-move-to-column col)
12963 (unless just-align
12964 (run-hooks 'org-after-tags-change-hook)))))
12966 (defun org-change-tag-in-region (beg end tag off)
12967 "Add or remove TAG for each entry in the region.
12968 This works in the agenda, and also in an org-mode buffer."
12969 (interactive
12970 (list (region-beginning) (region-end)
12971 (let ((org-last-tags-completion-table
12972 (if (org-mode-p)
12973 (org-get-buffer-tags)
12974 (org-global-tags-completion-table))))
12975 (org-icompleting-read
12976 "Tag: " 'org-tags-completion-function nil nil nil
12977 'org-tags-history))
12978 (progn
12979 (message "[s]et or [r]emove? ")
12980 (equal (read-char-exclusive) ?r))))
12981 (if (fboundp 'deactivate-mark) (deactivate-mark))
12982 (let ((agendap (equal major-mode 'org-agenda-mode))
12983 l1 l2 m buf pos newhead (cnt 0))
12984 (goto-char end)
12985 (setq l2 (1- (org-current-line)))
12986 (goto-char beg)
12987 (setq l1 (org-current-line))
12988 (loop for l from l1 to l2 do
12989 (org-goto-line l)
12990 (setq m (get-text-property (point) 'org-hd-marker))
12991 (when (or (and (org-mode-p) (org-on-heading-p))
12992 (and agendap m))
12993 (setq buf (if agendap (marker-buffer m) (current-buffer))
12994 pos (if agendap m (point)))
12995 (with-current-buffer buf
12996 (save-excursion
12997 (save-restriction
12998 (goto-char pos)
12999 (setq cnt (1+ cnt))
13000 (org-toggle-tag tag (if off 'off 'on))
13001 (setq newhead (org-get-heading)))))
13002 (and agendap (org-agenda-change-all-lines newhead m))))
13003 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13005 (defun org-tags-completion-function (string predicate &optional flag)
13006 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13007 (confirm (lambda (x) (stringp (car x)))))
13008 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13009 (setq s1 (match-string 1 string)
13010 s2 (match-string 2 string))
13011 (setq s1 "" s2 string))
13012 (cond
13013 ((eq flag nil)
13014 ;; try completion
13015 (setq rtn (try-completion s2 ctable confirm))
13016 (if (stringp rtn)
13017 (setq rtn
13018 (concat s1 s2 (substring rtn (length s2))
13019 (if (and org-add-colon-after-tag-completion
13020 (assoc rtn ctable))
13021 ":" ""))))
13022 rtn)
13023 ((eq flag t)
13024 ;; all-completions
13025 (all-completions s2 ctable confirm)
13027 ((eq flag 'lambda)
13028 ;; exact match?
13029 (assoc s2 ctable)))
13032 (defun org-fast-tag-insert (kwd tags face &optional end)
13033 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13034 (insert (format "%-12s" (concat kwd ":"))
13035 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13036 (or end "")))
13038 (defun org-fast-tag-show-exit (flag)
13039 (save-excursion
13040 (org-goto-line 3)
13041 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13042 (replace-match ""))
13043 (when flag
13044 (end-of-line 1)
13045 (org-move-to-column (- (window-width) 19) t)
13046 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13048 (defun org-set-current-tags-overlay (current prefix)
13049 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13050 (if (featurep 'xemacs)
13051 (org-overlay-display org-tags-overlay (concat prefix s)
13052 'secondary-selection)
13053 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13054 (org-overlay-display org-tags-overlay (concat prefix s)))))
13056 (defvar org-last-tag-selection-key nil)
13057 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13058 "Fast tag selection with single keys.
13059 CURRENT is the current list of tags in the headline, INHERITED is the
13060 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13061 possibly with grouping information. TODO-TABLE is a similar table with
13062 TODO keywords, should these have keys assigned to them.
13063 If the keys are nil, a-z are automatically assigned.
13064 Returns the new tags string, or nil to not change the current settings."
13065 (let* ((fulltable (append table todo-table))
13066 (maxlen (apply 'max (mapcar
13067 (lambda (x)
13068 (if (stringp (car x)) (string-width (car x)) 0))
13069 fulltable)))
13070 (buf (current-buffer))
13071 (expert (eq org-fast-tag-selection-single-key 'expert))
13072 (buffer-tags nil)
13073 (fwidth (+ maxlen 3 1 3))
13074 (ncol (/ (- (window-width) 4) fwidth))
13075 (i-face 'org-done)
13076 (c-face 'org-todo)
13077 tg cnt e c char c1 c2 ntable tbl rtn
13078 ov-start ov-end ov-prefix
13079 (exit-after-next org-fast-tag-selection-single-key)
13080 (done-keywords org-done-keywords)
13081 groups ingroup)
13082 (save-excursion
13083 (beginning-of-line 1)
13084 (if (looking-at
13085 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13086 (setq ov-start (match-beginning 1)
13087 ov-end (match-end 1)
13088 ov-prefix "")
13089 (setq ov-start (1- (point-at-eol))
13090 ov-end (1+ ov-start))
13091 (skip-chars-forward "^\n\r")
13092 (setq ov-prefix
13093 (concat
13094 (buffer-substring (1- (point)) (point))
13095 (if (> (current-column) org-tags-column)
13097 (make-string (- org-tags-column (current-column)) ?\ ))))))
13098 (move-overlay org-tags-overlay ov-start ov-end)
13099 (save-window-excursion
13100 (if expert
13101 (set-buffer (get-buffer-create " *Org tags*"))
13102 (delete-other-windows)
13103 (split-window-vertically)
13104 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13105 (erase-buffer)
13106 (org-set-local 'org-done-keywords done-keywords)
13107 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13108 (org-fast-tag-insert "Current" current c-face "\n\n")
13109 (org-fast-tag-show-exit exit-after-next)
13110 (org-set-current-tags-overlay current ov-prefix)
13111 (setq tbl fulltable char ?a cnt 0)
13112 (while (setq e (pop tbl))
13113 (cond
13114 ((equal (car e) :startgroup)
13115 (push '() groups) (setq ingroup t)
13116 (when (not (= cnt 0))
13117 (setq cnt 0)
13118 (insert "\n"))
13119 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13120 ((equal (car e) :endgroup)
13121 (setq ingroup nil cnt 0)
13122 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13123 ((equal e '(:newline))
13124 (when (not (= cnt 0))
13125 (setq cnt 0)
13126 (insert "\n")
13127 (setq e (car tbl))
13128 (while (equal (car tbl) '(:newline))
13129 (insert "\n")
13130 (setq tbl (cdr tbl)))))
13132 (setq tg (copy-sequence (car e)) c2 nil)
13133 (if (cdr e)
13134 (setq c (cdr e))
13135 ;; automatically assign a character.
13136 (setq c1 (string-to-char
13137 (downcase (substring
13138 tg (if (= (string-to-char tg) ?@) 1 0)))))
13139 (if (or (rassoc c1 ntable) (rassoc c1 table))
13140 (while (or (rassoc char ntable) (rassoc char table))
13141 (setq char (1+ char)))
13142 (setq c2 c1))
13143 (setq c (or c2 char)))
13144 (if ingroup (push tg (car groups)))
13145 (setq tg (org-add-props tg nil 'face
13146 (cond
13147 ((not (assoc tg table))
13148 (org-get-todo-face tg))
13149 ((member tg current) c-face)
13150 ((member tg inherited) i-face)
13151 (t nil))))
13152 (if (and (= cnt 0) (not ingroup)) (insert " "))
13153 (insert "[" c "] " tg (make-string
13154 (- fwidth 4 (length tg)) ?\ ))
13155 (push (cons tg c) ntable)
13156 (when (= (setq cnt (1+ cnt)) ncol)
13157 (insert "\n")
13158 (if ingroup (insert " "))
13159 (setq cnt 0)))))
13160 (setq ntable (nreverse ntable))
13161 (insert "\n")
13162 (goto-char (point-min))
13163 (if (not expert) (org-fit-window-to-buffer))
13164 (setq rtn
13165 (catch 'exit
13166 (while t
13167 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13168 (if (not groups) "no " "")
13169 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13170 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13171 (setq org-last-tag-selection-key c)
13172 (cond
13173 ((= c ?\r) (throw 'exit t))
13174 ((= c ?!)
13175 (setq groups (not groups))
13176 (goto-char (point-min))
13177 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13178 ((= c ?\C-c)
13179 (if (not expert)
13180 (org-fast-tag-show-exit
13181 (setq exit-after-next (not exit-after-next)))
13182 (setq expert nil)
13183 (delete-other-windows)
13184 (set-window-buffer (split-window-vertically) " *Org tags*")
13185 (org-switch-to-buffer-other-window " *Org tags*")
13186 (org-fit-window-to-buffer)))
13187 ((or (= c ?\C-g)
13188 (and (= c ?q) (not (rassoc c ntable))))
13189 (org-detach-overlay org-tags-overlay)
13190 (setq quit-flag t))
13191 ((= c ?\ )
13192 (setq current nil)
13193 (if exit-after-next (setq exit-after-next 'now)))
13194 ((= c ?\t)
13195 (condition-case nil
13196 (setq tg (org-icompleting-read
13197 "Tag: "
13198 (or buffer-tags
13199 (with-current-buffer buf
13200 (org-get-buffer-tags)))))
13201 (quit (setq tg "")))
13202 (when (string-match "\\S-" tg)
13203 (add-to-list 'buffer-tags (list tg))
13204 (if (member tg current)
13205 (setq current (delete tg current))
13206 (push tg current)))
13207 (if exit-after-next (setq exit-after-next 'now)))
13208 ((setq e (rassoc c todo-table) tg (car e))
13209 (with-current-buffer buf
13210 (save-excursion (org-todo tg)))
13211 (if exit-after-next (setq exit-after-next 'now)))
13212 ((setq e (rassoc c ntable) tg (car e))
13213 (if (member tg current)
13214 (setq current (delete tg current))
13215 (loop for g in groups do
13216 (if (member tg g)
13217 (mapc (lambda (x)
13218 (setq current (delete x current)))
13219 g)))
13220 (push tg current))
13221 (if exit-after-next (setq exit-after-next 'now))))
13223 ;; Create a sorted list
13224 (setq current
13225 (sort current
13226 (lambda (a b)
13227 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13228 (if (eq exit-after-next 'now) (throw 'exit t))
13229 (goto-char (point-min))
13230 (beginning-of-line 2)
13231 (delete-region (point) (point-at-eol))
13232 (org-fast-tag-insert "Current" current c-face)
13233 (org-set-current-tags-overlay current ov-prefix)
13234 (while (re-search-forward
13235 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13236 (setq tg (match-string 1))
13237 (add-text-properties
13238 (match-beginning 1) (match-end 1)
13239 (list 'face
13240 (cond
13241 ((member tg current) c-face)
13242 ((member tg inherited) i-face)
13243 (t (get-text-property (match-beginning 1) 'face))))))
13244 (goto-char (point-min)))))
13245 (org-detach-overlay org-tags-overlay)
13246 (if rtn
13247 (mapconcat 'identity current ":")
13248 nil))))
13250 (defun org-get-tags-string ()
13251 "Get the TAGS string in the current headline."
13252 (unless (org-on-heading-p t)
13253 (error "Not on a heading"))
13254 (save-excursion
13255 (beginning-of-line 1)
13256 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13257 (org-match-string-no-properties 1)
13258 "")))
13260 (defun org-get-tags ()
13261 "Get the list of tags specified in the current headline."
13262 (org-split-string (org-get-tags-string) ":"))
13264 (defun org-get-buffer-tags ()
13265 "Get a table of all tags used in the buffer, for completion."
13266 (let (tags)
13267 (save-excursion
13268 (goto-char (point-min))
13269 (while (re-search-forward
13270 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13271 (when (equal (char-after (point-at-bol 0)) ?*)
13272 (mapc (lambda (x) (add-to-list 'tags x))
13273 (org-split-string (org-match-string-no-properties 1) ":")))))
13274 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13275 (mapcar 'list tags)))
13277 ;;;; The mapping API
13279 ;;;###autoload
13280 (defun org-map-entries (func &optional match scope &rest skip)
13281 "Call FUNC at each headline selected by MATCH in SCOPE.
13283 FUNC is a function or a lisp form. The function will be called without
13284 arguments, with the cursor positioned at the beginning of the headline.
13285 The return values of all calls to the function will be collected and
13286 returned as a list.
13288 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13289 does not need to preserve point. After evaluation, the cursor will be
13290 moved to the end of the line (presumably of the headline of the
13291 processed entry) and search continues from there. Under some
13292 circumstances, this may not produce the wanted results. For example,
13293 if you have removed (e.g. archived) the current (sub)tree it could
13294 mean that the next entry will be skipped entirely. In such cases, you
13295 can specify the position from where search should continue by making
13296 FUNC set the variable `org-map-continue-from' to the desired buffer
13297 position.
13299 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13300 Only headlines that are matched by this query will be considered during
13301 the iteration. When MATCH is nil or t, all headlines will be
13302 visited by the iteration.
13304 SCOPE determines the scope of this command. It can be any of:
13306 nil The current buffer, respecting the restriction if any
13307 tree The subtree started with the entry at point
13308 file The current buffer, without restriction
13309 file-with-archives
13310 The current buffer, and any archives associated with it
13311 agenda All agenda files
13312 agenda-with-archives
13313 All agenda files with any archive files associated with them
13314 \(file1 file2 ...)
13315 If this is a list, all files in the list will be scanned
13317 The remaining args are treated as settings for the skipping facilities of
13318 the scanner. The following items can be given here:
13320 archive skip trees with the archive tag.
13321 comment skip trees with the COMMENT keyword
13322 function or Emacs Lisp form:
13323 will be used as value for `org-agenda-skip-function', so whenever
13324 the function returns t, FUNC will not be called for that
13325 entry and search will continue from the point where the
13326 function leaves it.
13328 If your function needs to retrieve the tags including inherited tags
13329 at the *current* entry, you can use the value of the variable
13330 `org-scanner-tags' which will be much faster than getting the value
13331 with `org-get-tags-at'. If your function gets properties with
13332 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13333 to t around the call to `org-entry-properties' to get the same speedup.
13334 Note that if your function moves around to retrieve tags and properties at
13335 a *different* entry, you cannot use these techniques."
13336 (let* ((org-agenda-archives-mode nil) ; just to make sure
13337 (org-agenda-skip-archived-trees (memq 'archive skip))
13338 (org-agenda-skip-comment-trees (memq 'comment skip))
13339 (org-agenda-skip-function
13340 (car (org-delete-all '(comment archive) skip)))
13341 (org-tags-match-list-sublevels t)
13342 matcher file res
13343 org-todo-keywords-for-agenda
13344 org-done-keywords-for-agenda
13345 org-todo-keyword-alist-for-agenda
13346 org-drawers-for-agenda
13347 org-tag-alist-for-agenda)
13349 (cond
13350 ((eq match t) (setq matcher t))
13351 ((eq match nil) (setq matcher t))
13352 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13354 (save-excursion
13355 (save-restriction
13356 (when (eq scope 'tree)
13357 (org-back-to-heading t)
13358 (org-narrow-to-subtree)
13359 (setq scope nil))
13361 (if (not scope)
13362 (progn
13363 (org-prepare-agenda-buffers
13364 (list (buffer-file-name (current-buffer))))
13365 (setq res (org-scan-tags func matcher)))
13366 ;; Get the right scope
13367 (cond
13368 ((and scope (listp scope) (symbolp (car scope)))
13369 (setq scope (eval scope)))
13370 ((eq scope 'agenda)
13371 (setq scope (org-agenda-files t)))
13372 ((eq scope 'agenda-with-archives)
13373 (setq scope (org-agenda-files t))
13374 (setq scope (org-add-archive-files scope)))
13375 ((eq scope 'file)
13376 (setq scope (list (buffer-file-name))))
13377 ((eq scope 'file-with-archives)
13378 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13379 (org-prepare-agenda-buffers scope)
13380 (while (setq file (pop scope))
13381 (with-current-buffer (org-find-base-buffer-visiting file)
13382 (save-excursion
13383 (save-restriction
13384 (widen)
13385 (goto-char (point-min))
13386 (setq res (append res (org-scan-tags func matcher))))))))))
13387 res))
13389 ;;;; Properties
13391 ;;; Setting and retrieving properties
13393 (defconst org-special-properties
13394 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13395 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE")
13396 "The special properties valid in Org-mode.
13398 These are properties that are not defined in the property drawer,
13399 but in some other way.")
13401 (defconst org-default-properties
13402 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13403 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13404 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13405 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13406 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13407 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13408 "Some properties that are used by Org-mode for various purposes.
13409 Being in this list makes sure that they are offered for completion.")
13411 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13412 "Regular expression matching the first line of a property drawer.")
13414 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13415 "Regular expression matching the last line of a property drawer.")
13417 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13418 "Regular expression matching the first line of a property drawer.")
13420 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13421 "Regular expression matching the first line of a property drawer.")
13423 (defconst org-property-drawer-re
13424 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13425 org-property-end-re "\\)\n?")
13426 "Matches an entire property drawer.")
13428 (defconst org-clock-drawer-re
13429 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13430 org-property-end-re "\\)\n?")
13431 "Matches an entire clock drawer.")
13433 (defun org-property-action ()
13434 "Do an action on properties."
13435 (interactive)
13436 (let (c)
13437 (org-at-property-p)
13438 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13439 (setq c (read-char-exclusive))
13440 (cond
13441 ((equal c ?s)
13442 (call-interactively 'org-set-property))
13443 ((equal c ?d)
13444 (call-interactively 'org-delete-property))
13445 ((equal c ?D)
13446 (call-interactively 'org-delete-property-globally))
13447 ((equal c ?c)
13448 (call-interactively 'org-compute-property-at-point))
13449 (t (error "No such property action %c" c)))))
13451 (defun org-set-effort (&optional value)
13452 "Set the effort property of the current entry.
13453 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13454 allowed value."
13455 (interactive "P")
13456 (if (equal value 0) (setq value 10))
13457 (let* ((completion-ignore-case t)
13458 (prop org-effort-property)
13459 (cur (org-entry-get nil prop))
13460 (allowed (org-property-get-allowed-values nil prop 'table))
13461 (existing (mapcar 'list (org-property-values prop)))
13463 (val (cond
13464 ((stringp value) value)
13465 ((and allowed (integerp value))
13466 (or (car (nth (1- value) allowed))
13467 (car (org-last allowed))))
13468 (allowed
13469 (message "Select 1-9,0, [RET%s]: %s"
13470 (if cur (concat "=" cur) "")
13471 (mapconcat 'car allowed " "))
13472 (setq rpl (read-char-exclusive))
13473 (if (equal rpl ?\r)
13475 (setq rpl (- rpl ?0))
13476 (if (equal rpl 0) (setq rpl 10))
13477 (if (and (> rpl 0) (<= rpl (length allowed)))
13478 (car (nth (1- rpl) allowed))
13479 (org-completing-read "Effort: " allowed nil))))
13481 (let (org-completion-use-ido org-completion-use-iswitchb)
13482 (org-completing-read
13483 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13484 (concat "[" cur "]") "")
13485 ": ")
13486 existing nil nil "" nil cur))))))
13487 (unless (equal (org-entry-get nil prop) val)
13488 (org-entry-put nil prop val))
13489 (message "%s is now %s" prop val)))
13491 (defun org-at-property-p ()
13492 "Is cursor inside a property drawer?"
13493 (save-excursion
13494 (beginning-of-line 1)
13495 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13496 (save-match-data ;; Used by calling procedures
13497 (let ((p (point))
13498 (range (unless (org-before-first-heading-p)
13499 (org-get-property-block))))
13500 (and range (<= (car range) p) (< p (cdr range))))))))
13502 (defun org-get-property-block (&optional beg end force)
13503 "Return the (beg . end) range of the body of the property drawer.
13504 BEG and END can be beginning and end of subtree, if not given
13505 they will be found.
13506 If the drawer does not exist and FORCE is non-nil, create the drawer."
13507 (catch 'exit
13508 (save-excursion
13509 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13510 (end (or end (progn (outline-next-heading) (point)))))
13511 (goto-char beg)
13512 (if (re-search-forward org-property-start-re end t)
13513 (setq beg (1+ (match-end 0)))
13514 (if force
13515 (save-excursion
13516 (org-insert-property-drawer)
13517 (setq end (progn (outline-next-heading) (point))))
13518 (throw 'exit nil))
13519 (goto-char beg)
13520 (if (re-search-forward org-property-start-re end t)
13521 (setq beg (1+ (match-end 0)))))
13522 (if (re-search-forward org-property-end-re end t)
13523 (setq end (match-beginning 0))
13524 (or force (throw 'exit nil))
13525 (goto-char beg)
13526 (setq end beg)
13527 (org-indent-line-function)
13528 (insert ":END:\n"))
13529 (cons beg end)))))
13531 (defun org-entry-properties (&optional pom which specific)
13532 "Get all properties of the entry at point-or-marker POM.
13533 This includes the TODO keyword, the tags, time strings for deadline,
13534 scheduled, and clocking, and any additional properties defined in the
13535 entry. The return value is an alist, keys may occur multiple times
13536 if the property key was used several times.
13537 POM may also be nil, in which case the current entry is used.
13538 If WHICH is nil or `all', get all properties. If WHICH is
13539 `special' or `standard', only get that subclass. If WHICH
13540 is a string only get exactly this property. SPECIFIC can be a string, the
13541 specific property we are interested in. Specifying it can speed
13542 things up because then unnecessary parsing is avoided."
13543 (setq which (or which 'all))
13544 (org-with-point-at pom
13545 (let ((clockstr (substring org-clock-string 0 -1))
13546 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13547 (case-fold-search nil)
13548 beg end range props sum-props key key1 value string clocksum)
13549 (save-excursion
13550 (when (condition-case nil
13551 (and (org-mode-p) (org-back-to-heading t))
13552 (error nil))
13553 (setq beg (point))
13554 (setq sum-props (get-text-property (point) 'org-summaries))
13555 (setq clocksum (get-text-property (point) :org-clock-minutes))
13556 (outline-next-heading)
13557 (setq end (point))
13558 (when (memq which '(all special))
13559 ;; Get the special properties, like TODO and tags
13560 (goto-char beg)
13561 (when (and (or (not specific) (string= specific "TODO"))
13562 (looking-at org-todo-line-regexp) (match-end 2))
13563 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13564 (when (and (or (not specific) (string= specific "PRIORITY"))
13565 (looking-at org-priority-regexp))
13566 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13567 (when (or (not specific) (string= specific "FILE"))
13568 (push (cons "FILE" buffer-file-name) props))
13569 (when (and (or (not specific) (string= specific "TAGS"))
13570 (setq value (org-get-tags-string))
13571 (string-match "\\S-" value))
13572 (push (cons "TAGS" value) props))
13573 (when (and (or (not specific) (string= specific "ALLTAGS"))
13574 (setq value (org-get-tags-at)))
13575 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
13576 ":"))
13577 props))
13578 (when (or (not specific) (string= specific "BLOCKED"))
13579 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
13580 (when (or (not specific)
13581 (member specific
13582 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
13583 "TIMESTAMP" "TIMESTAMP_IA")))
13584 (catch 'match
13585 (while (re-search-forward org-maybe-keyword-time-regexp end t)
13586 (setq key (if (match-end 1)
13587 (substring (org-match-string-no-properties 1)
13588 0 -1))
13589 string (if (equal key clockstr)
13590 (org-no-properties
13591 (org-trim
13592 (buffer-substring
13593 (match-beginning 3) (goto-char
13594 (point-at-eol)))))
13595 (substring (org-match-string-no-properties 3)
13596 1 -1)))
13597 ;; Get the correct property name from the key. This is
13598 ;; necessary if the user has configured time keywords.
13599 (setq key1 (concat key ":"))
13600 (cond
13601 ((not key)
13602 (setq key
13603 (if (= (char-after (match-beginning 3)) ?\[)
13604 "TIMESTAMP_IA" "TIMESTAMP")))
13605 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
13606 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
13607 ((equal key1 org-closed-string) (setq key "CLOSED"))
13608 ((equal key1 org-clock-string) (setq key "CLOCK")))
13609 (if (and specific (equal key specific) (not (equal key "CLOCK")))
13610 (progn
13611 (push (cons key string) props)
13612 ;; no need to search further if match is found
13613 (throw 'match t))
13614 (when (or (equal key "CLOCK") (not (assoc key props)))
13615 (push (cons key string) props))))))
13618 (when (memq which '(all standard))
13619 ;; Get the standard properties, like :PROP: ...
13620 (setq range (org-get-property-block beg end))
13621 (when range
13622 (goto-char (car range))
13623 (while (re-search-forward
13624 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
13625 (cdr range) t)
13626 (setq key (org-match-string-no-properties 1)
13627 value (org-trim (or (org-match-string-no-properties 2) "")))
13628 (unless (member key excluded)
13629 (push (cons key (or value "")) props)))))
13630 (if clocksum
13631 (push (cons "CLOCKSUM"
13632 (org-columns-number-to-string (/ (float clocksum) 60.)
13633 'add_times))
13634 props))
13635 (unless (assoc "CATEGORY" props)
13636 (push (cons "CATEGORY" (org-get-category)) props))
13637 (append sum-props (nreverse props)))))))
13639 (defun org-entry-get (pom property &optional inherit literal-nil)
13640 "Get value of PROPERTY for entry at point-or-marker POM.
13641 If INHERIT is non-nil and the entry does not have the property,
13642 then also check higher levels of the hierarchy.
13643 If INHERIT is the symbol `selective', use inheritance only if the setting
13644 in `org-use-property-inheritance' selects PROPERTY for inheritance.
13645 If the property is present but empty, the return value is the empty string.
13646 If the property is not present at all, nil is returned.
13648 If LITERAL-NIL is set, return the string value \"nil\" as a string,
13649 do not interpret it as the list atom nil. This is used for inheritance
13650 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
13651 (org-with-point-at pom
13652 (if (and inherit (if (eq inherit 'selective)
13653 (org-property-inherit-p property)
13655 (org-entry-get-with-inheritance property literal-nil)
13656 (if (member property org-special-properties)
13657 ;; We need a special property. Use `org-entry-properties' to
13658 ;; retrieve it, but specify the wanted property
13659 (cdr (assoc property (org-entry-properties nil 'special property)))
13660 (let ((range (unless (org-before-first-heading-p)
13661 (org-get-property-block))))
13662 (if (and range
13663 (goto-char (car range))
13664 (re-search-forward
13665 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
13666 (cdr range) t))
13667 ;; Found the property, return it.
13668 (if (match-end 1)
13669 (if literal-nil
13670 (org-match-string-no-properties 1)
13671 (org-not-nil (org-match-string-no-properties 1)))
13672 "")))))))
13674 (defun org-property-or-variable-value (var &optional inherit)
13675 "Check if there is a property fixing the value of VAR.
13676 If yes, return this value. If not, return the current value of the variable."
13677 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13678 (if (and prop (stringp prop) (string-match "\\S-" prop))
13679 (read prop)
13680 (symbol-value var))))
13682 (defun org-entry-delete (pom property)
13683 "Delete the property PROPERTY from entry at point-or-marker POM."
13684 (org-with-point-at pom
13685 (if (member property org-special-properties)
13686 nil ; cannot delete these properties.
13687 (let ((range (org-get-property-block)))
13688 (if (and range
13689 (goto-char (car range))
13690 (re-search-forward
13691 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
13692 (cdr range) t))
13693 (progn
13694 (delete-region (match-beginning 0) (1+ (point-at-eol)))
13696 nil)))))
13698 ;; Multi-values properties are properties that contain multiple values
13699 ;; These values are assumed to be single words, separated by whitespace.
13700 (defun org-entry-add-to-multivalued-property (pom property value)
13701 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
13702 (let* ((old (org-entry-get pom property))
13703 (values (and old (org-split-string old "[ \t]"))))
13704 (setq value (org-entry-protect-space value))
13705 (unless (member value values)
13706 (setq values (cons value values))
13707 (org-entry-put pom property
13708 (mapconcat 'identity values " ")))))
13710 (defun org-entry-remove-from-multivalued-property (pom property value)
13711 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
13712 (let* ((old (org-entry-get pom property))
13713 (values (and old (org-split-string old "[ \t]"))))
13714 (setq value (org-entry-protect-space value))
13715 (when (member value values)
13716 (setq values (delete value values))
13717 (org-entry-put pom property
13718 (mapconcat 'identity values " ")))))
13720 (defun org-entry-member-in-multivalued-property (pom property value)
13721 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
13722 (let* ((old (org-entry-get pom property))
13723 (values (and old (org-split-string old "[ \t]"))))
13724 (setq value (org-entry-protect-space value))
13725 (member value values)))
13727 (defun org-entry-get-multivalued-property (pom property)
13728 "Return a list of values in a multivalued property."
13729 (let* ((value (org-entry-get pom property))
13730 (values (and value (org-split-string value "[ \t]"))))
13731 (mapcar 'org-entry-restore-space values)))
13733 (defun org-entry-put-multivalued-property (pom property &rest values)
13734 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
13735 VALUES should be a list of strings. Spaces will be protected."
13736 (org-entry-put pom property
13737 (mapconcat 'org-entry-protect-space values " "))
13738 (let* ((value (org-entry-get pom property))
13739 (values (and value (org-split-string value "[ \t]"))))
13740 (mapcar 'org-entry-restore-space values)))
13742 (defun org-entry-protect-space (s)
13743 "Protect spaces and newline in string S."
13744 (while (string-match " " s)
13745 (setq s (replace-match "%20" t t s)))
13746 (while (string-match "\n" s)
13747 (setq s (replace-match "%0A" t t s)))
13750 (defun org-entry-restore-space (s)
13751 "Restore spaces and newline in string S."
13752 (while (string-match "%20" s)
13753 (setq s (replace-match " " t t s)))
13754 (while (string-match "%0A" s)
13755 (setq s (replace-match "\n" t t s)))
13758 (defvar org-entry-property-inherited-from (make-marker)
13759 "Marker pointing to the entry from where a property was inherited.
13760 Each call to `org-entry-get-with-inheritance' will set this marker to the
13761 location of the entry where the inheritance search matched. If there was
13762 no match, the marker will point nowhere.
13763 Note that also `org-entry-get' calls this function, if the INHERIT flag
13764 is set.")
13766 (defun org-entry-get-with-inheritance (property &optional literal-nil)
13767 "Get entry property, and search higher levels if not present.
13768 The search will stop at the first ancestor which has the property defined.
13769 If the value found is \"nil\", return nil to show that the property
13770 should be considered as undefined (this is the meaning of nil here).
13771 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
13772 (move-marker org-entry-property-inherited-from nil)
13773 (let (tmp)
13774 (unless (org-before-first-heading-p)
13775 (save-excursion
13776 (save-restriction
13777 (widen)
13778 (catch 'ex
13779 (while t
13780 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
13781 (org-back-to-heading t)
13782 (move-marker org-entry-property-inherited-from (point))
13783 (throw 'ex tmp))
13784 (or (org-up-heading-safe) (throw 'ex nil)))))))
13785 (setq tmp (or tmp
13786 (cdr (assoc property org-file-properties))
13787 (cdr (assoc property org-global-properties))
13788 (cdr (assoc property org-global-properties-fixed))))
13789 (if literal-nil tmp (org-not-nil tmp))))
13791 (defvar org-property-changed-functions nil
13792 "Hook called when the value of a property has changed.
13793 Each hook function should accept two arguments, the name of the property
13794 and the new value.")
13796 (defun org-entry-put (pom property value)
13797 "Set PROPERTY to VALUE for entry at point-or-marker POM."
13798 (org-with-point-at pom
13799 (org-back-to-heading t)
13800 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
13801 range)
13802 (cond
13803 ((equal property "TODO")
13804 (when (and (stringp value) (string-match "\\S-" value)
13805 (not (member value org-todo-keywords-1)))
13806 (error "\"%s\" is not a valid TODO state" value))
13807 (if (or (not value)
13808 (not (string-match "\\S-" value)))
13809 (setq value 'none))
13810 (org-todo value)
13811 (org-set-tags nil 'align))
13812 ((equal property "PRIORITY")
13813 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
13814 (string-to-char value) ?\ ))
13815 (org-set-tags nil 'align))
13816 ((equal property "SCHEDULED")
13817 (if (re-search-forward org-scheduled-time-regexp end t)
13818 (cond
13819 ((eq value 'earlier) (org-timestamp-change -1 'day))
13820 ((eq value 'later) (org-timestamp-change 1 'day))
13821 (t (call-interactively 'org-schedule)))
13822 (call-interactively 'org-schedule)))
13823 ((equal property "DEADLINE")
13824 (if (re-search-forward org-deadline-time-regexp end t)
13825 (cond
13826 ((eq value 'earlier) (org-timestamp-change -1 'day))
13827 ((eq value 'later) (org-timestamp-change 1 'day))
13828 (t (call-interactively 'org-deadline)))
13829 (call-interactively 'org-deadline)))
13830 ((member property org-special-properties)
13831 (error "The %s property can not yet be set with `org-entry-put'"
13832 property))
13833 (t ; a non-special property
13834 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
13835 (setq range (org-get-property-block beg end 'force))
13836 (goto-char (car range))
13837 (if (re-search-forward
13838 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
13839 (progn
13840 (delete-region (match-beginning 1) (match-end 1))
13841 (goto-char (match-beginning 1)))
13842 (goto-char (cdr range))
13843 (insert "\n")
13844 (backward-char 1)
13845 (org-indent-line-function)
13846 (insert ":" property ":"))
13847 (and value (insert " " value))
13848 (org-indent-line-function)))))
13849 (run-hook-with-args 'org-property-changed-functions property value)))
13851 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
13852 "Get all property keys in the current buffer.
13853 With INCLUDE-SPECIALS, also list the special properties that reflect things
13854 like tags and TODO state.
13855 With INCLUDE-DEFAULTS, also include properties that has special meaning
13856 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
13857 With INCLUDE-COLUMNS, also include property names given in COLUMN
13858 formats in the current buffer."
13859 (let (rtn range cfmt s p)
13860 (save-excursion
13861 (save-restriction
13862 (widen)
13863 (goto-char (point-min))
13864 (while (re-search-forward org-property-start-re nil t)
13865 (setq range (org-get-property-block))
13866 (goto-char (car range))
13867 (while (re-search-forward
13868 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
13869 (cdr range) t)
13870 (add-to-list 'rtn (org-match-string-no-properties 1)))
13871 (outline-next-heading))))
13873 (when include-specials
13874 (setq rtn (append org-special-properties rtn)))
13876 (when include-defaults
13877 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
13878 (add-to-list 'rtn org-effort-property))
13880 (when include-columns
13881 (save-excursion
13882 (save-restriction
13883 (widen)
13884 (goto-char (point-min))
13885 (while (re-search-forward
13886 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
13887 nil t)
13888 (setq cfmt (match-string 2) s 0)
13889 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
13890 cfmt s)
13891 (setq s (match-end 0)
13892 p (match-string 1 cfmt))
13893 (unless (or (equal p "ITEM")
13894 (member p org-special-properties))
13895 (add-to-list 'rtn (match-string 1 cfmt))))))))
13897 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
13899 (defun org-property-values (key)
13900 "Return a list of all values of property KEY."
13901 (save-excursion
13902 (save-restriction
13903 (widen)
13904 (goto-char (point-min))
13905 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
13906 values)
13907 (while (re-search-forward re nil t)
13908 (add-to-list 'values (org-trim (match-string 1))))
13909 (delete "" values)))))
13911 (defun org-insert-property-drawer ()
13912 "Insert a property drawer into the current entry."
13913 (interactive)
13914 (org-back-to-heading t)
13915 (looking-at outline-regexp)
13916 (let ((indent (if org-adapt-indentation
13917 (- (match-end 0)(match-beginning 0))
13919 (beg (point))
13920 (re (concat "^[ \t]*" org-keyword-time-regexp))
13921 end hiddenp)
13922 (outline-next-heading)
13923 (setq end (point))
13924 (goto-char beg)
13925 (while (re-search-forward re end t))
13926 (setq hiddenp (outline-invisible-p))
13927 (end-of-line 1)
13928 (and (equal (char-after) ?\n) (forward-char 1))
13929 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
13930 (if (member (match-string 1) '("CLOCK:" ":END:"))
13931 ;; just skip this line
13932 (beginning-of-line 2)
13933 ;; Drawer start, find the end
13934 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
13935 (beginning-of-line 1)))
13936 (org-skip-over-state-notes)
13937 (skip-chars-backward " \t\n\r")
13938 (if (eq (char-before) ?*) (forward-char 1))
13939 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
13940 (beginning-of-line 0)
13941 (org-indent-to-column indent)
13942 (beginning-of-line 2)
13943 (org-indent-to-column indent)
13944 (beginning-of-line 0)
13945 (if hiddenp
13946 (save-excursion
13947 (org-back-to-heading t)
13948 (hide-entry))
13949 (org-flag-drawer t))))
13951 (defvar org-property-set-functions-alist nil
13952 "Property set function alist.
13953 Each entry should have the following format:
13955 (PROPERTY . READ-FUNCTION)
13957 The read function will be called with the same argument as
13958 `org-completing-read'.")
13960 (defun org-set-property-function (property)
13961 "Get the function that should be used to set PROPERTY.
13962 This is computed according to `org-property-set-functions-alist'."
13963 (or (cdr (assoc property org-property-set-functions-alist))
13964 'org-completing-read))
13966 (defun org-read-property-value (property)
13967 "Read PROPERTY value from user."
13968 (let* ((completion-ignore-case t)
13969 (allowed (org-property-get-allowed-values nil property 'table))
13970 (cur (org-entry-get nil property))
13971 (prompt (concat property " value"
13972 (if (and cur (string-match "\\S-" cur))
13973 (concat " [" cur "]") "") ": "))
13974 (set-function (org-set-property-function property))
13975 (val (if allowed
13976 (funcall set-function prompt allowed nil
13977 (not (get-text-property 0 'org-unrestricted
13978 (caar allowed))))
13979 (let (org-completion-use-ido org-completion-use-iswitchb)
13980 (funcall set-function prompt
13981 (mapcar 'list (org-property-values property))
13982 nil nil "" nil cur)))))
13983 (if (equal val "")
13985 val)))
13987 (defun org-read-property-name ()
13988 "Read a property name."
13989 (let* ((completion-ignore-case t)
13990 (keys (org-buffer-property-keys nil t t))
13991 (property (org-icompleting-read "Property: " (mapcar 'list keys))))
13992 (if (member property keys)
13993 property
13994 (or (cdr (assoc (downcase property)
13995 (mapcar (lambda (x) (cons (downcase x) x))
13996 keys)))
13997 property))))
13999 (defun org-set-property (property value)
14000 "In the current entry, set PROPERTY to VALUE.
14001 When called interactively, this will prompt for a property name, offering
14002 completion on existing and default properties. And then it will prompt
14003 for a value, offering completion either on allowed values (via an inherited
14004 xxx_ALL property) or on existing values in other instances of this property
14005 in the current file."
14006 (interactive (list nil nil))
14007 (let* ((property (or property (org-read-property-name)))
14008 (value (or value (org-read-property-value property))))
14009 (unless (equal (org-entry-get nil property) value)
14010 (org-entry-put nil property value))))
14012 (defun org-delete-property (property)
14013 "In the current entry, delete PROPERTY."
14014 (interactive
14015 (let* ((completion-ignore-case t)
14016 (prop (org-icompleting-read "Property: "
14017 (org-entry-properties nil 'standard))))
14018 (list prop)))
14019 (message "Property %s %s" property
14020 (if (org-entry-delete nil property)
14021 "deleted"
14022 "was not present in the entry")))
14024 (defun org-delete-property-globally (property)
14025 "Remove PROPERTY globally, from all entries."
14026 (interactive
14027 (let* ((completion-ignore-case t)
14028 (prop (org-icompleting-read
14029 "Globally remove property: "
14030 (mapcar 'list (org-buffer-property-keys)))))
14031 (list prop)))
14032 (save-excursion
14033 (save-restriction
14034 (widen)
14035 (goto-char (point-min))
14036 (let ((cnt 0))
14037 (while (re-search-forward
14038 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
14039 nil t)
14040 (setq cnt (1+ cnt))
14041 (replace-match ""))
14042 (message "Property \"%s\" removed from %d entries" property cnt)))))
14044 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14046 (defun org-compute-property-at-point ()
14047 "Compute the property at point.
14048 This looks for an enclosing column format, extracts the operator and
14049 then applies it to the property in the column format's scope."
14050 (interactive)
14051 (unless (org-at-property-p)
14052 (error "Not at a property"))
14053 (let ((prop (org-match-string-no-properties 2)))
14054 (org-columns-get-format-and-top-level)
14055 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14056 (error "No operator defined for property %s" prop))
14057 (org-columns-compute prop)))
14059 (defvar org-property-allowed-value-functions nil
14060 "Hook for functions supplying allowed values for a specific property.
14061 The functions must take a single argument, the name of the property, and
14062 return a flat list of allowed values. If \":ETC\" is one of
14063 the values, this means that these values are intended as defaults for
14064 completion, but that other values should be allowed too.
14065 The functions must return nil if they are not responsible for this
14066 property.")
14068 (defun org-property-get-allowed-values (pom property &optional table)
14069 "Get allowed values for the property PROPERTY.
14070 When TABLE is non-nil, return an alist that can directly be used for
14071 completion."
14072 (let (vals)
14073 (cond
14074 ((equal property "TODO")
14075 (setq vals (org-with-point-at pom
14076 (append org-todo-keywords-1 '("")))))
14077 ((equal property "PRIORITY")
14078 (let ((n org-lowest-priority))
14079 (while (>= n org-highest-priority)
14080 (push (char-to-string n) vals)
14081 (setq n (1- n)))))
14082 ((member property org-special-properties))
14083 ((setq vals (run-hook-with-args-until-success
14084 'org-property-allowed-value-functions property)))
14086 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14087 (when (and vals (string-match "\\S-" vals))
14088 (setq vals (car (read-from-string (concat "(" vals ")"))))
14089 (setq vals (mapcar (lambda (x)
14090 (cond ((stringp x) x)
14091 ((numberp x) (number-to-string x))
14092 ((symbolp x) (symbol-name x))
14093 (t "???")))
14094 vals)))))
14095 (when (member ":ETC" vals)
14096 (setq vals (remove ":ETC" vals))
14097 (org-add-props (car vals) '(org-unrestricted t)))
14098 (if table (mapcar 'list vals) vals)))
14100 (defun org-property-previous-allowed-value (&optional previous)
14101 "Switch to the next allowed value for this property."
14102 (interactive)
14103 (org-property-next-allowed-value t))
14105 (defun org-property-next-allowed-value (&optional previous)
14106 "Switch to the next allowed value for this property."
14107 (interactive)
14108 (unless (org-at-property-p)
14109 (error "Not at a property"))
14110 (let* ((key (match-string 2))
14111 (value (match-string 3))
14112 (allowed (or (org-property-get-allowed-values (point) key)
14113 (and (member value '("[ ]" "[-]" "[X]"))
14114 '("[ ]" "[X]"))))
14115 nval)
14116 (unless allowed
14117 (error "Allowed values for this property have not been defined"))
14118 (if previous (setq allowed (reverse allowed)))
14119 (if (member value allowed)
14120 (setq nval (car (cdr (member value allowed)))))
14121 (setq nval (or nval (car allowed)))
14122 (if (equal nval value)
14123 (error "Only one allowed value for this property"))
14124 (org-at-property-p)
14125 (replace-match (concat " :" key ": " nval) t t)
14126 (org-indent-line-function)
14127 (beginning-of-line 1)
14128 (skip-chars-forward " \t")
14129 (run-hook-with-args 'org-property-changed-functions key nval)))
14131 (defun org-find-olp (path &optional this-buffer)
14132 "Return a marker pointing to the entry at outline path OLP.
14133 If anything goes wrong, throw an error.
14134 You can wrap this call to catch the error like this:
14136 (condition-case msg
14137 (org-mobile-locate-entry (match-string 4))
14138 (error (nth 1 msg)))
14140 The return value will then be either a string with the error message,
14141 or a marker if everything is OK.
14143 If THIS-BUFFER is set, the outline path does not contain a file,
14144 only headings."
14145 (let* ((file (if this-buffer buffer-file-name (pop path)))
14146 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14147 (level 1)
14148 (lmin 1)
14149 (lmax 1)
14150 limit re end found pos heading cnt)
14151 (unless buffer (error "File not found :%s" file))
14152 (with-current-buffer buffer
14153 (save-excursion
14154 (save-restriction
14155 (widen)
14156 (setq limit (point-max))
14157 (goto-char (point-min))
14158 (while (setq heading (pop path))
14159 (setq re (format org-complex-heading-regexp-format
14160 (regexp-quote heading)))
14161 (setq cnt 0 pos (point))
14162 (while (re-search-forward re end t)
14163 (setq level (- (match-end 1) (match-beginning 1)))
14164 (if (and (>= level lmin) (<= level lmax))
14165 (setq found (match-beginning 0) cnt (1+ cnt))))
14166 (when (= cnt 0) (error "Heading not found on level %d: %s"
14167 lmax heading))
14168 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14169 lmax heading))
14170 (goto-char found)
14171 (setq lmin (1+ level) lmax (+ lmin (if org-odd-levels-only 1 0)))
14172 (setq end (save-excursion (org-end-of-subtree t t))))
14173 (when (org-on-heading-p)
14174 (move-marker (make-marker) (point))))))))
14176 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14177 "Find node HEADING in BUFFER.
14178 Return a marker to the heading if it was found, or nil if not.
14179 If POS-ONLY is set, return just the position instead of a marker.
14181 The heading text must match exact, but it may have a TODO keyword,
14182 a priority cookie and tags in the standard locations."
14183 (with-current-buffer (or buffer (current-buffer))
14184 (save-excursion
14185 (save-restriction
14186 (widen)
14187 (goto-char (point-min))
14188 (let (case-fold-search)
14189 (if (re-search-forward
14190 (format org-complex-heading-regexp-format
14191 (regexp-quote heading)) nil t)
14192 (if pos-only
14193 (match-beginning 0)
14194 (move-marker (make-marker) (match-beginning 0)))))))))
14196 (defun org-find-exact-heading-in-directory (heading &optional dir)
14197 "Find Org node headline HEADING in all .org files in directory DIR.
14198 When the target headline is found, return a marker to this location."
14199 (let ((files (directory-files (or dir default-directory)
14200 nil "\\`[^.#].*\\.org\\'"))
14201 file visiting m buffer)
14202 (catch 'found
14203 (while (setq file (pop files))
14204 (message "trying %s" file)
14205 (setq visiting (org-find-base-buffer-visiting file))
14206 (setq buffer (or visiting (find-file-noselect file)))
14207 (setq m (org-find-exact-headline-in-buffer
14208 heading buffer))
14209 (when (and (not m) (not visiting)) (kill-buffer buffer))
14210 (and m (throw 'found m))))))
14212 (defun org-find-entry-with-id (ident)
14213 "Locate the entry that contains the ID property with exact value IDENT.
14214 IDENT can be a string, a symbol or a number, this function will search for
14215 the string representation of it.
14216 Return the position where this entry starts, or nil if there is no such entry."
14217 (interactive "sID: ")
14218 (let ((id (cond
14219 ((stringp ident) ident)
14220 ((symbol-name ident) (symbol-name ident))
14221 ((numberp ident) (number-to-string ident))
14222 (t (error "IDENT %s must be a string, symbol or number" ident))))
14223 (case-fold-search nil))
14224 (save-excursion
14225 (save-restriction
14226 (widen)
14227 (goto-char (point-min))
14228 (when (re-search-forward
14229 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14230 nil t)
14231 (org-back-to-heading t)
14232 (point))))))
14234 ;;;; Timestamps
14236 (defvar org-last-changed-timestamp nil)
14237 (defvar org-last-inserted-timestamp nil
14238 "The last time stamp inserted with `org-insert-time-stamp'.")
14239 (defvar org-time-was-given) ; dynamically scoped parameter
14240 (defvar org-end-time-was-given) ; dynamically scoped parameter
14241 (defvar org-ts-what) ; dynamically scoped parameter
14243 (defun org-time-stamp (arg &optional inactive)
14244 "Prompt for a date/time and insert a time stamp.
14245 If the user specifies a time like HH:MM, or if this command is called
14246 with a prefix argument, the time stamp will contain date and time.
14247 Otherwise, only the date will be included. All parts of a date not
14248 specified by the user will be filled in from the current date/time.
14249 So if you press just return without typing anything, the time stamp
14250 will represent the current date/time. If there is already a timestamp
14251 at the cursor, it will be modified."
14252 (interactive "P")
14253 (let* ((ts nil)
14254 (default-time
14255 ;; Default time is either today, or, when entering a range,
14256 ;; the range start.
14257 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14258 (save-excursion
14259 (re-search-backward
14260 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14261 (- (point) 20) t)))
14262 (apply 'encode-time (org-parse-time-string (match-string 1)))
14263 (current-time)))
14264 (default-input (and ts (org-get-compact-tod ts)))
14265 org-time-was-given org-end-time-was-given time)
14266 (cond
14267 ((and (org-at-timestamp-p t)
14268 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14269 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14270 (insert "--")
14271 (setq time (let ((this-command this-command))
14272 (org-read-date arg 'totime nil nil
14273 default-time default-input)))
14274 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14275 ((org-at-timestamp-p t)
14276 (setq time (let ((this-command this-command))
14277 (org-read-date arg 'totime nil nil default-time default-input)))
14278 (when (org-at-timestamp-p t) ; just to get the match data
14279 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14280 (replace-match "")
14281 (setq org-last-changed-timestamp
14282 (org-insert-time-stamp
14283 time (or org-time-was-given arg)
14284 inactive nil nil (list org-end-time-was-given))))
14285 (message "Timestamp updated"))
14287 (setq time (let ((this-command this-command))
14288 (org-read-date arg 'totime nil nil default-time default-input)))
14289 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14290 nil nil (list org-end-time-was-given))))))
14292 ;; FIXME: can we use this for something else, like computing time differences?
14293 (defun org-get-compact-tod (s)
14294 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14295 (let* ((t1 (match-string 1 s))
14296 (h1 (string-to-number (match-string 2 s)))
14297 (m1 (string-to-number (match-string 3 s)))
14298 (t2 (and (match-end 4) (match-string 5 s)))
14299 (h2 (and t2 (string-to-number (match-string 6 s))))
14300 (m2 (and t2 (string-to-number (match-string 7 s))))
14301 dh dm)
14302 (if (not t2)
14304 (setq dh (- h2 h1) dm (- m2 m1))
14305 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14306 (concat t1 "+" (number-to-string dh)
14307 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14309 (defun org-time-stamp-inactive (&optional arg)
14310 "Insert an inactive time stamp.
14311 An inactive time stamp is enclosed in square brackets instead of angle
14312 brackets. It is inactive in the sense that it does not trigger agenda entries,
14313 does not link to the calendar and cannot be changed with the S-cursor keys.
14314 So these are more for recording a certain time/date."
14315 (interactive "P")
14316 (org-time-stamp arg 'inactive))
14318 (defvar org-date-ovl (make-overlay 1 1))
14319 (overlay-put org-date-ovl 'face 'org-warning)
14320 (org-detach-overlay org-date-ovl)
14322 (defvar org-ans1) ; dynamically scoped parameter
14323 (defvar org-ans2) ; dynamically scoped parameter
14325 (defvar org-plain-time-of-day-regexp) ; defined below
14327 (defvar org-overriding-default-time nil) ; dynamically scoped
14328 (defvar org-read-date-overlay nil)
14329 (defvar org-dcst nil) ; dynamically scoped
14330 (defvar org-read-date-history nil)
14331 (defvar org-read-date-final-answer nil)
14333 (defun org-read-date (&optional with-time to-time from-string prompt
14334 default-time default-input)
14335 "Read a date, possibly a time, and make things smooth for the user.
14336 The prompt will suggest to enter an ISO date, but you can also enter anything
14337 which will at least partially be understood by `parse-time-string'.
14338 Unrecognized parts of the date will default to the current day, month, year,
14339 hour and minute. If this command is called to replace a timestamp at point,
14340 of to enter the second timestamp of a range, the default time is taken
14341 from the existing stamp. Furthermore, the command prefers the future,
14342 so if you are giving a date where the year is not given, and the day-month
14343 combination is already past in the current year, it will assume you
14344 mean next year. For details, see the manual. A few examples:
14346 3-2-5 --> 2003-02-05
14347 feb 15 --> currentyear-02-15
14348 2/15 --> currentyear-02-15
14349 sep 12 9 --> 2009-09-12
14350 12:45 --> today 12:45
14351 22 sept 0:34 --> currentyear-09-22 0:34
14352 12 --> currentyear-currentmonth-12
14353 Fri --> nearest Friday (today or later)
14354 etc.
14356 Furthermore you can specify a relative date by giving, as the *first* thing
14357 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14358 change in days weeks, months, years.
14359 With a single plus or minus, the date is relative to today. With a double
14360 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14361 +4d --> four days from today
14362 +4 --> same as above
14363 +2w --> two weeks from today
14364 ++5 --> five days from default date
14366 The function understands only English month and weekday abbreviations,
14367 but this can be configured with the variables `parse-time-months' and
14368 `parse-time-weekdays'.
14370 While prompting, a calendar is popped up - you can also select the
14371 date with the mouse (button 1). The calendar shows a period of three
14372 months. To scroll it to other months, use the keys `>' and `<'.
14373 If you don't like the calendar, turn it off with
14374 \(setq org-read-date-popup-calendar nil)
14376 With optional argument TO-TIME, the date will immediately be converted
14377 to an internal time.
14378 With an optional argument WITH-TIME, the prompt will suggest to also
14379 insert a time. Note that when WITH-TIME is not set, you can still
14380 enter a time, and this function will inform the calling routine about
14381 this change. The calling routine may then choose to change the format
14382 used to insert the time stamp into the buffer to include the time.
14383 With optional argument FROM-STRING, read from this string instead from
14384 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14385 the time/date that is used for everything that is not specified by the
14386 user."
14387 (require 'parse-time)
14388 (let* ((org-time-stamp-rounding-minutes
14389 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14390 (org-dcst org-display-custom-times)
14391 (ct (org-current-time))
14392 (def (or org-overriding-default-time default-time ct))
14393 (defdecode (decode-time def))
14394 (dummy (progn
14395 (when (< (nth 2 defdecode) org-extend-today-until)
14396 (setcar (nthcdr 2 defdecode) -1)
14397 (setcar (nthcdr 1 defdecode) 59)
14398 (setq def (apply 'encode-time defdecode)
14399 defdecode (decode-time def)))))
14400 (calendar-frame-setup nil)
14401 (calendar-setup nil)
14402 (calendar-move-hook nil)
14403 (calendar-view-diary-initially-flag nil)
14404 (calendar-view-holidays-initially-flag nil)
14405 (timestr (format-time-string
14406 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14407 (prompt (concat (if prompt (concat prompt " ") "")
14408 (format "Date+time [%s]: " timestr)))
14409 ans (org-ans0 "") org-ans1 org-ans2 final)
14411 (cond
14412 (from-string (setq ans from-string))
14413 (org-read-date-popup-calendar
14414 (save-excursion
14415 (save-window-excursion
14416 (calendar)
14417 (calendar-forward-day (- (time-to-days def)
14418 (calendar-absolute-from-gregorian
14419 (calendar-current-date))))
14420 (org-eval-in-calendar nil t)
14421 (let* ((old-map (current-local-map))
14422 (map (copy-keymap calendar-mode-map))
14423 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14424 (org-defkey map (kbd "RET") 'org-calendar-select)
14425 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14426 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14427 (org-defkey minibuffer-local-map [(meta shift left)]
14428 (lambda () (interactive)
14429 (org-eval-in-calendar '(calendar-backward-month 1))))
14430 (org-defkey minibuffer-local-map [(meta shift right)]
14431 (lambda () (interactive)
14432 (org-eval-in-calendar '(calendar-forward-month 1))))
14433 (org-defkey minibuffer-local-map [(meta shift up)]
14434 (lambda () (interactive)
14435 (org-eval-in-calendar '(calendar-backward-year 1))))
14436 (org-defkey minibuffer-local-map [(meta shift down)]
14437 (lambda () (interactive)
14438 (org-eval-in-calendar '(calendar-forward-year 1))))
14439 (org-defkey minibuffer-local-map [?\e (shift left)]
14440 (lambda () (interactive)
14441 (org-eval-in-calendar '(calendar-backward-month 1))))
14442 (org-defkey minibuffer-local-map [?\e (shift right)]
14443 (lambda () (interactive)
14444 (org-eval-in-calendar '(calendar-forward-month 1))))
14445 (org-defkey minibuffer-local-map [?\e (shift up)]
14446 (lambda () (interactive)
14447 (org-eval-in-calendar '(calendar-backward-year 1))))
14448 (org-defkey minibuffer-local-map [?\e (shift down)]
14449 (lambda () (interactive)
14450 (org-eval-in-calendar '(calendar-forward-year 1))))
14451 (org-defkey minibuffer-local-map [(shift up)]
14452 (lambda () (interactive)
14453 (org-eval-in-calendar '(calendar-backward-week 1))))
14454 (org-defkey minibuffer-local-map [(shift down)]
14455 (lambda () (interactive)
14456 (org-eval-in-calendar '(calendar-forward-week 1))))
14457 (org-defkey minibuffer-local-map [(shift left)]
14458 (lambda () (interactive)
14459 (org-eval-in-calendar '(calendar-backward-day 1))))
14460 (org-defkey minibuffer-local-map [(shift right)]
14461 (lambda () (interactive)
14462 (org-eval-in-calendar '(calendar-forward-day 1))))
14463 (org-defkey minibuffer-local-map ">"
14464 (lambda () (interactive)
14465 (org-eval-in-calendar '(scroll-calendar-left 1))))
14466 (org-defkey minibuffer-local-map "<"
14467 (lambda () (interactive)
14468 (org-eval-in-calendar '(scroll-calendar-right 1))))
14469 (org-defkey minibuffer-local-map "\C-v"
14470 (lambda () (interactive)
14471 (org-eval-in-calendar
14472 '(calendar-scroll-left-three-months 1))))
14473 (org-defkey minibuffer-local-map "\M-v"
14474 (lambda () (interactive)
14475 (org-eval-in-calendar
14476 '(calendar-scroll-right-three-months 1))))
14477 (run-hooks 'org-read-date-minibuffer-setup-hook)
14478 (unwind-protect
14479 (progn
14480 (use-local-map map)
14481 (add-hook 'post-command-hook 'org-read-date-display)
14482 (setq org-ans0 (read-string prompt default-input
14483 'org-read-date-history nil))
14484 ;; org-ans0: from prompt
14485 ;; org-ans1: from mouse click
14486 ;; org-ans2: from calendar motion
14487 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14488 (remove-hook 'post-command-hook 'org-read-date-display)
14489 (use-local-map old-map)
14490 (when org-read-date-overlay
14491 (delete-overlay org-read-date-overlay)
14492 (setq org-read-date-overlay nil)))))))
14494 (t ; Naked prompt only
14495 (unwind-protect
14496 (setq ans (read-string prompt default-input
14497 'org-read-date-history timestr))
14498 (when org-read-date-overlay
14499 (delete-overlay org-read-date-overlay)
14500 (setq org-read-date-overlay nil)))))
14502 (setq final (org-read-date-analyze ans def defdecode))
14504 ;; One round trip to get rid of 34th of August and stuff like that....
14505 (setq final (decode-time (apply 'encode-time final)))
14507 (setq org-read-date-final-answer ans)
14509 (if to-time
14510 (apply 'encode-time final)
14511 (if (and (boundp 'org-time-was-given) org-time-was-given)
14512 (format "%04d-%02d-%02d %02d:%02d"
14513 (nth 5 final) (nth 4 final) (nth 3 final)
14514 (nth 2 final) (nth 1 final))
14515 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
14517 (defvar def)
14518 (defvar defdecode)
14519 (defvar with-time)
14520 (defvar org-read-date-analyze-futurep nil)
14521 (defun org-read-date-display ()
14522 "Display the current date prompt interpretation in the minibuffer."
14523 (when org-read-date-display-live
14524 (when org-read-date-overlay
14525 (delete-overlay org-read-date-overlay))
14526 (let ((p (point)))
14527 (end-of-line 1)
14528 (while (not (equal (buffer-substring
14529 (max (point-min) (- (point) 4)) (point))
14530 " "))
14531 (insert " "))
14532 (goto-char p))
14533 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
14534 " " (or org-ans1 org-ans2)))
14535 (org-end-time-was-given nil)
14536 (f (org-read-date-analyze ans def defdecode))
14537 (fmts (if org-dcst
14538 org-time-stamp-custom-formats
14539 org-time-stamp-formats))
14540 (fmt (if (or with-time
14541 (and (boundp 'org-time-was-given) org-time-was-given))
14542 (cdr fmts)
14543 (car fmts)))
14544 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
14545 (when (and org-end-time-was-given
14546 (string-match org-plain-time-of-day-regexp txt))
14547 (setq txt (concat (substring txt 0 (match-end 0)) "-"
14548 org-end-time-was-given
14549 (substring txt (match-end 0)))))
14550 (when org-read-date-analyze-futurep
14551 (setq txt (concat txt " (=>F)")))
14552 (setq org-read-date-overlay
14553 (make-overlay (1- (point-at-eol)) (point-at-eol)))
14554 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
14556 (defun org-read-date-analyze (ans def defdecode)
14557 "Analyze the combined answer of the date prompt."
14558 ;; FIXME: cleanup and comment
14559 (let ((nowdecode (decode-time (current-time)))
14560 delta deltan deltaw deltadef year month day
14561 hour minute second wday pm h2 m2 tl wday1
14562 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
14563 (setq org-read-date-analyze-futurep nil)
14564 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
14565 (setq ans "+0"))
14567 (when (setq delta (org-read-date-get-relative ans (current-time) def))
14568 (setq ans (replace-match "" t t ans)
14569 deltan (car delta)
14570 deltaw (nth 1 delta)
14571 deltadef (nth 2 delta)))
14573 ;; Check if there is an iso week date in there
14574 ;; If yes, store the info and postpone interpreting it until the rest
14575 ;; of the parsing is done
14576 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
14577 (setq iso-year (if (match-end 1)
14578 (org-small-year-to-year
14579 (string-to-number (match-string 1 ans))))
14580 iso-weekday (if (match-end 3)
14581 (string-to-number (match-string 3 ans)))
14582 iso-week (string-to-number (match-string 2 ans)))
14583 (setq ans (replace-match "" t t ans)))
14585 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
14586 (when (string-match
14587 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
14588 (setq year (if (match-end 2)
14589 (string-to-number (match-string 2 ans))
14590 (progn (setq kill-year t)
14591 (string-to-number (format-time-string "%Y"))))
14592 month (string-to-number (match-string 3 ans))
14593 day (string-to-number (match-string 4 ans)))
14594 (if (< year 100) (setq year (+ 2000 year)))
14595 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14596 t nil ans)))
14597 ;; Help matching american dates, like 5/30 or 5/30/7
14598 (when (string-match
14599 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
14600 (setq year (if (match-end 4)
14601 (string-to-number (match-string 4 ans))
14602 (progn (setq kill-year t)
14603 (string-to-number (format-time-string "%Y"))))
14604 month (string-to-number (match-string 1 ans))
14605 day (string-to-number (match-string 2 ans)))
14606 (if (< year 100) (setq year (+ 2000 year)))
14607 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14608 t nil ans)))
14609 ;; Help matching am/pm times, because `parse-time-string' does not do that.
14610 ;; If there is a time with am/pm, and *no* time without it, we convert
14611 ;; so that matching will be successful.
14612 (loop for i from 1 to 2 do ; twice, for end time as well
14613 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
14614 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
14615 (setq hour (string-to-number (match-string 1 ans))
14616 minute (if (match-end 3)
14617 (string-to-number (match-string 3 ans))
14619 pm (equal ?p
14620 (string-to-char (downcase (match-string 4 ans)))))
14621 (if (and (= hour 12) (not pm))
14622 (setq hour 0)
14623 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
14624 (setq ans (replace-match (format "%02d:%02d" hour minute)
14625 t t ans))))
14627 ;; Check if a time range is given as a duration
14628 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
14629 (setq hour (string-to-number (match-string 1 ans))
14630 h2 (+ hour (string-to-number (match-string 3 ans)))
14631 minute (string-to-number (match-string 2 ans))
14632 m2 (+ minute (if (match-end 5) (string-to-number
14633 (match-string 5 ans))0)))
14634 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
14635 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
14636 t t ans)))
14638 ;; Check if there is a time range
14639 (when (boundp 'org-end-time-was-given)
14640 (setq org-time-was-given nil)
14641 (when (and (string-match org-plain-time-of-day-regexp ans)
14642 (match-end 8))
14643 (setq org-end-time-was-given (match-string 8 ans))
14644 (setq ans (concat (substring ans 0 (match-beginning 7))
14645 (substring ans (match-end 7))))))
14647 (setq tl (parse-time-string ans)
14648 day (or (nth 3 tl) (nth 3 defdecode))
14649 month (or (nth 4 tl)
14650 (if (and org-read-date-prefer-future
14651 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
14652 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
14653 (nth 4 defdecode)))
14654 year (or (and (not kill-year) (nth 5 tl))
14655 (if (and org-read-date-prefer-future
14656 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
14657 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
14658 (nth 5 defdecode)))
14659 hour (or (nth 2 tl) (nth 2 defdecode))
14660 minute (or (nth 1 tl) (nth 1 defdecode))
14661 second (or (nth 0 tl) 0)
14662 wday (nth 6 tl))
14664 (when (and (eq org-read-date-prefer-future 'time)
14665 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
14666 (equal day (nth 3 nowdecode))
14667 (equal month (nth 4 nowdecode))
14668 (equal year (nth 5 nowdecode))
14669 (nth 2 tl)
14670 (or (< (nth 2 tl) (nth 2 nowdecode))
14671 (and (= (nth 2 tl) (nth 2 nowdecode))
14672 (nth 1 tl)
14673 (< (nth 1 tl) (nth 1 nowdecode)))))
14674 (setq day (1+ day)
14675 futurep t))
14677 ;; Special date definitions below
14678 (cond
14679 (iso-week
14680 ;; There was an iso week
14681 (require 'cal-iso)
14682 (setq futurep nil)
14683 (setq year (or iso-year year)
14684 day (or iso-weekday wday 1)
14685 wday nil ; to make sure that the trigger below does not match
14686 iso-date (calendar-gregorian-from-absolute
14687 (calendar-absolute-from-iso
14688 (list iso-week day year))))
14689 ; FIXME: Should we also push ISO weeks into the future?
14690 ; (when (and org-read-date-prefer-future
14691 ; (not iso-year)
14692 ; (< (calendar-absolute-from-gregorian iso-date)
14693 ; (time-to-days (current-time))))
14694 ; (setq year (1+ year)
14695 ; iso-date (calendar-gregorian-from-absolute
14696 ; (calendar-absolute-from-iso
14697 ; (list iso-week day year)))))
14698 (setq month (car iso-date)
14699 year (nth 2 iso-date)
14700 day (nth 1 iso-date)))
14701 (deltan
14702 (setq futurep nil)
14703 (unless deltadef
14704 (let ((now (decode-time (current-time))))
14705 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
14706 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
14707 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
14708 ((equal deltaw "m") (setq month (+ month deltan)))
14709 ((equal deltaw "y") (setq year (+ year deltan)))))
14710 ((and wday (not (nth 3 tl)))
14711 (setq futurep nil)
14712 ;; Weekday was given, but no day, so pick that day in the week
14713 ;; on or after the derived date.
14714 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
14715 (unless (equal wday wday1)
14716 (setq day (+ day (% (- wday wday1 -7) 7))))))
14717 (if (and (boundp 'org-time-was-given)
14718 (nth 2 tl))
14719 (setq org-time-was-given t))
14720 (if (< year 100) (setq year (+ 2000 year)))
14721 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
14722 (setq org-read-date-analyze-futurep futurep)
14723 (list second minute hour day month year)))
14725 (defvar parse-time-weekdays)
14727 (defun org-read-date-get-relative (s today default)
14728 "Check string S for special relative date string.
14729 TODAY and DEFAULT are internal times, for today and for a default.
14730 Return shift list (N what def-flag)
14731 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
14732 N is the number of WHATs to shift.
14733 DEF-FLAG is t when a double ++ or -- indicates shift relative to
14734 the DEFAULT date rather than TODAY."
14735 (when (and
14736 (string-match
14737 (concat
14738 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
14739 "\\([0-9]+\\)?"
14740 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
14741 "\\([ \t]\\|$\\)") s)
14742 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
14743 (let* ((dir (if (> (match-end 1) (match-beginning 1))
14744 (string-to-char (substring (match-string 1 s) -1))
14745 ?+))
14746 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
14747 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
14748 (what (if (match-end 3) (match-string 3 s) "d"))
14749 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
14750 (date (if rel default today))
14751 (wday (nth 6 (decode-time date)))
14752 delta)
14753 (if wday1
14754 (progn
14755 (setq delta (mod (+ 7 (- wday1 wday)) 7))
14756 (if (= dir ?-) (setq delta (- delta 7)))
14757 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
14758 (list delta "d" rel))
14759 (list (* n (if (= dir ?-) -1 1)) what rel)))))
14761 (defun org-order-calendar-date-args (arg1 arg2 arg3)
14762 "Turn a user-specified date into the internal representation.
14763 The internal representation needed by the calendar is (month day year).
14764 This is a wrapper to handle the brain-dead convention in calendar that
14765 user function argument order change dependent on argument order."
14766 (if (boundp 'calendar-date-style)
14767 (cond
14768 ((eq calendar-date-style 'american)
14769 (list arg1 arg2 arg3))
14770 ((eq calendar-date-style 'european)
14771 (list arg2 arg1 arg3))
14772 ((eq calendar-date-style 'iso)
14773 (list arg2 arg3 arg1)))
14774 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
14775 (if (org-bound-and-true-p european-calendar-style)
14776 (list arg2 arg1 arg3)
14777 (list arg1 arg2 arg3)))))
14779 (defun org-eval-in-calendar (form &optional keepdate)
14780 "Eval FORM in the calendar window and return to current window.
14781 Also, store the cursor date in variable org-ans2."
14782 (let ((sf (selected-frame))
14783 (sw (selected-window)))
14784 (select-window (get-buffer-window "*Calendar*" t))
14785 (eval form)
14786 (when (and (not keepdate) (calendar-cursor-to-date))
14787 (let* ((date (calendar-cursor-to-date))
14788 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14789 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
14790 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
14791 (select-window sw)
14792 (org-select-frame-set-input-focus sf)))
14794 (defun org-calendar-select ()
14795 "Return to `org-read-date' with the date currently selected.
14796 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14797 (interactive)
14798 (when (calendar-cursor-to-date)
14799 (let* ((date (calendar-cursor-to-date))
14800 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14801 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14802 (if (active-minibuffer-window) (exit-minibuffer))))
14804 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
14805 "Insert a date stamp for the date given by the internal TIME.
14806 WITH-HM means use the stamp format that includes the time of the day.
14807 INACTIVE means use square brackets instead of angular ones, so that the
14808 stamp will not contribute to the agenda.
14809 PRE and POST are optional strings to be inserted before and after the
14810 stamp.
14811 The command returns the inserted time stamp."
14812 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
14813 stamp)
14814 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
14815 (insert-before-markers (or pre ""))
14816 (when (listp extra)
14817 (setq extra (car extra))
14818 (if (and (stringp extra)
14819 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
14820 (setq extra (format "-%02d:%02d"
14821 (string-to-number (match-string 1 extra))
14822 (string-to-number (match-string 2 extra))))
14823 (setq extra nil)))
14824 (when extra
14825 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
14826 (insert-before-markers (setq stamp (format-time-string fmt time)))
14827 (insert-before-markers (or post ""))
14828 (setq org-last-inserted-timestamp stamp)))
14830 (defun org-toggle-time-stamp-overlays ()
14831 "Toggle the use of custom time stamp formats."
14832 (interactive)
14833 (setq org-display-custom-times (not org-display-custom-times))
14834 (unless org-display-custom-times
14835 (let ((p (point-min)) (bmp (buffer-modified-p)))
14836 (while (setq p (next-single-property-change p 'display))
14837 (if (and (get-text-property p 'display)
14838 (eq (get-text-property p 'face) 'org-date))
14839 (remove-text-properties
14840 p (setq p (next-single-property-change p 'display))
14841 '(display t))))
14842 (set-buffer-modified-p bmp)))
14843 (if (featurep 'xemacs)
14844 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
14845 (org-restart-font-lock)
14846 (setq org-table-may-need-update t)
14847 (if org-display-custom-times
14848 (message "Time stamps are overlayed with custom format")
14849 (message "Time stamp overlays removed")))
14851 (defun org-display-custom-time (beg end)
14852 "Overlay modified time stamp format over timestamp between BEG and END."
14853 (let* ((ts (buffer-substring beg end))
14854 t1 w1 with-hm tf time str w2 (off 0))
14855 (save-match-data
14856 (setq t1 (org-parse-time-string ts t))
14857 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
14858 (setq off (- (match-end 0) (match-beginning 0)))))
14859 (setq end (- end off))
14860 (setq w1 (- end beg)
14861 with-hm (and (nth 1 t1) (nth 2 t1))
14862 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
14863 time (org-fix-decoded-time t1)
14864 str (org-add-props
14865 (format-time-string
14866 (substring tf 1 -1) (apply 'encode-time time))
14867 nil 'mouse-face 'highlight)
14868 w2 (length str))
14869 (if (not (= w2 w1))
14870 (add-text-properties (1+ beg) (+ 2 beg)
14871 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
14872 (if (featurep 'xemacs)
14873 (progn
14874 (put-text-property beg end 'invisible t)
14875 (put-text-property beg end 'end-glyph (make-glyph str)))
14876 (put-text-property beg end 'display str))))
14878 (defun org-translate-time (string)
14879 "Translate all timestamps in STRING to custom format.
14880 But do this only if the variable `org-display-custom-times' is set."
14881 (when org-display-custom-times
14882 (save-match-data
14883 (let* ((start 0)
14884 (re org-ts-regexp-both)
14885 t1 with-hm inactive tf time str beg end)
14886 (while (setq start (string-match re string start))
14887 (setq beg (match-beginning 0)
14888 end (match-end 0)
14889 t1 (save-match-data
14890 (org-parse-time-string (substring string beg end) t))
14891 with-hm (and (nth 1 t1) (nth 2 t1))
14892 inactive (equal (substring string beg (1+ beg)) "[")
14893 tf (funcall (if with-hm 'cdr 'car)
14894 org-time-stamp-custom-formats)
14895 time (org-fix-decoded-time t1)
14896 str (format-time-string
14897 (concat
14898 (if inactive "[" "<") (substring tf 1 -1)
14899 (if inactive "]" ">"))
14900 (apply 'encode-time time))
14901 string (replace-match str t t string)
14902 start (+ start (length str)))))))
14903 string)
14905 (defun org-fix-decoded-time (time)
14906 "Set 0 instead of nil for the first 6 elements of time.
14907 Don't touch the rest."
14908 (let ((n 0))
14909 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
14911 (defun org-days-to-time (timestamp-string)
14912 "Difference between TIMESTAMP-STRING and now in days."
14913 (- (time-to-days (org-time-string-to-time timestamp-string))
14914 (time-to-days (current-time))))
14916 (defun org-deadline-close (timestamp-string &optional ndays)
14917 "Is the time in TIMESTAMP-STRING close to the current date?"
14918 (setq ndays (or ndays (org-get-wdays timestamp-string)))
14919 (and (< (org-days-to-time timestamp-string) ndays)
14920 (not (org-entry-is-done-p))))
14922 (defun org-get-wdays (ts)
14923 "Get the deadline lead time appropriate for timestring TS."
14924 (cond
14925 ((<= org-deadline-warning-days 0)
14926 ;; 0 or negative, enforce this value no matter what
14927 (- org-deadline-warning-days))
14928 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
14929 ;; lead time is specified.
14930 (floor (* (string-to-number (match-string 1 ts))
14931 (cdr (assoc (match-string 2 ts)
14932 '(("d" . 1) ("w" . 7)
14933 ("m" . 30.4) ("y" . 365.25)))))))
14934 ;; go for the default.
14935 (t org-deadline-warning-days)))
14937 (defun org-calendar-select-mouse (ev)
14938 "Return to `org-read-date' with the date currently selected.
14939 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14940 (interactive "e")
14941 (mouse-set-point ev)
14942 (when (calendar-cursor-to-date)
14943 (let* ((date (calendar-cursor-to-date))
14944 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14945 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14946 (if (active-minibuffer-window) (exit-minibuffer))))
14948 (defun org-check-deadlines (ndays)
14949 "Check if there are any deadlines due or past due.
14950 A deadline is considered due if it happens within `org-deadline-warning-days'
14951 days from today's date. If the deadline appears in an entry marked DONE,
14952 it is not shown. The prefix arg NDAYS can be used to test that many
14953 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
14954 (interactive "P")
14955 (let* ((org-warn-days
14956 (cond
14957 ((equal ndays '(4)) 100000)
14958 (ndays (prefix-numeric-value ndays))
14959 (t (abs org-deadline-warning-days))))
14960 (case-fold-search nil)
14961 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
14962 (callback
14963 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
14965 (message "%d deadlines past-due or due within %d days"
14966 (org-occur regexp nil callback)
14967 org-warn-days)))
14969 (defun org-check-before-date (date)
14970 "Check if there are deadlines or scheduled entries before DATE."
14971 (interactive (list (org-read-date)))
14972 (let ((case-fold-search nil)
14973 (regexp (concat "\\<\\(" org-deadline-string
14974 "\\|" org-scheduled-string
14975 "\\) *<\\([^>]+\\)>"))
14976 (callback
14977 (lambda () (time-less-p
14978 (org-time-string-to-time (match-string 2))
14979 (org-time-string-to-time date)))))
14980 (message "%d entries before %s"
14981 (org-occur regexp nil callback) date)))
14983 (defun org-check-after-date (date)
14984 "Check if there are deadlines or scheduled entries after DATE."
14985 (interactive (list (org-read-date)))
14986 (let ((case-fold-search nil)
14987 (regexp (concat "\\<\\(" org-deadline-string
14988 "\\|" org-scheduled-string
14989 "\\) *<\\([^>]+\\)>"))
14990 (callback
14991 (lambda () (not
14992 (time-less-p
14993 (org-time-string-to-time (match-string 2))
14994 (org-time-string-to-time date))))))
14995 (message "%d entries after %s"
14996 (org-occur regexp nil callback) date)))
14998 (defun org-evaluate-time-range (&optional to-buffer)
14999 "Evaluate a time range by computing the difference between start and end.
15000 Normally the result is just printed in the echo area, but with prefix arg
15001 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15002 If the time range is actually in a table, the result is inserted into the
15003 next column.
15004 For time difference computation, a year is assumed to be exactly 365
15005 days in order to avoid rounding problems."
15006 (interactive "P")
15008 (org-clock-update-time-maybe)
15009 (save-excursion
15010 (unless (org-at-date-range-p t)
15011 (goto-char (point-at-bol))
15012 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15013 (if (not (org-at-date-range-p t))
15014 (error "Not at a time-stamp range, and none found in current line")))
15015 (let* ((ts1 (match-string 1))
15016 (ts2 (match-string 2))
15017 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15018 (match-end (match-end 0))
15019 (time1 (org-time-string-to-time ts1))
15020 (time2 (org-time-string-to-time ts2))
15021 (t1 (org-float-time time1))
15022 (t2 (org-float-time time2))
15023 (diff (abs (- t2 t1)))
15024 (negative (< (- t2 t1) 0))
15025 ;; (ys (floor (* 365 24 60 60)))
15026 (ds (* 24 60 60))
15027 (hs (* 60 60))
15028 (fy "%dy %dd %02d:%02d")
15029 (fy1 "%dy %dd")
15030 (fd "%dd %02d:%02d")
15031 (fd1 "%dd")
15032 (fh "%02d:%02d")
15033 y d h m align)
15034 (if havetime
15035 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15037 d (floor (/ diff ds)) diff (mod diff ds)
15038 h (floor (/ diff hs)) diff (mod diff hs)
15039 m (floor (/ diff 60)))
15040 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15042 d (floor (+ (/ diff ds) 0.5))
15043 h 0 m 0))
15044 (if (not to-buffer)
15045 (message "%s" (org-make-tdiff-string y d h m))
15046 (if (org-at-table-p)
15047 (progn
15048 (goto-char match-end)
15049 (setq align t)
15050 (and (looking-at " *|") (goto-char (match-end 0))))
15051 (goto-char match-end))
15052 (if (looking-at
15053 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15054 (replace-match ""))
15055 (if negative (insert " -"))
15056 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15057 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15058 (insert " " (format fh h m))))
15059 (if align (org-table-align))
15060 (message "Time difference inserted")))))
15062 (defun org-make-tdiff-string (y d h m)
15063 (let ((fmt "")
15064 (l nil))
15065 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15066 l (push y l)))
15067 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15068 l (push d l)))
15069 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15070 l (push h l)))
15071 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15072 l (push m l)))
15073 (apply 'format fmt (nreverse l))))
15075 (defun org-time-string-to-time (s)
15076 (apply 'encode-time (org-parse-time-string s)))
15077 (defun org-time-string-to-seconds (s)
15078 (org-float-time (org-time-string-to-time s)))
15080 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
15081 "Convert a time stamp to an absolute day number.
15082 If there is a specifier for a cyclic time stamp, get the closest date to
15083 DAYNR.
15084 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15085 The variable date is bound by the calendar when this is called."
15086 (cond
15087 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15088 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15089 daynr
15090 (+ daynr 1000)))
15091 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15092 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15093 (time-to-days (current-time))) (match-string 0 s)
15094 prefer show-all))
15095 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
15097 (defun org-days-to-iso-week (days)
15098 "Return the iso week number."
15099 (require 'cal-iso)
15100 (car (calendar-iso-from-absolute days)))
15102 (defun org-small-year-to-year (year)
15103 "Convert 2-digit years into 4-digit years.
15104 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15105 The year 2000 cannot be abbreviated. Any year larger than 99
15106 is returned unchanged."
15107 (if (< year 38)
15108 (setq year (+ 2000 year))
15109 (if (< year 100)
15110 (setq year (+ 1900 year))))
15111 year)
15113 (defun org-time-from-absolute (d)
15114 "Return the time corresponding to date D.
15115 D may be an absolute day number, or a calendar-type list (month day year)."
15116 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15117 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15119 (defun org-calendar-holiday ()
15120 "List of holidays, for Diary display in Org-mode."
15121 (require 'holidays)
15122 (let ((hl (funcall
15123 (if (fboundp 'calendar-check-holidays)
15124 'calendar-check-holidays 'check-calendar-holidays) date)))
15125 (if hl (mapconcat 'identity hl "; "))))
15127 (defun org-diary-sexp-entry (sexp entry date)
15128 "Process a SEXP diary ENTRY for DATE."
15129 (require 'diary-lib)
15130 (let ((result (if calendar-debug-sexp
15131 (let ((stack-trace-on-error t))
15132 (eval (car (read-from-string sexp))))
15133 (condition-case nil
15134 (eval (car (read-from-string sexp)))
15135 (error
15136 (beep)
15137 (message "Bad sexp at line %d in %s: %s"
15138 (org-current-line)
15139 (buffer-file-name) sexp)
15140 (sleep-for 2))))))
15141 (cond ((stringp result) (split-string result "; "))
15142 ((and (consp result)
15143 (not (consp (cdr result)))
15144 (stringp (cdr result))) (cdr result))
15145 ((and (consp result)
15146 (stringp (car result))) result)
15147 (result entry)
15148 (t nil))))
15150 (defun org-diary-to-ical-string (frombuf)
15151 "Get iCalendar entries from diary entries in buffer FROMBUF.
15152 This uses the icalendar.el library."
15153 (let* ((tmpdir (if (featurep 'xemacs)
15154 (temp-directory)
15155 temporary-file-directory))
15156 (tmpfile (make-temp-name
15157 (expand-file-name "orgics" tmpdir)))
15158 buf rtn b e)
15159 (with-current-buffer frombuf
15160 (icalendar-export-region (point-min) (point-max) tmpfile)
15161 (setq buf (find-buffer-visiting tmpfile))
15162 (set-buffer buf)
15163 (goto-char (point-min))
15164 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15165 (setq b (match-beginning 0)))
15166 (goto-char (point-max))
15167 (if (re-search-backward "^END:VEVENT" nil t)
15168 (setq e (match-end 0)))
15169 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15170 (kill-buffer buf)
15171 (delete-file tmpfile)
15172 rtn))
15174 (defun org-closest-date (start current change prefer show-all)
15175 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15176 When PREFER is `past', return a date that is either CURRENT or past.
15177 When PREFER is `future', return a date that is either CURRENT or future.
15178 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15179 ;; Make the proper lists from the dates
15180 (catch 'exit
15181 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15182 dn dw sday cday n1 n2 n0
15183 d m y y1 y2 date1 date2 nmonths nm ny m2)
15185 (setq start (org-date-to-gregorian start)
15186 current (org-date-to-gregorian
15187 (if show-all
15188 current
15189 (time-to-days (current-time))))
15190 sday (calendar-absolute-from-gregorian start)
15191 cday (calendar-absolute-from-gregorian current))
15193 (if (<= cday sday) (throw 'exit sday))
15195 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15196 (setq dn (string-to-number (match-string 1 change))
15197 dw (cdr (assoc (match-string 2 change) a1)))
15198 (error "Invalid change specifier: %s" change))
15199 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15200 (cond
15201 ((eq dw 'day)
15202 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15203 n2 (+ n1 dn)))
15204 ((eq dw 'year)
15205 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15206 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15207 (setq date1 (list m d y1)
15208 n1 (calendar-absolute-from-gregorian date1)
15209 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15210 n2 (calendar-absolute-from-gregorian date2)))
15211 ((eq dw 'month)
15212 ;; approx number of month between the two dates
15213 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15214 ;; How often does dn fit in there?
15215 (setq d (nth 1 start) m (car start) y (nth 2 start)
15216 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15217 m (+ m nm)
15218 ny (floor (/ m 12))
15219 y (+ y ny)
15220 m (- m (* ny 12)))
15221 (while (> m 12) (setq m (- m 12) y (1+ y)))
15222 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15223 (setq m2 (+ m dn) y2 y)
15224 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15225 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15226 (while (<= n2 cday)
15227 (setq n1 n2 m m2 y y2)
15228 (setq m2 (+ m dn) y2 y)
15229 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15230 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15231 ;; Make sure n1 is the earlier date
15232 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15233 (if show-all
15234 (cond
15235 ((eq prefer 'past) (if (= cday n2) n2 n1))
15236 ((eq prefer 'future) (if (= cday n1) n1 n2))
15237 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15238 (cond
15239 ((eq prefer 'past) (if (= cday n2) n2 n1))
15240 ((eq prefer 'future) (if (= cday n1) n1 n2))
15241 (t (if (= cday n1) n1 n2)))))))
15243 (defun org-date-to-gregorian (date)
15244 "Turn any specification of DATE into a Gregorian date for the calendar."
15245 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15246 ((and (listp date) (= (length date) 3)) date)
15247 ((stringp date)
15248 (setq date (org-parse-time-string date))
15249 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15250 ((listp date)
15251 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15253 (defun org-parse-time-string (s &optional nodefault)
15254 "Parse the standard Org-mode time string.
15255 This should be a lot faster than the normal `parse-time-string'.
15256 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15257 hour and minute fields will be nil if not given."
15258 (if (string-match org-ts-regexp0 s)
15259 (list 0
15260 (if (or (match-beginning 8) (not nodefault))
15261 (string-to-number (or (match-string 8 s) "0")))
15262 (if (or (match-beginning 7) (not nodefault))
15263 (string-to-number (or (match-string 7 s) "0")))
15264 (string-to-number (match-string 4 s))
15265 (string-to-number (match-string 3 s))
15266 (string-to-number (match-string 2 s))
15267 nil nil nil)
15268 (error "Not a standard Org-mode time string: %s" s)))
15270 (defun org-timestamp-up (&optional arg)
15271 "Increase the date item at the cursor by one.
15272 If the cursor is on the year, change the year. If it is on the month or
15273 the day, change that.
15274 With prefix ARG, change by that many units."
15275 (interactive "p")
15276 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15278 (defun org-timestamp-down (&optional arg)
15279 "Decrease the date item at the cursor by one.
15280 If the cursor is on the year, change the year. If it is on the month or
15281 the day, change that.
15282 With prefix ARG, change by that many units."
15283 (interactive "p")
15284 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15286 (defun org-timestamp-up-day (&optional arg)
15287 "Increase the date in the time stamp by one day.
15288 With prefix ARG, change that many days."
15289 (interactive "p")
15290 (if (and (not (org-at-timestamp-p t))
15291 (org-on-heading-p))
15292 (org-todo 'up)
15293 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15295 (defun org-timestamp-down-day (&optional arg)
15296 "Decrease the date in the time stamp by one day.
15297 With prefix ARG, change that many days."
15298 (interactive "p")
15299 (if (and (not (org-at-timestamp-p t))
15300 (org-on-heading-p))
15301 (org-todo 'down)
15302 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15304 (defun org-at-timestamp-p (&optional inactive-ok)
15305 "Determine if the cursor is in or at a timestamp."
15306 (interactive)
15307 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15308 (pos (point))
15309 (ans (or (looking-at tsr)
15310 (save-excursion
15311 (skip-chars-backward "^[<\n\r\t")
15312 (if (> (point) (point-min)) (backward-char 1))
15313 (and (looking-at tsr)
15314 (> (- (match-end 0) pos) -1))))))
15315 (and ans
15316 (boundp 'org-ts-what)
15317 (setq org-ts-what
15318 (cond
15319 ((= pos (match-beginning 0)) 'bracket)
15320 ((= pos (1- (match-end 0))) 'bracket)
15321 ((org-pos-in-match-range pos 2) 'year)
15322 ((org-pos-in-match-range pos 3) 'month)
15323 ((org-pos-in-match-range pos 7) 'hour)
15324 ((org-pos-in-match-range pos 8) 'minute)
15325 ((or (org-pos-in-match-range pos 4)
15326 (org-pos-in-match-range pos 5)) 'day)
15327 ((and (> pos (or (match-end 8) (match-end 5)))
15328 (< pos (match-end 0)))
15329 (- pos (or (match-end 8) (match-end 5))))
15330 (t 'day))))
15331 ans))
15333 (defun org-toggle-timestamp-type ()
15334 "Toggle the type (<active> or [inactive]) of a time stamp."
15335 (interactive)
15336 (when (org-at-timestamp-p t)
15337 (let ((beg (match-beginning 0)) (end (match-end 0))
15338 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
15339 (save-excursion
15340 (goto-char beg)
15341 (while (re-search-forward "[][<>]" end t)
15342 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
15343 t t)))
15344 (message "Timestamp is now %sactive"
15345 (if (equal (char-after beg) ?<) "" "in")))))
15347 (defun org-timestamp-change (n &optional what updown)
15348 "Change the date in the time stamp at point.
15349 The date will be changed by N times WHAT. WHAT can be `day', `month',
15350 `year', `minute', `second'. If WHAT is not given, the cursor position
15351 in the timestamp determines what will be changed."
15352 (let ((pos (point))
15353 with-hm inactive
15354 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
15355 org-ts-what
15356 extra rem
15357 ts time time0)
15358 (if (not (org-at-timestamp-p t))
15359 (error "Not at a timestamp"))
15360 (if (and (not what) (eq org-ts-what 'bracket))
15361 (org-toggle-timestamp-type)
15362 (if (and (not what) (not (eq org-ts-what 'day))
15363 org-display-custom-times
15364 (get-text-property (point) 'display)
15365 (not (get-text-property (1- (point)) 'display)))
15366 (setq org-ts-what 'day))
15367 (setq org-ts-what (or what org-ts-what)
15368 inactive (= (char-after (match-beginning 0)) ?\[)
15369 ts (match-string 0))
15370 (replace-match "")
15371 (if (string-match
15372 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
15374 (setq extra (match-string 1 ts)))
15375 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15376 (setq with-hm t))
15377 (setq time0 (org-parse-time-string ts))
15378 (when (and updown
15379 (eq org-ts-what 'minute)
15380 (not current-prefix-arg))
15381 ;; This looks like s-up and s-down. Change by one rounding step.
15382 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
15383 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
15384 (setcar (cdr time0) (+ (nth 1 time0)
15385 (if (> n 0) (- rem) (- dm rem))))))
15386 (setq time
15387 (encode-time (or (car time0) 0)
15388 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
15389 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
15390 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
15391 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
15392 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
15393 (nthcdr 6 time0)))
15394 (when (and (member org-ts-what '(hour minute))
15395 extra
15396 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
15397 (setq extra (org-modify-ts-extra
15398 extra
15399 (if (eq org-ts-what 'hour) 2 5)
15400 n dm)))
15401 (when (integerp org-ts-what)
15402 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
15403 (if (eq what 'calendar)
15404 (let ((cal-date (org-get-date-from-calendar)))
15405 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15406 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15407 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15408 (setcar time0 (or (car time0) 0))
15409 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15410 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15411 (setq time (apply 'encode-time time0))))
15412 (setq org-last-changed-timestamp
15413 (org-insert-time-stamp time with-hm inactive nil nil extra))
15414 (org-clock-update-time-maybe)
15415 (goto-char pos)
15416 ;; Try to recenter the calendar window, if any
15417 (if (and org-calendar-follow-timestamp-change
15418 (get-buffer-window "*Calendar*" t)
15419 (memq org-ts-what '(day month year)))
15420 (org-recenter-calendar (time-to-days time))))))
15422 (defun org-modify-ts-extra (s pos n dm)
15423 "Change the different parts of the lead-time and repeat fields in timestamp."
15424 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15425 ng h m new rem)
15426 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15427 (cond
15428 ((or (org-pos-in-match-range pos 2)
15429 (org-pos-in-match-range pos 3))
15430 (setq m (string-to-number (match-string 3 s))
15431 h (string-to-number (match-string 2 s)))
15432 (if (org-pos-in-match-range pos 2)
15433 (setq h (+ h n))
15434 (setq n (* dm (org-no-warnings (signum n))))
15435 (when (not (= 0 (setq rem (% m dm))))
15436 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
15437 (setq m (+ m n)))
15438 (if (< m 0) (setq m (+ m 60) h (1- h)))
15439 (if (> m 59) (setq m (- m 60) h (1+ h)))
15440 (setq h (min 24 (max 0 h)))
15441 (setq ng 1 new (format "-%02d:%02d" h m)))
15442 ((org-pos-in-match-range pos 6)
15443 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15444 ((org-pos-in-match-range pos 5)
15445 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
15447 ((org-pos-in-match-range pos 9)
15448 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
15449 ((org-pos-in-match-range pos 8)
15450 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
15452 (when ng
15453 (setq s (concat
15454 (substring s 0 (match-beginning ng))
15456 (substring s (match-end ng))))))
15459 (defun org-recenter-calendar (date)
15460 "If the calendar is visible, recenter it to DATE."
15461 (let* ((win (selected-window))
15462 (cwin (get-buffer-window "*Calendar*" t))
15463 (calendar-move-hook nil))
15464 (when cwin
15465 (select-window cwin)
15466 (calendar-goto-date (if (listp date) date
15467 (calendar-gregorian-from-absolute date)))
15468 (select-window win))))
15470 (defun org-goto-calendar (&optional arg)
15471 "Go to the Emacs calendar at the current date.
15472 If there is a time stamp in the current line, go to that date.
15473 A prefix ARG can be used to force the current date."
15474 (interactive "P")
15475 (let ((tsr org-ts-regexp) diff
15476 (calendar-move-hook nil)
15477 (calendar-view-holidays-initially-flag nil)
15478 (calendar-view-diary-initially-flag nil))
15479 (if (or (org-at-timestamp-p)
15480 (save-excursion
15481 (beginning-of-line 1)
15482 (looking-at (concat ".*" tsr))))
15483 (let ((d1 (time-to-days (current-time)))
15484 (d2 (time-to-days
15485 (org-time-string-to-time (match-string 1)))))
15486 (setq diff (- d2 d1))))
15487 (calendar)
15488 (calendar-goto-today)
15489 (if (and diff (not arg)) (calendar-forward-day diff))))
15491 (defun org-get-date-from-calendar ()
15492 "Return a list (month day year) of date at point in calendar."
15493 (with-current-buffer "*Calendar*"
15494 (save-match-data
15495 (calendar-cursor-to-date))))
15497 (defun org-date-from-calendar ()
15498 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
15499 If there is already a time stamp at the cursor position, update it."
15500 (interactive)
15501 (if (org-at-timestamp-p t)
15502 (org-timestamp-change 0 'calendar)
15503 (let ((cal-date (org-get-date-from-calendar)))
15504 (org-insert-time-stamp
15505 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
15507 (defun org-minutes-to-hh:mm-string (m)
15508 "Compute H:MM from a number of minutes."
15509 (let ((h (/ m 60)))
15510 (setq m (- m (* 60 h)))
15511 (format org-time-clocksum-format h m)))
15513 (defun org-hh:mm-string-to-minutes (s)
15514 "Convert a string H:MM to a number of minutes.
15515 If the string is just a number, interpret it as minutes.
15516 In fact, the first hh:mm or number in the string will be taken,
15517 there can be extra stuff in the string.
15518 If no number is found, the return value is 0."
15519 (cond
15520 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
15521 (+ (* (string-to-number (match-string 1 s)) 60)
15522 (string-to-number (match-string 2 s))))
15523 ((string-match "\\([0-9]+\\)" s)
15524 (string-to-number (match-string 1 s)))
15525 (t 0)))
15527 (defcustom org-effort-durations
15528 `(("h" . 60)
15529 ("d" . ,(* 60 8))
15530 ("w" . ,(* 60 8 5))
15531 ("m" . ,(* 60 8 5 4))
15532 ("y" . ,(* 60 8 5 40)))
15533 "Conversion factor to minutes for an effort modifier.
15535 Each entry has the form (MODIFIER . MINUTES).
15537 In an effort string, a number followed by MODIFIER is multiplied
15538 by the specified number of MINUTES to obtain an effort in
15539 minutes.
15541 For example, if the value of this variable is ((\"hours\" . 60)), then an
15542 effort string \"2hours\" is equivalent to 120 minutes."
15543 :group 'org-agenda
15544 :type '(alist :key-type (string :tag "Modifier")
15545 :value-type (number :tag "Minutes")))
15547 (defun org-duration-string-to-minutes (s)
15548 "Convert a duration string S to minutes.
15550 A bare number is interpreted as minutes, modifiers can be set by
15551 customizing `org-effort-durations' (which see).
15553 Entries containing a colon are interpreted as H:MM by
15554 `org-hh:mm-string-to-minutes'."
15555 (let ((result 0)
15556 (re (concat "\\([0-9]+\\) *\\("
15557 (regexp-opt (mapcar 'car org-effort-durations))
15558 "\\)")))
15559 (while (string-match re s)
15560 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
15561 (string-to-number (match-string 1 s))))
15562 (setq s (replace-match "" nil t s)))
15563 (incf result (org-hh:mm-string-to-minutes s))
15564 result))
15566 ;;;; Files
15568 (defun org-save-all-org-buffers ()
15569 "Save all Org-mode buffers without user confirmation."
15570 (interactive)
15571 (message "Saving all Org-mode buffers...")
15572 (save-some-buffers t 'org-mode-p)
15573 (when (featurep 'org-id) (org-id-locations-save))
15574 (message "Saving all Org-mode buffers... done"))
15576 (defun org-revert-all-org-buffers ()
15577 "Revert all Org-mode buffers.
15578 Prompt for confirmation when there are unsaved changes.
15579 Be sure you know what you are doing before letting this function
15580 overwrite your changes.
15582 This function is useful in a setup where one tracks org files
15583 with a version control system, to revert on one machine after pulling
15584 changes from another. I believe the procedure must be like this:
15586 1. M-x org-save-all-org-buffers
15587 2. Pull changes from the other machine, resolve conflicts
15588 3. M-x org-revert-all-org-buffers"
15589 (interactive)
15590 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
15591 (error "Abort"))
15592 (save-excursion
15593 (save-window-excursion
15594 (mapc
15595 (lambda (b)
15596 (when (and (with-current-buffer b (org-mode-p))
15597 (with-current-buffer b buffer-file-name))
15598 (switch-to-buffer b)
15599 (revert-buffer t 'no-confirm)))
15600 (buffer-list))
15601 (when (and (featurep 'org-id) org-id-track-globally)
15602 (org-id-locations-load)))))
15604 ;;;; Agenda files
15606 ;;;###autoload
15607 (defun org-switchb (&optional arg)
15608 "Switch between Org buffers.
15609 With a prefix argument, restrict available to files.
15610 With two prefix arguments, restrict available buffers to agenda files.
15612 Defaults to `iswitchb' for buffer name completion.
15613 Set `org-completion-use-ido' to make it use ido instead."
15614 (interactive "P")
15615 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
15616 ((equal arg '(16)) (org-buffer-list 'agenda))
15617 (t (org-buffer-list))))
15618 (org-completion-use-iswitchb org-completion-use-iswitchb)
15619 (org-completion-use-ido org-completion-use-ido))
15620 (unless (or org-completion-use-ido org-completion-use-iswitchb)
15621 (setq org-completion-use-iswitchb t))
15622 (switch-to-buffer
15623 (org-icompleting-read "Org buffer: "
15624 (mapcar 'list (mapcar 'buffer-name blist))
15625 nil t))))
15627 ;;; Define some older names previously used for this functionality
15628 ;;;###autoload
15629 (defalias 'org-ido-switchb 'org-switchb)
15630 ;;;###autoload
15631 (defalias 'org-iswitchb 'org-switchb)
15633 (defun org-buffer-list (&optional predicate exclude-tmp)
15634 "Return a list of Org buffers.
15635 PREDICATE can be `export', `files' or `agenda'.
15637 export restrict the list to Export buffers.
15638 files restrict the list to buffers visiting Org files.
15639 agenda restrict the list to buffers visiting agenda files.
15641 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
15642 (let* ((bfn nil)
15643 (agenda-files (and (eq predicate 'agenda)
15644 (mapcar 'file-truename (org-agenda-files t))))
15645 (filter
15646 (cond
15647 ((eq predicate 'files)
15648 (lambda (b) (with-current-buffer b (org-mode-p))))
15649 ((eq predicate 'export)
15650 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
15651 ((eq predicate 'agenda)
15652 (lambda (b)
15653 (with-current-buffer b
15654 (and (org-mode-p)
15655 (setq bfn (buffer-file-name b))
15656 (member (file-truename bfn) agenda-files)))))
15657 (t (lambda (b) (with-current-buffer b
15658 (or (org-mode-p)
15659 (string-match "\*Org .*Export"
15660 (buffer-name b)))))))))
15661 (delq nil
15662 (mapcar
15663 (lambda(b)
15664 (if (and (funcall filter b)
15665 (or (not exclude-tmp)
15666 (not (string-match "tmp" (buffer-name b)))))
15668 nil))
15669 (buffer-list)))))
15671 (defun org-agenda-files (&optional unrestricted archives)
15672 "Get the list of agenda files.
15673 Optional UNRESTRICTED means return the full list even if a restriction
15674 is currently in place.
15675 When ARCHIVES is t, include all archive files that are really being
15676 used by the agenda files. If ARCHIVE is `ifmode', do this only if
15677 `org-agenda-archives-mode' is t."
15678 (let ((files
15679 (cond
15680 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
15681 ((stringp org-agenda-files) (org-read-agenda-file-list))
15682 ((listp org-agenda-files) org-agenda-files)
15683 (t (error "Invalid value of `org-agenda-files'")))))
15684 (setq files (apply 'append
15685 (mapcar (lambda (f)
15686 (if (file-directory-p f)
15687 (directory-files
15688 f t org-agenda-file-regexp)
15689 (list f)))
15690 files)))
15691 (when org-agenda-skip-unavailable-files
15692 (setq files (delq nil
15693 (mapcar (function
15694 (lambda (file)
15695 (and (file-readable-p file) file)))
15696 files))))
15697 (when (or (eq archives t)
15698 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
15699 (setq files (org-add-archive-files files)))
15700 files))
15702 (defun org-agenda-file-p (&optional file)
15703 "Return non-nil, if FILE is an agenda file.
15704 If FILE is omitted, use the file associated with the current
15705 buffer."
15706 (member (or file (buffer-file-name))
15707 (org-agenda-files t)))
15709 (defun org-edit-agenda-file-list ()
15710 "Edit the list of agenda files.
15711 Depending on setup, this either uses customize to edit the variable
15712 `org-agenda-files', or it visits the file that is holding the list. In the
15713 latter case, the buffer is set up in a way that saving it automatically kills
15714 the buffer and restores the previous window configuration."
15715 (interactive)
15716 (if (stringp org-agenda-files)
15717 (let ((cw (current-window-configuration)))
15718 (find-file org-agenda-files)
15719 (org-set-local 'org-window-configuration cw)
15720 (org-add-hook 'after-save-hook
15721 (lambda ()
15722 (set-window-configuration
15723 (prog1 org-window-configuration
15724 (kill-buffer (current-buffer))))
15725 (org-install-agenda-files-menu)
15726 (message "New agenda file list installed"))
15727 nil 'local)
15728 (message "%s" (substitute-command-keys
15729 "Edit list and finish with \\[save-buffer]")))
15730 (customize-variable 'org-agenda-files)))
15732 (defun org-store-new-agenda-file-list (list)
15733 "Set new value for the agenda file list and save it correctly."
15734 (if (stringp org-agenda-files)
15735 (let ((fe (org-read-agenda-file-list t)) b u)
15736 (while (setq b (find-buffer-visiting org-agenda-files))
15737 (kill-buffer b))
15738 (with-temp-file org-agenda-files
15739 (insert
15740 (mapconcat
15741 (lambda (f) ;; Keep un-expanded entries.
15742 (if (setq u (assoc f fe))
15743 (cdr u)
15745 list "\n")
15746 "\n")))
15747 (let ((org-mode-hook nil) (org-inhibit-startup t)
15748 (org-insert-mode-line-in-empty-file nil))
15749 (setq org-agenda-files list)
15750 (customize-save-variable 'org-agenda-files org-agenda-files))))
15752 (defun org-read-agenda-file-list (&optional pair-with-expansion)
15753 "Read the list of agenda files from a file.
15754 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
15755 filenames, used by `org-store-new-agenda-file-list' to write back
15756 un-expanded file names."
15757 (when (file-directory-p org-agenda-files)
15758 (error "`org-agenda-files' cannot be a single directory"))
15759 (when (stringp org-agenda-files)
15760 (with-temp-buffer
15761 (insert-file-contents org-agenda-files)
15762 (mapcar
15763 (lambda (f)
15764 (let ((e (expand-file-name (substitute-in-file-name f)
15765 org-directory)))
15766 (if pair-with-expansion
15767 (cons e f)
15768 e)))
15769 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
15771 ;;;###autoload
15772 (defun org-cycle-agenda-files ()
15773 "Cycle through the files in `org-agenda-files'.
15774 If the current buffer visits an agenda file, find the next one in the list.
15775 If the current buffer does not, find the first agenda file."
15776 (interactive)
15777 (let* ((fs (org-agenda-files t))
15778 (files (append fs (list (car fs))))
15779 (tcf (if buffer-file-name (file-truename buffer-file-name)))
15780 file)
15781 (unless files (error "No agenda files"))
15782 (catch 'exit
15783 (while (setq file (pop files))
15784 (if (equal (file-truename file) tcf)
15785 (when (car files)
15786 (find-file (car files))
15787 (throw 'exit t))))
15788 (find-file (car fs)))
15789 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
15791 (defun org-agenda-file-to-front (&optional to-end)
15792 "Move/add the current file to the top of the agenda file list.
15793 If the file is not present in the list, it is added to the front. If it is
15794 present, it is moved there. With optional argument TO-END, add/move to the
15795 end of the list."
15796 (interactive "P")
15797 (let ((org-agenda-skip-unavailable-files nil)
15798 (file-alist (mapcar (lambda (x)
15799 (cons (file-truename x) x))
15800 (org-agenda-files t)))
15801 (ctf (file-truename buffer-file-name))
15802 x had)
15803 (setq x (assoc ctf file-alist) had x)
15805 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
15806 (if to-end
15807 (setq file-alist (append (delq x file-alist) (list x)))
15808 (setq file-alist (cons x (delq x file-alist))))
15809 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
15810 (org-install-agenda-files-menu)
15811 (message "File %s to %s of agenda file list"
15812 (if had "moved" "added") (if to-end "end" "front"))))
15814 (defun org-remove-file (&optional file)
15815 "Remove current file from the list of files in variable `org-agenda-files'.
15816 These are the files which are being checked for agenda entries.
15817 Optional argument FILE means use this file instead of the current."
15818 (interactive)
15819 (let* ((org-agenda-skip-unavailable-files nil)
15820 (file (or file buffer-file-name))
15821 (true-file (file-truename file))
15822 (afile (abbreviate-file-name file))
15823 (files (delq nil (mapcar
15824 (lambda (x)
15825 (if (equal true-file
15826 (file-truename x))
15827 nil x))
15828 (org-agenda-files t)))))
15829 (if (not (= (length files) (length (org-agenda-files t))))
15830 (progn
15831 (org-store-new-agenda-file-list files)
15832 (org-install-agenda-files-menu)
15833 (message "Removed file: %s" afile))
15834 (message "File was not in list: %s (not removed)" afile))))
15836 (defun org-file-menu-entry (file)
15837 (vector file (list 'find-file file) t))
15839 (defun org-check-agenda-file (file)
15840 "Make sure FILE exists. If not, ask user what to do."
15841 (when (not (file-exists-p file))
15842 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
15843 (abbreviate-file-name file))
15844 (let ((r (downcase (read-char-exclusive))))
15845 (cond
15846 ((equal r ?r)
15847 (org-remove-file file)
15848 (throw 'nextfile t))
15849 (t (error "Abort"))))))
15851 (defun org-get-agenda-file-buffer (file)
15852 "Get a buffer visiting FILE. If the buffer needs to be created, add
15853 it to the list of buffers which might be released later."
15854 (let ((buf (org-find-base-buffer-visiting file)))
15855 (if buf
15856 buf ; just return it
15857 ;; Make a new buffer and remember it
15858 (setq buf (find-file-noselect file))
15859 (if buf (push buf org-agenda-new-buffers))
15860 buf)))
15862 (defun org-release-buffers (blist)
15863 "Release all buffers in list, asking the user for confirmation when needed.
15864 When a buffer is unmodified, it is just killed. When modified, it is saved
15865 \(if the user agrees) and then killed."
15866 (let (buf file)
15867 (while (setq buf (pop blist))
15868 (setq file (buffer-file-name buf))
15869 (when (and (buffer-modified-p buf)
15870 file
15871 (y-or-n-p (format "Save file %s? " file)))
15872 (with-current-buffer buf (save-buffer)))
15873 (kill-buffer buf))))
15875 (defun org-prepare-agenda-buffers (files)
15876 "Create buffers for all agenda files, protect archived trees and comments."
15877 (interactive)
15878 (let ((pa '(:org-archived t))
15879 (pc '(:org-comment t))
15880 (pall '(:org-archived t :org-comment t))
15881 (inhibit-read-only t)
15882 (rea (concat ":" org-archive-tag ":"))
15883 bmp file re)
15884 (save-excursion
15885 (save-restriction
15886 (while (setq file (pop files))
15887 (catch 'nextfile
15888 (if (bufferp file)
15889 (set-buffer file)
15890 (org-check-agenda-file file)
15891 (set-buffer (org-get-agenda-file-buffer file)))
15892 (widen)
15893 (setq bmp (buffer-modified-p))
15894 (org-refresh-category-properties)
15895 (setq org-todo-keywords-for-agenda
15896 (append org-todo-keywords-for-agenda org-todo-keywords-1))
15897 (setq org-done-keywords-for-agenda
15898 (append org-done-keywords-for-agenda org-done-keywords))
15899 (setq org-todo-keyword-alist-for-agenda
15900 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
15901 (setq org-drawers-for-agenda
15902 (append org-drawers-for-agenda org-drawers))
15903 (setq org-tag-alist-for-agenda
15904 (append org-tag-alist-for-agenda org-tag-alist))
15906 (save-excursion
15907 (remove-text-properties (point-min) (point-max) pall)
15908 (when org-agenda-skip-archived-trees
15909 (goto-char (point-min))
15910 (while (re-search-forward rea nil t)
15911 (if (org-on-heading-p t)
15912 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
15913 (goto-char (point-min))
15914 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
15915 (while (re-search-forward re nil t)
15916 (add-text-properties
15917 (match-beginning 0) (org-end-of-subtree t) pc)))
15918 (set-buffer-modified-p bmp)))))
15919 (setq org-todo-keywords-for-agenda
15920 (org-uniquify org-todo-keywords-for-agenda))
15921 (setq org-todo-keyword-alist-for-agenda
15922 (org-uniquify org-todo-keyword-alist-for-agenda)
15923 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
15925 ;;;; Embedded LaTeX
15927 (defvar org-cdlatex-mode-map (make-sparse-keymap)
15928 "Keymap for the minor `org-cdlatex-mode'.")
15930 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
15931 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
15932 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
15933 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
15934 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
15936 (defvar org-cdlatex-texmathp-advice-is-done nil
15937 "Flag remembering if we have applied the advice to texmathp already.")
15939 (define-minor-mode org-cdlatex-mode
15940 "Toggle the minor `org-cdlatex-mode'.
15941 This mode supports entering LaTeX environment and math in LaTeX fragments
15942 in Org-mode.
15943 \\{org-cdlatex-mode-map}"
15944 nil " OCDL" nil
15945 (when org-cdlatex-mode (require 'cdlatex))
15946 (unless org-cdlatex-texmathp-advice-is-done
15947 (setq org-cdlatex-texmathp-advice-is-done t)
15948 (defadvice texmathp (around org-math-always-on activate)
15949 "Always return t in org-mode buffers.
15950 This is because we want to insert math symbols without dollars even outside
15951 the LaTeX math segments. If Orgmode thinks that point is actually inside
15952 an embedded LaTeX fragment, let texmathp do its job.
15953 \\[org-cdlatex-mode-map]"
15954 (interactive)
15955 (let (p)
15956 (cond
15957 ((not (org-mode-p)) ad-do-it)
15958 ((eq this-command 'cdlatex-math-symbol)
15959 (setq ad-return-value t
15960 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
15962 (let ((p (org-inside-LaTeX-fragment-p)))
15963 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
15964 (setq ad-return-value t
15965 texmathp-why '("Org-mode embedded math" . 0))
15966 (if p ad-do-it)))))))))
15968 (defun turn-on-org-cdlatex ()
15969 "Unconditionally turn on `org-cdlatex-mode'."
15970 (org-cdlatex-mode 1))
15972 (defun org-inside-LaTeX-fragment-p ()
15973 "Test if point is inside a LaTeX fragment.
15974 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
15975 sequence appearing also before point.
15976 Even though the matchers for math are configurable, this function assumes
15977 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
15978 delimiters are skipped when they have been removed by customization.
15979 The return value is nil, or a cons cell with the delimiter and
15980 and the position of this delimiter.
15982 This function does a reasonably good job, but can locally be fooled by
15983 for example currency specifications. For example it will assume being in
15984 inline math after \"$22.34\". The LaTeX fragment formatter will only format
15985 fragments that are properly closed, but during editing, we have to live
15986 with the uncertainty caused by missing closing delimiters. This function
15987 looks only before point, not after."
15988 (catch 'exit
15989 (let ((pos (point))
15990 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
15991 (lim (progn
15992 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
15993 (point)))
15994 dd-on str (start 0) m re)
15995 (goto-char pos)
15996 (when dodollar
15997 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
15998 re (nth 1 (assoc "$" org-latex-regexps)))
15999 (while (string-match re str start)
16000 (cond
16001 ((= (match-end 0) (length str))
16002 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16003 ((= (match-end 0) (- (length str) 5))
16004 (throw 'exit nil))
16005 (t (setq start (match-end 0))))))
16006 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16007 (goto-char pos)
16008 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16009 (and (match-beginning 2) (throw 'exit nil))
16010 ;; count $$
16011 (while (re-search-backward "\\$\\$" lim t)
16012 (setq dd-on (not dd-on)))
16013 (goto-char pos)
16014 (if dd-on (cons "$$" m))))))
16016 (defun org-inside-latex-macro-p ()
16017 "Is point inside a LaTeX macro or its arguments?"
16018 (save-match-data
16019 (org-in-regexp
16020 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16022 (defun org-try-cdlatex-tab ()
16023 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16024 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16025 - inside a LaTeX fragment, or
16026 - after the first word in a line, where an abbreviation expansion could
16027 insert a LaTeX environment."
16028 (when org-cdlatex-mode
16029 (cond
16030 ((save-excursion
16031 (skip-chars-backward "a-zA-Z0-9*")
16032 (skip-chars-backward " \t")
16033 (bolp))
16034 (cdlatex-tab) t)
16035 ((org-inside-LaTeX-fragment-p)
16036 (cdlatex-tab) t)
16037 (t nil))))
16039 (defun org-cdlatex-underscore-caret (&optional arg)
16040 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16041 Revert to the normal definition outside of these fragments."
16042 (interactive "P")
16043 (if (org-inside-LaTeX-fragment-p)
16044 (call-interactively 'cdlatex-sub-superscript)
16045 (let (org-cdlatex-mode)
16046 (call-interactively (key-binding (vector last-input-event))))))
16048 (defun org-cdlatex-math-modify (&optional arg)
16049 "Execute `cdlatex-math-modify' in LaTeX fragments.
16050 Revert to the normal definition outside of these fragments."
16051 (interactive "P")
16052 (if (org-inside-LaTeX-fragment-p)
16053 (call-interactively 'cdlatex-math-modify)
16054 (let (org-cdlatex-mode)
16055 (call-interactively (key-binding (vector last-input-event))))))
16057 (defvar org-latex-fragment-image-overlays nil
16058 "List of overlays carrying the images of latex fragments.")
16059 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16061 (defun org-remove-latex-fragment-image-overlays ()
16062 "Remove all overlays with LaTeX fragment images in current buffer."
16063 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16064 (setq org-latex-fragment-image-overlays nil))
16066 (defun org-preview-latex-fragment (&optional subtree)
16067 "Preview the LaTeX fragment at point, or all locally or globally.
16068 If the cursor is in a LaTeX fragment, create the image and overlay
16069 it over the source code. If there is no fragment at point, display
16070 all fragments in the current text, from one headline to the next. With
16071 prefix SUBTREE, display all fragments in the current subtree. With a
16072 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16073 the cursor is before the first headline,
16074 display all fragments in the buffer.
16075 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16076 (interactive "P")
16077 (org-remove-latex-fragment-image-overlays)
16078 (save-excursion
16079 (save-restriction
16080 (let (beg end at msg)
16081 (cond
16082 ((or (equal subtree '(16))
16083 (not (save-excursion
16084 (re-search-backward (concat "^" outline-regexp) nil t))))
16085 (setq beg (point-min) end (point-max)
16086 msg "Creating images for buffer...%s"))
16087 ((equal subtree '(4))
16088 (org-back-to-heading)
16089 (setq beg (point) end (org-end-of-subtree t)
16090 msg "Creating images for subtree...%s"))
16092 (if (setq at (org-inside-LaTeX-fragment-p))
16093 (goto-char (max (point-min) (- (cdr at) 2)))
16094 (org-back-to-heading))
16095 (setq beg (point) end (progn (outline-next-heading) (point))
16096 msg (if at "Creating image...%s"
16097 "Creating images for entry...%s"))))
16098 (message msg "")
16099 (narrow-to-region beg end)
16100 (goto-char beg)
16101 (org-format-latex
16102 (concat "ltxpng/" (file-name-sans-extension
16103 (file-name-nondirectory
16104 buffer-file-name)))
16105 default-directory 'overlays msg at 'forbuffer 'dvipng)
16106 (message msg "done. Use `C-c C-c' to remove images.")))))
16108 (defvar org-latex-regexps
16109 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16110 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16111 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16112 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16113 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16114 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16115 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16116 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16117 "Regular expressions for matching embedded LaTeX.")
16119 (defvar org-export-have-math nil) ;; dynamic scoping
16120 (defun org-format-latex (prefix &optional dir overlays msg at
16121 forbuffer processing-type)
16122 "Replace LaTeX fragments with links to an image, and produce images.
16123 Some of the options can be changed using the variable
16124 `org-format-latex-options'."
16125 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16126 (let* ((prefixnodir (file-name-nondirectory prefix))
16127 (absprefix (expand-file-name prefix dir))
16128 (todir (file-name-directory absprefix))
16129 (opt org-format-latex-options)
16130 (matchers (plist-get opt :matchers))
16131 (re-list org-latex-regexps)
16132 (org-format-latex-header-extra
16133 (plist-get (org-infile-export-plist) :latex-header-extra))
16134 (cnt 0) txt hash link beg end re e checkdir
16135 executables-checked string
16136 m n block linkfile movefile ov)
16137 ;; Check the different regular expressions
16138 (while (setq e (pop re-list))
16139 (setq m (car e) re (nth 1 e) n (nth 2 e)
16140 block (if (nth 3 e) "\n\n" ""))
16141 (when (member m matchers)
16142 (goto-char (point-min))
16143 (while (re-search-forward re nil t)
16144 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16145 (not (get-text-property (match-beginning n)
16146 'org-protected))
16147 (or (not overlays)
16148 (not (eq (get-char-property (match-beginning n)
16149 'org-overlay-type)
16150 'org-latex-overlay))))
16151 (setq org-export-have-math t)
16152 (cond
16153 ((eq processing-type 'verbatim)
16154 ;; Leave the text verbatim, just protect it
16155 (add-text-properties (match-beginning n) (match-end n)
16156 '(org-protected t)))
16157 ((eq processing-type 'mathjax)
16158 ;; Prepare for MathJax processing
16159 (setq string (match-string n))
16160 (if (member m '("$" "$1"))
16161 (save-excursion
16162 (delete-region (match-beginning n) (match-end n))
16163 (goto-char (match-beginning n))
16164 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16165 "\\)")
16166 '(org-protected t))))
16167 (add-text-properties (match-beginning n) (match-end n)
16168 '(org-protected t))))
16169 ((or (eq processing-type 'dvipng) t)
16170 ;; Process to an image
16171 (setq txt (match-string n)
16172 beg (match-beginning n) end (match-end n)
16173 cnt (1+ cnt))
16174 (let (print-length print-level) ; make sure full list is printed
16175 (setq hash (sha1 (prin1-to-string
16176 (list org-format-latex-header
16177 org-format-latex-header-extra
16178 org-export-latex-default-packages-alist
16179 org-export-latex-packages-alist
16180 org-format-latex-options
16181 forbuffer txt)))
16182 linkfile (format "%s_%s.png" prefix hash)
16183 movefile (format "%s_%s.png" absprefix hash)))
16184 (setq link (concat block "[[file:" linkfile "]]" block))
16185 (if msg (message msg cnt))
16186 (goto-char beg)
16187 (unless checkdir ; make sure the directory exists
16188 (setq checkdir t)
16189 (or (file-directory-p todir) (make-directory todir t)))
16191 (unless executables-checked
16192 (org-check-external-command
16193 "latex" "needed to convert LaTeX fragments to images")
16194 (org-check-external-command
16195 "dvipng" "needed to convert LaTeX fragments to images")
16196 (setq executables-checked t))
16198 (unless (file-exists-p movefile)
16199 (org-create-formula-image
16200 txt movefile opt forbuffer))
16201 (if overlays
16202 (progn
16203 (mapc (lambda (o)
16204 (if (eq (overlay-get o 'org-overlay-type)
16205 'org-latex-overlay)
16206 (delete-overlay o)))
16207 (overlays-in beg end))
16208 (setq ov (make-overlay beg end))
16209 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16210 (if (featurep 'xemacs)
16211 (progn
16212 (overlay-put ov 'invisible t)
16213 (overlay-put
16214 ov 'end-glyph
16215 (make-glyph (vector 'png :file movefile))))
16216 (overlay-put
16217 ov 'display
16218 (list 'image :type 'png :file movefile :ascent 'center)))
16219 (push ov org-latex-fragment-image-overlays)
16220 (goto-char end))
16221 (delete-region beg end)
16222 (insert (org-add-props link
16223 (list 'org-latex-src
16224 (replace-regexp-in-string
16225 "\"" "" txt)))))))))))))
16227 ;; This function borrows from Ganesh Swami's latex2png.el
16228 (defun org-create-formula-image (string tofile options buffer)
16229 "This calls dvipng."
16230 (require 'org-latex)
16231 (let* ((tmpdir (if (featurep 'xemacs)
16232 (temp-directory)
16233 temporary-file-directory))
16234 (texfilebase (make-temp-name
16235 (expand-file-name "orgtex" tmpdir)))
16236 (texfile (concat texfilebase ".tex"))
16237 (dvifile (concat texfilebase ".dvi"))
16238 (pngfile (concat texfilebase ".png"))
16239 (fnh (if (featurep 'xemacs)
16240 (font-height (get-face-font 'default))
16241 (face-attribute 'default :height nil)))
16242 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
16243 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
16244 (fg (or (plist-get options (if buffer :foreground :html-foreground))
16245 "Black"))
16246 (bg (or (plist-get options (if buffer :background :html-background))
16247 "Transparent")))
16248 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
16249 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
16250 (with-temp-file texfile
16251 (insert (org-splice-latex-header
16252 org-format-latex-header
16253 org-export-latex-default-packages-alist
16254 org-export-latex-packages-alist t
16255 org-format-latex-header-extra))
16256 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
16257 (require 'org-latex)
16258 (org-export-latex-fix-inputenc))
16259 (let ((dir default-directory))
16260 (condition-case nil
16261 (progn
16262 (cd tmpdir)
16263 (call-process "latex" nil nil nil texfile))
16264 (error nil))
16265 (cd dir))
16266 (if (not (file-exists-p dvifile))
16267 (progn (message "Failed to create dvi file from %s" texfile) nil)
16268 (condition-case nil
16269 (call-process "dvipng" nil nil nil
16270 "-fg" fg "-bg" bg
16271 "-D" dpi
16272 ;;"-x" scale "-y" scale
16273 "-T" "tight"
16274 "-o" pngfile
16275 dvifile)
16276 (error nil))
16277 (if (not (file-exists-p pngfile))
16278 (if org-format-latex-signal-error
16279 (error "Failed to create png file from %s" texfile)
16280 (message "Failed to create png file from %s" texfile)
16281 nil)
16282 ;; Use the requested file name and clean up
16283 (copy-file pngfile tofile 'replace)
16284 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16285 (delete-file (concat texfilebase e)))
16286 pngfile))))
16288 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
16289 "Fill a LaTeX header template TPL.
16290 In the template, the following place holders will be recognized:
16292 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
16293 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
16294 [PACKAGES] \\usepackage statements for PKG
16295 [NO-PACKAGES] do not include PKG
16296 [EXTRA] the string EXTRA
16297 [NO-EXTRA] do not include EXTRA
16299 For backward compatibility, if both the positive and the negative place
16300 holder is missing, the positive one (without the \"NO-\") will be
16301 assumed to be present at the end of the template.
16302 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
16303 EXTRA is a string.
16304 SNIPPETS-P indicates if this is run to create snippet images for HTML."
16305 (let (rpl (end ""))
16306 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
16307 (setq rpl (if (or (match-end 1) (not def-pkg))
16308 "" (org-latex-packages-to-string def-pkg snippets-p t))
16309 tpl (replace-match rpl t t tpl))
16310 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
16312 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
16313 (setq rpl (if (or (match-end 1) (not pkg))
16314 "" (org-latex-packages-to-string pkg snippets-p t))
16315 tpl (replace-match rpl t t tpl))
16316 (if pkg (setq end
16317 (concat end "\n"
16318 (org-latex-packages-to-string pkg snippets-p)))))
16320 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
16321 (setq rpl (if (or (match-end 1) (not extra))
16322 "" (concat extra "\n"))
16323 tpl (replace-match rpl t t tpl))
16324 (if (and extra (string-match "\\S-" extra))
16325 (setq end (concat end "\n" extra))))
16327 (if (string-match "\\S-" end)
16328 (concat tpl "\n" end)
16329 tpl)))
16331 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
16332 "Turn an alist of packages into a string with the \\usepackage macros."
16333 (setq pkg (mapconcat (lambda(p)
16334 (cond
16335 ((stringp p) p)
16336 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
16337 (format "%% Package %s omitted" (cadr p)))
16338 ((equal "" (car p))
16339 (format "\\usepackage{%s}" (cadr p)))
16341 (format "\\usepackage[%s]{%s}"
16342 (car p) (cadr p)))))
16344 "\n"))
16345 (if newline (concat pkg "\n") pkg))
16347 (defun org-dvipng-color (attr)
16348 "Return an rgb color specification for dvipng."
16349 (apply 'format "rgb %s %s %s"
16350 (mapcar 'org-normalize-color
16351 (color-values (face-attribute 'default attr nil)))))
16353 (defun org-normalize-color (value)
16354 "Return string to be used as color value for an RGB component."
16355 (format "%g" (/ value 65535.0)))
16357 ;; Image display
16360 (defvar org-inline-image-overlays nil)
16361 (make-variable-buffer-local 'org-inline-image-overlays)
16363 (defun org-toggle-inline-images (&optional include-linked)
16364 "Toggle the display of inline images.
16365 INCLUDE-LINKED is passed to `org-display-inline-images'."
16366 (interactive "P")
16367 (if org-inline-image-overlays
16368 (progn
16369 (org-remove-inline-images)
16370 (message "Inline image display turned off"))
16371 (org-display-inline-images include-linked)
16372 (if org-inline-image-overlays
16373 (message "%d images displayed inline"
16374 (length org-inline-image-overlays))
16375 (message "No images to display inline"))))
16377 (defun org-display-inline-images (&optional include-linked refresh beg end)
16378 "Display inline images.
16379 Normally only links without a description part are inlined, because this
16380 is how it will work for export. When INCLUDE-LINKED is set, also links
16381 with a description part will be inlined. This can be nice for a quick
16382 look at those images, but it does not reflect what exported files will look
16383 like.
16384 When REFRESH is set, refresh existing images between BEG and END.
16385 This will create new image displays only if necessary.
16386 BEG and END default to the buffer boundaries."
16387 (interactive "P")
16388 (unless refresh
16389 (org-remove-inline-images)
16390 (if (fboundp 'clear-image-cache) (clear-image-cache)))
16391 (save-excursion
16392 (save-restriction
16393 (widen)
16394 (setq beg (or beg (point-min)) end (or end (point-max)))
16395 (goto-char (point-min))
16396 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
16397 (substring (org-image-file-name-regexp) 0 -2)
16398 "\\)\\]" (if include-linked "" "\\]")))
16399 old file ov img)
16400 (while (re-search-forward re end t)
16401 (setq old (get-char-property-and-overlay (match-beginning 1)
16402 'org-image-overlay))
16403 (setq file (expand-file-name
16404 (concat (or (match-string 3) "") (match-string 4))))
16405 (when (file-exists-p file)
16406 (if (and (car-safe old) refresh)
16407 (image-refresh (overlay-get (cdr old) 'display))
16408 (setq img (save-match-data (create-image file)))
16409 (when img
16410 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
16411 (overlay-put ov 'display img)
16412 (overlay-put ov 'face 'default)
16413 (overlay-put ov 'org-image-overlay t)
16414 (overlay-put ov 'modification-hooks
16415 (list 'org-display-inline-modification-hook))
16416 (push ov org-inline-image-overlays)))))))))
16418 (defun org-display-inline-modification-hook (ov after beg end &optional len)
16419 "Remove inline-display overlay if a corresponding region is modified."
16420 (let ((inhibit-modification-hooks t))
16421 (when (and ov after)
16422 (delete ov org-inline-image-overlays)
16423 (delete-overlay ov))))
16425 (defun org-remove-inline-images ()
16426 "Remove inline display of images."
16427 (interactive)
16428 (mapc 'delete-overlay org-inline-image-overlays)
16429 (setq org-inline-image-overlays nil))
16431 ;;;; Key bindings
16433 ;; Make `C-c C-x' a prefix key
16434 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
16436 ;; TAB key with modifiers
16437 (org-defkey org-mode-map "\C-i" 'org-cycle)
16438 (org-defkey org-mode-map [(tab)] 'org-cycle)
16439 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
16440 (org-defkey org-mode-map [(meta tab)] 'pcomplete)
16441 (org-defkey org-mode-map "\M-\t" 'pcomplete)
16442 (org-defkey org-mode-map "\M-\C-i" 'pcomplete)
16443 ;; The following line is necessary under Suse GNU/Linux
16444 (unless (featurep 'xemacs)
16445 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
16446 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
16447 (define-key org-mode-map [backtab] 'org-shifttab)
16449 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
16450 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
16451 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
16453 ;; Cursor keys with modifiers
16454 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
16455 (org-defkey org-mode-map [(meta right)] 'org-metaright)
16456 (org-defkey org-mode-map [(meta up)] 'org-metaup)
16457 (org-defkey org-mode-map [(meta down)] 'org-metadown)
16459 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
16460 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
16461 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
16462 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
16464 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
16465 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
16466 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
16467 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
16469 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
16470 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
16472 ;; Babel keys
16473 (define-key org-mode-map org-babel-key-prefix org-babel-map)
16474 (mapc (lambda (pair)
16475 (define-key org-babel-map (car pair) (cdr pair)))
16476 org-babel-key-bindings)
16478 ;;; Extra keys for tty access.
16479 ;; We only set them when really needed because otherwise the
16480 ;; menus don't show the simple keys
16482 (when (or org-use-extra-keys
16483 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
16484 (not window-system))
16485 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
16486 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
16487 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
16488 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
16489 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
16490 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
16491 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
16492 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
16493 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
16494 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
16495 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
16496 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
16497 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
16498 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
16499 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
16500 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
16501 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
16502 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
16503 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
16504 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
16505 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
16506 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
16507 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
16508 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
16509 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
16510 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
16511 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
16512 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
16514 ;; All the other keys
16516 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
16517 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
16518 (if (boundp 'narrow-map)
16519 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
16520 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
16521 (if (boundp 'narrow-map)
16522 (org-defkey narrow-map "b" 'org-narrow-to-block)
16523 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
16524 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
16525 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
16526 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
16527 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
16528 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
16529 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
16530 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
16531 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
16532 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
16533 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
16534 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
16535 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
16536 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
16537 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
16538 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
16539 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
16540 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
16541 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
16542 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
16543 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
16544 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
16545 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
16546 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
16547 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
16548 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
16549 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
16550 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
16551 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
16552 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
16553 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
16554 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
16555 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
16556 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
16557 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
16558 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
16559 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
16560 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
16561 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
16562 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
16563 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
16564 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16565 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
16566 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
16567 (org-defkey org-mode-map "\C-c^" 'org-sort)
16568 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
16569 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
16570 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
16571 (org-defkey org-mode-map "\C-m" 'org-return)
16572 (org-defkey org-mode-map "\C-j" 'org-return-indent)
16573 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
16574 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
16575 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
16576 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
16577 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
16578 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
16579 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
16580 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
16581 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
16582 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
16583 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
16584 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
16585 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
16586 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
16587 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
16588 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
16589 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
16590 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
16591 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
16592 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
16593 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
16595 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
16596 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
16597 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
16598 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
16600 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
16601 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
16602 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
16603 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
16604 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
16605 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
16606 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
16607 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
16608 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
16609 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
16610 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
16611 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
16612 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
16613 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
16614 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
16615 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
16616 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
16617 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
16619 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
16620 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
16621 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
16622 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
16623 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
16625 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
16627 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
16629 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
16630 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
16632 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
16635 (when (featurep 'xemacs)
16636 (org-defkey org-mode-map 'button3 'popup-mode-menu))
16639 (defconst org-speed-commands-default
16641 ("Outline Navigation")
16642 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
16643 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
16644 ("f" . (org-speed-move-safe 'org-forward-same-level))
16645 ("b" . (org-speed-move-safe 'org-backward-same-level))
16646 ("u" . (org-speed-move-safe 'outline-up-heading))
16647 ("j" . org-goto)
16648 ("g" . (org-refile t))
16649 ("Outline Visibility")
16650 ("c" . org-cycle)
16651 ("C" . org-shifttab)
16652 (" " . org-display-outline-path)
16653 ("Outline Structure Editing")
16654 ("U" . org-shiftmetaup)
16655 ("D" . org-shiftmetadown)
16656 ("r" . org-metaright)
16657 ("l" . org-metaleft)
16658 ("R" . org-shiftmetaright)
16659 ("L" . org-shiftmetaleft)
16660 ("i" . (progn (forward-char 1) (call-interactively
16661 'org-insert-heading-respect-content)))
16662 ("^" . org-sort)
16663 ("w" . org-refile)
16664 ("a" . org-archive-subtree-default-with-confirmation)
16665 ("." . org-mark-subtree)
16666 ("Clock Commands")
16667 ("I" . org-clock-in)
16668 ("O" . org-clock-out)
16669 ("Meta Data Editing")
16670 ("t" . org-todo)
16671 ("0" . (org-priority ?\ ))
16672 ("1" . (org-priority ?A))
16673 ("2" . (org-priority ?B))
16674 ("3" . (org-priority ?C))
16675 (";" . org-set-tags-command)
16676 ("e" . org-set-effort)
16677 ("Agenda Views etc")
16678 ("v" . org-agenda)
16679 ("/" . org-sparse-tree)
16680 ("Misc")
16681 ("o" . org-open-at-point)
16682 ("?" . org-speed-command-help)
16683 ("<" . (org-agenda-set-restriction-lock 'subtree))
16684 (">" . (org-agenda-remove-restriction-lock))
16686 "The default speed commands.")
16688 (defun org-print-speed-command (e)
16689 (if (> (length (car e)) 1)
16690 (progn
16691 (princ "\n")
16692 (princ (car e))
16693 (princ "\n")
16694 (princ (make-string (length (car e)) ?-))
16695 (princ "\n"))
16696 (princ (car e))
16697 (princ " ")
16698 (if (symbolp (cdr e))
16699 (princ (symbol-name (cdr e)))
16700 (prin1 (cdr e)))
16701 (princ "\n")))
16703 (defun org-speed-command-help ()
16704 "Show the available speed commands."
16705 (interactive)
16706 (if (not org-use-speed-commands)
16707 (error "Speed commands are not activated, customize `org-use-speed-commands'")
16708 (with-output-to-temp-buffer "*Help*"
16709 (princ "User-defined Speed commands\n===========================\n")
16710 (mapc 'org-print-speed-command org-speed-commands-user)
16711 (princ "\n")
16712 (princ "Built-in Speed commands\n=======================\n")
16713 (mapc 'org-print-speed-command org-speed-commands-default))
16714 (with-current-buffer "*Help*"
16715 (setq truncate-lines t))))
16717 (defun org-speed-move-safe (cmd)
16718 "Execute CMD, but make sure that the cursor always ends up in a headline.
16719 If not, return to the original position and throw an error."
16720 (interactive)
16721 (let ((pos (point)))
16722 (call-interactively cmd)
16723 (unless (and (bolp) (org-on-heading-p))
16724 (goto-char pos)
16725 (error "Boundary reached while executing %s" cmd))))
16727 (defvar org-self-insert-command-undo-counter 0)
16729 (defvar org-table-auto-blank-field) ; defined in org-table.el
16730 (defvar org-speed-command nil)
16732 (defun org-speed-command-default-hook (keys)
16733 "Hook for activating single-letter speed commands.
16734 `org-speed-commands-default' specifies a minimal command set. Use
16735 `org-speed-commands-user' for further customization."
16736 (when (or (and (bolp) (looking-at outline-regexp))
16737 (and (functionp org-use-speed-commands)
16738 (funcall org-use-speed-commands)))
16739 (cdr (assoc keys (append org-speed-commands-user
16740 org-speed-commands-default)))))
16742 (defun org-babel-speed-command-hook (keys)
16743 "Hook for activating single-letter code block commands."
16744 (when (and (bolp) (looking-at org-babel-src-block-regexp))
16745 (cdr (assoc keys org-babel-key-bindings))))
16747 (defcustom org-speed-command-hook
16748 '(org-speed-command-default-hook org-babel-speed-command-hook)
16749 "Hook for activating speed commands at strategic locations.
16750 Hook functions are called in sequence until a valid handler is
16751 found.
16753 Each hook takes a single argument, a user-pressed command key
16754 which is also a `self-insert-command' from the global map.
16756 Within the hook, examine the cursor position and the command key
16757 and return nil or a valid handler as appropriate. Handler could
16758 be one of an interactive command, a function, or a form.
16760 Set `org-use-speed-commands' to non-nil value to enable this
16761 hook. The default setting is `org-speed-command-default-hook'."
16762 :group 'org-structure
16763 :type 'hook)
16765 (defun org-self-insert-command (N)
16766 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
16767 If the cursor is in a table looking at whitespace, the whitespace is
16768 overwritten, and the table is not marked as requiring realignment."
16769 (interactive "p")
16770 (cond
16771 ((and org-use-speed-commands
16772 (setq org-speed-command
16773 (run-hook-with-args-until-success
16774 'org-speed-command-hook (this-command-keys))))
16775 (cond
16776 ((commandp org-speed-command)
16777 (setq this-command org-speed-command)
16778 (call-interactively org-speed-command))
16779 ((functionp org-speed-command)
16780 (funcall org-speed-command))
16781 ((and org-speed-command (listp org-speed-command))
16782 (eval org-speed-command))
16783 (t (let (org-use-speed-commands)
16784 (call-interactively 'org-self-insert-command)))))
16785 ((and
16786 (org-table-p)
16787 (progn
16788 ;; check if we blank the field, and if that triggers align
16789 (and (featurep 'org-table) org-table-auto-blank-field
16790 (member last-command
16791 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
16792 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
16793 ;; got extra space, this field does not determine column width
16794 (let (org-table-may-need-update) (org-table-blank-field))
16795 ;; no extra space, this field may determine column width
16796 (org-table-blank-field)))
16798 (eq N 1)
16799 (looking-at "[^|\n]* |"))
16800 (let (org-table-may-need-update)
16801 (goto-char (1- (match-end 0)))
16802 (delete-backward-char 1)
16803 (goto-char (match-beginning 0))
16804 (self-insert-command N)))
16806 (setq org-table-may-need-update t)
16807 (self-insert-command N)
16808 (org-fix-tags-on-the-fly)
16809 (if org-self-insert-cluster-for-undo
16810 (if (not (eq last-command 'org-self-insert-command))
16811 (setq org-self-insert-command-undo-counter 1)
16812 (if (>= org-self-insert-command-undo-counter 20)
16813 (setq org-self-insert-command-undo-counter 1)
16814 (and (> org-self-insert-command-undo-counter 0)
16815 buffer-undo-list
16816 (not (cadr buffer-undo-list)) ; remove nil entry
16817 (setcdr buffer-undo-list (cddr buffer-undo-list)))
16818 (setq org-self-insert-command-undo-counter
16819 (1+ org-self-insert-command-undo-counter))))))))
16821 (defun org-fix-tags-on-the-fly ()
16822 (when (and (equal (char-after (point-at-bol)) ?*)
16823 (org-on-heading-p))
16824 (org-align-tags-here org-tags-column)))
16826 (defun org-delete-backward-char (N)
16827 "Like `delete-backward-char', insert whitespace at field end in tables.
16828 When deleting backwards, in tables this function will insert whitespace in
16829 front of the next \"|\" separator, to keep the table aligned. The table will
16830 still be marked for re-alignment if the field did fill the entire column,
16831 because, in this case the deletion might narrow the column."
16832 (interactive "p")
16833 (if (and (org-table-p)
16834 (eq N 1)
16835 (string-match "|" (buffer-substring (point-at-bol) (point)))
16836 (looking-at ".*?|"))
16837 (let ((pos (point))
16838 (noalign (looking-at "[^|\n\r]* |"))
16839 (c org-table-may-need-update))
16840 (backward-delete-char N)
16841 (if (not overwrite-mode)
16842 (progn
16843 (skip-chars-forward "^|")
16844 (insert " ")
16845 (goto-char (1- pos))))
16846 ;; noalign: if there were two spaces at the end, this field
16847 ;; does not determine the width of the column.
16848 (if noalign (setq org-table-may-need-update c)))
16849 (backward-delete-char N)
16850 (org-fix-tags-on-the-fly)))
16852 (defun org-delete-char (N)
16853 "Like `delete-char', but insert whitespace at field end in tables.
16854 When deleting characters, in tables this function will insert whitespace in
16855 front of the next \"|\" separator, to keep the table aligned. The table will
16856 still be marked for re-alignment if the field did fill the entire column,
16857 because, in this case the deletion might narrow the column."
16858 (interactive "p")
16859 (if (and (org-table-p)
16860 (not (bolp))
16861 (not (= (char-after) ?|))
16862 (eq N 1))
16863 (if (looking-at ".*?|")
16864 (let ((pos (point))
16865 (noalign (looking-at "[^|\n\r]* |"))
16866 (c org-table-may-need-update))
16867 (replace-match (concat
16868 (substring (match-string 0) 1 -1)
16869 " |"))
16870 (goto-char pos)
16871 ;; noalign: if there were two spaces at the end, this field
16872 ;; does not determine the width of the column.
16873 (if noalign (setq org-table-may-need-update c)))
16874 (delete-char N))
16875 (delete-char N)
16876 (org-fix-tags-on-the-fly)))
16878 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
16879 (put 'org-self-insert-command 'delete-selection t)
16880 (put 'orgtbl-self-insert-command 'delete-selection t)
16881 (put 'org-delete-char 'delete-selection 'supersede)
16882 (put 'org-delete-backward-char 'delete-selection 'supersede)
16883 (put 'org-yank 'delete-selection 'yank)
16885 ;; Make `flyspell-mode' delay after some commands
16886 (put 'org-self-insert-command 'flyspell-delayed t)
16887 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
16888 (put 'org-delete-char 'flyspell-delayed t)
16889 (put 'org-delete-backward-char 'flyspell-delayed t)
16891 ;; Make pabbrev-mode expand after org-mode commands
16892 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
16893 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
16895 ;; How to do this: Measure non-white length of current string
16896 ;; If equal to column width, we should realign.
16898 (defun org-remap (map &rest commands)
16899 "In MAP, remap the functions given in COMMANDS.
16900 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
16901 (let (new old)
16902 (while commands
16903 (setq old (pop commands) new (pop commands))
16904 (if (fboundp 'command-remapping)
16905 (org-defkey map (vector 'remap old) new)
16906 (substitute-key-definition old new map global-map)))))
16908 (when (eq org-enable-table-editor 'optimized)
16909 ;; If the user wants maximum table support, we need to hijack
16910 ;; some standard editing functions
16911 (org-remap org-mode-map
16912 'self-insert-command 'org-self-insert-command
16913 'delete-char 'org-delete-char
16914 'delete-backward-char 'org-delete-backward-char)
16915 (org-defkey org-mode-map "|" 'org-force-self-insert))
16917 (defvar org-ctrl-c-ctrl-c-hook nil
16918 "Hook for functions attaching themselves to `C-c C-c'.
16919 This can be used to add additional functionality to the C-c C-c key which
16920 executes context-dependent commands.
16921 Each function will be called with no arguments. The function must check
16922 if the context is appropriate for it to act. If yes, it should do its
16923 thing and then return a non-nil value. If the context is wrong,
16924 just do nothing and return nil.")
16926 (defvar org-tab-first-hook nil
16927 "Hook for functions to attach themselves to TAB.
16928 See `org-ctrl-c-ctrl-c-hook' for more information.
16929 This hook runs as the first action when TAB is pressed, even before
16930 `org-cycle' messes around with the `outline-regexp' to cater for
16931 inline tasks and plain list item folding.
16932 If any function in this hook returns t, any other actions that
16933 would have been caused by TAB (such as table field motion or visibility
16934 cycling) will not occur.")
16936 (defvar org-tab-after-check-for-table-hook nil
16937 "Hook for functions to attach themselves to TAB.
16938 See `org-ctrl-c-ctrl-c-hook' for more information.
16939 This hook runs after it has been established that the cursor is not in a
16940 table, but before checking if the cursor is in a headline or if global cycling
16941 should be done.
16942 If any function in this hook returns t, not other actions like visibility
16943 cycling will be done.")
16945 (defvar org-tab-after-check-for-cycling-hook nil
16946 "Hook for functions to attach themselves to TAB.
16947 See `org-ctrl-c-ctrl-c-hook' for more information.
16948 This hook runs after it has been established that not table field motion and
16949 not visibility should be done because of current context. This is probably
16950 the place where a package like yasnippets can hook in.")
16952 (defvar org-tab-before-tab-emulation-hook nil
16953 "Hook for functions to attach themselves to TAB.
16954 See `org-ctrl-c-ctrl-c-hook' for more information.
16955 This hook runs after every other options for TAB have been exhausted, but
16956 before indentation and \t insertion takes place.")
16958 (defvar org-metaleft-hook nil
16959 "Hook for functions attaching themselves to `M-left'.
16960 See `org-ctrl-c-ctrl-c-hook' for more information.")
16961 (defvar org-metaright-hook nil
16962 "Hook for functions attaching themselves to `M-right'.
16963 See `org-ctrl-c-ctrl-c-hook' for more information.")
16964 (defvar org-metaup-hook nil
16965 "Hook for functions attaching themselves to `M-up'.
16966 See `org-ctrl-c-ctrl-c-hook' for more information.")
16967 (defvar org-metadown-hook nil
16968 "Hook for functions attaching themselves to `M-down'.
16969 See `org-ctrl-c-ctrl-c-hook' for more information.")
16970 (defvar org-shiftmetaleft-hook nil
16971 "Hook for functions attaching themselves to `M-S-left'.
16972 See `org-ctrl-c-ctrl-c-hook' for more information.")
16973 (defvar org-shiftmetaright-hook nil
16974 "Hook for functions attaching themselves to `M-S-right'.
16975 See `org-ctrl-c-ctrl-c-hook' for more information.")
16976 (defvar org-shiftmetaup-hook nil
16977 "Hook for functions attaching themselves to `M-S-up'.
16978 See `org-ctrl-c-ctrl-c-hook' for more information.")
16979 (defvar org-shiftmetadown-hook nil
16980 "Hook for functions attaching themselves to `M-S-down'.
16981 See `org-ctrl-c-ctrl-c-hook' for more information.")
16982 (defvar org-metareturn-hook nil
16983 "Hook for functions attaching themselves to `M-RET'.
16984 See `org-ctrl-c-ctrl-c-hook' for more information.")
16985 (defvar org-shiftup-hook nil
16986 "Hook for functions attaching themselves to `S-up'.
16987 See `org-ctrl-c-ctrl-c-hook' for more information.")
16988 (defvar org-shiftup-final-hook nil
16989 "Hook for functions attaching themselves to `S-up'.
16990 This one runs after all other options except shift-select have been excluded.
16991 See `org-ctrl-c-ctrl-c-hook' for more information.")
16992 (defvar org-shiftdown-hook nil
16993 "Hook for functions attaching themselves to `S-down'.
16994 See `org-ctrl-c-ctrl-c-hook' for more information.")
16995 (defvar org-shiftdown-final-hook nil
16996 "Hook for functions attaching themselves to `S-down'.
16997 This one runs after all other options except shift-select have been excluded.
16998 See `org-ctrl-c-ctrl-c-hook' for more information.")
16999 (defvar org-shiftleft-hook nil
17000 "Hook for functions attaching themselves to `S-left'.
17001 See `org-ctrl-c-ctrl-c-hook' for more information.")
17002 (defvar org-shiftleft-final-hook nil
17003 "Hook for functions attaching themselves to `S-left'.
17004 This one runs after all other options except shift-select have been excluded.
17005 See `org-ctrl-c-ctrl-c-hook' for more information.")
17006 (defvar org-shiftright-hook nil
17007 "Hook for functions attaching themselves to `S-right'.
17008 See `org-ctrl-c-ctrl-c-hook' for more information.")
17009 (defvar org-shiftright-final-hook nil
17010 "Hook for functions attaching themselves to `S-right'.
17011 This one runs after all other options except shift-select have been excluded.
17012 See `org-ctrl-c-ctrl-c-hook' for more information.")
17014 (defun org-modifier-cursor-error ()
17015 "Throw an error, a modified cursor command was applied in wrong context."
17016 (error "This command is active in special context like tables, headlines or items"))
17018 (defun org-shiftselect-error ()
17019 "Throw an error because Shift-Cursor command was applied in wrong context."
17020 (if (and (boundp 'shift-select-mode) shift-select-mode)
17021 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
17022 (error "This command works only in special context like headlines or timestamps")))
17024 (defun org-call-for-shift-select (cmd)
17025 (let ((this-command-keys-shift-translated t))
17026 (call-interactively cmd)))
17028 (defun org-shifttab (&optional arg)
17029 "Global visibility cycling or move to previous table field.
17030 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17031 on context.
17032 See the individual commands for more information."
17033 (interactive "P")
17034 (cond
17035 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17036 ((integerp arg)
17037 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
17038 (message "Content view to level: %d" arg)
17039 (org-content (prefix-numeric-value arg2))
17040 (setq org-cycle-global-status 'overview)))
17041 (t (call-interactively 'org-global-cycle))))
17043 (defun org-shiftmetaleft ()
17044 "Promote subtree or delete table column.
17045 Calls `org-promote-subtree', `org-outdent-item',
17046 or `org-table-delete-column', depending on context.
17047 See the individual commands for more information."
17048 (interactive)
17049 (cond
17050 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
17051 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17052 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
17053 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
17054 (t (org-modifier-cursor-error))))
17056 (defun org-shiftmetaright ()
17057 "Demote subtree or insert table column.
17058 Calls `org-demote-subtree', `org-indent-item',
17059 or `org-table-insert-column', depending on context.
17060 See the individual commands for more information."
17061 (interactive)
17062 (cond
17063 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
17064 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17065 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
17066 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
17067 (t (org-modifier-cursor-error))))
17069 (defun org-shiftmetaup (&optional arg)
17070 "Move subtree up or kill table row.
17071 Calls `org-move-subtree-up' or `org-table-kill-row' or
17072 `org-move-item-up' depending on context. See the individual commands
17073 for more information."
17074 (interactive "P")
17075 (cond
17076 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
17077 ((org-at-table-p) (call-interactively 'org-table-kill-row))
17078 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17079 ((org-at-item-p) (call-interactively 'org-move-item-up))
17080 (t (org-modifier-cursor-error))))
17082 (defun org-shiftmetadown (&optional arg)
17083 "Move subtree down or insert table row.
17084 Calls `org-move-subtree-down' or `org-table-insert-row' or
17085 `org-move-item-down', depending on context. See the individual
17086 commands for more information."
17087 (interactive "P")
17088 (cond
17089 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
17090 ((org-at-table-p) (call-interactively 'org-table-insert-row))
17091 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17092 ((org-at-item-p) (call-interactively 'org-move-item-down))
17093 (t (org-modifier-cursor-error))))
17095 (defsubst org-hidden-tree-error ()
17096 (error
17097 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
17099 (defun org-metaleft (&optional arg)
17100 "Promote heading or move table column to left.
17101 Calls `org-do-promote' or `org-table-move-column', depending on context.
17102 With no specific context, calls the Emacs default `backward-word'.
17103 See the individual commands for more information."
17104 (interactive "P")
17105 (cond
17106 ((run-hook-with-args-until-success 'org-metaleft-hook))
17107 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
17108 ((org-with-limited-levels
17109 (or (org-on-heading-p)
17110 (and (org-region-active-p)
17111 (save-excursion
17112 (goto-char (region-beginning))
17113 (org-on-heading-p)))))
17114 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17115 (call-interactively 'org-do-promote))
17116 ;; At an inline task.
17117 ((org-on-heading-p)
17118 (call-interactively 'org-inlinetask-promote))
17119 ((or (org-at-item-p)
17120 (and (org-region-active-p)
17121 (save-excursion
17122 (goto-char (region-beginning))
17123 (org-at-item-p))))
17124 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17125 (call-interactively 'org-outdent-item))
17126 (t (call-interactively 'backward-word))))
17128 (defun org-metaright (&optional arg)
17129 "Demote subtree or move table column to right.
17130 Calls `org-do-demote' or `org-table-move-column', depending on context.
17131 With no specific context, calls the Emacs default `forward-word'.
17132 See the individual commands for more information."
17133 (interactive "P")
17134 (cond
17135 ((run-hook-with-args-until-success 'org-metaright-hook))
17136 ((org-at-table-p) (call-interactively 'org-table-move-column))
17137 ((org-with-limited-levels
17138 (or (org-on-heading-p)
17139 (and (org-region-active-p)
17140 (save-excursion
17141 (goto-char (region-beginning))
17142 (org-on-heading-p)))))
17143 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17144 (call-interactively 'org-do-demote))
17145 ;; At an inline task.
17146 ((org-on-heading-p)
17147 (call-interactively 'org-inlinetask-demote))
17148 ((or (org-at-item-p)
17149 (and (org-region-active-p)
17150 (save-excursion
17151 (goto-char (region-beginning))
17152 (org-at-item-p))))
17153 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17154 (call-interactively 'org-indent-item))
17155 (t (call-interactively 'forward-word))))
17157 (defun org-check-for-hidden (what)
17158 "Check if there are hidden headlines/items in the current visual line.
17159 WHAT can be either `headlines' or `items'. If the current line is
17160 an outline or item heading and it has a folded subtree below it,
17161 this function returns t, nil otherwise."
17162 (let ((re (cond
17163 ((eq what 'headlines) (concat "^" org-outline-regexp))
17164 ((eq what 'items) (org-item-beginning-re))
17165 (t (error "This should not happen"))))
17166 beg end)
17167 (save-excursion
17168 (catch 'exit
17169 (unless (org-region-active-p)
17170 (setq beg (point-at-bol))
17171 (beginning-of-line 2)
17172 (while (and (not (eobp)) ;; this is like `next-line'
17173 (get-char-property (1- (point)) 'invisible))
17174 (beginning-of-line 2))
17175 (setq end (point))
17176 (goto-char beg)
17177 (goto-char (point-at-eol))
17178 (setq end (max end (point)))
17179 (while (re-search-forward re end t)
17180 (if (get-char-property (match-beginning 0) 'invisible)
17181 (throw 'exit t))))
17182 nil))))
17184 (defun org-metaup (&optional arg)
17185 "Move subtree up or move table row up.
17186 Calls `org-move-subtree-up' or `org-table-move-row' or
17187 `org-move-item-up', depending on context. See the individual commands
17188 for more information."
17189 (interactive "P")
17190 (cond
17191 ((run-hook-with-args-until-success 'org-metaup-hook))
17192 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
17193 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17194 ((org-at-item-p) (call-interactively 'org-move-item-up))
17195 (t (transpose-lines 1) (beginning-of-line -1))))
17197 (defun org-metadown (&optional arg)
17198 "Move subtree down or move table row down.
17199 Calls `org-move-subtree-down' or `org-table-move-row' or
17200 `org-move-item-down', depending on context. See the individual
17201 commands for more information."
17202 (interactive "P")
17203 (cond
17204 ((run-hook-with-args-until-success 'org-metadown-hook))
17205 ((org-at-table-p) (call-interactively 'org-table-move-row))
17206 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17207 ((org-at-item-p) (call-interactively 'org-move-item-down))
17208 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
17210 (defun org-shiftup (&optional arg)
17211 "Increase item in timestamp or increase priority of current headline.
17212 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
17213 depending on context. See the individual commands for more information."
17214 (interactive "P")
17215 (cond
17216 ((run-hook-with-args-until-success 'org-shiftup-hook))
17217 ((and org-support-shift-select (org-region-active-p))
17218 (org-call-for-shift-select 'previous-line))
17219 ((org-at-timestamp-p t)
17220 (call-interactively (if org-edit-timestamp-down-means-later
17221 'org-timestamp-down 'org-timestamp-up)))
17222 ((and (not (eq org-support-shift-select 'always))
17223 org-enable-priority-commands
17224 (org-on-heading-p))
17225 (call-interactively 'org-priority-up))
17226 ((and (not org-support-shift-select) (org-at-item-p))
17227 (call-interactively 'org-previous-item))
17228 ((org-clocktable-try-shift 'up arg))
17229 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
17230 (org-support-shift-select
17231 (org-call-for-shift-select 'previous-line))
17232 (t (org-shiftselect-error))))
17234 (defun org-shiftdown (&optional arg)
17235 "Decrease item in timestamp or decrease priority of current headline.
17236 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
17237 depending on context. See the individual commands for more information."
17238 (interactive "P")
17239 (cond
17240 ((run-hook-with-args-until-success 'org-shiftdown-hook))
17241 ((and org-support-shift-select (org-region-active-p))
17242 (org-call-for-shift-select 'next-line))
17243 ((org-at-timestamp-p t)
17244 (call-interactively (if org-edit-timestamp-down-means-later
17245 'org-timestamp-up 'org-timestamp-down)))
17246 ((and (not (eq org-support-shift-select 'always))
17247 org-enable-priority-commands
17248 (org-on-heading-p))
17249 (call-interactively 'org-priority-down))
17250 ((and (not org-support-shift-select) (org-at-item-p))
17251 (call-interactively 'org-next-item))
17252 ((org-clocktable-try-shift 'down arg))
17253 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
17254 (org-support-shift-select
17255 (org-call-for-shift-select 'next-line))
17256 (t (org-shiftselect-error))))
17258 (defun org-shiftright (&optional arg)
17259 "Cycle the thing at point or in the current line, depending on context.
17260 Depending on context, this does one of the following:
17262 - switch a timestamp at point one day into the future
17263 - on a headline, switch to the next TODO keyword.
17264 - on an item, switch entire list to the next bullet type
17265 - on a property line, switch to the next allowed value
17266 - on a clocktable definition line, move time block into the future"
17267 (interactive "P")
17268 (cond
17269 ((run-hook-with-args-until-success 'org-shiftright-hook))
17270 ((and org-support-shift-select (org-region-active-p))
17271 (org-call-for-shift-select 'forward-char))
17272 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
17273 ((and (not (eq org-support-shift-select 'always))
17274 (org-on-heading-p))
17275 (let ((org-inhibit-logging
17276 (not org-treat-S-cursor-todo-selection-as-state-change))
17277 (org-inhibit-blocking
17278 (not org-treat-S-cursor-todo-selection-as-state-change)))
17279 (org-call-with-arg 'org-todo 'right)))
17280 ((or (and org-support-shift-select
17281 (not (eq org-support-shift-select 'always))
17282 (org-at-item-bullet-p))
17283 (and (not org-support-shift-select) (org-at-item-p)))
17284 (org-call-with-arg 'org-cycle-list-bullet nil))
17285 ((and (not (eq org-support-shift-select 'always))
17286 (org-at-property-p))
17287 (call-interactively 'org-property-next-allowed-value))
17288 ((org-clocktable-try-shift 'right arg))
17289 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
17290 (org-support-shift-select
17291 (org-call-for-shift-select 'forward-char))
17292 (t (org-shiftselect-error))))
17294 (defun org-shiftleft (&optional arg)
17295 "Cycle the thing at point or in the current line, depending on context.
17296 Depending on context, this does one of the following:
17298 - switch a timestamp at point one day into the past
17299 - on a headline, switch to the previous TODO keyword.
17300 - on an item, switch entire list to the previous bullet type
17301 - on a property line, switch to the previous allowed value
17302 - on a clocktable definition line, move time block into the past"
17303 (interactive "P")
17304 (cond
17305 ((run-hook-with-args-until-success 'org-shiftleft-hook))
17306 ((and org-support-shift-select (org-region-active-p))
17307 (org-call-for-shift-select 'backward-char))
17308 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
17309 ((and (not (eq org-support-shift-select 'always))
17310 (org-on-heading-p))
17311 (let ((org-inhibit-logging
17312 (not org-treat-S-cursor-todo-selection-as-state-change))
17313 (org-inhibit-blocking
17314 (not org-treat-S-cursor-todo-selection-as-state-change)))
17315 (org-call-with-arg 'org-todo 'left)))
17316 ((or (and org-support-shift-select
17317 (not (eq org-support-shift-select 'always))
17318 (org-at-item-bullet-p))
17319 (and (not org-support-shift-select) (org-at-item-p)))
17320 (org-call-with-arg 'org-cycle-list-bullet 'previous))
17321 ((and (not (eq org-support-shift-select 'always))
17322 (org-at-property-p))
17323 (call-interactively 'org-property-previous-allowed-value))
17324 ((org-clocktable-try-shift 'left arg))
17325 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
17326 (org-support-shift-select
17327 (org-call-for-shift-select 'backward-char))
17328 (t (org-shiftselect-error))))
17330 (defun org-shiftcontrolright ()
17331 "Switch to next TODO set."
17332 (interactive)
17333 (cond
17334 ((and org-support-shift-select (org-region-active-p))
17335 (org-call-for-shift-select 'forward-word))
17336 ((and (not (eq org-support-shift-select 'always))
17337 (org-on-heading-p))
17338 (org-call-with-arg 'org-todo 'nextset))
17339 (org-support-shift-select
17340 (org-call-for-shift-select 'forward-word))
17341 (t (org-shiftselect-error))))
17343 (defun org-shiftcontrolleft ()
17344 "Switch to previous TODO set."
17345 (interactive)
17346 (cond
17347 ((and org-support-shift-select (org-region-active-p))
17348 (org-call-for-shift-select 'backward-word))
17349 ((and (not (eq org-support-shift-select 'always))
17350 (org-on-heading-p))
17351 (org-call-with-arg 'org-todo 'previousset))
17352 (org-support-shift-select
17353 (org-call-for-shift-select 'backward-word))
17354 (t (org-shiftselect-error))))
17356 (defun org-ctrl-c-ret ()
17357 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
17358 (interactive)
17359 (cond
17360 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
17361 (t (call-interactively 'org-insert-heading))))
17363 (defun org-copy-special ()
17364 "Copy region in table or copy current subtree.
17365 Calls `org-table-copy' or `org-copy-subtree', depending on context.
17366 See the individual commands for more information."
17367 (interactive)
17368 (call-interactively
17369 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
17371 (defun org-cut-special ()
17372 "Cut region in table or cut current subtree.
17373 Calls `org-table-copy' or `org-cut-subtree', depending on context.
17374 See the individual commands for more information."
17375 (interactive)
17376 (call-interactively
17377 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
17379 (defun org-paste-special (arg)
17380 "Paste rectangular region into table, or past subtree relative to level.
17381 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
17382 See the individual commands for more information."
17383 (interactive "P")
17384 (if (org-at-table-p)
17385 (org-table-paste-rectangle)
17386 (org-paste-subtree arg)))
17388 (defun org-edit-special (&optional arg)
17389 "Call a special editor for the stuff at point.
17390 When at a table, call the formula editor with `org-table-edit-formulas'.
17391 When at the first line of an src example, call `org-edit-src-code'.
17392 When in an #+include line, visit the include file. Otherwise call
17393 `ffap' to visit the file at point."
17394 (interactive)
17395 ;; possibly prep session before editing source
17396 (when arg
17397 (let* ((info (org-babel-get-src-block-info))
17398 (lang (nth 0 info))
17399 (params (nth 2 info))
17400 (session (cdr (assoc :session params))))
17401 (when (and info session) ;; we are in a source-code block with a session
17402 (funcall
17403 (intern (concat "org-babel-prep-session:" lang)) session params))))
17404 (cond ;; proceed with `org-edit-special'
17405 ((save-excursion
17406 (beginning-of-line 1)
17407 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
17408 (find-file (org-trim (match-string 1))))
17409 ((org-edit-src-code))
17410 ((org-edit-fixed-width-region))
17411 ((org-at-table.el-p)
17412 (org-edit-src-code))
17413 ((or (org-at-table-p)
17414 (save-excursion
17415 (beginning-of-line 1)
17416 (looking-at "[ \t]*#\\+TBLFM:")))
17417 (call-interactively 'org-table-edit-formulas))
17418 (t (call-interactively 'ffap))))
17420 (defun org-ctrl-c-ctrl-c (&optional arg)
17421 "Set tags in headline, or update according to changed information at point.
17423 This command does many different things, depending on context:
17425 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
17426 this is what we do.
17428 - If the cursor is on a statistics cookie, update it.
17430 - If the cursor is in a headline, prompt for tags and insert them
17431 into the current line, aligned to `org-tags-column'. When called
17432 with prefix arg, realign all tags in the current buffer.
17434 - If the cursor is in one of the special #+KEYWORD lines, this
17435 triggers scanning the buffer for these lines and updating the
17436 information.
17438 - If the cursor is inside a table, realign the table. This command
17439 works even if the automatic table editor has been turned off.
17441 - If the cursor is on a #+TBLFM line, re-apply the formulas to
17442 the entire table.
17444 - If the cursor is at a footnote reference or definition, jump to
17445 the corresponding definition or references, respectively.
17447 - If the cursor is a the beginning of a dynamic block, update it.
17449 - If the current buffer is a capture buffer, close note and file it.
17451 - If the cursor is on a <<<target>>>, update radio targets and
17452 corresponding links in this buffer.
17454 - If the cursor is on a numbered item in a plain list, renumber the
17455 ordered list.
17457 - If the cursor is on a checkbox, toggle it.
17459 - If the cursor is on a code block, evaluate it. The variable
17460 `org-confirm-babel-evaluate' can be used to control prompting
17461 before code block evaluation, by default every code block
17462 evaluation requires confirmation. Code block evaluation can be
17463 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
17464 (interactive "P")
17465 (let ((org-enable-table-editor t))
17466 (cond
17467 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
17468 org-occur-highlights
17469 org-latex-fragment-image-overlays)
17470 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
17471 (org-remove-occur-highlights)
17472 (org-remove-latex-fragment-image-overlays)
17473 (message "Temporary highlights/overlays removed from current buffer"))
17474 ((and (local-variable-p 'org-finish-function (current-buffer))
17475 (fboundp org-finish-function))
17476 (funcall org-finish-function))
17477 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
17478 ((or (looking-at org-property-start-re)
17479 (org-at-property-p))
17480 (call-interactively 'org-property-action))
17481 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
17482 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
17483 (or (org-on-heading-p) (org-at-item-p)))
17484 (call-interactively 'org-update-statistics-cookies))
17485 ((org-on-heading-p) (call-interactively 'org-set-tags))
17486 ((org-at-table.el-p)
17487 (message "Use C-c ' to edit table.el tables"))
17488 ((org-at-table-p)
17489 (org-table-maybe-eval-formula)
17490 (if arg
17491 (call-interactively 'org-table-recalculate)
17492 (org-table-maybe-recalculate-line))
17493 (call-interactively 'org-table-align)
17494 (orgtbl-send-table 'maybe))
17495 ((or (org-footnote-at-reference-p)
17496 (org-footnote-at-definition-p))
17497 (call-interactively 'org-footnote-action))
17498 ((org-at-item-checkbox-p)
17499 ;; Cursor at a checkbox: repair list and update checkboxes. Send
17500 ;; list only if at top item.
17501 (let* ((cbox (match-string 1))
17502 (struct (org-list-struct))
17503 (old-struct (copy-tree struct))
17504 (parents (org-list-parents-alist struct))
17505 (prevs (org-list-prevs-alist struct))
17506 (orderedp (org-entry-get nil "ORDERED"))
17507 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
17508 block-item)
17509 ;; Use a light version of `org-toggle-checkbox' to avoid
17510 ;; computing list structure twice.
17511 (org-list-set-checkbox (point-at-bol) struct
17512 (cond
17513 ((equal arg '(16)) "[-]")
17514 ((equal arg '(4)) nil)
17515 ((equal "[ ]" cbox) "[X]")
17516 (t "[ ]")))
17517 (org-list-struct-fix-ind struct parents)
17518 (org-list-struct-fix-bul struct prevs)
17519 (setq block-item
17520 (org-list-struct-fix-box struct parents prevs orderedp))
17521 (when block-item
17522 (message
17523 "Checkboxes were removed due to unchecked box at line %d"
17524 (org-current-line block-item)))
17525 (org-list-struct-apply-struct struct old-struct)
17526 (org-update-checkbox-count-maybe)
17527 (when firstp (org-list-send-list 'maybe))))
17528 ((org-at-item-p)
17529 ;; Cursor at an item: repair list. Do checkbox related actions
17530 ;; only if function was called with an argument. Send list only
17531 ;; if at top item.
17532 (let* ((struct (org-list-struct))
17533 (old-struct (copy-tree struct))
17534 (parents (org-list-parents-alist struct))
17535 (prevs (org-list-prevs-alist struct))
17536 (firstp (= (org-list-get-top-point struct) (point-at-bol))))
17537 (org-list-struct-fix-ind struct parents)
17538 (org-list-struct-fix-bul struct prevs)
17539 (when arg
17540 (org-list-set-checkbox (point-at-bol) struct "[ ]")
17541 (org-list-struct-fix-box struct parents prevs))
17542 (org-list-struct-apply-struct struct old-struct)
17543 (when arg (org-update-checkbox-count-maybe))
17544 (when firstp (org-list-send-list 'maybe))))
17545 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
17546 ;; Dynamic block
17547 (beginning-of-line 1)
17548 (save-excursion (org-update-dblock)))
17549 ((save-excursion
17550 (beginning-of-line 1)
17551 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
17552 (cond
17553 ((equal (match-string 1) "TBLFM")
17554 ;; Recalculate the table before this line
17555 (save-excursion
17556 (beginning-of-line 1)
17557 (skip-chars-backward " \r\n\t")
17558 (if (org-at-table-p)
17559 (org-call-with-arg 'org-table-recalculate (or arg t)))))
17561 (let ((org-inhibit-startup-visibility-stuff t)
17562 (org-startup-align-all-tables nil))
17563 (org-save-outline-visibility 'use-markers (org-mode-restart)))
17564 (message "Local setup has been refreshed"))))
17565 ((org-clock-update-time-maybe))
17566 (t (error "C-c C-c can do nothing useful at this location")))))
17568 (defun org-mode-restart ()
17569 "Restart Org-mode, to scan again for special lines.
17570 Also updates the keyword regular expressions."
17571 (interactive)
17572 (org-mode)
17573 (message "Org-mode restarted"))
17575 (defun org-kill-note-or-show-branches ()
17576 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
17577 (interactive)
17578 (if (not org-finish-function)
17579 (progn
17580 (hide-subtree)
17581 (call-interactively 'show-branches))
17582 (let ((org-note-abort t))
17583 (funcall org-finish-function))))
17585 (defun org-return (&optional indent)
17586 "Goto next table row or insert a newline.
17587 Calls `org-table-next-row' or `newline', depending on context.
17588 See the individual commands for more information."
17589 (interactive)
17590 (cond
17591 ((bobp) (if indent (newline-and-indent) (newline)))
17592 ((org-at-table-p)
17593 (org-table-justify-field-maybe)
17594 (call-interactively 'org-table-next-row))
17595 ;; when `newline-and-indent' is called within a list, make sure
17596 ;; text moved stays inside the item.
17597 ((and (org-in-item-p) indent)
17598 (if (and (org-at-item-p) (>= (point) (match-end 0)))
17599 (progn
17600 (newline)
17601 (org-indent-line-to (length (match-string 0))))
17602 (let ((ind (org-get-indentation)))
17603 (newline)
17604 (if (org-looking-back org-list-end-re)
17605 (org-indent-line-function)
17606 (org-indent-line-to ind)))))
17607 ((and org-return-follows-link
17608 (eq (get-text-property (point) 'face) 'org-link))
17609 (call-interactively 'org-open-at-point))
17610 ((and (org-at-heading-p)
17611 (looking-at
17612 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
17613 (org-show-entry)
17614 (end-of-line 1)
17615 (newline))
17616 (t (if indent (newline-and-indent) (newline)))))
17618 (defun org-return-indent ()
17619 "Goto next table row or insert a newline and indent.
17620 Calls `org-table-next-row' or `newline-and-indent', depending on
17621 context. See the individual commands for more information."
17622 (interactive)
17623 (org-return t))
17625 (defun org-ctrl-c-star ()
17626 "Compute table, or change heading status of lines.
17627 Calls `org-table-recalculate' or `org-toggle-heading',
17628 depending on context."
17629 (interactive)
17630 (cond
17631 ((org-at-table-p)
17632 (call-interactively 'org-table-recalculate))
17634 ;; Convert all lines in region to list items
17635 (call-interactively 'org-toggle-heading))))
17637 (defun org-ctrl-c-minus ()
17638 "Insert separator line in table or modify bullet status of line.
17639 Also turns a plain line or a region of lines into list items.
17640 Calls `org-table-insert-hline', `org-toggle-item', or
17641 `org-cycle-list-bullet', depending on context."
17642 (interactive)
17643 (cond
17644 ((org-at-table-p)
17645 (call-interactively 'org-table-insert-hline))
17646 ((org-region-active-p)
17647 (call-interactively 'org-toggle-item))
17648 ((org-in-item-p)
17649 (call-interactively 'org-cycle-list-bullet))
17651 (call-interactively 'org-toggle-item))))
17653 (defun org-toggle-item (arg)
17654 "Convert headings or normal lines to items, items to normal lines.
17655 If there is no active region, only the current line is considered.
17657 If the first non blank line in the region is an headline, convert
17658 all headlines to items.
17660 If it is an item, convert all items to normal lines.
17662 If it is normal text, change region into an item. With a prefix
17663 argument ARG, change each line in region into an item."
17664 (interactive "P")
17665 (let (l2 l beg end)
17666 (if (org-region-active-p)
17667 (setq beg (region-beginning) end (region-end))
17668 (setq beg (point-at-bol)
17669 end (min (1+ (point-at-eol)) (point-max))))
17670 (org-with-limited-levels
17671 (save-excursion
17672 (goto-char end)
17673 (setq l2 (org-current-line))
17674 (goto-char beg)
17675 (beginning-of-line 1)
17676 ;; Ignore blank lines at beginning of region
17677 (skip-chars-forward " \t\r\n")
17678 (beginning-of-line 1)
17679 (setq l (1- (org-current-line)))
17680 (cond
17681 ;; Case 1. Start at an item: de-itemize.
17682 ((org-at-item-p)
17683 (while (< (setq l (1+ l)) l2)
17684 (when (org-at-item-p)
17685 (skip-chars-forward " \t")
17686 (delete-region (point) (match-end 0)))
17687 (beginning-of-line 2)))
17688 ;; Case 2. Start an an heading: convert to items.
17689 ((org-on-heading-p)
17690 (let* ((bul (org-list-bullet-string "-"))
17691 (len (length bul))
17692 (ind 0) (level 0))
17693 (while (< (setq l (1+ l)) l2)
17694 (cond
17695 ((looking-at outline-regexp)
17696 (let* ((lvl (org-reduced-level
17697 (- (length (match-string 0)) 2)))
17698 (s (concat (make-string (* len lvl) ? ) bul)))
17699 (replace-match s t t)
17700 (setq ind (length s) level lvl)))
17701 ;; Ignore blank lines and inline tasks.
17702 ((looking-at "^[ \t]*$"))
17703 ((looking-at "^\\*+ "))
17704 ;; Ensure normal text belongs to the new item.
17705 (t (org-indent-line-to (+ (max (- (org-get-indentation) level 2) 0)
17706 ind))))
17707 (beginning-of-line 2))))
17708 ;; Case 3. Normal line with ARG: turn each of them into items
17709 ;; unless they are already one.
17710 (arg
17711 (while (< (setq l (1+ l)) l2)
17712 (unless (or (org-on-heading-p) (org-at-item-p))
17713 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
17714 (replace-match
17715 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
17716 (beginning-of-line 2)))
17717 ;; Case 4. Normal line without ARG: make the first line of
17718 ;; region an item, and shift indentation of others
17719 ;; lines to set them as item's body.
17720 (t (let* ((bul (org-list-bullet-string "-"))
17721 (bul-len (length bul))
17722 (ref-ind (org-get-indentation)))
17723 (skip-chars-forward " \t")
17724 (insert bul)
17725 (beginning-of-line 2)
17726 (while (and (< (setq l (1+ l)) l2) (< (point) end))
17727 ;; Ensure that lines less indented than first one
17728 ;; still get included in item body.
17729 (org-indent-line-to (+ (max ref-ind (org-get-indentation))
17730 bul-len))
17731 (beginning-of-line 2)))))))))
17733 (defun org-toggle-heading (&optional nstars)
17734 "Convert headings to normal text, or items or text to headings.
17735 If there is no active region, only the current line is considered.
17737 If the first non blank line is an headline, remove the stars from
17738 all headlines in the region.
17740 If it is a plain list item, turn all plain list items into headings.
17742 If it is a normal line, turn each and every normal line (i.e. not
17743 an heading or an item) in the region into a heading.
17745 When converting a line into a heading, the number of stars is chosen
17746 such that the lines become children of the current entry. However,
17747 when a prefix argument is given, its value determines the number of
17748 stars to add."
17749 (interactive "P")
17750 (let (l2 l itemp beg end)
17751 (if (org-region-active-p)
17752 (setq beg (region-beginning) end (copy-marker (region-end)))
17753 (setq beg (point-at-bol)
17754 end (min (1+ (point-at-eol)) (point-max))))
17755 ;; Ensure inline tasks don't count as headings.
17756 (org-with-limited-levels
17757 (save-excursion
17758 (goto-char end)
17759 (setq l2 (org-current-line))
17760 (goto-char beg)
17761 (beginning-of-line 1)
17762 ;; Ignore blank lines at beginning of region
17763 (skip-chars-forward " \t\r\n")
17764 (beginning-of-line 1)
17765 (setq l (1- (org-current-line)))
17766 (cond
17767 ;; Case 1. Started at an heading: de-star headings.
17768 ((org-on-heading-p)
17769 (while (< (setq l (1+ l)) l2)
17770 (when (org-on-heading-p t)
17771 (looking-at outline-regexp) (replace-match ""))
17772 (beginning-of-line 2)))
17773 ;; Case 2. Started at an item: change items into headlines.
17774 ((org-at-item-p)
17775 (let ((stars (make-string
17776 (if nstars
17777 (prefix-numeric-value current-prefix-arg)
17778 (or (org-current-level) 0))
17779 ?*)))
17780 (while (< (point) end)
17781 (when (org-at-item-p)
17782 ;; Pay attention to cases when region ends before list.
17783 (let* ((struct (org-list-struct))
17784 (list-end (min (org-list-get-bottom-point struct) end)))
17785 (save-restriction
17786 (narrow-to-region (point) list-end)
17787 (insert
17788 (org-list-to-subtree
17789 (org-list-parse-list t)
17790 '(:istart (concat stars (funcall get-stars depth))
17791 :icount (concat stars
17792 (funcall get-stars depth))))))))
17793 (beginning-of-line 2))))
17794 ;; Case 3. Started at normal text: make every line an heading,
17795 ;; skipping headlines and items.
17796 (t (let* ((stars (make-string
17797 (if nstars
17798 (prefix-numeric-value current-prefix-arg)
17799 (or (org-current-level) 0))
17800 ?*))
17801 (add-stars (cond (nstars "")
17802 ((equal stars "") "*")
17803 (org-odd-levels-only "**")
17804 (t "*")))
17805 (rpl (concat stars add-stars " ")))
17806 (while (< (setq l (1+ l)) l2)
17807 (unless (or (org-on-heading-p) (org-at-item-p))
17808 (when (looking-at "\\([ \t]*\\)\\(\\S-\\)")
17809 (replace-match (concat rpl (match-string 2)))))
17810 (beginning-of-line 2)))))))))
17812 (defun org-meta-return (&optional arg)
17813 "Insert a new heading or wrap a region in a table.
17814 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
17815 See the individual commands for more information."
17816 (interactive "P")
17817 (cond
17818 ((run-hook-with-args-until-success 'org-metareturn-hook))
17819 ((org-at-table-p)
17820 (call-interactively 'org-table-wrap-region))
17821 (t (call-interactively 'org-insert-heading))))
17823 ;;; Menu entries
17825 ;; Define the Org-mode menus
17826 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
17827 '("Tbl"
17828 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
17829 ["Next Field" org-cycle (org-at-table-p)]
17830 ["Previous Field" org-shifttab (org-at-table-p)]
17831 ["Next Row" org-return (org-at-table-p)]
17832 "--"
17833 ["Blank Field" org-table-blank-field (org-at-table-p)]
17834 ["Edit Field" org-table-edit-field (org-at-table-p)]
17835 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
17836 "--"
17837 ("Column"
17838 ["Move Column Left" org-metaleft (org-at-table-p)]
17839 ["Move Column Right" org-metaright (org-at-table-p)]
17840 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
17841 ["Insert Column" org-shiftmetaright (org-at-table-p)])
17842 ("Row"
17843 ["Move Row Up" org-metaup (org-at-table-p)]
17844 ["Move Row Down" org-metadown (org-at-table-p)]
17845 ["Delete Row" org-shiftmetaup (org-at-table-p)]
17846 ["Insert Row" org-shiftmetadown (org-at-table-p)]
17847 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
17848 "--"
17849 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
17850 ("Rectangle"
17851 ["Copy Rectangle" org-copy-special (org-at-table-p)]
17852 ["Cut Rectangle" org-cut-special (org-at-table-p)]
17853 ["Paste Rectangle" org-paste-special (org-at-table-p)]
17854 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
17855 "--"
17856 ("Calculate"
17857 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
17858 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
17859 ["Edit Formulas" org-edit-special (org-at-table-p)]
17860 "--"
17861 ["Recalculate line" org-table-recalculate (org-at-table-p)]
17862 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
17863 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
17864 "--"
17865 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
17866 "--"
17867 ["Sum Column/Rectangle" org-table-sum
17868 (or (org-at-table-p) (org-region-active-p))]
17869 ["Which Column?" org-table-current-column (org-at-table-p)])
17870 ["Debug Formulas"
17871 org-table-toggle-formula-debugger
17872 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
17873 ["Show Col/Row Numbers"
17874 org-table-toggle-coordinate-overlays
17875 :style toggle
17876 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
17877 "--"
17878 ["Create" org-table-create (and (not (org-at-table-p))
17879 org-enable-table-editor)]
17880 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
17881 ["Import from File" org-table-import (not (org-at-table-p))]
17882 ["Export to File" org-table-export (org-at-table-p)]
17883 "--"
17884 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
17886 (easy-menu-define org-org-menu org-mode-map "Org menu"
17887 '("Org"
17888 ("Show/Hide"
17889 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
17890 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
17891 ["Sparse Tree..." org-sparse-tree t]
17892 ["Reveal Context" org-reveal t]
17893 ["Show All" show-all t]
17894 "--"
17895 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
17896 "--"
17897 ["New Heading" org-insert-heading t]
17898 ("Navigate Headings"
17899 ["Up" outline-up-heading t]
17900 ["Next" outline-next-visible-heading t]
17901 ["Previous" outline-previous-visible-heading t]
17902 ["Next Same Level" outline-forward-same-level t]
17903 ["Previous Same Level" outline-backward-same-level t]
17904 "--"
17905 ["Jump" org-goto t])
17906 ("Edit Structure"
17907 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
17908 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
17909 "--"
17910 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
17911 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
17912 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
17913 "--"
17914 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
17915 "--"
17916 ["Promote Heading" org-metaleft (not (org-at-table-p))]
17917 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
17918 ["Demote Heading" org-metaright (not (org-at-table-p))]
17919 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
17920 "--"
17921 ["Sort Region/Children" org-sort (not (org-at-table-p))]
17922 "--"
17923 ["Convert to odd levels" org-convert-to-odd-levels t]
17924 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
17925 ("Editing"
17926 ["Emphasis..." org-emphasize t]
17927 ["Edit Source Example" org-edit-special t]
17928 "--"
17929 ["Footnote new/jump" org-footnote-action t]
17930 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
17931 ("Archive"
17932 ["Archive (default method)" org-archive-subtree-default t]
17933 "--"
17934 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
17935 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
17936 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
17938 "--"
17939 ("Hyperlinks"
17940 ["Store Link (Global)" org-store-link t]
17941 ["Find existing link to here" org-occur-link-in-agenda-files t]
17942 ["Insert Link" org-insert-link t]
17943 ["Follow Link" org-open-at-point t]
17944 "--"
17945 ["Next link" org-next-link t]
17946 ["Previous link" org-previous-link t]
17947 "--"
17948 ["Descriptive Links"
17949 (progn (add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
17950 :style radio
17951 :selected (member '(org-link) buffer-invisibility-spec)]
17952 ["Literal Links"
17953 (progn
17954 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
17955 :style radio
17956 :selected (not (member '(org-link) buffer-invisibility-spec))])
17957 "--"
17958 ("TODO Lists"
17959 ["TODO/DONE/-" org-todo t]
17960 ("Select keyword"
17961 ["Next keyword" org-shiftright (org-on-heading-p)]
17962 ["Previous keyword" org-shiftleft (org-on-heading-p)]
17963 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
17964 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
17965 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
17966 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
17967 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
17968 "--"
17969 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
17970 :selected org-enforce-todo-dependencies :style toggle :active t]
17971 "Settings for tree at point"
17972 ["Do Children sequentially" org-toggle-ordered-property :style radio
17973 :selected (org-entry-get nil "ORDERED")
17974 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
17975 ["Do Children parallel" org-toggle-ordered-property :style radio
17976 :selected (not (org-entry-get nil "ORDERED"))
17977 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
17978 "--"
17979 ["Set Priority" org-priority t]
17980 ["Priority Up" org-shiftup t]
17981 ["Priority Down" org-shiftdown t]
17982 "--"
17983 ["Get news from all feeds" org-feed-update-all t]
17984 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
17985 ["Customize feeds" (customize-variable 'org-feed-alist) t])
17986 ("TAGS and Properties"
17987 ["Set Tags" org-set-tags-command t]
17988 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
17989 "--"
17990 ["Set property" org-set-property t]
17991 ["Column view of properties" org-columns t]
17992 ["Insert Column View DBlock" org-insert-columns-dblock t])
17993 ("Dates and Scheduling"
17994 ["Timestamp" org-time-stamp t]
17995 ["Timestamp (inactive)" org-time-stamp-inactive t]
17996 ("Change Date"
17997 ["1 Day Later" org-shiftright t]
17998 ["1 Day Earlier" org-shiftleft t]
17999 ["1 ... Later" org-shiftup t]
18000 ["1 ... Earlier" org-shiftdown t])
18001 ["Compute Time Range" org-evaluate-time-range t]
18002 ["Schedule Item" org-schedule t]
18003 ["Deadline" org-deadline t]
18004 "--"
18005 ["Custom time format" org-toggle-time-stamp-overlays
18006 :style radio :selected org-display-custom-times]
18007 "--"
18008 ["Goto Calendar" org-goto-calendar t]
18009 ["Date from Calendar" org-date-from-calendar t]
18010 "--"
18011 ["Start/Restart Timer" org-timer-start t]
18012 ["Pause/Continue Timer" org-timer-pause-or-continue t]
18013 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
18014 ["Insert Timer String" org-timer t]
18015 ["Insert Timer Item" org-timer-item t])
18016 ("Logging work"
18017 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
18018 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
18019 ["Clock out" org-clock-out t]
18020 ["Clock cancel" org-clock-cancel t]
18021 "--"
18022 ["Mark as default task" org-clock-mark-default-task t]
18023 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
18024 ["Goto running clock" org-clock-goto t]
18025 "--"
18026 ["Display times" org-clock-display t]
18027 ["Create clock table" org-clock-report t]
18028 "--"
18029 ["Record DONE time"
18030 (progn (setq org-log-done (not org-log-done))
18031 (message "Switching to %s will %s record a timestamp"
18032 (car org-done-keywords)
18033 (if org-log-done "automatically" "not")))
18034 :style toggle :selected org-log-done])
18035 "--"
18036 ["Agenda Command..." org-agenda t]
18037 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
18038 ("File List for Agenda")
18039 ("Special views current file"
18040 ["TODO Tree" org-show-todo-tree t]
18041 ["Check Deadlines" org-check-deadlines t]
18042 ["Timeline" org-timeline t]
18043 ["Tags/Property tree" org-match-sparse-tree t])
18044 "--"
18045 ["Export/Publish..." org-export t]
18046 ("LaTeX"
18047 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
18048 :selected org-cdlatex-mode]
18049 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
18050 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
18051 ["Modify math symbol" org-cdlatex-math-modify
18052 (org-inside-LaTeX-fragment-p)]
18053 ["Insert citation" org-reftex-citation t]
18054 "--"
18055 ["Template for BEAMER" org-insert-beamer-options-template t])
18056 "--"
18057 ("MobileOrg"
18058 ["Push Files and Views" org-mobile-push t]
18059 ["Get Captured and Flagged" org-mobile-pull t]
18060 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
18061 "--"
18062 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
18063 "--"
18064 ("Documentation"
18065 ["Show Version" org-version t]
18066 ["Info Documentation" org-info t])
18067 ("Customize"
18068 ["Browse Org Group" org-customize t]
18069 "--"
18070 ["Expand This Menu" org-create-customize-menu
18071 (fboundp 'customize-menu-create)])
18072 ["Send bug report" org-submit-bug-report t]
18073 "--"
18074 ("Refresh/Reload"
18075 ["Refresh setup current buffer" org-mode-restart t]
18076 ["Reload Org (after update)" org-reload t]
18077 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
18080 (defun org-info (&optional node)
18081 "Read documentation for Org-mode in the info system.
18082 With optional NODE, go directly to that node."
18083 (interactive)
18084 (info (format "(org)%s" (or node ""))))
18086 ;;;###autoload
18087 (defun org-submit-bug-report ()
18088 "Submit a bug report on Org-mode via mail.
18090 Don't hesitate to report any problems or inaccurate documentation.
18092 If you don't have setup sending mail from (X)Emacs, please copy the
18093 output buffer into your mail program, as it gives us important
18094 information about your Org-mode version and configuration."
18095 (interactive)
18096 (require 'reporter)
18097 (org-load-modules-maybe)
18098 (org-require-autoloaded-modules)
18099 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
18100 (reporter-submit-bug-report
18101 "emacs-orgmode@gnu.org"
18102 (org-version)
18103 (let (list)
18104 (save-window-excursion
18105 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
18106 (delete-other-windows)
18107 (erase-buffer)
18108 (insert "You are about to submit a bug report to the Org-mode mailing list.
18110 We would like to add your full Org-mode and Outline configuration to the
18111 bug report. This greatly simplifies the work of the maintainer and
18112 other experts on the mailing list.
18114 HOWEVER, some variables you have customized may contain private
18115 information. The names of customers, colleagues, or friends, might
18116 appear in the form of file names, tags, todo states, or search strings.
18117 If you answer yes to the prompt, you might want to check and remove
18118 such private information before sending the email.")
18119 (add-text-properties (point-min) (point-max) '(face org-warning))
18120 (when (yes-or-no-p "Include your Org-mode configuration ")
18121 (mapatoms
18122 (lambda (v)
18123 (and (boundp v)
18124 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
18125 (or (and (symbol-value v)
18126 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
18127 (and
18128 (get v 'custom-type) (get v 'standard-value)
18129 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
18130 (push v list)))))
18131 (kill-buffer (get-buffer "*Warn about privacy*"))
18132 list))
18133 nil nil
18134 "Remember to cover the basics, that is, what you expected to happen and
18135 what in fact did happen. You don't know how to make a good report? See
18137 http://orgmode.org/manual/Feedback.html#Feedback
18139 Your bug report will be posted to the Org-mode mailing list.
18140 ------------------------------------------------------------------------")
18141 (save-excursion
18142 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
18143 (replace-match "\\1Bug: \\3 [\\2]")))))
18146 (defun org-install-agenda-files-menu ()
18147 (let ((bl (buffer-list)))
18148 (save-excursion
18149 (while bl
18150 (set-buffer (pop bl))
18151 (if (org-mode-p) (setq bl nil)))
18152 (when (org-mode-p)
18153 (easy-menu-change
18154 '("Org") "File List for Agenda"
18155 (append
18156 (list
18157 ["Edit File List" (org-edit-agenda-file-list) t]
18158 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
18159 ["Remove Current File from List" org-remove-file t]
18160 ["Cycle through agenda files" org-cycle-agenda-files t]
18161 ["Occur in all agenda files" org-occur-in-agenda-files t]
18162 "--")
18163 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
18165 ;;;; Documentation
18167 ;;;###autoload
18168 (defun org-require-autoloaded-modules ()
18169 (interactive)
18170 (mapc 'require
18171 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
18172 org-docbook org-exp org-html org-icalendar
18173 org-id org-latex
18174 org-publish org-remember org-table
18175 org-timer org-xoxo)))
18177 ;;;###autoload
18178 (defun org-reload (&optional uncompiled)
18179 "Reload all org lisp files.
18180 With prefix arg UNCOMPILED, load the uncompiled versions."
18181 (interactive "P")
18182 (require 'find-func)
18183 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
18184 (dir-org (file-name-directory (org-find-library-name "org")))
18185 (dir-org-contrib (ignore-errors
18186 (file-name-directory
18187 (org-find-library-name "org-contribdir"))))
18188 (babel-files
18189 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
18190 (append (list nil "comint" "eval" "exp" "keys"
18191 "lob" "ref" "table" "tangle")
18192 (delq nil
18193 (mapcar
18194 (lambda (lang)
18195 (when (cdr lang) (symbol-name (car lang))))
18196 org-babel-load-languages)))))
18197 (files
18198 (append (directory-files dir-org t file-re)
18199 babel-files
18200 (and dir-org-contrib
18201 (directory-files dir-org-contrib t file-re))))
18202 (remove-re (concat (if (featurep 'xemacs)
18203 "org-colview" "org-colview-xemacs")
18204 "\\'")))
18205 (setq files (mapcar 'file-name-sans-extension files))
18206 (setq files (mapcar
18207 (lambda (x) (if (string-match remove-re x) nil x))
18208 files))
18209 (setq files (delq nil files))
18210 (mapc
18211 (lambda (f)
18212 (when (featurep (intern (file-name-nondirectory f)))
18213 (if (and (not uncompiled)
18214 (file-exists-p (concat f ".elc")))
18215 (load (concat f ".elc") nil nil t)
18216 (load (concat f ".el") nil nil t))))
18217 files))
18218 (org-version))
18220 ;;;###autoload
18221 (defun org-customize ()
18222 "Call the customize function with org as argument."
18223 (interactive)
18224 (org-load-modules-maybe)
18225 (org-require-autoloaded-modules)
18226 (customize-browse 'org))
18228 (defun org-create-customize-menu ()
18229 "Create a full customization menu for Org-mode, insert it into the menu."
18230 (interactive)
18231 (org-load-modules-maybe)
18232 (org-require-autoloaded-modules)
18233 (if (fboundp 'customize-menu-create)
18234 (progn
18235 (easy-menu-change
18236 '("Org") "Customize"
18237 `(["Browse Org group" org-customize t]
18238 "--"
18239 ,(customize-menu-create 'org)
18240 ["Set" Custom-set t]
18241 ["Save" Custom-save t]
18242 ["Reset to Current" Custom-reset-current t]
18243 ["Reset to Saved" Custom-reset-saved t]
18244 ["Reset to Standard Settings" Custom-reset-standard t]))
18245 (message "\"Org\"-menu now contains full customization menu"))
18246 (error "Cannot expand menu (outdated version of cus-edit.el)")))
18248 ;;;; Miscellaneous stuff
18250 ;;; Generally useful functions
18252 (defun org-get-at-bol (property)
18253 "Get text property PROPERTY at beginning of line."
18254 (get-text-property (point-at-bol) property))
18256 (defun org-find-text-property-in-string (prop s)
18257 "Return the first non-nil value of property PROP in string S."
18258 (or (get-text-property 0 prop s)
18259 (get-text-property (or (next-single-property-change 0 prop s) 0)
18260 prop s)))
18262 (defun org-display-warning (message) ;; Copied from Emacs-Muse
18263 "Display the given MESSAGE as a warning."
18264 (if (fboundp 'display-warning)
18265 (display-warning 'org message
18266 (if (featurep 'xemacs) 'warning :warning))
18267 (let ((buf (get-buffer-create "*Org warnings*")))
18268 (with-current-buffer buf
18269 (goto-char (point-max))
18270 (insert "Warning (Org): " message)
18271 (unless (bolp)
18272 (newline)))
18273 (display-buffer buf)
18274 (sit-for 0))))
18276 (defun org-eval (form)
18277 "Eval FORM and return result."
18278 (condition-case error
18279 (eval form)
18280 (error (format "%%![Error: %s]" error))))
18282 (defun org-in-commented-line ()
18283 "Is point in a line starting with `#'?"
18284 (equal (char-after (point-at-bol)) ?#))
18286 (defun org-in-indented-comment-line ()
18287 "Is point in a line starting with `#' after some white space?"
18288 (save-excursion
18289 (save-match-data
18290 (goto-char (point-at-bol))
18291 (looking-at "[ \t]*#"))))
18293 (defun org-in-verbatim-emphasis ()
18294 (save-match-data
18295 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
18297 (defun org-goto-marker-or-bmk (marker &optional bookmark)
18298 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
18299 (if (and marker (marker-buffer marker)
18300 (buffer-live-p (marker-buffer marker)))
18301 (progn
18302 (switch-to-buffer (marker-buffer marker))
18303 (if (or (> marker (point-max)) (< marker (point-min)))
18304 (widen))
18305 (goto-char marker)
18306 (org-show-context 'org-goto))
18307 (if bookmark
18308 (bookmark-jump bookmark)
18309 (error "Cannot find location"))))
18311 (defun org-quote-csv-field (s)
18312 "Quote field for inclusion in CSV material."
18313 (if (string-match "[\",]" s)
18314 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
18317 (defun org-force-self-insert (N)
18318 "Needed to enforce self-insert under remapping."
18319 (interactive "p")
18320 (self-insert-command N))
18322 (defun org-string-width (s)
18323 "Compute width of string, ignoring invisible characters.
18324 This ignores character with invisibility property `org-link', and also
18325 characters with property `org-cwidth', because these will become invisible
18326 upon the next fontification round."
18327 (let (b l)
18328 (when (or (eq t buffer-invisibility-spec)
18329 (assq 'org-link buffer-invisibility-spec))
18330 (while (setq b (text-property-any 0 (length s)
18331 'invisible 'org-link s))
18332 (setq s (concat (substring s 0 b)
18333 (substring s (or (next-single-property-change
18334 b 'invisible s) (length s)))))))
18335 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
18336 (setq s (concat (substring s 0 b)
18337 (substring s (or (next-single-property-change
18338 b 'org-cwidth s) (length s))))))
18339 (setq l (string-width s) b -1)
18340 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
18341 (setq l (- l (get-text-property b 'org-dwidth-n s))))
18344 (defun org-shorten-string (s maxlength)
18345 "Shorten string S so tht it is no longer than MAXLENGTH characters.
18346 If the string is shorter or has length MAXLENGTH, just return the
18347 original string. If it is longer, the functions finds a space in the
18348 string, breaks this string off at that locations and adds three dots
18349 as ellipsis. Including the ellipsis, the string will not be longer
18350 than MAXLENGTH. If finding a good breaking point in the string does
18351 not work, the string is just chopped off in the middle of a word
18352 if necessary."
18353 (if (<= (length s) maxlength)
18355 (let* ((n (max (- maxlength 4) 1))
18356 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
18357 (if (string-match re s)
18358 (concat (match-string 1 s) "...")
18359 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
18361 (defun org-get-indentation (&optional line)
18362 "Get the indentation of the current line, interpreting tabs.
18363 When LINE is given, assume it represents a line and compute its indentation."
18364 (if line
18365 (if (string-match "^ *" (org-remove-tabs line))
18366 (match-end 0))
18367 (save-excursion
18368 (beginning-of-line 1)
18369 (skip-chars-forward " \t")
18370 (current-column))))
18372 (defun org-get-string-indentation (s)
18373 "What indentation has S due to SPACE and TAB at the beginning of the string?"
18374 (let ((n -1) (i 0) (w tab-width) c)
18375 (catch 'exit
18376 (while (< (setq n (1+ n)) (length s))
18377 (setq c (aref s n))
18378 (cond ((= c ?\ ) (setq i (1+ i)))
18379 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
18380 (t (throw 'exit t)))))
18383 (defun org-remove-tabs (s &optional width)
18384 "Replace tabulators in S with spaces.
18385 Assumes that s is a single line, starting in column 0."
18386 (setq width (or width tab-width))
18387 (while (string-match "\t" s)
18388 (setq s (replace-match
18389 (make-string
18390 (- (* width (/ (+ (match-beginning 0) width) width))
18391 (match-beginning 0)) ?\ )
18392 t t s)))
18395 (defun org-fix-indentation (line ind)
18396 "Fix indentation in LINE.
18397 IND is a cons cell with target and minimum indentation.
18398 If the current indentation in LINE is smaller than the minimum,
18399 leave it alone. If it is larger than ind, set it to the target."
18400 (let* ((l (org-remove-tabs line))
18401 (i (org-get-indentation l))
18402 (i1 (car ind)) (i2 (cdr ind)))
18403 (if (>= i i2) (setq l (substring line i2)))
18404 (if (> i1 0)
18405 (concat (make-string i1 ?\ ) l)
18406 l)))
18408 (defun org-remove-indentation (code &optional n)
18409 "Remove the maximum common indentation from the lines in CODE.
18410 N may optionally be the number of spaces to remove."
18411 (with-temp-buffer
18412 (insert code)
18413 (org-do-remove-indentation n)
18414 (buffer-string)))
18416 (defun org-do-remove-indentation (&optional n)
18417 "Remove the maximum common indentation from the buffer."
18418 (untabify (point-min) (point-max))
18419 (let ((min 10000) re)
18420 (if n
18421 (setq min n)
18422 (goto-char (point-min))
18423 (while (re-search-forward "^ *[^ \n]" nil t)
18424 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
18425 (unless (or (= min 0) (= min 10000))
18426 (setq re (format "^ \\{%d\\}" min))
18427 (goto-char (point-min))
18428 (while (re-search-forward re nil t)
18429 (replace-match "")
18430 (end-of-line 1))
18431 min)))
18433 (defun org-fill-template (template alist)
18434 "Find each %key of ALIST in TEMPLATE and replace it."
18435 (let ((case-fold-search nil)
18436 entry key value)
18437 (setq alist (sort (copy-sequence alist)
18438 (lambda (a b) (< (length (car a)) (length (car b))))))
18439 (while (setq entry (pop alist))
18440 (setq template
18441 (replace-regexp-in-string
18442 (concat "%" (regexp-quote (car entry)))
18443 (cdr entry) template t t)))
18444 template))
18446 (defun org-base-buffer (buffer)
18447 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
18448 (if (not buffer)
18449 buffer
18450 (or (buffer-base-buffer buffer)
18451 buffer)))
18453 (defun org-trim (s)
18454 "Remove whitespace at beginning and end of string."
18455 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
18456 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
18459 (defun org-wrap (string &optional width lines)
18460 "Wrap string to either a number of lines, or a width in characters.
18461 If WIDTH is non-nil, the string is wrapped to that width, however many lines
18462 that costs. If there is a word longer than WIDTH, the text is actually
18463 wrapped to the length of that word.
18464 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
18465 many lines, whatever width that takes.
18466 The return value is a list of lines, without newlines at the end."
18467 (let* ((words (org-split-string string "[ \t\n]+"))
18468 (maxword (apply 'max (mapcar 'org-string-width words)))
18469 w ll)
18470 (cond (width
18471 (org-do-wrap words (max maxword width)))
18472 (lines
18473 (setq w maxword)
18474 (setq ll (org-do-wrap words maxword))
18475 (if (<= (length ll) lines)
18477 (setq ll words)
18478 (while (> (length ll) lines)
18479 (setq w (1+ w))
18480 (setq ll (org-do-wrap words w)))
18481 ll))
18482 (t (error "Cannot wrap this")))))
18484 (defun org-do-wrap (words width)
18485 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
18486 (let (lines line)
18487 (while words
18488 (setq line (pop words))
18489 (while (and words (< (+ (length line) (length (car words))) width))
18490 (setq line (concat line " " (pop words))))
18491 (setq lines (push line lines)))
18492 (nreverse lines)))
18494 (defun org-split-string (string &optional separators)
18495 "Splits STRING into substrings at SEPARATORS.
18496 No empty strings are returned if there are matches at the beginning
18497 and end of string."
18498 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
18499 (start 0)
18500 notfirst
18501 (list nil))
18502 (while (and (string-match rexp string
18503 (if (and notfirst
18504 (= start (match-beginning 0))
18505 (< start (length string)))
18506 (1+ start) start))
18507 (< (match-beginning 0) (length string)))
18508 (setq notfirst t)
18509 (or (eq (match-beginning 0) 0)
18510 (and (eq (match-beginning 0) (match-end 0))
18511 (eq (match-beginning 0) start))
18512 (setq list
18513 (cons (substring string start (match-beginning 0))
18514 list)))
18515 (setq start (match-end 0)))
18516 (or (eq start (length string))
18517 (setq list
18518 (cons (substring string start)
18519 list)))
18520 (nreverse list)))
18522 (defun org-quote-vert (s)
18523 "Replace \"|\" with \"\\vert\"."
18524 (while (string-match "|" s)
18525 (setq s (replace-match "\\vert" t t s)))
18528 (defun org-uuidgen-p (s)
18529 "Is S an ID created by UUIDGEN?"
18530 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
18532 (defun org-context ()
18533 "Return a list of contexts of the current cursor position.
18534 If several contexts apply, all are returned.
18535 Each context entry is a list with a symbol naming the context, and
18536 two positions indicating start and end of the context. Possible
18537 contexts are:
18539 :headline anywhere in a headline
18540 :headline-stars on the leading stars in a headline
18541 :todo-keyword on a TODO keyword (including DONE) in a headline
18542 :tags on the TAGS in a headline
18543 :priority on the priority cookie in a headline
18544 :item on the first line of a plain list item
18545 :item-bullet on the bullet/number of a plain list item
18546 :checkbox on the checkbox in a plain list item
18547 :table in an org-mode table
18548 :table-special on a special filed in a table
18549 :table-table in a table.el table
18550 :link on a hyperlink
18551 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
18552 :target on a <<target>>
18553 :radio-target on a <<<radio-target>>>
18554 :latex-fragment on a LaTeX fragment
18555 :latex-preview on a LaTeX fragment with overlayed preview image
18557 This function expects the position to be visible because it uses font-lock
18558 faces as a help to recognize the following contexts: :table-special, :link,
18559 and :keyword."
18560 (let* ((f (get-text-property (point) 'face))
18561 (faces (if (listp f) f (list f)))
18562 (p (point)) clist o)
18563 ;; First the large context
18564 (cond
18565 ((org-on-heading-p t)
18566 (push (list :headline (point-at-bol) (point-at-eol)) clist)
18567 (when (progn
18568 (beginning-of-line 1)
18569 (looking-at org-todo-line-tags-regexp))
18570 (push (org-point-in-group p 1 :headline-stars) clist)
18571 (push (org-point-in-group p 2 :todo-keyword) clist)
18572 (push (org-point-in-group p 4 :tags) clist))
18573 (goto-char p)
18574 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
18575 (if (looking-at "\\[#[A-Z0-9]\\]")
18576 (push (org-point-in-group p 0 :priority) clist)))
18578 ((org-at-item-p)
18579 (push (org-point-in-group p 2 :item-bullet) clist)
18580 (push (list :item (point-at-bol)
18581 (save-excursion (org-end-of-item) (point)))
18582 clist)
18583 (and (org-at-item-checkbox-p)
18584 (push (org-point-in-group p 0 :checkbox) clist)))
18586 ((org-at-table-p)
18587 (push (list :table (org-table-begin) (org-table-end)) clist)
18588 (if (memq 'org-formula faces)
18589 (push (list :table-special
18590 (previous-single-property-change p 'face)
18591 (next-single-property-change p 'face)) clist)))
18592 ((org-at-table-p 'any)
18593 (push (list :table-table) clist)))
18594 (goto-char p)
18596 ;; Now the small context
18597 (cond
18598 ((org-at-timestamp-p)
18599 (push (org-point-in-group p 0 :timestamp) clist))
18600 ((memq 'org-link faces)
18601 (push (list :link
18602 (previous-single-property-change p 'face)
18603 (next-single-property-change p 'face)) clist))
18604 ((memq 'org-special-keyword faces)
18605 (push (list :keyword
18606 (previous-single-property-change p 'face)
18607 (next-single-property-change p 'face)) clist))
18608 ((org-on-target-p)
18609 (push (org-point-in-group p 0 :target) clist)
18610 (goto-char (1- (match-beginning 0)))
18611 (if (looking-at org-radio-target-regexp)
18612 (push (org-point-in-group p 0 :radio-target) clist))
18613 (goto-char p))
18614 ((setq o (car (delq nil
18615 (mapcar
18616 (lambda (x)
18617 (if (memq x org-latex-fragment-image-overlays) x))
18618 (overlays-at (point))))))
18619 (push (list :latex-fragment
18620 (overlay-start o) (overlay-end o)) clist)
18621 (push (list :latex-preview
18622 (overlay-start o) (overlay-end o)) clist))
18623 ((org-inside-LaTeX-fragment-p)
18624 ;; FIXME: positions wrong.
18625 (push (list :latex-fragment (point) (point)) clist)))
18627 (setq clist (nreverse (delq nil clist)))
18628 clist))
18630 ;; FIXME: Compare with at-regexp-p Do we need both?
18631 (defun org-in-regexp (re &optional nlines visually)
18632 "Check if point is inside a match of regexp.
18633 Normally only the current line is checked, but you can include NLINES extra
18634 lines both before and after point into the search.
18635 If VISUALLY is set, require that the cursor is not after the match but
18636 really on, so that the block visually is on the match."
18637 (catch 'exit
18638 (let ((pos (point))
18639 (eol (point-at-eol (+ 1 (or nlines 0))))
18640 (inc (if visually 1 0)))
18641 (save-excursion
18642 (beginning-of-line (- 1 (or nlines 0)))
18643 (while (re-search-forward re eol t)
18644 (if (and (<= (match-beginning 0) pos)
18645 (>= (+ inc (match-end 0)) pos))
18646 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
18648 (defun org-at-regexp-p (regexp)
18649 "Is point inside a match of REGEXP in the current line?"
18650 (catch 'exit
18651 (save-excursion
18652 (let ((pos (point)) (end (point-at-eol)))
18653 (beginning-of-line 1)
18654 (while (re-search-forward regexp end t)
18655 (if (and (<= (match-beginning 0) pos)
18656 (>= (match-end 0) pos))
18657 (throw 'exit t)))
18658 nil))))
18660 (defun org-in-regexps-block-p (start-re end-re &optional bound)
18661 "Return t if the current point is between matches of START-RE and END-RE.
18662 This will also return t if point is on one of the two matches or
18663 in an unfinished block. END-RE can be a string or a form
18664 returning a string.
18666 An optional third argument bounds the search for START-RE. It
18667 defaults to previous heading or `point-min'."
18668 (let ((pos (point))
18669 (limit (or bound (save-excursion (outline-previous-heading)))))
18670 (save-excursion
18671 ;; we're on a block when point is on start-re...
18672 (or (org-at-regexp-p start-re)
18673 ;; ... or start-re can be found above...
18674 (and (re-search-backward start-re limit t)
18675 ;; ... but no end-re between start-re and point.
18676 (not (re-search-forward (eval end-re) pos t)))))))
18678 (defun org-occur-in-agenda-files (regexp &optional nlines)
18679 "Call `multi-occur' with buffers for all agenda files."
18680 (interactive "sOrg-files matching: \np")
18681 (let* ((files (org-agenda-files))
18682 (tnames (mapcar 'file-truename files))
18683 (extra org-agenda-text-search-extra-files)
18685 (when (eq (car extra) 'agenda-archives)
18686 (setq extra (cdr extra))
18687 (setq files (org-add-archive-files files)))
18688 (while (setq f (pop extra))
18689 (unless (member (file-truename f) tnames)
18690 (add-to-list 'files f 'append)
18691 (add-to-list 'tnames (file-truename f) 'append)))
18692 (multi-occur
18693 (mapcar (lambda (x)
18694 (with-current-buffer
18695 (or (get-file-buffer x) (find-file-noselect x))
18696 (widen)
18697 (current-buffer)))
18698 files)
18699 regexp)))
18701 (if (boundp 'occur-mode-find-occurrence-hook)
18702 ;; Emacs 23
18703 (add-hook 'occur-mode-find-occurrence-hook
18704 (lambda ()
18705 (when (org-mode-p)
18706 (org-reveal))))
18707 ;; Emacs 22
18708 (defadvice occur-mode-goto-occurrence
18709 (after org-occur-reveal activate)
18710 (and (org-mode-p) (org-reveal)))
18711 (defadvice occur-mode-goto-occurrence-other-window
18712 (after org-occur-reveal activate)
18713 (and (org-mode-p) (org-reveal)))
18714 (defadvice occur-mode-display-occurrence
18715 (after org-occur-reveal activate)
18716 (when (org-mode-p)
18717 (let ((pos (occur-mode-find-occurrence)))
18718 (with-current-buffer (marker-buffer pos)
18719 (save-excursion
18720 (goto-char pos)
18721 (org-reveal)))))))
18723 (defun org-occur-link-in-agenda-files ()
18724 "Create a link and search for it in the agendas.
18725 The link is not stored in `org-stored-links', it is just created
18726 for the search purpose."
18727 (interactive)
18728 (let ((link (condition-case nil
18729 (org-store-link nil)
18730 (error "Unable to create a link to here"))))
18731 (org-occur-in-agenda-files (regexp-quote link))))
18733 (defun org-uniquify (list)
18734 "Remove duplicate elements from LIST."
18735 (let (res)
18736 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
18737 res))
18739 (defun org-delete-all (elts list)
18740 "Remove all elements in ELTS from LIST."
18741 (while elts
18742 (setq list (delete (pop elts) list)))
18743 list)
18745 (defun org-count (cl-item cl-seq)
18746 "Count the number of occurrences of ITEM in SEQ.
18747 Taken from `count' in cl-seq.el with all keyword arguments removed."
18748 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
18749 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
18750 (while (< cl-start cl-end)
18751 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
18752 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
18753 (setq cl-start (1+ cl-start)))
18754 cl-count))
18756 (defun org-remove-if (predicate seq)
18757 "Remove everything from SEQ that fulfills PREDICATE."
18758 (let (res e)
18759 (while seq
18760 (setq e (pop seq))
18761 (if (not (funcall predicate e)) (push e res)))
18762 (nreverse res)))
18764 (defun org-remove-if-not (predicate seq)
18765 "Remove everything from SEQ that does not fulfill PREDICATE."
18766 (let (res e)
18767 (while seq
18768 (setq e (pop seq))
18769 (if (funcall predicate e) (push e res)))
18770 (nreverse res)))
18772 (defun org-back-over-empty-lines ()
18773 "Move backwards over whitespace, to the beginning of the first empty line.
18774 Returns the number of empty lines passed."
18775 (let ((pos (point)))
18776 (skip-chars-backward " \t\n\r")
18777 ;; (if (cdr (assoc 'heading org-blank-before-new-entry))
18778 ;; (skip-chars-backward " \t\n\r")
18779 ;; (forward-line -1))
18780 (beginning-of-line 2)
18781 (goto-char (min (point) pos))
18782 (count-lines (point) pos)))
18784 (defun org-skip-whitespace ()
18785 (skip-chars-forward " \t\n\r"))
18787 (defun org-point-in-group (point group &optional context)
18788 "Check if POINT is in match-group GROUP.
18789 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
18790 match. If the match group does not exist or point is not inside it,
18791 return nil."
18792 (and (match-beginning group)
18793 (>= point (match-beginning group))
18794 (<= point (match-end group))
18795 (if context
18796 (list context (match-beginning group) (match-end group))
18797 t)))
18799 (defun org-switch-to-buffer-other-window (&rest args)
18800 "Switch to buffer in a second window on the current frame.
18801 In particular, do not allow pop-up frames.
18802 Returns the newly created buffer."
18803 (let (pop-up-frames special-display-buffer-names special-display-regexps
18804 special-display-function)
18805 (apply 'switch-to-buffer-other-window args)))
18807 (defun org-combine-plists (&rest plists)
18808 "Create a single property list from all plists in PLISTS.
18809 The process starts by copying the first list, and then setting properties
18810 from the other lists. Settings in the last list are the most significant
18811 ones and overrule settings in the other lists."
18812 (let ((rtn (copy-sequence (pop plists)))
18813 p v ls)
18814 (while plists
18815 (setq ls (pop plists))
18816 (while ls
18817 (setq p (pop ls) v (pop ls))
18818 (setq rtn (plist-put rtn p v))))
18819 rtn))
18821 (defun org-move-line-down (arg)
18822 "Move the current line down. With prefix argument, move it past ARG lines."
18823 (interactive "p")
18824 (let ((col (current-column))
18825 beg end pos)
18826 (beginning-of-line 1) (setq beg (point))
18827 (beginning-of-line 2) (setq end (point))
18828 (beginning-of-line (+ 1 arg))
18829 (setq pos (move-marker (make-marker) (point)))
18830 (insert (delete-and-extract-region beg end))
18831 (goto-char pos)
18832 (org-move-to-column col)))
18834 (defun org-move-line-up (arg)
18835 "Move the current line up. With prefix argument, move it past ARG lines."
18836 (interactive "p")
18837 (let ((col (current-column))
18838 beg end pos)
18839 (beginning-of-line 1) (setq beg (point))
18840 (beginning-of-line 2) (setq end (point))
18841 (beginning-of-line (- arg))
18842 (setq pos (move-marker (make-marker) (point)))
18843 (insert (delete-and-extract-region beg end))
18844 (goto-char pos)
18845 (org-move-to-column col)))
18847 (defun org-replace-escapes (string table)
18848 "Replace %-escapes in STRING with values in TABLE.
18849 TABLE is an association list with keys like \"%a\" and string values.
18850 The sequences in STRING may contain normal field width and padding information,
18851 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
18852 so values can contain further %-escapes if they are define later in TABLE."
18853 (let ((tbl (copy-alist table))
18854 (case-fold-search nil)
18855 (pchg 0)
18856 e re rpl)
18857 (while (setq e (pop tbl))
18858 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
18859 (when (and (cdr e) (string-match re (cdr e)))
18860 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
18861 (safe "SREF"))
18862 (add-text-properties 0 3 (list 'sref sref) safe)
18863 (setcdr e (replace-match safe t t (cdr e)))))
18864 (while (string-match re string)
18865 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
18866 (cdr e)))
18867 (setq string (replace-match rpl t t string))))
18868 (while (setq pchg (next-property-change pchg string))
18869 (let ((sref (get-text-property pchg 'sref string)))
18870 (when (and sref (string-match "SREF" string pchg))
18871 (setq string (replace-match sref t t string)))))
18872 string))
18874 (defun org-sublist (list start end)
18875 "Return a section of LIST, from START to END.
18876 Counting starts at 1."
18877 (let (rtn (c start))
18878 (setq list (nthcdr (1- start) list))
18879 (while (and list (<= c end))
18880 (push (pop list) rtn)
18881 (setq c (1+ c)))
18882 (nreverse rtn)))
18884 (defun org-find-base-buffer-visiting (file)
18885 "Like `find-buffer-visiting' but always return the base buffer and
18886 not an indirect buffer."
18887 (let ((buf (or (get-file-buffer file)
18888 (find-buffer-visiting file))))
18889 (if buf
18890 (or (buffer-base-buffer buf) buf)
18891 nil)))
18893 (defun org-image-file-name-regexp (&optional extensions)
18894 "Return regexp matching the file names of images.
18895 If EXTENSIONS is given, only match these."
18896 (if (and (not extensions) (fboundp 'image-file-name-regexp))
18897 (image-file-name-regexp)
18898 (let ((image-file-name-extensions
18899 (or extensions
18900 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
18901 "xbm" "xpm" "pbm" "pgm" "ppm"))))
18902 (concat "\\."
18903 (regexp-opt (nconc (mapcar 'upcase
18904 image-file-name-extensions)
18905 image-file-name-extensions)
18907 "\\'"))))
18909 (defun org-file-image-p (file &optional extensions)
18910 "Return non-nil if FILE is an image."
18911 (save-match-data
18912 (string-match (org-image-file-name-regexp extensions) file)))
18914 (defun org-get-cursor-date ()
18915 "Return the date at cursor in as a time.
18916 This works in the calendar and in the agenda, anywhere else it just
18917 returns the current time."
18918 (let (date day defd)
18919 (cond
18920 ((eq major-mode 'calendar-mode)
18921 (setq date (calendar-cursor-to-date)
18922 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18923 ((eq major-mode 'org-agenda-mode)
18924 (setq day (get-text-property (point) 'day))
18925 (if day
18926 (setq date (calendar-gregorian-from-absolute day)
18927 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
18928 (nth 2 date))))))
18929 (or defd (current-time))))
18931 (defvar org-agenda-action-marker (make-marker)
18932 "Marker pointing to the entry for the next agenda action.")
18934 (defun org-mark-entry-for-agenda-action ()
18935 "Mark the current entry as target of an agenda action.
18936 Agenda actions are actions executed from the agenda with the key `k',
18937 which make use of the date at the cursor."
18938 (interactive)
18939 (move-marker org-agenda-action-marker
18940 (save-excursion (org-back-to-heading t) (point))
18941 (current-buffer))
18942 (message
18943 "Entry marked for action; press `k' at desired date in agenda or calendar"))
18945 (defun org-mark-subtree ()
18946 "Mark the current subtree.
18947 This puts point at the start of the current subtree, and mark at the end.
18949 If point is in an inline task, mark that task instead."
18950 (interactive)
18951 (let ((inline-task-p
18952 (and (featurep 'org-inlinetask)
18953 (org-inlinetask-in-task-p)))
18954 (beg))
18955 ;; Get beginning of subtree
18956 (cond
18957 (inline-task-p (org-inlinetask-goto-beginning))
18958 ((org-at-heading-p) (beginning-of-line))
18959 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
18960 (setq beg (point))
18961 ;; Get end of it
18962 (if inline-task-p
18963 (org-inlinetask-goto-end)
18964 (org-end-of-subtree))
18965 ;; Mark zone
18966 (push-mark (point) nil t)
18967 (goto-char beg)))
18969 ;;; Paragraph filling stuff.
18970 ;; We want this to be just right, so use the full arsenal.
18972 (defun org-indent-line-function ()
18973 "Indent line depending on context."
18974 (interactive)
18975 (let* ((pos (point))
18976 (itemp (org-at-item-p))
18977 (case-fold-search t)
18978 (org-drawer-regexp (or org-drawer-regexp "\000"))
18979 (inline-task-p (and (featurep 'org-inlinetask)
18980 (org-inlinetask-in-task-p)))
18981 (inline-re (and inline-task-p
18982 (org-inlinetask-outline-regexp)))
18983 column)
18984 (beginning-of-line 1)
18985 (cond
18986 ;; Comments
18987 ((looking-at "# ") (setq column 0))
18988 ;; Headings
18989 ((looking-at "\\*+ ") (setq column 0))
18990 ;; Literal examples
18991 ((looking-at "[ \t]*:[ \t]")
18992 (setq column (org-get-indentation))) ; do nothing
18993 ;; Drawers
18994 ((and (looking-at "[ \t]*:END:")
18995 (save-excursion (re-search-backward org-drawer-regexp nil t)))
18996 (save-excursion
18997 (goto-char (1- (match-beginning 1)))
18998 (setq column (current-column))))
18999 ;; Special blocks
19000 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
19001 (save-excursion
19002 (re-search-backward
19003 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
19004 (setq column (org-get-indentation (match-string 0))))
19005 ((and (not (looking-at "[ \t]*#\\+begin_"))
19006 (org-in-regexps-block-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
19007 (save-excursion
19008 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
19009 (setq column
19010 (if (equal (downcase (match-string 1)) "src")
19011 ;; src blocks: let `org-edit-src-exit' handle them
19012 (org-get-indentation)
19013 (org-get-indentation (match-string 0)))))
19014 ;; Lists
19015 ((ignore-errors (goto-char (org-in-item-p)))
19016 (setq column (if itemp
19017 (org-get-indentation)
19018 (org-list-item-body-column (point))))
19019 (goto-char pos))
19020 ;; This line has nothing special, look at the previous relevant
19021 ;; line to compute indentation
19023 (beginning-of-line 0)
19024 (while (and (not (bobp))
19025 (not (looking-at org-drawer-regexp))
19026 ;; When point started in an inline task, do not move
19027 ;; above task starting line.
19028 (not (and inline-task-p
19029 (looking-at inline-re)))
19030 ;; Skip comments, verbatim, empty lines, tables,
19031 ;; inline tasks, lists, drawers and blocks.
19032 (or (and (looking-at "[ \t]*:END:")
19033 (re-search-backward org-drawer-regexp nil t))
19034 (and (looking-at "[ \t]*#\\+end_")
19035 (re-search-backward "[ \t]*#\\+begin_"nil t))
19036 (looking-at "[ \t]*[\n:#|]")
19037 (and (ignore-errors (goto-char (org-in-item-p)))
19038 (goto-char
19039 (org-list-get-top-point (org-list-struct))))
19040 (and (not inline-task-p)
19041 (featurep 'org-inlinetask)
19042 (org-inlinetask-in-task-p)
19043 (or (org-inlinetask-goto-beginning) t))))
19044 (beginning-of-line 0))
19045 (cond
19046 ;; There was an heading above.
19047 ((looking-at "\\*+[ \t]+")
19048 (if (not org-adapt-indentation)
19049 (setq column 0)
19050 (goto-char (match-end 0))
19051 (setq column (current-column))))
19052 ;; A drawer had started and is unfinished
19053 ((looking-at org-drawer-regexp)
19054 (goto-char (1- (match-beginning 1)))
19055 (setq column (current-column)))
19056 ;; Else, nothing noticeable found: get indentation and go on.
19057 (t (setq column (org-get-indentation))))))
19058 ;; Now apply indentation and move cursor accordingly
19059 (goto-char pos)
19060 (if (<= (current-column) (current-indentation))
19061 (org-indent-line-to column)
19062 (save-excursion (org-indent-line-to column)))
19063 ;; Special polishing for properties, see `org-property-format'
19064 (setq column (current-column))
19065 (beginning-of-line 1)
19066 (if (looking-at
19067 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
19068 (replace-match (concat (match-string 1)
19069 (format org-property-format
19070 (match-string 2) (match-string 3)))
19071 t t))
19072 (org-move-to-column column)))
19074 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
19075 "Variable to store copy of `adaptive-fill-regexp'.
19076 Since `adaptive-fill-regexp' is set to never match, we need to
19077 store a backup of its value before entering `org-mode' so that
19078 the functionality can be provided as a fall-back.")
19080 (defun org-set-autofill-regexps ()
19081 (interactive)
19082 ;; In the paragraph separator we include headlines, because filling
19083 ;; text in a line directly attached to a headline would otherwise
19084 ;; fill the headline as well.
19085 (org-set-local 'comment-start-skip "^#+[ \t]*")
19086 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
19087 ;; The paragraph starter includes hand-formatted lists.
19088 (org-set-local
19089 'paragraph-start
19090 (concat
19091 "\f" "\\|"
19092 "[ ]*$" "\\|"
19093 "\\*+ " "\\|"
19094 "[ \t]*#" "\\|"
19095 (org-item-re) "\\|"
19096 "[ \t]*[:|]" "\\|"
19097 "\\$\\$" "\\|"
19098 "\\\\\\(begin\\|end\\|[][]\\)"))
19099 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
19100 ;; But only if the user has not turned off tables or fixed-width regions
19101 (org-set-local
19102 'auto-fill-inhibit-regexp
19103 (concat "\\*+ \\|#\\+"
19104 "\\|[ \t]*" org-keyword-time-regexp
19105 (if (or org-enable-table-editor org-enable-fixed-width-editor)
19106 (concat
19107 "\\|[ \t]*["
19108 (if org-enable-table-editor "|" "")
19109 (if org-enable-fixed-width-editor ":" "")
19110 "]"))))
19111 ;; We use our own fill-paragraph function, to make sure that tables
19112 ;; and fixed-width regions are not wrapped. That function will pass
19113 ;; through to `fill-paragraph' when appropriate.
19114 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
19115 ;; Adaptive filling: To get full control, first make sure that
19116 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
19117 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
19118 (org-set-local 'org-adaptive-fill-regexp-backup
19119 adaptive-fill-regexp))
19120 (org-set-local 'adaptive-fill-regexp "\000")
19121 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
19122 (org-set-local 'adaptive-fill-function
19123 'org-adaptive-fill-function)
19124 (org-set-local
19125 'align-mode-rules-list
19126 '((org-in-buffer-settings
19127 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
19128 (modes . '(org-mode))))))
19130 (defun org-fill-paragraph (&optional justify)
19131 "Re-align a table, pass through to fill-paragraph if no table."
19132 (let ((table-p (org-at-table-p))
19133 (table.el-p (org-at-table.el-p))
19134 (itemp (org-in-item-p)))
19135 (cond ((and (equal (char-after (point-at-bol)) ?*)
19136 (save-excursion (goto-char (point-at-bol))
19137 (looking-at outline-regexp)))
19138 t) ; skip headlines
19139 (table.el-p t) ; skip table.el tables
19140 (table-p (org-table-align) t) ; align Org tables
19141 (itemp ; align text in items
19142 (let* ((struct (save-excursion (goto-char itemp)
19143 (org-list-struct)))
19144 (parents (org-list-parents-alist struct))
19145 (children (org-list-get-children itemp struct parents))
19146 beg end prev next prefix)
19147 ;; Determine in which part of item point is: before
19148 ;; first child, after last child, between two
19149 ;; sub-lists, or simply in item if there's no child.
19150 (cond
19151 ((not children)
19152 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19153 beg itemp
19154 end (org-list-get-item-end itemp struct)))
19155 ((< (point) (setq next (car children)))
19156 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19157 beg itemp
19158 end next))
19159 ((> (point) (setq prev (car (last children))))
19160 (setq beg (org-list-get-item-end prev struct)
19161 end (org-list-get-item-end itemp struct)
19162 prefix (save-excursion
19163 (goto-char beg)
19164 (skip-chars-forward " \t")
19165 (make-string (current-column) ?\ ))))
19166 (t (catch 'exit
19167 (while (setq next (pop children))
19168 (if (> (point) next)
19169 (setq prev next)
19170 (setq beg (org-list-get-item-end prev struct)
19171 end next
19172 prefix (save-excursion
19173 (goto-char beg)
19174 (skip-chars-forward " \t")
19175 (make-string (current-column) ?\ )))
19176 (throw 'exit nil))))))
19177 ;; Use `fill-paragraph' with buffer narrowed to item
19178 ;; without any child, and with our computed PREFIX.
19179 (flet ((fill-context-prefix (from to &optional flr) prefix))
19180 (save-restriction
19181 (narrow-to-region beg end)
19182 (save-excursion (fill-paragraph justify)))) t))
19183 ;; Special case where point is not in a list but is on
19184 ;; a paragraph adjacent to a list: make sure this paragraph
19185 ;; doesn't get merged with the end of the list by narrowing
19186 ;; buffer first.
19187 ((save-excursion (fill-forward-paragraph -1)
19188 (setq itemp (org-in-item-p)))
19189 (let ((struct (save-excursion (goto-char itemp)
19190 (org-list-struct))))
19191 (save-restriction
19192 (narrow-to-region (org-list-get-bottom-point struct)
19193 (save-excursion (fill-forward-paragraph 1)
19194 (point)))
19195 (fill-paragraph justify) t)))
19196 ;; Else simply call `fill-paragraph'.
19197 (t nil))))
19199 ;; For reference, this is the default value of adaptive-fill-regexp
19200 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
19202 (defun org-adaptive-fill-function ()
19203 "Return a fill prefix for org-mode files."
19204 (let (itemp)
19205 (save-excursion
19206 (cond
19207 ;; Comment line
19208 ((looking-at "#[ \t]+")
19209 (match-string-no-properties 0))
19210 ;; Point is in a list after `backward-paragraph': original
19211 ;; point wasn't in the list, or filling would have been taken
19212 ;; care of by `org-auto-fill-function', but the list and the
19213 ;; real paragraph are not separated by a blank line. Thus, move
19214 ;; point after the list to go back to real paragraph and
19215 ;; determine fill-prefix. If point is at an item, do not
19216 ;; compute prefix and list structure, as first line of
19217 ;; paragraph will be skipped anyway.
19218 ((org-at-item-p) "")
19219 ((setq itemp (org-in-item-p))
19220 (goto-char itemp)
19221 (let* ((struct (org-list-struct))
19222 (bottom (org-list-get-bottom-point struct)))
19223 (goto-char bottom)
19224 (make-string (org-get-indentation) ?\ )))
19225 ;; Other text
19226 ((looking-at org-adaptive-fill-regexp-backup)
19227 (match-string-no-properties 0))))))
19229 (defun org-auto-fill-function ()
19230 "Auto-fill function."
19231 (let (itemp prefix)
19232 ;; When in a list, compute an appropriate fill-prefix and make
19233 ;; sure it will be used by `do-auto-fill'.
19234 (if (setq itemp (org-in-item-p))
19235 (progn
19236 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
19237 (flet ((fill-context-prefix (from to &optional flr) prefix))
19238 (do-auto-fill)))
19239 ;; Else just use `do-auto-fill'.
19240 (do-auto-fill))))
19242 ;;; Other stuff.
19244 (defun org-toggle-fixed-width-section (arg)
19245 "Toggle the fixed-width export.
19246 If there is no active region, the QUOTE keyword at the current headline is
19247 inserted or removed. When present, it causes the text between this headline
19248 and the next to be exported as fixed-width text, and unmodified.
19249 If there is an active region, this command adds or removes a colon as the
19250 first character of this line. If the first character of a line is a colon,
19251 this line is also exported in fixed-width font."
19252 (interactive "P")
19253 (let* ((cc 0)
19254 (regionp (org-region-active-p))
19255 (beg (if regionp (region-beginning) (point)))
19256 (end (if regionp (region-end)))
19257 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
19258 (case-fold-search nil)
19259 (re "[ \t]*\\(: \\)")
19260 off)
19261 (if regionp
19262 (save-excursion
19263 (goto-char beg)
19264 (setq cc (current-column))
19265 (beginning-of-line 1)
19266 (setq off (looking-at re))
19267 (while (> nlines 0)
19268 (setq nlines (1- nlines))
19269 (beginning-of-line 1)
19270 (cond
19271 (arg
19272 (org-move-to-column cc t)
19273 (insert ": \n")
19274 (forward-line -1))
19275 ((and off (looking-at re))
19276 (replace-match "" t t nil 1))
19277 ((not off) (org-move-to-column cc t) (insert ": ")))
19278 (forward-line 1)))
19279 (save-excursion
19280 (org-back-to-heading)
19281 (if (looking-at (concat outline-regexp
19282 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
19283 (replace-match "" t t nil 1)
19284 (if (looking-at outline-regexp)
19285 (progn
19286 (goto-char (match-end 0))
19287 (insert org-quote-string " "))))))))
19289 (defun org-reftex-citation ()
19290 "Use reftex-citation to insert a citation into the buffer.
19291 This looks for a line like
19293 #+BIBLIOGRAPHY: foo plain option:-d
19295 and derives from it that foo.bib is the bibliography file relevant
19296 for this document. It then installs the necessary environment for RefTeX
19297 to work in this buffer and calls `reftex-citation' to insert a citation
19298 into the buffer.
19300 Export of such citations to both LaTeX and HTML is handled by the contributed
19301 package org-exp-bibtex by Taru Karttunen."
19302 (interactive)
19303 (let ((reftex-docstruct-symbol 'rds)
19304 (reftex-cite-format "\\cite{%l}")
19305 rds bib)
19306 (save-excursion
19307 (save-restriction
19308 (widen)
19309 (let ((case-fold-search t)
19310 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
19311 (if (not (save-excursion
19312 (or (re-search-forward re nil t)
19313 (re-search-backward re nil t))))
19314 (error "No bibliography defined in file")
19315 (setq bib (concat (match-string 1) ".bib")
19316 rds (list (list 'bib bib)))))))
19317 (call-interactively 'reftex-citation)))
19319 ;;;; Functions extending outline functionality
19321 (defun org-beginning-of-line (&optional arg)
19322 "Go to the beginning of the current line. If that is invisible, continue
19323 to a visible line beginning. This makes the function of C-a more intuitive.
19324 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
19325 first attempt, and only move to after the tags when the cursor is already
19326 beyond the end of the headline."
19327 (interactive "P")
19328 (let ((pos (point))
19329 (special (if (consp org-special-ctrl-a/e)
19330 (car org-special-ctrl-a/e)
19331 org-special-ctrl-a/e))
19332 refpos)
19333 (if (org-bound-and-true-p line-move-visual)
19334 (beginning-of-visual-line 1)
19335 (beginning-of-line 1))
19336 (if (and arg (fboundp 'move-beginning-of-line))
19337 (call-interactively 'move-beginning-of-line)
19338 (if (bobp)
19340 (backward-char 1)
19341 (if (org-truely-invisible-p)
19342 (while (and (not (bobp)) (org-truely-invisible-p))
19343 (backward-char 1)
19344 (beginning-of-line 1))
19345 (forward-char 1))))
19346 (when special
19347 (cond
19348 ((and (looking-at org-complex-heading-regexp)
19349 (= (char-after (match-end 1)) ?\ ))
19350 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
19351 (point-at-eol)))
19352 (goto-char
19353 (if (eq special t)
19354 (cond ((> pos refpos) refpos)
19355 ((= pos (point)) refpos)
19356 (t (point)))
19357 (cond ((> pos (point)) (point))
19358 ((not (eq last-command this-command)) (point))
19359 (t refpos)))))
19360 ((org-at-item-p)
19361 (goto-char
19362 (if (eq special t)
19363 (cond ((> pos (match-end 0)) (match-end 0))
19364 ((= pos (point)) (match-end 0))
19365 (t (point)))
19366 (cond ((> pos (point)) (point))
19367 ((not (eq last-command this-command)) (point))
19368 (t (match-end 0))))))))
19369 (org-no-warnings
19370 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
19372 (defun org-end-of-line (&optional arg)
19373 "Go to the end of the line.
19374 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
19375 first attempt, and only move to after the tags when the cursor is already
19376 beyond the end of the headline."
19377 (interactive "P")
19378 (let ((special (if (consp org-special-ctrl-a/e)
19379 (cdr org-special-ctrl-a/e)
19380 org-special-ctrl-a/e)))
19381 (if (or (not special)
19382 (not (org-on-heading-p))
19383 arg)
19384 (call-interactively
19385 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
19386 ((fboundp 'move-end-of-line) 'move-end-of-line)
19387 (t 'end-of-line)))
19388 (let ((pos (point)))
19389 (beginning-of-line 1)
19390 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
19391 (if (eq special t)
19392 (if (or (< pos (match-beginning 1))
19393 (= pos (match-end 0)))
19394 (goto-char (match-beginning 1))
19395 (goto-char (match-end 0)))
19396 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
19397 (goto-char (match-end 0))
19398 (goto-char (match-beginning 1))))
19399 (call-interactively (if (fboundp 'move-end-of-line)
19400 'move-end-of-line
19401 'end-of-line)))))
19402 (org-no-warnings
19403 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
19405 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
19406 (define-key org-mode-map "\C-e" 'org-end-of-line)
19408 (defun org-backward-sentence (&optional arg)
19409 "Go to beginning of sentence, or beginning of table field.
19410 This will call `backward-sentence' or `org-table-beginning-of-field',
19411 depending on context."
19412 (interactive "P")
19413 (cond
19414 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
19415 (t (call-interactively 'backward-sentence))))
19417 (defun org-forward-sentence (&optional arg)
19418 "Go to end of sentence, or end of table field.
19419 This will call `forward-sentence' or `org-table-end-of-field',
19420 depending on context."
19421 (interactive "P")
19422 (cond
19423 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
19424 (t (call-interactively 'forward-sentence))))
19426 (define-key org-mode-map "\M-a" 'org-backward-sentence)
19427 (define-key org-mode-map "\M-e" 'org-forward-sentence)
19429 (defun org-kill-line (&optional arg)
19430 "Kill line, to tags or end of line."
19431 (interactive "P")
19432 (cond
19433 ((or (not org-special-ctrl-k)
19434 (bolp)
19435 (not (org-on-heading-p)))
19436 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
19437 org-ctrl-k-protect-subtree)
19438 (if (or (eq org-ctrl-k-protect-subtree 'error)
19439 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
19440 (error "C-k aborted - would kill hidden subtree")))
19441 (call-interactively 'kill-line))
19442 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
19443 (kill-region (point) (match-beginning 1))
19444 (org-set-tags nil t))
19445 (t (kill-region (point) (point-at-eol)))))
19447 (define-key org-mode-map "\C-k" 'org-kill-line)
19449 (defun org-yank (&optional arg)
19450 "Yank. If the kill is a subtree, treat it specially.
19451 This command will look at the current kill and check if is a single
19452 subtree, or a series of subtrees[1]. If it passes the test, and if the
19453 cursor is at the beginning of a line or after the stars of a currently
19454 empty headline, then the yank is handled specially. How exactly depends
19455 on the value of the following variables, both set by default.
19457 org-yank-folded-subtrees
19458 When set, the subtree(s) will be folded after insertion, but only
19459 if doing so would now swallow text after the yanked text.
19461 org-yank-adjusted-subtrees
19462 When set, the subtree will be promoted or demoted in order to
19463 fit into the local outline tree structure, which means that the level
19464 will be adjusted so that it becomes the smaller one of the two
19465 *visible* surrounding headings.
19467 Any prefix to this command will cause `yank' to be called directly with
19468 no special treatment. In particular, a simple \\[universal-argument] prefix \
19469 will just
19470 plainly yank the text as it is.
19472 \[1] The test checks if the first non-white line is a heading
19473 and if there are no other headings with fewer stars."
19474 (interactive "P")
19475 (org-yank-generic 'yank arg))
19477 (defun org-yank-generic (command arg)
19478 "Perform some yank-like command.
19480 This function implements the behavior described in the `org-yank'
19481 documentation. However, it has been generalized to work for any
19482 interactive command with similar behavior."
19484 ;; pretend to be command COMMAND
19485 (setq this-command command)
19487 (if arg
19488 (call-interactively command)
19490 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
19491 (and (org-kill-is-subtree-p)
19492 (or (bolp)
19493 (and (looking-at "[ \t]*$")
19494 (string-match
19495 "\\`\\*+\\'"
19496 (buffer-substring (point-at-bol) (point)))))))
19497 swallowp)
19498 (cond
19499 ((and subtreep org-yank-folded-subtrees)
19500 (let ((beg (point))
19501 end)
19502 (if (and subtreep org-yank-adjusted-subtrees)
19503 (org-paste-subtree nil nil 'for-yank)
19504 (call-interactively command))
19506 (setq end (point))
19507 (goto-char beg)
19508 (when (and (bolp) subtreep
19509 (not (setq swallowp
19510 (org-yank-folding-would-swallow-text beg end))))
19511 (or (looking-at outline-regexp)
19512 (re-search-forward (concat "^" outline-regexp) end t))
19513 (while (and (< (point) end) (looking-at outline-regexp))
19514 (hide-subtree)
19515 (org-cycle-show-empty-lines 'folded)
19516 (condition-case nil
19517 (outline-forward-same-level 1)
19518 (error (goto-char end)))))
19519 (when swallowp
19520 (message
19521 "Inserted text not folded because that would swallow text"))
19523 (goto-char end)
19524 (skip-chars-forward " \t\n\r")
19525 (beginning-of-line 1)
19526 (push-mark beg 'nomsg)))
19527 ((and subtreep org-yank-adjusted-subtrees)
19528 (let ((beg (point-at-bol)))
19529 (org-paste-subtree nil nil 'for-yank)
19530 (push-mark beg 'nomsg)))
19532 (call-interactively command))))))
19534 (defun org-yank-folding-would-swallow-text (beg end)
19535 "Would hide-subtree at BEG swallow any text after END?"
19536 (let (level)
19537 (save-excursion
19538 (goto-char beg)
19539 (when (or (looking-at outline-regexp)
19540 (re-search-forward (concat "^" outline-regexp) end t))
19541 (setq level (org-outline-level)))
19542 (goto-char end)
19543 (skip-chars-forward " \t\r\n\v\f")
19544 (if (or (eobp)
19545 (and (bolp) (looking-at org-outline-regexp)
19546 (<= (org-outline-level) level)))
19547 nil ; Nothing would be swallowed
19548 t)))) ; something would swallow
19550 (define-key org-mode-map "\C-y" 'org-yank)
19552 (defun org-truely-invisible-p ()
19553 "Check if point is at a character currently not visible.
19554 This version does not only check the character property, but also
19555 `visible-mode'."
19556 ;; Early versions of noutline don't have `outline-invisible-p'.
19557 (if (org-bound-and-true-p visible-mode)
19559 (outline-invisible-p)))
19561 (defun org-invisible-p2 ()
19562 "Check if point is at a character currently not visible."
19563 (save-excursion
19564 (if (and (eolp) (not (bobp))) (backward-char 1))
19565 ;; Early versions of noutline don't have `outline-invisible-p'.
19566 (outline-invisible-p)))
19568 (defun org-back-to-heading (&optional invisible-ok)
19569 "Call `outline-back-to-heading', but provide a better error message."
19570 (condition-case nil
19571 (outline-back-to-heading invisible-ok)
19572 (error (error "Before first headline at position %d in buffer %s"
19573 (point) (current-buffer)))))
19575 (defun org-beginning-of-defun ()
19576 "Go to the beginning of the subtree, i.e. back to the heading."
19577 (org-back-to-heading))
19578 (defun org-end-of-defun ()
19579 "Go to the end of the subtree."
19580 (org-end-of-subtree nil t))
19582 (defun org-before-first-heading-p ()
19583 "Before first heading?"
19584 (save-excursion
19585 (end-of-line)
19586 (null (re-search-backward "^\\*+ " nil t))))
19588 (defun org-on-heading-p (&optional ignored)
19589 (outline-on-heading-p t))
19590 (defun org-at-heading-p (&optional ignored)
19591 (outline-on-heading-p t))
19593 (defun org-point-at-end-of-empty-headline ()
19594 "If point is at the end of an empty headline, return t, else nil.
19595 If the heading only contains a TODO keyword, it is still still considered
19596 empty."
19597 (and (looking-at "[ \t]*$")
19598 (save-excursion
19599 (beginning-of-line 1)
19600 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
19601 "\\)?[ \t]*$")))))
19602 (defun org-at-heading-or-item-p ()
19603 (or (org-on-heading-p) (org-at-item-p)))
19605 (defun org-on-target-p ()
19606 (or (org-in-regexp org-radio-target-regexp)
19607 (org-in-regexp org-target-regexp)))
19609 (defun org-up-heading-all (arg)
19610 "Move to the heading line of which the present line is a subheading.
19611 This function considers both visible and invisible heading lines.
19612 With argument, move up ARG levels."
19613 (if (fboundp 'outline-up-heading-all)
19614 (outline-up-heading-all arg) ; emacs 21 version of outline.el
19615 (outline-up-heading arg t))) ; emacs 22 version of outline.el
19617 (defun org-up-heading-safe ()
19618 "Move to the heading line of which the present line is a subheading.
19619 This version will not throw an error. It will return the level of the
19620 headline found, or nil if no higher level is found.
19622 Also, this function will be a lot faster than `outline-up-heading',
19623 because it relies on stars being the outline starters. This can really
19624 make a significant difference in outlines with very many siblings."
19625 (let (start-level re)
19626 (org-back-to-heading t)
19627 (setq start-level (funcall outline-level))
19628 (if (equal start-level 1)
19630 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
19631 (if (re-search-backward re nil t)
19632 (funcall outline-level)))))
19634 (defun org-first-sibling-p ()
19635 "Is this heading the first child of its parents?"
19636 (interactive)
19637 (let ((re (concat "^" outline-regexp))
19638 level l)
19639 (unless (org-at-heading-p t)
19640 (error "Not at a heading"))
19641 (setq level (funcall outline-level))
19642 (save-excursion
19643 (if (not (re-search-backward re nil t))
19645 (setq l (funcall outline-level))
19646 (< l level)))))
19648 (defun org-goto-sibling (&optional previous)
19649 "Goto the next sibling, even if it is invisible.
19650 When PREVIOUS is set, go to the previous sibling instead. Returns t
19651 when a sibling was found. When none is found, return nil and don't
19652 move point."
19653 (let ((fun (if previous 're-search-backward 're-search-forward))
19654 (pos (point))
19655 (re (concat "^" outline-regexp))
19656 level l)
19657 (when (condition-case nil (org-back-to-heading t) (error nil))
19658 (setq level (funcall outline-level))
19659 (catch 'exit
19660 (or previous (forward-char 1))
19661 (while (funcall fun re nil t)
19662 (setq l (funcall outline-level))
19663 (when (< l level) (goto-char pos) (throw 'exit nil))
19664 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
19665 (goto-char pos)
19666 nil))))
19668 (defun org-show-siblings ()
19669 "Show all siblings of the current headline."
19670 (save-excursion
19671 (while (org-goto-sibling) (org-flag-heading nil)))
19672 (save-excursion
19673 (while (org-goto-sibling 'previous)
19674 (org-flag-heading nil))))
19676 (defun org-goto-first-child ()
19677 "Goto the first child, even if it is invisible.
19678 Return t when a child was found. Otherwise don't move point and
19679 return nil."
19680 (let (level (pos (point)) (re (concat "^" outline-regexp)))
19681 (when (condition-case nil (org-back-to-heading t) (error nil))
19682 (setq level (outline-level))
19683 (forward-char 1)
19684 (if (and (re-search-forward re nil t) (> (outline-level) level))
19685 (progn (goto-char (match-beginning 0)) t)
19686 (goto-char pos) nil))))
19688 (defun org-show-hidden-entry ()
19689 "Show an entry where even the heading is hidden."
19690 (save-excursion
19691 (org-show-entry)))
19693 (defun org-flag-heading (flag &optional entry)
19694 "Flag the current heading. FLAG non-nil means make invisible.
19695 When ENTRY is non-nil, show the entire entry."
19696 (save-excursion
19697 (org-back-to-heading t)
19698 ;; Check if we should show the entire entry
19699 (if entry
19700 (progn
19701 (org-show-entry)
19702 (save-excursion
19703 (and (outline-next-heading)
19704 (org-flag-heading nil))))
19705 (outline-flag-region (max (point-min) (1- (point)))
19706 (save-excursion (outline-end-of-heading) (point))
19707 flag))))
19709 (defun org-get-next-sibling ()
19710 "Move to next heading of the same level, and return point.
19711 If there is no such heading, return nil.
19712 This is like outline-next-sibling, but invisible headings are ok."
19713 (let ((level (funcall outline-level)))
19714 (outline-next-heading)
19715 (while (and (not (eobp)) (> (funcall outline-level) level))
19716 (outline-next-heading))
19717 (if (or (eobp) (< (funcall outline-level) level))
19719 (point))))
19721 (defun org-get-last-sibling ()
19722 "Move to previous heading of the same level, and return point.
19723 If there is no such heading, return nil."
19724 (let ((opoint (point))
19725 (level (funcall outline-level)))
19726 (outline-previous-heading)
19727 (when (and (/= (point) opoint) (outline-on-heading-p t))
19728 (while (and (> (funcall outline-level) level)
19729 (not (bobp)))
19730 (outline-previous-heading))
19731 (if (< (funcall outline-level) level)
19733 (point)))))
19735 (defun org-end-of-subtree (&optional invisible-OK to-heading)
19736 ;; This contains an exact copy of the original function, but it uses
19737 ;; `org-back-to-heading', to make it work also in invisible
19738 ;; trees. And is uses an invisible-OK argument.
19739 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
19740 ;; Furthermore, when used inside Org, finding the end of a large subtree
19741 ;; with many children and grandchildren etc, this can be much faster
19742 ;; than the outline version.
19743 (org-back-to-heading invisible-OK)
19744 (let ((first t)
19745 (level (funcall outline-level)))
19746 (if (and (org-mode-p) (< level 1000))
19747 ;; A true heading (not a plain list item), in Org-mode
19748 ;; This means we can easily find the end by looking
19749 ;; only for the right number of stars. Using a regexp to do
19750 ;; this is so much faster than using a Lisp loop.
19751 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
19752 (forward-char 1)
19753 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
19754 ;; something else, do it the slow way
19755 (while (and (not (eobp))
19756 (or first (> (funcall outline-level) level)))
19757 (setq first nil)
19758 (outline-next-heading)))
19759 (unless to-heading
19760 (if (memq (preceding-char) '(?\n ?\^M))
19761 (progn
19762 ;; Go to end of line before heading
19763 (forward-char -1)
19764 (if (memq (preceding-char) '(?\n ?\^M))
19765 ;; leave blank line before heading
19766 (forward-char -1))))))
19767 (point))
19769 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
19770 "Use Org version in org-mode, for dramatic speed-up."
19771 (if (org-mode-p)
19772 (progn
19773 (org-end-of-subtree nil t)
19774 (unless (eobp) (backward-char 1)))
19775 ad-do-it))
19777 (defun org-forward-same-level (arg &optional invisible-ok)
19778 "Move forward to the arg'th subheading at same level as this one.
19779 Stop at the first and last subheadings of a superior heading.
19780 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
19781 it wil also look at invisible ones."
19782 (interactive "p")
19783 (org-back-to-heading invisible-ok)
19784 (org-on-heading-p)
19785 (let* ((level (- (match-end 0) (match-beginning 0) 1))
19786 (re (format "^\\*\\{1,%d\\} " level))
19788 (forward-char 1)
19789 (while (> arg 0)
19790 (while (and (re-search-forward re nil 'move)
19791 (setq l (- (match-end 0) (match-beginning 0) 1))
19792 (= l level)
19793 (not invisible-ok)
19794 (progn (backward-char 1) (outline-invisible-p)))
19795 (if (< l level) (setq arg 1)))
19796 (setq arg (1- arg)))
19797 (beginning-of-line 1)))
19799 (defun org-backward-same-level (arg &optional invisible-ok)
19800 "Move backward to the arg'th subheading at same level as this one.
19801 Stop at the first and last subheadings of a superior heading."
19802 (interactive "p")
19803 (org-back-to-heading)
19804 (org-on-heading-p)
19805 (let* ((level (- (match-end 0) (match-beginning 0) 1))
19806 (re (format "^\\*\\{1,%d\\} " level))
19808 (while (> arg 0)
19809 (while (and (re-search-backward re nil 'move)
19810 (setq l (- (match-end 0) (match-beginning 0) 1))
19811 (= l level)
19812 (not invisible-ok)
19813 (outline-invisible-p))
19814 (if (< l level) (setq arg 1)))
19815 (setq arg (1- arg)))))
19817 (defun org-show-subtree ()
19818 "Show everything after this heading at deeper levels."
19819 (outline-flag-region
19820 (point)
19821 (save-excursion
19822 (org-end-of-subtree t t))
19823 nil))
19825 (defun org-show-entry ()
19826 "Show the body directly following this heading.
19827 Show the heading too, if it is currently invisible."
19828 (interactive)
19829 (save-excursion
19830 (condition-case nil
19831 (progn
19832 (org-back-to-heading t)
19833 (outline-flag-region
19834 (max (point-min) (1- (point)))
19835 (save-excursion
19836 (if (re-search-forward
19837 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
19838 (match-beginning 1)
19839 (point-max)))
19840 nil)
19841 (org-cycle-hide-drawers 'children))
19842 (error nil))))
19844 (defun org-make-options-regexp (kwds &optional extra)
19845 "Make a regular expression for keyword lines."
19846 (concat
19848 "#?[ \t]*\\+\\("
19849 (mapconcat 'regexp-quote kwds "\\|")
19850 (if extra (concat "\\|" extra))
19851 "\\):[ \t]*"
19852 "\\(.*\\)"))
19854 ;; Make isearch reveal the necessary context
19855 (defun org-isearch-end ()
19856 "Reveal context after isearch exits."
19857 (when isearch-success ; only if search was successful
19858 (if (featurep 'xemacs)
19859 ;; Under XEmacs, the hook is run in the correct place,
19860 ;; we directly show the context.
19861 (org-show-context 'isearch)
19862 ;; In Emacs the hook runs *before* restoring the overlays.
19863 ;; So we have to use a one-time post-command-hook to do this.
19864 ;; (Emacs 22 has a special variable, see function `org-mode')
19865 (unless (and (boundp 'isearch-mode-end-hook-quit)
19866 isearch-mode-end-hook-quit)
19867 ;; Only when the isearch was not quitted.
19868 (org-add-hook 'post-command-hook 'org-isearch-post-command
19869 'append 'local)))))
19871 (defun org-isearch-post-command ()
19872 "Remove self from hook, and show context."
19873 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
19874 (org-show-context 'isearch))
19877 ;;;; Integration with and fixes for other packages
19879 ;;; Imenu support
19881 (defvar org-imenu-markers nil
19882 "All markers currently used by Imenu.")
19883 (make-variable-buffer-local 'org-imenu-markers)
19885 (defun org-imenu-new-marker (&optional pos)
19886 "Return a new marker for use by Imenu, and remember the marker."
19887 (let ((m (make-marker)))
19888 (move-marker m (or pos (point)))
19889 (push m org-imenu-markers)
19892 (defun org-imenu-get-tree ()
19893 "Produce the index for Imenu."
19894 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
19895 (setq org-imenu-markers nil)
19896 (let* ((n org-imenu-depth)
19897 (re (concat "^" outline-regexp))
19898 (subs (make-vector (1+ n) nil))
19899 (last-level 0)
19900 m level head)
19901 (save-excursion
19902 (save-restriction
19903 (widen)
19904 (goto-char (point-max))
19905 (while (re-search-backward re nil t)
19906 (setq level (org-reduced-level (funcall outline-level)))
19907 (when (<= level n)
19908 (looking-at org-complex-heading-regexp)
19909 (setq head (org-link-display-format
19910 (org-match-string-no-properties 4))
19911 m (org-imenu-new-marker))
19912 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
19913 (if (>= level last-level)
19914 (push (cons head m) (aref subs level))
19915 (push (cons head (aref subs (1+ level))) (aref subs level))
19916 (loop for i from (1+ level) to n do (aset subs i nil)))
19917 (setq last-level level)))))
19918 (aref subs 1)))
19920 (eval-after-load "imenu"
19921 '(progn
19922 (add-hook 'imenu-after-jump-hook
19923 (lambda ()
19924 (if (org-mode-p)
19925 (org-show-context 'org-goto))))))
19927 (defun org-link-display-format (link)
19928 "Replace a link with either the description, or the link target
19929 if no description is present"
19930 (save-match-data
19931 (if (string-match org-bracket-link-analytic-regexp link)
19932 (replace-match (if (match-end 5)
19933 (match-string 5 link)
19934 (concat (match-string 1 link)
19935 (match-string 3 link)))
19936 nil t link)
19937 link)))
19939 ;; Speedbar support
19941 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
19942 "Overlay marking the agenda restriction line in speedbar.")
19943 (overlay-put org-speedbar-restriction-lock-overlay
19944 'face 'org-agenda-restriction-lock)
19945 (overlay-put org-speedbar-restriction-lock-overlay
19946 'help-echo "Agendas are currently limited to this item.")
19947 (org-detach-overlay org-speedbar-restriction-lock-overlay)
19949 (defun org-speedbar-set-agenda-restriction ()
19950 "Restrict future agenda commands to the location at point in speedbar.
19951 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
19952 (interactive)
19953 (require 'org-agenda)
19954 (let (p m tp np dir txt)
19955 (cond
19956 ((setq p (text-property-any (point-at-bol) (point-at-eol)
19957 'org-imenu t))
19958 (setq m (get-text-property p 'org-imenu-marker))
19959 (with-current-buffer (marker-buffer m)
19960 (goto-char m)
19961 (org-agenda-set-restriction-lock 'subtree)))
19962 ((setq p (text-property-any (point-at-bol) (point-at-eol)
19963 'speedbar-function 'speedbar-find-file))
19964 (setq tp (previous-single-property-change
19965 (1+ p) 'speedbar-function)
19966 np (next-single-property-change
19967 tp 'speedbar-function)
19968 dir (speedbar-line-directory)
19969 txt (buffer-substring-no-properties (or tp (point-min))
19970 (or np (point-max))))
19971 (with-current-buffer (find-file-noselect
19972 (let ((default-directory dir))
19973 (expand-file-name txt)))
19974 (unless (org-mode-p)
19975 (error "Cannot restrict to non-Org-mode file"))
19976 (org-agenda-set-restriction-lock 'file)))
19977 (t (error "Don't know how to restrict Org-mode's agenda")))
19978 (move-overlay org-speedbar-restriction-lock-overlay
19979 (point-at-bol) (point-at-eol))
19980 (setq current-prefix-arg nil)
19981 (org-agenda-maybe-redo)))
19983 (eval-after-load "speedbar"
19984 '(progn
19985 (speedbar-add-supported-extension ".org")
19986 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
19987 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
19988 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
19989 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19990 (add-hook 'speedbar-visiting-tag-hook
19991 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
19993 ;;; Fixes and Hacks for problems with other packages
19995 ;; Make flyspell not check words in links, to not mess up our keymap
19996 (defun org-mode-flyspell-verify ()
19997 "Don't let flyspell put overlays at active buttons."
19998 (and (not (get-text-property (max (1- (point)) (point-min)) 'keymap))
19999 (not (get-text-property (max (1- (point)) (point-min)) 'org-no-flyspell))))
20001 (defun org-remove-flyspell-overlays-in (beg end)
20002 "Remove flyspell overlays in region."
20003 (and (org-bound-and-true-p flyspell-mode)
20004 (fboundp 'flyspell-delete-region-overlays)
20005 (flyspell-delete-region-overlays beg end))
20006 (add-text-properties beg end '(org-no-flyspell t)))
20008 ;; Make `bookmark-jump' shows the jump location if it was hidden.
20009 (eval-after-load "bookmark"
20010 '(if (boundp 'bookmark-after-jump-hook)
20011 ;; We can use the hook
20012 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
20013 ;; Hook not available, use advice
20014 (defadvice bookmark-jump (after org-make-visible activate)
20015 "Make the position visible."
20016 (org-bookmark-jump-unhide))))
20018 ;; Make sure saveplace shows the location if it was hidden
20019 (eval-after-load "saveplace"
20020 '(defadvice save-place-find-file-hook (after org-make-visible activate)
20021 "Make the position visible."
20022 (org-bookmark-jump-unhide)))
20024 ;; Make sure ecb shows the location if it was hidden
20025 (eval-after-load "ecb"
20026 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
20027 "Make hierarchy visible when jumping into location from ECB tree buffer."
20028 (if (org-mode-p)
20029 (org-show-context))))
20031 (defun org-bookmark-jump-unhide ()
20032 "Unhide the current position, to show the bookmark location."
20033 (and (org-mode-p)
20034 (or (outline-invisible-p)
20035 (save-excursion (goto-char (max (point-min) (1- (point))))
20036 (outline-invisible-p)))
20037 (org-show-context 'bookmark-jump)))
20039 ;; Make session.el ignore our circular variable
20040 (eval-after-load "session"
20041 '(add-to-list 'session-globals-exclude 'org-mark-ring))
20043 ;;;; Experimental code
20045 (defun org-closed-in-range ()
20046 "Sparse tree of items closed in a certain time range.
20047 Still experimental, may disappear in the future."
20048 (interactive)
20049 ;; Get the time interval from the user.
20050 (let* ((time1 (org-float-time
20051 (org-read-date nil 'to-time nil "Starting date: ")))
20052 (time2 (org-float-time
20053 (org-read-date nil 'to-time nil "End date:")))
20054 ;; callback function
20055 (callback (lambda ()
20056 (let ((time
20057 (org-float-time
20058 (apply 'encode-time
20059 (org-parse-time-string
20060 (match-string 1))))))
20061 ;; check if time in interval
20062 (and (>= time time1) (<= time time2))))))
20063 ;; make tree, check each match with the callback
20064 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
20066 ;;;; Finish up
20068 (provide 'org)
20070 (run-hooks 'org-load-hook)
20072 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
20074 ;;; org.el ends here