Bufix: remove useless whitespace added after planning.
[org-mode.git] / lisp / org.el
blobcc7085c22e3f651ac9bb3c7089d24a73c22ceb34
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.6
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 "Awk" awk)
154 (const :tag "C" C)
155 (const :tag "R" R)
156 (const :tag "Asymptote" asymptote)
157 (const :tag "Calc" calc)
158 (const :tag "Clojure" clojure)
159 (const :tag "CSS" css)
160 (const :tag "Ditaa" ditaa)
161 (const :tag "Dot" dot)
162 (const :tag "Emacs Lisp" emacs-lisp)
163 (const :tag "Gnuplot" gnuplot)
164 (const :tag "Haskell" haskell)
165 (const :tag "Javascript" js)
166 (const :tag "Latex" latex)
167 (const :tag "Ledger" ledger)
168 (const :tag "Lilypond" lilypond)
169 (const :tag "Maxima" maxima)
170 (const :tag "Matlab" matlab)
171 (const :tag "Mscgen" mscgen)
172 (const :tag "Ocaml" ocaml)
173 (const :tag "Octave" octave)
174 (const :tag "Org" org)
175 (const :tag "Perl" perl)
176 (const :tag "PlantUML" plantuml)
177 (const :tag "Python" python)
178 (const :tag "Ruby" ruby)
179 (const :tag "Sass" sass)
180 (const :tag "Scheme" scheme)
181 (const :tag "Screen" screen)
182 (const :tag "Shell Script" sh)
183 (const :tag "Sql" sql)
184 (const :tag "Sqlite" sqlite))
185 :value-type (boolean :tag "Activate" :value t)))
187 ;;;; Customization variables
188 (defcustom org-clone-delete-id nil
189 "Remove ID property of clones of a subtree.
190 When non-nil, clones of a subtree don't inherit the ID property.
191 Otherwise they inherit the ID property with a new unique
192 identifier."
193 :type 'boolean
194 :group 'org-id)
196 ;;; Version
198 (defconst org-version "7.6"
199 "The version number of the file org.el.")
201 (defun org-version (&optional here)
202 "Show the org-mode version in the echo area.
203 With prefix arg HERE, insert it at point."
204 (interactive "P")
205 (let* ((origin default-directory)
206 (version org-version)
207 (git-version)
208 (dir (concat (file-name-directory (locate-library "org")) "../" )))
209 (when (and (file-exists-p (expand-file-name ".git" dir))
210 (executable-find "git"))
211 (unwind-protect
212 (progn
213 (cd dir)
214 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
215 (with-current-buffer "*Shell Command Output*"
216 (goto-char (point-min))
217 (setq git-version (buffer-substring (point) (point-at-eol))))
218 (subst-char-in-string ?- ?. git-version t)
219 (when (string-match "\\S-"
220 (shell-command-to-string
221 "git diff-index --name-only HEAD --"))
222 (setq git-version (concat git-version ".dirty")))
223 (setq version (concat version " (" git-version ")"))))
224 (cd origin)))
225 (setq version (format "Org-mode version %s" version))
226 (if here (insert version))
227 (message version)))
229 ;;; Compatibility constants
231 ;;; The custom variables
233 (defgroup org nil
234 "Outline-based notes management and organizer."
235 :tag "Org"
236 :group 'outlines
237 :group 'calendar)
239 (defcustom org-mode-hook nil
240 "Mode hook for Org-mode, run after the mode was turned on."
241 :group 'org
242 :type 'hook)
244 (defcustom org-load-hook nil
245 "Hook that is run after org.el has been loaded."
246 :group 'org
247 :type 'hook)
249 (defvar org-modules) ; defined below
250 (defvar org-modules-loaded nil
251 "Have the modules been loaded already?")
253 (defun org-load-modules-maybe (&optional force)
254 "Load all extensions listed in `org-modules'."
255 (when (or force (not org-modules-loaded))
256 (mapc (lambda (ext)
257 (condition-case nil (require ext)
258 (error (message "Problems while trying to load feature `%s'" ext))))
259 org-modules)
260 (setq org-modules-loaded t)))
262 (defun org-set-modules (var value)
263 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
264 (set var value)
265 (when (featurep 'org)
266 (org-load-modules-maybe 'force)))
268 (when (org-bound-and-true-p org-modules)
269 (let ((a (member 'org-infojs org-modules)))
270 (and a (setcar a 'org-jsinfo))))
272 (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)
273 "Modules that should always be loaded together with org.el.
274 If a description starts with <C>, the file is not part of Emacs
275 and loading it will require that you have downloaded and properly installed
276 the org-mode distribution.
278 You can also use this system to load external packages (i.e. neither Org
279 core modules, nor modules from the CONTRIB directory). Just add symbols
280 to the end of the list. If the package is called org-xyz.el, then you need
281 to add the symbol `xyz', and the package must have a call to
283 (provide 'org-xyz)"
284 :group 'org
285 :set 'org-set-modules
286 :type
287 '(set :greedy t
288 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
289 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
290 (const :tag " crypt: Encryption of subtrees" org-crypt)
291 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
292 (const :tag " docview: Links to doc-view buffers" org-docview)
293 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
294 (const :tag " id: Global IDs for identifying entries" org-id)
295 (const :tag " info: Links to Info nodes" org-info)
296 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
297 (const :tag " habit: Track your consistency with habits" org-habit)
298 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
299 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
300 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
301 (const :tag " mew Links to Mew folders/messages" org-mew)
302 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
303 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
304 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
305 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
306 (const :tag " vm: Links to VM folders/messages" org-vm)
307 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
308 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
309 (const :tag " mouse: Additional mouse support" org-mouse)
310 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
312 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
313 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
314 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
315 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
316 (const :tag "C collector: Collect properties into tables" org-collector)
317 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
318 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
319 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
320 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
321 (const :tag "C eval: Include command output as text" org-eval)
322 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
323 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
324 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
325 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
326 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
328 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
330 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
331 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
332 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
333 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
334 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
335 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
336 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
337 (const :tag "C mtags: Support for muse-like tags" org-mtags)
338 (const :tag "C odt: OpenDocumentText exporter for Org-mode" org-odt)
339 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
340 (const :tag "C registry: A registry for Org-mode links" org-registry)
341 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
342 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
343 (const :tag "C secretary: Team management with org-mode" org-secretary)
344 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
345 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
346 (const :tag "C track: Keep up with Org-mode development" org-track)
347 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
348 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
349 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
351 (defcustom org-support-shift-select nil
352 "Non-nil means make shift-cursor commands select text when possible.
354 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
355 selecting a region, or enlarge regions started in this way.
356 In Org-mode, in special contexts, these same keys are used for other
357 purposes, important enough to compete with shift selection. Org tries
358 to balance these needs by supporting `shift-select-mode' outside these
359 special contexts, under control of this variable.
361 The default of this variable is nil, to avoid confusing behavior. Shifted
362 cursor keys will then execute Org commands in the following contexts:
363 - on a headline, changing TODO state (left/right) and priority (up/down)
364 - on a time stamp, changing the time
365 - in a plain list item, changing the bullet type
366 - in a property definition line, switching between allowed values
367 - in the BEGIN line of a clock table (changing the time block).
368 Outside these contexts, the commands will throw an error.
370 When this variable is t and the cursor is not in a special context,
371 Org-mode will support shift-selection for making and enlarging regions.
372 To make this more effective, the bullet cycling will no longer happen
373 anywhere in an item line, but only if the cursor is exactly on the bullet.
375 If you set this variable to the symbol `always', then the keys
376 will not be special in headlines, property lines, and item lines, to make
377 shift selection work there as well. If this is what you want, you can
378 use the following alternative commands: `C-c C-t' and `C-c ,' to
379 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
380 TODO sets, `C-c -' to cycle item bullet types, and properties can be
381 edited by hand or in column view.
383 However, when the cursor is on a timestamp, shift-cursor commands
384 will still edit the time stamp - this is just too good to give up.
386 XEmacs user should have this variable set to nil, because shift-select-mode
387 is Emacs 23 only."
388 :group 'org
389 :type '(choice
390 (const :tag "Never" nil)
391 (const :tag "When outside special context" t)
392 (const :tag "Everywhere except timestamps" always)))
394 (defgroup org-startup nil
395 "Options concerning startup of Org-mode."
396 :tag "Org Startup"
397 :group 'org)
399 (defcustom org-startup-folded t
400 "Non-nil means entering Org-mode will switch to OVERVIEW.
401 This can also be configured on a per-file basis by adding one of
402 the following lines anywhere in the buffer:
404 #+STARTUP: fold (or `overview', this is equivalent)
405 #+STARTUP: nofold (or `showall', this is equivalent)
406 #+STARTUP: content
407 #+STARTUP: showeverything"
408 :group 'org-startup
409 :type '(choice
410 (const :tag "nofold: show all" nil)
411 (const :tag "fold: overview" t)
412 (const :tag "content: all headlines" content)
413 (const :tag "show everything, even drawers" showeverything)))
415 (defcustom org-startup-truncated t
416 "Non-nil means entering Org-mode will set `truncate-lines'.
417 This is useful since some lines containing links can be very long and
418 uninteresting. Also tables look terrible when wrapped."
419 :group 'org-startup
420 :type 'boolean)
422 (defcustom org-startup-indented nil
423 "Non-nil means turn on `org-indent-mode' on startup.
424 This can also be configured on a per-file basis by adding one of
425 the following lines anywhere in the buffer:
427 #+STARTUP: indent
428 #+STARTUP: noindent"
429 :group 'org-structure
430 :type '(choice
431 (const :tag "Not" nil)
432 (const :tag "Globally (slow on startup in large files)" t)))
434 (defcustom org-use-sub-superscripts t
435 "Non-nil means interpret \"_\" and \"^\" for export.
436 When this option is turned on, you can use TeX-like syntax for sub- and
437 superscripts. Several characters after \"_\" or \"^\" will be
438 considered as a single item - so grouping with {} is normally not
439 needed. For example, the following things will be parsed as single
440 sub- or superscripts.
442 10^24 or 10^tau several digits will be considered 1 item.
443 10^-12 or 10^-tau a leading sign with digits or a word
444 x^2-y^3 will be read as x^2 - y^3, because items are
445 terminated by almost any nonword/nondigit char.
446 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
448 Still, ambiguity is possible - so when in doubt use {} to enclose the
449 sub/superscript. If you set this variable to the symbol `{}',
450 the braces are *required* in order to trigger interpretations as
451 sub/superscript. This can be helpful in documents that need \"_\"
452 frequently in plain text.
454 Not all export backends support this, but HTML does.
456 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
457 :group 'org-startup
458 :group 'org-export-translation
459 :type '(choice
460 (const :tag "Always interpret" t)
461 (const :tag "Only with braces" {})
462 (const :tag "Never interpret" nil)))
464 (if (fboundp 'defvaralias)
465 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
468 (defcustom org-startup-with-beamer-mode nil
469 "Non-nil means turn on `org-beamer-mode' on startup.
470 This can also be configured on a per-file basis by adding one of
471 the following lines anywhere in the buffer:
473 #+STARTUP: beamer"
474 :group 'org-startup
475 :type 'boolean)
477 (defcustom org-startup-align-all-tables nil
478 "Non-nil means align all tables when visiting a file.
479 This is useful when the column width in tables is forced with <N> cookies
480 in table fields. Such tables will look correct only after the first re-align.
481 This can also be configured on a per-file basis by adding one of
482 the following lines anywhere in the buffer:
483 #+STARTUP: align
484 #+STARTUP: noalign"
485 :group 'org-startup
486 :type 'boolean)
488 (defcustom org-startup-with-inline-images nil
489 "Non-nil means show inline images when loading a new Org file.
490 This can also be configured on a per-file basis by adding one of
491 the following lines anywhere in the buffer:
492 #+STARTUP: inlineimages
493 #+STARTUP: noinlineimages"
494 :group 'org-startup
495 :type 'boolean)
497 (defcustom org-insert-mode-line-in-empty-file nil
498 "Non-nil means insert the first line setting Org-mode in empty files.
499 When the function `org-mode' is called interactively in an empty file, this
500 normally means that the file name does not automatically trigger Org-mode.
501 To ensure that the file will always be in Org-mode in the future, a
502 line enforcing Org-mode will be inserted into the buffer, if this option
503 has been set."
504 :group 'org-startup
505 :type 'boolean)
507 (defcustom org-replace-disputed-keys nil
508 "Non-nil means use alternative key bindings for some keys.
509 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
510 These keys are also used by other packages like shift-selection-mode'
511 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
512 If you want to use Org-mode together with one of these other modes,
513 or more generally if you would like to move some Org-mode commands to
514 other keys, set this variable and configure the keys with the variable
515 `org-disputed-keys'.
517 This option is only relevant at load-time of Org-mode, and must be set
518 *before* org.el is loaded. Changing it requires a restart of Emacs to
519 become effective."
520 :group 'org-startup
521 :type 'boolean)
523 (defcustom org-use-extra-keys nil
524 "Non-nil means use extra key sequence definitions for certain commands.
525 This happens automatically if you run XEmacs or if `window-system'
526 is nil. This variable lets you do the same manually. You must
527 set it before loading org.
529 Example: on Carbon Emacs 22 running graphically, with an external
530 keyboard on a Powerbook, the default way of setting M-left might
531 not work for either Alt or ESC. Setting this variable will make
532 it work for ESC."
533 :group 'org-startup
534 :type 'boolean)
536 (if (fboundp 'defvaralias)
537 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
539 (defcustom org-disputed-keys
540 '(([(shift up)] . [(meta p)])
541 ([(shift down)] . [(meta n)])
542 ([(shift left)] . [(meta -)])
543 ([(shift right)] . [(meta +)])
544 ([(control shift right)] . [(meta shift +)])
545 ([(control shift left)] . [(meta shift -)]))
546 "Keys for which Org-mode and other modes compete.
547 This is an alist, cars are the default keys, second element specifies
548 the alternative to use when `org-replace-disputed-keys' is t.
550 Keys can be specified in any syntax supported by `define-key'.
551 The value of this option takes effect only at Org-mode's startup,
552 therefore you'll have to restart Emacs to apply it after changing."
553 :group 'org-startup
554 :type 'alist)
556 (defun org-key (key)
557 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
558 Or return the original if not disputed.
559 Also apply the translations defined in `org-xemacs-key-equivalents'."
560 (when org-replace-disputed-keys
561 (let* ((nkey (key-description key))
562 (x (org-find-if (lambda (x)
563 (equal (key-description (car x)) nkey))
564 org-disputed-keys)))
565 (setq key (if x (cdr x) key))))
566 (when (featurep 'xemacs)
567 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
568 key)
570 (defun org-find-if (predicate seq)
571 (catch 'exit
572 (while seq
573 (if (funcall predicate (car seq))
574 (throw 'exit (car seq))
575 (pop seq)))))
577 (defun org-defkey (keymap key def)
578 "Define a key, possibly translated, as returned by `org-key'."
579 (define-key keymap (org-key key) def))
581 (defcustom org-ellipsis nil
582 "The ellipsis to use in the Org-mode outline.
583 When nil, just use the standard three dots. When a string, use that instead,
584 When a face, use the standard 3 dots, but with the specified face.
585 The change affects only Org-mode (which will then use its own display table).
586 Changing this requires executing `M-x org-mode' in a buffer to become
587 effective."
588 :group 'org-startup
589 :type '(choice (const :tag "Default" nil)
590 (face :tag "Face" :value org-warning)
591 (string :tag "String" :value "...#")))
593 (defvar org-display-table nil
594 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
596 (defgroup org-keywords nil
597 "Keywords in Org-mode."
598 :tag "Org Keywords"
599 :group 'org)
601 (defcustom org-deadline-string "DEADLINE:"
602 "String to mark deadline entries.
603 A deadline is this string, followed by a time stamp. Should be a word,
604 terminated by a colon. You can insert a schedule keyword and
605 a timestamp with \\[org-deadline].
606 Changes become only effective after restarting Emacs."
607 :group 'org-keywords
608 :type 'string)
610 (defcustom org-scheduled-string "SCHEDULED:"
611 "String to mark scheduled TODO entries.
612 A schedule is this string, followed by a time stamp. Should be a word,
613 terminated by a colon. You can insert a schedule keyword and
614 a timestamp with \\[org-schedule].
615 Changes become only effective after restarting Emacs."
616 :group 'org-keywords
617 :type 'string)
619 (defcustom org-closed-string "CLOSED:"
620 "String used as the prefix for timestamps logging closing a TODO entry."
621 :group 'org-keywords
622 :type 'string)
624 (defcustom org-clock-string "CLOCK:"
625 "String used as prefix for timestamps clocking work hours on an item."
626 :group 'org-keywords
627 :type 'string)
629 (defcustom org-comment-string "COMMENT"
630 "Entries starting with this keyword will never be exported.
631 An entry can be toggled between COMMENT and normal with
632 \\[org-toggle-comment].
633 Changes become only effective after restarting Emacs."
634 :group 'org-keywords
635 :type 'string)
637 (defcustom org-quote-string "QUOTE"
638 "Entries starting with this keyword will be exported in fixed-width font.
639 Quoting applies only to the text in the entry following the headline, and does
640 not extend beyond the next headline, even if that is lower level.
641 An entry can be toggled between QUOTE and normal with
642 \\[org-toggle-fixed-width-section]."
643 :group 'org-keywords
644 :type 'string)
646 (defconst org-repeat-re
647 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
648 "Regular expression for specifying repeated events.
649 After a match, group 1 contains the repeat expression.")
651 (defgroup org-structure nil
652 "Options concerning the general structure of Org-mode files."
653 :tag "Org Structure"
654 :group 'org)
656 (defgroup org-reveal-location nil
657 "Options about how to make context of a location visible."
658 :tag "Org Reveal Location"
659 :group 'org-structure)
661 (defconst org-context-choice
662 '(choice
663 (const :tag "Always" t)
664 (const :tag "Never" nil)
665 (repeat :greedy t :tag "Individual contexts"
666 (cons
667 (choice :tag "Context"
668 (const agenda)
669 (const org-goto)
670 (const occur-tree)
671 (const tags-tree)
672 (const link-search)
673 (const mark-goto)
674 (const bookmark-jump)
675 (const isearch)
676 (const default))
677 (boolean))))
678 "Contexts for the reveal options.")
680 (defcustom org-show-hierarchy-above '((default . t))
681 "Non-nil means show full hierarchy when revealing a location.
682 Org-mode often shows locations in an org-mode file which might have
683 been invisible before. When this is set, the hierarchy of headings
684 above the exposed location is shown.
685 Turning this off for example for sparse trees makes them very compact.
686 Instead of t, this can also be an alist specifying this option for different
687 contexts. Valid contexts are
688 agenda when exposing an entry from the agenda
689 org-goto when using the command `org-goto' on key C-c C-j
690 occur-tree when using the command `org-occur' on key C-c /
691 tags-tree when constructing a sparse tree based on tags matches
692 link-search when exposing search matches associated with a link
693 mark-goto when exposing the jump goal of a mark
694 bookmark-jump when exposing a bookmark location
695 isearch when exiting from an incremental search
696 default default for all contexts not set explicitly"
697 :group 'org-reveal-location
698 :type org-context-choice)
700 (defcustom org-show-following-heading '((default . nil))
701 "Non-nil means show following heading when revealing a location.
702 Org-mode often shows locations in an org-mode file which might have
703 been invisible before. When this is set, the heading following the
704 match is shown.
705 Turning this off for example for sparse trees makes them very compact,
706 but makes it harder to edit the location of the match. In such a case,
707 use the command \\[org-reveal] to show more context.
708 Instead of t, this can also be an alist specifying this option for different
709 contexts. See `org-show-hierarchy-above' for valid contexts."
710 :group 'org-reveal-location
711 :type org-context-choice)
713 (defcustom org-show-siblings '((default . nil) (isearch t))
714 "Non-nil means show all sibling heading when revealing a location.
715 Org-mode often shows locations in an org-mode file which might have
716 been invisible before. When this is set, the sibling of the current entry
717 heading are all made visible. If `org-show-hierarchy-above' is t,
718 the same happens on each level of the hierarchy above the current entry.
720 By default this is on for the isearch context, off for all other contexts.
721 Turning this off for example for sparse trees makes them very compact,
722 but makes it harder to edit the location of the match. In such a case,
723 use the command \\[org-reveal] to show more context.
724 Instead of t, this can also be an alist specifying this option for different
725 contexts. See `org-show-hierarchy-above' for valid contexts."
726 :group 'org-reveal-location
727 :type org-context-choice)
729 (defcustom org-show-entry-below '((default . nil))
730 "Non-nil means show the entry below a headline when revealing a location.
731 Org-mode often shows locations in an org-mode file which might have
732 been invisible before. When this is set, the text below the headline that is
733 exposed is also shown.
735 By default this is off for all contexts.
736 Instead of t, this can also be an alist specifying this option for different
737 contexts. See `org-show-hierarchy-above' for valid contexts."
738 :group 'org-reveal-location
739 :type org-context-choice)
741 (defcustom org-indirect-buffer-display 'other-window
742 "How should indirect tree buffers be displayed?
743 This applies to indirect buffers created with the commands
744 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
745 Valid values are:
746 current-window Display in the current window
747 other-window Just display in another window.
748 dedicated-frame Create one new frame, and re-use it each time.
749 new-frame Make a new frame each time. Note that in this case
750 previously-made indirect buffers are kept, and you need to
751 kill these buffers yourself."
752 :group 'org-structure
753 :group 'org-agenda-windows
754 :type '(choice
755 (const :tag "In current window" current-window)
756 (const :tag "In current frame, other window" other-window)
757 (const :tag "Each time a new frame" new-frame)
758 (const :tag "One dedicated frame" dedicated-frame)))
760 (defcustom org-use-speed-commands nil
761 "Non-nil means activate single letter commands at beginning of a headline.
762 This may also be a function to test for appropriate locations where speed
763 commands should be active."
764 :group 'org-structure
765 :type '(choice
766 (const :tag "Never" nil)
767 (const :tag "At beginning of headline stars" t)
768 (function)))
770 (defcustom org-speed-commands-user nil
771 "Alist of additional speed commands.
772 This list will be checked before `org-speed-commands-default'
773 when the variable `org-use-speed-commands' is non-nil
774 and when the cursor is at the beginning of a headline.
775 The car if each entry is a string with a single letter, which must
776 be assigned to `self-insert-command' in the global map.
777 The cdr is either a command to be called interactively, a function
778 to be called, or a form to be evaluated.
779 An entry that is just a list with a single string will be interpreted
780 as a descriptive headline that will be added when listing the speed
781 commands in the Help buffer using the `?' speed command."
782 :group 'org-structure
783 :type '(repeat :value ("k" . ignore)
784 (choice :value ("k" . ignore)
785 (list :tag "Descriptive Headline" (string :tag "Headline"))
786 (cons :tag "Letter and Command"
787 (string :tag "Command letter")
788 (choice
789 (function)
790 (sexp))))))
792 (defgroup org-cycle nil
793 "Options concerning visibility cycling in Org-mode."
794 :tag "Org Cycle"
795 :group 'org-structure)
797 (defcustom org-cycle-skip-children-state-if-no-children t
798 "Non-nil means skip CHILDREN state in entries that don't have any."
799 :group 'org-cycle
800 :type 'boolean)
802 (defcustom org-cycle-max-level nil
803 "Maximum level which should still be subject to visibility cycling.
804 Levels higher than this will, for cycling, be treated as text, not a headline.
805 When `org-odd-levels-only' is set, a value of N in this variable actually
806 means 2N-1 stars as the limiting headline.
807 When nil, cycle all levels.
808 Note that the limiting level of cycling is also influenced by
809 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
810 `org-inlinetask-min-level' is, cycling will be limited to levels one less
811 than its value."
812 :group 'org-cycle
813 :type '(choice
814 (const :tag "No limit" nil)
815 (integer :tag "Maximum level")))
817 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
818 "Names of drawers. Drawers are not opened by cycling on the headline above.
819 Drawers only open with a TAB on the drawer line itself. A drawer looks like
820 this:
821 :DRAWERNAME:
822 .....
823 :END:
824 The drawer \"PROPERTIES\" is special for capturing properties through
825 the property API.
827 Drawers can be defined on the per-file basis with a line like:
829 #+DRAWERS: HIDDEN STATE PROPERTIES"
830 :group 'org-structure
831 :group 'org-cycle
832 :type '(repeat (string :tag "Drawer Name")))
834 (defcustom org-hide-block-startup nil
835 "Non-nil means entering Org-mode will fold all blocks.
836 This can also be set in on a per-file basis with
838 #+STARTUP: hideblocks
839 #+STARTUP: showblocks"
840 :group 'org-startup
841 :group 'org-cycle
842 :type 'boolean)
844 (defcustom org-cycle-global-at-bob nil
845 "Cycle globally if cursor is at beginning of buffer and not at a headline.
846 This makes it possible to do global cycling without having to use S-TAB or
847 \\[universal-argument] TAB. For this special case to work, the first line \
848 of the buffer
849 must not be a headline - it may be empty or some other text. When used in
850 this way, `org-cycle-hook' is disables temporarily, to make sure the
851 cursor stays at the beginning of the buffer.
852 When this option is nil, don't do anything special at the beginning
853 of the buffer."
854 :group 'org-cycle
855 :type 'boolean)
857 (defcustom org-cycle-level-after-item/entry-creation t
858 "Non-nil means cycle entry level or item indentation in new empty entries.
860 When the cursor is at the end of an empty headline, i.e with only stars
861 and maybe a TODO keyword, TAB will then switch the entry to become a child,
862 and then all possible ancestor states, before returning to the original state.
863 This makes data entry extremely fast: M-RET to create a new headline,
864 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
866 When the cursor is at the end of an empty plain list item, one TAB will
867 make it a subitem, two or more tabs will back up to make this an item
868 higher up in the item hierarchy."
869 :group 'org-cycle
870 :type 'boolean)
872 (defcustom org-cycle-emulate-tab t
873 "Where should `org-cycle' emulate TAB.
874 nil Never
875 white Only in completely white lines
876 whitestart Only at the beginning of lines, before the first non-white char
877 t Everywhere except in headlines
878 exc-hl-bol Everywhere except at the start of a headline
879 If TAB is used in a place where it does not emulate TAB, the current subtree
880 visibility is cycled."
881 :group 'org-cycle
882 :type '(choice (const :tag "Never" nil)
883 (const :tag "Only in completely white lines" white)
884 (const :tag "Before first char in a line" whitestart)
885 (const :tag "Everywhere except in headlines" t)
886 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
889 (defcustom org-cycle-separator-lines 2
890 "Number of empty lines needed to keep an empty line between collapsed trees.
891 If you leave an empty line between the end of a subtree and the following
892 headline, this empty line is hidden when the subtree is folded.
893 Org-mode will leave (exactly) one empty line visible if the number of
894 empty lines is equal or larger to the number given in this variable.
895 So the default 2 means at least 2 empty lines after the end of a subtree
896 are needed to produce free space between a collapsed subtree and the
897 following headline.
899 If the number is negative, and the number of empty lines is at least -N,
900 all empty lines are shown.
902 Special case: when 0, never leave empty lines in collapsed view."
903 :group 'org-cycle
904 :type 'integer)
905 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
907 (defcustom org-pre-cycle-hook nil
908 "Hook that is run before visibility cycling is happening.
909 The function(s) in this hook must accept a single argument which indicates
910 the new state that will be set right after running this hook. The
911 argument is a symbol. Before a global state change, it can have the values
912 `overview', `content', or `all'. Before a local state change, it can have
913 the values `folded', `children', or `subtree'."
914 :group 'org-cycle
915 :type 'hook)
917 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
918 org-cycle-hide-drawers
919 org-cycle-show-empty-lines
920 org-optimize-window-after-visibility-change)
921 "Hook that is run after `org-cycle' has changed the buffer visibility.
922 The function(s) in this hook must accept a single argument which indicates
923 the new state that was set by the most recent `org-cycle' command. The
924 argument is a symbol. After a global state change, it can have the values
925 `overview', `content', or `all'. After a local state change, it can have
926 the values `folded', `children', or `subtree'."
927 :group 'org-cycle
928 :type 'hook)
930 (defgroup org-edit-structure nil
931 "Options concerning structure editing in Org-mode."
932 :tag "Org Edit Structure"
933 :group 'org-structure)
935 (defcustom org-odd-levels-only nil
936 "Non-nil means skip even levels and only use odd levels for the outline.
937 This has the effect that two stars are being added/taken away in
938 promotion/demotion commands. It also influences how levels are
939 handled by the exporters.
940 Changing it requires restart of `font-lock-mode' to become effective
941 for fontification also in regions already fontified.
942 You may also set this on a per-file basis by adding one of the following
943 lines to the buffer:
945 #+STARTUP: odd
946 #+STARTUP: oddeven"
947 :group 'org-edit-structure
948 :group 'org-appearance
949 :type 'boolean)
951 (defcustom org-adapt-indentation t
952 "Non-nil means adapt indentation to outline node level.
954 When this variable is set, Org assumes that you write outlines by
955 indenting text in each node to align with the headline (after the stars).
956 The following issues are influenced by this variable:
958 - When this is set and the *entire* text in an entry is indented, the
959 indentation is increased by one space in a demotion command, and
960 decreased by one in a promotion command. If any line in the entry
961 body starts with text at column 0, indentation is not changed at all.
963 - Property drawers and planning information is inserted indented when
964 this variable s set. When nil, they will not be indented.
966 - TAB indents a line relative to context. The lines below a headline
967 will be indented when this variable is set.
969 Note that this is all about true indentation, by adding and removing
970 space characters. See also `org-indent.el' which does level-dependent
971 indentation in a virtual way, i.e. at display time in Emacs."
972 :group 'org-edit-structure
973 :type 'boolean)
975 (defcustom org-special-ctrl-a/e nil
976 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
978 When t, `C-a' will bring back the cursor to the beginning of the
979 headline text, i.e. after the stars and after a possible TODO keyword.
980 In an item, this will be the position after the bullet.
981 When the cursor is already at that position, another `C-a' will bring
982 it to the beginning of the line.
984 `C-e' will jump to the end of the headline, ignoring the presence of tags
985 in the headline. A second `C-e' will then jump to the true end of the
986 line, after any tags. This also means that, when this variable is
987 non-nil, `C-e' also will never jump beyond the end of the heading of a
988 folded section, i.e. not after the ellipses.
990 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
991 going to the true line boundary first. Only a directly following, identical
992 keypress will bring the cursor to the special positions.
994 This may also be a cons cell where the behavior for `C-a' and `C-e' is
995 set separately."
996 :group 'org-edit-structure
997 :type '(choice
998 (const :tag "off" nil)
999 (const :tag "on: after stars/bullet and before tags first" t)
1000 (const :tag "reversed: true line boundary first" reversed)
1001 (cons :tag "Set C-a and C-e separately"
1002 (choice :tag "Special C-a"
1003 (const :tag "off" nil)
1004 (const :tag "on: after stars/bullet first" t)
1005 (const :tag "reversed: before stars/bullet first" reversed))
1006 (choice :tag "Special C-e"
1007 (const :tag "off" nil)
1008 (const :tag "on: before tags first" t)
1009 (const :tag "reversed: after tags first" reversed)))))
1010 (if (fboundp 'defvaralias)
1011 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1013 (defcustom org-special-ctrl-k nil
1014 "Non-nil means `C-k' will behave specially in headlines.
1015 When nil, `C-k' will call the default `kill-line' command.
1016 When t, the following will happen while the cursor is in the headline:
1018 - When the cursor is at the beginning of a headline, kill the entire
1019 line and possible the folded subtree below the line.
1020 - When in the middle of the headline text, kill the headline up to the tags.
1021 - When after the headline text, kill the tags."
1022 :group 'org-edit-structure
1023 :type 'boolean)
1025 (defcustom org-ctrl-k-protect-subtree nil
1026 "Non-nil means, do not delete a hidden subtree with C-k.
1027 When set to the symbol `error', simply throw an error when C-k is
1028 used to kill (part-of) a headline that has hidden text behind it.
1029 Any other non-nil value will result in a query to the user, if it is
1030 OK to kill that hidden subtree. When nil, kill without remorse."
1031 :group 'org-edit-structure
1032 :type '(choice
1033 (const :tag "Do not protect hidden subtrees" nil)
1034 (const :tag "Protect hidden subtrees with a security query" t)
1035 (const :tag "Never kill a hidden subtree with C-k" error)))
1037 (defcustom org-yank-folded-subtrees t
1038 "Non-nil means when yanking subtrees, fold them.
1039 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1040 it starts with a heading and all other headings in it are either children
1041 or siblings, then fold all the subtrees. However, do this only if no
1042 text after the yank would be swallowed into a folded tree by this action."
1043 :group 'org-edit-structure
1044 :type 'boolean)
1046 (defcustom org-yank-adjusted-subtrees nil
1047 "Non-nil means when yanking subtrees, adjust the level.
1048 With this setting, `org-paste-subtree' is used to insert the subtree, see
1049 this function for details."
1050 :group 'org-edit-structure
1051 :type 'boolean)
1053 (defcustom org-M-RET-may-split-line '((default . t))
1054 "Non-nil means M-RET will split the line at the cursor position.
1055 When nil, it will go to the end of the line before making a
1056 new line.
1057 You may also set this option in a different way for different
1058 contexts. Valid contexts are:
1060 headline when creating a new headline
1061 item when creating a new item
1062 table in a table field
1063 default the value to be used for all contexts not explicitly
1064 customized"
1065 :group 'org-structure
1066 :group 'org-table
1067 :type '(choice
1068 (const :tag "Always" t)
1069 (const :tag "Never" nil)
1070 (repeat :greedy t :tag "Individual contexts"
1071 (cons
1072 (choice :tag "Context"
1073 (const headline)
1074 (const item)
1075 (const table)
1076 (const default))
1077 (boolean)))))
1080 (defcustom org-insert-heading-respect-content nil
1081 "Non-nil means insert new headings after the current subtree.
1082 When nil, the new heading is created directly after the current line.
1083 The commands \\[org-insert-heading-respect-content] and
1084 \\[org-insert-todo-heading-respect-content] turn this variable on
1085 for the duration of the command."
1086 :group 'org-structure
1087 :type 'boolean)
1089 (defcustom org-blank-before-new-entry '((heading . auto)
1090 (plain-list-item . auto))
1091 "Should `org-insert-heading' leave a blank line before new heading/item?
1092 The value is an alist, with `heading' and `plain-list-item' as car,
1093 and a boolean flag as cdr. The cdr may also be the symbol `auto', and then
1094 Org will look at the surrounding headings/items and try to make an
1095 intelligent decision whether to insert a blank line or not.
1097 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1098 set, the setting here is ignored and no empty line is inserted, to avoid
1099 breaking the list structure."
1100 :group 'org-edit-structure
1101 :type '(list
1102 (cons (const heading)
1103 (choice (const :tag "Never" nil)
1104 (const :tag "Always" t)
1105 (const :tag "Auto" auto)))
1106 (cons (const plain-list-item)
1107 (choice (const :tag "Never" nil)
1108 (const :tag "Always" t)
1109 (const :tag "Auto" auto)))))
1111 (defcustom org-insert-heading-hook nil
1112 "Hook being run after inserting a new heading."
1113 :group 'org-edit-structure
1114 :type 'hook)
1116 (defcustom org-enable-fixed-width-editor t
1117 "Non-nil means lines starting with \":\" are treated as fixed-width.
1118 This currently only means they are never auto-wrapped.
1119 When nil, such lines will be treated like ordinary lines.
1120 See also the QUOTE keyword."
1121 :group 'org-edit-structure
1122 :type 'boolean)
1124 (defcustom org-goto-auto-isearch t
1125 "Non-nil means typing characters in `org-goto' starts incremental search."
1126 :group 'org-edit-structure
1127 :type 'boolean)
1129 (defgroup org-sparse-trees nil
1130 "Options concerning sparse trees in Org-mode."
1131 :tag "Org Sparse Trees"
1132 :group 'org-structure)
1134 (defcustom org-highlight-sparse-tree-matches t
1135 "Non-nil means highlight all matches that define a sparse tree.
1136 The highlights will automatically disappear the next time the buffer is
1137 changed by an edit command."
1138 :group 'org-sparse-trees
1139 :type 'boolean)
1141 (defcustom org-remove-highlights-with-change t
1142 "Non-nil means any change to the buffer will remove temporary highlights.
1143 Such highlights are created by `org-occur' and `org-clock-display'.
1144 When nil, `C-c C-c needs to be used to get rid of the highlights.
1145 The highlights created by `org-preview-latex-fragment' always need
1146 `C-c C-c' to be removed."
1147 :group 'org-sparse-trees
1148 :group 'org-time
1149 :type 'boolean)
1152 (defcustom org-occur-hook '(org-first-headline-recenter)
1153 "Hook that is run after `org-occur' has constructed a sparse tree.
1154 This can be used to recenter the window to show as much of the structure
1155 as possible."
1156 :group 'org-sparse-trees
1157 :type 'hook)
1159 (defgroup org-imenu-and-speedbar nil
1160 "Options concerning imenu and speedbar in Org-mode."
1161 :tag "Org Imenu and Speedbar"
1162 :group 'org-structure)
1164 (defcustom org-imenu-depth 2
1165 "The maximum level for Imenu access to Org-mode headlines.
1166 This also applied for speedbar access."
1167 :group 'org-imenu-and-speedbar
1168 :type 'integer)
1170 (defgroup org-table nil
1171 "Options concerning tables in Org-mode."
1172 :tag "Org Table"
1173 :group 'org)
1175 (defcustom org-enable-table-editor 'optimized
1176 "Non-nil means lines starting with \"|\" are handled by the table editor.
1177 When nil, such lines will be treated like ordinary lines.
1179 When equal to the symbol `optimized', the table editor will be optimized to
1180 do the following:
1181 - Automatic overwrite mode in front of whitespace in table fields.
1182 This makes the structure of the table stay in tact as long as the edited
1183 field does not exceed the column width.
1184 - Minimize the number of realigns. Normally, the table is aligned each time
1185 TAB or RET are pressed to move to another field. With optimization this
1186 happens only if changes to a field might have changed the column width.
1187 Optimization requires replacing the functions `self-insert-command',
1188 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1189 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1190 very good at guessing when a re-align will be necessary, but you can always
1191 force one with \\[org-ctrl-c-ctrl-c].
1193 If you would like to use the optimized version in Org-mode, but the
1194 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1196 This variable can be used to turn on and off the table editor during a session,
1197 but in order to toggle optimization, a restart is required.
1199 See also the variable `org-table-auto-blank-field'."
1200 :group 'org-table
1201 :type '(choice
1202 (const :tag "off" nil)
1203 (const :tag "on" t)
1204 (const :tag "on, optimized" optimized)))
1206 (defcustom org-self-insert-cluster-for-undo t
1207 "Non-nil means cluster self-insert commands for undo when possible.
1208 If this is set, then, like in the Emacs command loop, 20 consecutive
1209 characters will be undone together.
1210 This is configurable, because there is some impact on typing performance."
1211 :group 'org-table
1212 :type 'boolean)
1214 (defcustom org-table-tab-recognizes-table.el t
1215 "Non-nil means TAB will automatically notice a table.el table.
1216 When it sees such a table, it moves point into it and - if necessary -
1217 calls `table-recognize-table'."
1218 :group 'org-table-editing
1219 :type 'boolean)
1221 (defgroup org-link nil
1222 "Options concerning links in Org-mode."
1223 :tag "Org Link"
1224 :group 'org)
1226 (defvar org-link-abbrev-alist-local nil
1227 "Buffer-local version of `org-link-abbrev-alist', which see.
1228 The value of this is taken from the #+LINK lines.")
1229 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1231 (defcustom org-link-abbrev-alist nil
1232 "Alist of link abbreviations.
1233 The car of each element is a string, to be replaced at the start of a link.
1234 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1235 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1237 [[linkkey:tag][description]]
1239 The 'linkkey' must be a word word, starting with a letter, followed
1240 by letters, numbers, '-' or '_'.
1242 If REPLACE is a string, the tag will simply be appended to create the link.
1243 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1244 the placeholder \"%h\" will cause a url-encoded version of the tag to
1245 be inserted at that point (see the function `url-hexify-string').
1247 REPLACE may also be a function that will be called with the tag as the
1248 only argument to create the link, which should be returned as a string.
1250 See the manual for examples."
1251 :group 'org-link
1252 :type '(repeat
1253 (cons
1254 (string :tag "Protocol")
1255 (choice
1256 (string :tag "Format")
1257 (function)))))
1259 (defcustom org-descriptive-links t
1260 "Non-nil means hide link part and only show description of bracket links.
1261 Bracket links are like [[link][description]]. This variable sets the initial
1262 state in new org-mode buffers. The setting can then be toggled on a
1263 per-buffer basis from the Org->Hyperlinks menu."
1264 :group 'org-link
1265 :type 'boolean)
1267 (defcustom org-link-file-path-type 'adaptive
1268 "How the path name in file links should be stored.
1269 Valid values are:
1271 relative Relative to the current directory, i.e. the directory of the file
1272 into which the link is being inserted.
1273 absolute Absolute path, if possible with ~ for home directory.
1274 noabbrev Absolute path, no abbreviation of home directory.
1275 adaptive Use relative path for files in the current directory and sub-
1276 directories of it. For other files, use an absolute path."
1277 :group 'org-link
1278 :type '(choice
1279 (const relative)
1280 (const absolute)
1281 (const noabbrev)
1282 (const adaptive)))
1284 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1285 "Types of links that should be activated in Org-mode files.
1286 This is a list of symbols, each leading to the activation of a certain link
1287 type. In principle, it does not hurt to turn on most link types - there may
1288 be a small gain when turning off unused link types. The types are:
1290 bracket The recommended [[link][description]] or [[link]] links with hiding.
1291 angle Links in angular brackets that may contain whitespace like
1292 <bbdb:Carsten Dominik>.
1293 plain Plain links in normal text, no whitespace, like http://google.com.
1294 radio Text that is matched by a radio target, see manual for details.
1295 tag Tag settings in a headline (link to tag search).
1296 date Time stamps (link to calendar).
1297 footnote Footnote labels.
1299 Changing this variable requires a restart of Emacs to become effective."
1300 :group 'org-link
1301 :type '(set :greedy t
1302 (const :tag "Double bracket links" bracket)
1303 (const :tag "Angular bracket links" angle)
1304 (const :tag "Plain text links" plain)
1305 (const :tag "Radio target matches" radio)
1306 (const :tag "Tags" tag)
1307 (const :tag "Timestamps" date)
1308 (const :tag "Footnotes" footnote)))
1310 (defcustom org-make-link-description-function nil
1311 "Function to use to generate link descriptions from links.
1312 If nil the link location will be used. This function must take
1313 two parameters; the first is the link and the second the
1314 description `org-insert-link' has generated, and should return the
1315 description to use."
1316 :group 'org-link
1317 :type 'function)
1319 (defgroup org-link-store nil
1320 "Options concerning storing links in Org-mode."
1321 :tag "Org Store Link"
1322 :group 'org-link)
1324 (defcustom org-email-link-description-format "Email %c: %.30s"
1325 "Format of the description part of a link to an email or usenet message.
1326 The following %-escapes will be replaced by corresponding information:
1328 %F full \"From\" field
1329 %f name, taken from \"From\" field, address if no name
1330 %T full \"To\" field
1331 %t first name in \"To\" field, address if no name
1332 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1333 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1334 %s subject
1335 %d date
1336 %m message-id.
1338 You may use normal field width specification between the % and the letter.
1339 This is for example useful to limit the length of the subject.
1341 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1342 :group 'org-link-store
1343 :type 'string)
1345 (defcustom org-from-is-user-regexp
1346 (let (r1 r2)
1347 (when (and user-mail-address (not (string= user-mail-address "")))
1348 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1349 (when (and user-full-name (not (string= user-full-name "")))
1350 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1351 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1352 "Regexp matched against the \"From:\" header of an email or usenet message.
1353 It should match if the message is from the user him/herself."
1354 :group 'org-link-store
1355 :type 'regexp)
1357 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1358 "Non-nil means storing a link to an Org file will use entry IDs.
1360 Note that before this variable is even considered, org-id must be loaded,
1361 so please customize `org-modules' and turn it on.
1363 The variable can have the following values:
1365 t Create an ID if needed to make a link to the current entry.
1367 create-if-interactive
1368 If `org-store-link' is called directly (interactively, as a user
1369 command), do create an ID to support the link. But when doing the
1370 job for remember, only use the ID if it already exists. The
1371 purpose of this setting is to avoid proliferation of unwanted
1372 IDs, just because you happen to be in an Org file when you
1373 call `org-remember' that automatically and preemptively
1374 creates a link. If you do want to get an ID link in a remember
1375 template to an entry not having an ID, create it first by
1376 explicitly creating a link to it, using `C-c C-l' first.
1378 create-if-interactive-and-no-custom-id
1379 Like create-if-interactive, but do not create an ID if there is
1380 a CUSTOM_ID property defined in the entry. This is the default.
1382 use-existing
1383 Use existing ID, do not create one.
1385 nil Never use an ID to make a link, instead link using a text search for
1386 the headline text."
1387 :group 'org-link-store
1388 :type '(choice
1389 (const :tag "Create ID to make link" t)
1390 (const :tag "Create if storing link interactively"
1391 create-if-interactive)
1392 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1393 create-if-interactive-and-no-custom-id)
1394 (const :tag "Only use existing" use-existing)
1395 (const :tag "Do not use ID to create link" nil)))
1397 (defcustom org-context-in-file-links t
1398 "Non-nil means file links from `org-store-link' contain context.
1399 A search string will be added to the file name with :: as separator and
1400 used to find the context when the link is activated by the command
1401 `org-open-at-point'. When this option is t, the entire active region
1402 will be placed in the search string of the file link. If set to a
1403 positive integer, only the first n lines of context will be stored.
1405 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1406 negates this setting for the duration of the command."
1407 :group 'org-link-store
1408 :type '(choice boolean integer))
1410 (defcustom org-keep-stored-link-after-insertion nil
1411 "Non-nil means keep link in list for entire session.
1413 The command `org-store-link' adds a link pointing to the current
1414 location to an internal list. These links accumulate during a session.
1415 The command `org-insert-link' can be used to insert links into any
1416 Org-mode file (offering completion for all stored links). When this
1417 option is nil, every link which has been inserted once using \\[org-insert-link]
1418 will be removed from the list, to make completing the unused links
1419 more efficient."
1420 :group 'org-link-store
1421 :type 'boolean)
1423 (defgroup org-link-follow nil
1424 "Options concerning following links in Org-mode."
1425 :tag "Org Follow Link"
1426 :group 'org-link)
1428 (defcustom org-link-translation-function nil
1429 "Function to translate links with different syntax to Org syntax.
1430 This can be used to translate links created for example by the Planner
1431 or emacs-wiki packages to Org syntax.
1432 The function must accept two parameters, a TYPE containing the link
1433 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1434 which is everything after the link protocol. It should return a cons
1435 with possibly modified values of type and path.
1436 Org contains a function for this, so if you set this variable to
1437 `org-translate-link-from-planner', you should be able follow many
1438 links created by planner."
1439 :group 'org-link-follow
1440 :type 'function)
1442 (defcustom org-follow-link-hook nil
1443 "Hook that is run after a link has been followed."
1444 :group 'org-link-follow
1445 :type 'hook)
1447 (defcustom org-tab-follows-link nil
1448 "Non-nil means on links TAB will follow the link.
1449 Needs to be set before org.el is loaded.
1450 This really should not be used, it does not make sense, and the
1451 implementation is bad."
1452 :group 'org-link-follow
1453 :type 'boolean)
1455 (defcustom org-return-follows-link nil
1456 "Non-nil means on links RET will follow the link."
1457 :group 'org-link-follow
1458 :type 'boolean)
1460 (defcustom org-mouse-1-follows-link
1461 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1462 "Non-nil means mouse-1 on a link will follow the link.
1463 A longer mouse click will still set point. Does not work on XEmacs.
1464 Needs to be set before org.el is loaded."
1465 :group 'org-link-follow
1466 :type 'boolean)
1468 (defcustom org-mark-ring-length 4
1469 "Number of different positions to be recorded in the ring.
1470 Changing this requires a restart of Emacs to work correctly."
1471 :group 'org-link-follow
1472 :type 'integer)
1474 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1475 "Non-nil means internal links in Org files must exactly match a headline.
1476 When nil, the link search tries to match a phrase with all words
1477 in the search text."
1478 :group 'org-link-follow
1479 :type '(choice
1480 (const :tag "Use fuzy text search" nil)
1481 (const :tag "Match only exact headline" t)
1482 (const :tag "Match extact headline or query to create it"
1483 query-to-create)))
1485 (defcustom org-link-frame-setup
1486 '((vm . vm-visit-folder-other-frame)
1487 (gnus . org-gnus-no-new-news)
1488 (file . find-file-other-window)
1489 (wl . wl-other-frame))
1490 "Setup the frame configuration for following links.
1491 When following a link with Emacs, it may often be useful to display
1492 this link in another window or frame. This variable can be used to
1493 set this up for the different types of links.
1494 For VM, use any of
1495 `vm-visit-folder'
1496 `vm-visit-folder-other-window'
1497 `vm-visit-folder-other-frame'
1498 For Gnus, use any of
1499 `gnus'
1500 `gnus-other-frame'
1501 `org-gnus-no-new-news'
1502 For FILE, use any of
1503 `find-file'
1504 `find-file-other-window'
1505 `find-file-other-frame'
1506 For Wanderlust use any of
1507 `wl'
1508 `wl-other-frame'
1509 For the calendar, use the variable `calendar-setup'.
1510 For BBDB, it is currently only possible to display the matches in
1511 another window."
1512 :group 'org-link-follow
1513 :type '(list
1514 (cons (const vm)
1515 (choice
1516 (const vm-visit-folder)
1517 (const vm-visit-folder-other-window)
1518 (const vm-visit-folder-other-frame)))
1519 (cons (const gnus)
1520 (choice
1521 (const gnus)
1522 (const gnus-other-frame)
1523 (const org-gnus-no-new-news)))
1524 (cons (const file)
1525 (choice
1526 (const find-file)
1527 (const find-file-other-window)
1528 (const find-file-other-frame)))
1529 (cons (const wl)
1530 (choice
1531 (const wl)
1532 (const wl-other-frame)))))
1534 (defcustom org-display-internal-link-with-indirect-buffer nil
1535 "Non-nil means use indirect buffer to display infile links.
1536 Activating internal links (from one location in a file to another location
1537 in the same file) normally just jumps to the location. When the link is
1538 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1539 is displayed in
1540 another window. When this option is set, the other window actually displays
1541 an indirect buffer clone of the current buffer, to avoid any visibility
1542 changes to the current buffer."
1543 :group 'org-link-follow
1544 :type 'boolean)
1546 (defcustom org-open-non-existing-files nil
1547 "Non-nil means `org-open-file' will open non-existing files.
1548 When nil, an error will be generated.
1549 This variable applies only to external applications because they
1550 might choke on non-existing files. If the link is to a file that
1551 will be opened in Emacs, the variable is ignored."
1552 :group 'org-link-follow
1553 :type 'boolean)
1555 (defcustom org-open-directory-means-index-dot-org nil
1556 "Non-nil means a link to a directory really means to index.org.
1557 When nil, following a directory link will run dired or open a finder/explorer
1558 window on that directory."
1559 :group 'org-link-follow
1560 :type 'boolean)
1562 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1563 "Function and arguments to call for following mailto links.
1564 This is a list with the first element being a Lisp function, and the
1565 remaining elements being arguments to the function. In string arguments,
1566 %a will be replaced by the address, and %s will be replaced by the subject
1567 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1568 :group 'org-link-follow
1569 :type '(choice
1570 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1571 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1572 (const :tag "message-mail" (message-mail "%a" "%s"))
1573 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1575 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1576 "Non-nil means ask for confirmation before executing shell links.
1577 Shell links can be dangerous: just think about a link
1579 [[shell:rm -rf ~/*][Google Search]]
1581 This link would show up in your Org-mode document as \"Google Search\",
1582 but really it would remove your entire home directory.
1583 Therefore we advise against setting this variable to nil.
1584 Just change it to `y-or-n-p' if you want to confirm with a
1585 single keystroke rather than having to type \"yes\"."
1586 :group 'org-link-follow
1587 :type '(choice
1588 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1589 (const :tag "with y-or-n (faster)" y-or-n-p)
1590 (const :tag "no confirmation (dangerous)" nil)))
1591 (put 'org-confirm-shell-link-function
1592 'safe-local-variable
1593 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1595 (defcustom org-confirm-shell-link-not-regexp ""
1596 "A regexp to skip confirmation for shell links."
1597 :group 'org-link-follow
1598 :type 'regexp)
1600 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1601 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1602 Elisp links can be dangerous: just think about a link
1604 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1606 This link would show up in your Org-mode document as \"Google Search\",
1607 but really it would remove your entire home directory.
1608 Therefore we advise against setting this variable to nil.
1609 Just change it to `y-or-n-p' if you want to confirm with a
1610 single keystroke rather than having to type \"yes\"."
1611 :group 'org-link-follow
1612 :type '(choice
1613 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1614 (const :tag "with y-or-n (faster)" y-or-n-p)
1615 (const :tag "no confirmation (dangerous)" nil)))
1616 (put 'org-confirm-shell-link-function
1617 'safe-local-variable
1618 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1620 (defcustom org-confirm-elisp-link-not-regexp ""
1621 "A regexp to skip confirmation for Elisp links."
1622 :group 'org-link-follow
1623 :type 'regexp)
1625 (defconst org-file-apps-defaults-gnu
1626 '((remote . emacs)
1627 (system . mailcap)
1628 (t . mailcap))
1629 "Default file applications on a UNIX or GNU/Linux system.
1630 See `org-file-apps'.")
1632 (defconst org-file-apps-defaults-macosx
1633 '((remote . emacs)
1634 (t . "open %s")
1635 (system . "open %s")
1636 ("ps.gz" . "gv %s")
1637 ("eps.gz" . "gv %s")
1638 ("dvi" . "xdvi %s")
1639 ("fig" . "xfig %s"))
1640 "Default file applications on a MacOS X system.
1641 The system \"open\" is known as a default, but we use X11 applications
1642 for some files for which the OS does not have a good default.
1643 See `org-file-apps'.")
1645 (defconst org-file-apps-defaults-windowsnt
1646 (list
1647 '(remote . emacs)
1648 (cons t
1649 (list (if (featurep 'xemacs)
1650 'mswindows-shell-execute
1651 'w32-shell-execute)
1652 "open" 'file))
1653 (cons 'system
1654 (list (if (featurep 'xemacs)
1655 'mswindows-shell-execute
1656 'w32-shell-execute)
1657 "open" 'file)))
1658 "Default file applications on a Windows NT system.
1659 The system \"open\" is used for most files.
1660 See `org-file-apps'.")
1662 (defcustom org-file-apps
1664 (auto-mode . emacs)
1665 ("\\.mm\\'" . default)
1666 ("\\.x?html?\\'" . default)
1667 ("\\.pdf\\'" . default)
1669 "External applications for opening `file:path' items in a document.
1670 Org-mode uses system defaults for different file types, but
1671 you can use this variable to set the application for a given file
1672 extension. The entries in this list are cons cells where the car identifies
1673 files and the cdr the corresponding command. Possible values for the
1674 file identifier are
1675 \"string\" A string as a file identifier can be interpreted in different
1676 ways, depending on its contents:
1678 - Alphanumeric characters only:
1679 Match links with this file extension.
1680 Example: (\"pdf\" . \"evince %s\")
1681 to open PDFs with evince.
1683 - Regular expression: Match links where the
1684 filename matches the regexp. If you want to
1685 use groups here, use shy groups.
1687 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1688 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1689 to open *.html and *.xhtml with firefox.
1691 - Regular expression which contains (non-shy) groups:
1692 Match links where the whole link, including \"::\", and
1693 anything after that, matches the regexp.
1694 In a custom command string, %1, %2, etc. are replaced with
1695 the parts of the link that were matched by the groups.
1696 For backwards compatibility, if a command string is given
1697 that does not use any of the group matches, this case is
1698 handled identically to the second one (i.e. match against
1699 file name only).
1700 In a custom lisp form, you can access the group matches with
1701 (match-string n link).
1703 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1704 to open [[file:document.pdf::5]] with evince at page 5.
1706 `directory' Matches a directory
1707 `remote' Matches a remote file, accessible through tramp or efs.
1708 Remote files most likely should be visited through Emacs
1709 because external applications cannot handle such paths.
1710 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1711 so all files Emacs knows how to handle. Using this with
1712 command `emacs' will open most files in Emacs. Beware that this
1713 will also open html files inside Emacs, unless you add
1714 (\"html\" . default) to the list as well.
1715 t Default for files not matched by any of the other options.
1716 `system' The system command to open files, like `open' on Windows
1717 and Mac OS X, and mailcap under GNU/Linux. This is the command
1718 that will be selected if you call `C-c C-o' with a double
1719 \\[universal-argument] \\[universal-argument] prefix.
1721 Possible values for the command are:
1722 `emacs' The file will be visited by the current Emacs process.
1723 `default' Use the default application for this file type, which is the
1724 association for t in the list, most likely in the system-specific
1725 part.
1726 This can be used to overrule an unwanted setting in the
1727 system-specific variable.
1728 `system' Use the system command for opening files, like \"open\".
1729 This command is specified by the entry whose car is `system'.
1730 Most likely, the system-specific version of this variable
1731 does define this command, but you can overrule/replace it
1732 here.
1733 string A command to be executed by a shell; %s will be replaced
1734 by the path to the file.
1735 sexp A Lisp form which will be evaluated. The file path will
1736 be available in the Lisp variable `file'.
1737 For more examples, see the system specific constants
1738 `org-file-apps-defaults-macosx'
1739 `org-file-apps-defaults-windowsnt'
1740 `org-file-apps-defaults-gnu'."
1741 :group 'org-link-follow
1742 :type '(repeat
1743 (cons (choice :value ""
1744 (string :tag "Extension")
1745 (const :tag "System command to open files" system)
1746 (const :tag "Default for unrecognized files" t)
1747 (const :tag "Remote file" remote)
1748 (const :tag "Links to a directory" directory)
1749 (const :tag "Any files that have Emacs modes"
1750 auto-mode))
1751 (choice :value ""
1752 (const :tag "Visit with Emacs" emacs)
1753 (const :tag "Use default" default)
1754 (const :tag "Use the system command" system)
1755 (string :tag "Command")
1756 (sexp :tag "Lisp form")))))
1760 (defgroup org-refile nil
1761 "Options concerning refiling entries in Org-mode."
1762 :tag "Org Refile"
1763 :group 'org)
1765 (defcustom org-directory "~/org"
1766 "Directory with org files.
1767 This is just a default location to look for Org files. There is no need
1768 at all to put your files into this directory. It is only used in the
1769 following situations:
1771 1. When a remember template specifies a target file that is not an
1772 absolute path. The path will then be interpreted relative to
1773 `org-directory'
1774 2. When a remember note is filed away in an interactive way (when exiting the
1775 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1776 with `org-directory' as the default path."
1777 :group 'org-refile
1778 :group 'org-remember
1779 :type 'directory)
1781 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1782 "Default target for storing notes.
1783 Used as a fall back file for org-remember.el and org-capture.el, for
1784 templates that do not specify a target file."
1785 :group 'org-refile
1786 :group 'org-remember
1787 :type '(choice
1788 (const :tag "Default from remember-data-file" nil)
1789 file))
1791 (defcustom org-goto-interface 'outline
1792 "The default interface to be used for `org-goto'.
1793 Allowed values are:
1794 outline The interface shows an outline of the relevant file
1795 and the correct heading is found by moving through
1796 the outline or by searching with incremental search.
1797 outline-path-completion Headlines in the current buffer are offered via
1798 completion. This is the interface also used by
1799 the refile command."
1800 :group 'org-refile
1801 :type '(choice
1802 (const :tag "Outline" outline)
1803 (const :tag "Outline-path-completion" outline-path-completion)))
1805 (defcustom org-goto-max-level 5
1806 "Maximum target level when running `org-goto' with refile interface."
1807 :group 'org-refile
1808 :type 'integer)
1810 (defcustom org-reverse-note-order nil
1811 "Non-nil means store new notes at the beginning of a file or entry.
1812 When nil, new notes will be filed to the end of a file or entry.
1813 This can also be a list with cons cells of regular expressions that
1814 are matched against file names, and values."
1815 :group 'org-remember
1816 :group 'org-refile
1817 :type '(choice
1818 (const :tag "Reverse always" t)
1819 (const :tag "Reverse never" nil)
1820 (repeat :tag "By file name regexp"
1821 (cons regexp boolean))))
1823 (defcustom org-log-refile nil
1824 "Information to record when a task is refiled.
1826 Possible values are:
1828 nil Don't add anything
1829 time Add a time stamp to the task
1830 note Prompt for a note and add it with template `org-log-note-headings'
1832 This option can also be set with on a per-file-basis with
1834 #+STARTUP: nologrefile
1835 #+STARTUP: logrefile
1836 #+STARTUP: lognoterefile
1838 You can have local logging settings for a subtree by setting the LOGGING
1839 property to one or more of these keywords.
1841 When bulk-refiling from the agenda, the value `note' is forbidden and
1842 will temporarily be changed to `time'."
1843 :group 'org-refile
1844 :group 'org-progress
1845 :type '(choice
1846 (const :tag "No logging" nil)
1847 (const :tag "Record timestamp" time)
1848 (const :tag "Record timestamp with note." note)))
1850 (defcustom org-refile-targets nil
1851 "Targets for refiling entries with \\[org-refile].
1852 This is list of cons cells. Each cell contains:
1853 - a specification of the files to be considered, either a list of files,
1854 or a symbol whose function or variable value will be used to retrieve
1855 a file name or a list of file names. If you use `org-agenda-files' for
1856 that, all agenda files will be scanned for targets. Nil means consider
1857 headings in the current buffer.
1858 - A specification of how to find candidate refile targets. This may be
1859 any of:
1860 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1861 This tag has to be present in all target headlines, inheritance will
1862 not be considered.
1863 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1864 todo keyword.
1865 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1866 headlines that are refiling targets.
1867 - a cons cell (:level . N). Any headline of level N is considered a target.
1868 Note that, when `org-odd-levels-only' is set, level corresponds to
1869 order in hierarchy, not to the number of stars.
1870 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1871 Note that, when `org-odd-levels-only' is set, level corresponds to
1872 order in hierarchy, not to the number of stars.
1874 You can set the variable `org-refile-target-verify-function' to a function
1875 to verify each headline found by the simple criteria above.
1877 When this variable is nil, all top-level headlines in the current buffer
1878 are used, equivalent to the value `((nil . (:level . 1))'."
1879 :group 'org-refile
1880 :type '(repeat
1881 (cons
1882 (choice :value org-agenda-files
1883 (const :tag "All agenda files" org-agenda-files)
1884 (const :tag "Current buffer" nil)
1885 (function) (variable) (file))
1886 (choice :tag "Identify target headline by"
1887 (cons :tag "Specific tag" (const :value :tag) (string))
1888 (cons :tag "TODO keyword" (const :value :todo) (string))
1889 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1890 (cons :tag "Level number" (const :value :level) (integer))
1891 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1893 (defcustom org-refile-target-verify-function nil
1894 "Function to verify if the headline at point should be a refile target.
1895 The function will be called without arguments, with point at the
1896 beginning of the headline. It should return t and leave point
1897 where it is if the headline is a valid target for refiling.
1899 If the target should not be selected, the function must return nil.
1900 In addition to this, it may move point to a place from where the search
1901 should be continued. For example, the function may decide that the entire
1902 subtree of the current entry should be excluded and move point to the end
1903 of the subtree."
1904 :group 'org-refile
1905 :type 'function)
1907 (defcustom org-refile-use-cache nil
1908 "Non-nil means cache refile targets to speed up the process.
1909 The cache for a particular file will be updated automatically when
1910 the buffer has been killed, or when any of the marker used for flagging
1911 refile targets no longer points at a live buffer.
1912 If you have added new entries to a buffer that might themselves be targets,
1913 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1914 find that easier, `C-u C-u C-u C-c C-w'."
1915 :group 'org-refile
1916 :type 'boolean)
1918 (defcustom org-refile-use-outline-path nil
1919 "Non-nil means provide refile targets as paths.
1920 So a level 3 headline will be available as level1/level2/level3.
1922 When the value is `file', also include the file name (without directory)
1923 into the path. In this case, you can also stop the completion after
1924 the file name, to get entries inserted as top level in the file.
1926 When `full-file-path', include the full file path."
1927 :group 'org-refile
1928 :type '(choice
1929 (const :tag "Not" nil)
1930 (const :tag "Yes" t)
1931 (const :tag "Start with file name" file)
1932 (const :tag "Start with full file path" full-file-path)))
1934 (defcustom org-outline-path-complete-in-steps t
1935 "Non-nil means complete the outline path in hierarchical steps.
1936 When Org-mode uses the refile interface to select an outline path
1937 \(see variable `org-refile-use-outline-path'), the completion of
1938 the path can be done is a single go, or if can be done in steps down
1939 the headline hierarchy. Going in steps is probably the best if you
1940 do not use a special completion package like `ido' or `icicles'.
1941 However, when using these packages, going in one step can be very
1942 fast, while still showing the whole path to the entry."
1943 :group 'org-refile
1944 :type 'boolean)
1946 (defcustom org-refile-allow-creating-parent-nodes nil
1947 "Non-nil means allow to create new nodes as refile targets.
1948 New nodes are then created by adding \"/new node name\" to the completion
1949 of an existing node. When the value of this variable is `confirm',
1950 new node creation must be confirmed by the user (recommended)
1951 When nil, the completion must match an existing entry.
1953 Note that, if the new heading is not seen by the criteria
1954 listed in `org-refile-targets', multiple instances of the same
1955 heading would be created by trying again to file under the new
1956 heading."
1957 :group 'org-refile
1958 :type '(choice
1959 (const :tag "Never" nil)
1960 (const :tag "Always" t)
1961 (const :tag "Prompt for confirmation" confirm)))
1963 (defgroup org-todo nil
1964 "Options concerning TODO items in Org-mode."
1965 :tag "Org TODO"
1966 :group 'org)
1968 (defgroup org-progress nil
1969 "Options concerning Progress logging in Org-mode."
1970 :tag "Org Progress"
1971 :group 'org-time)
1973 (defvar org-todo-interpretation-widgets
1975 (:tag "Sequence (cycling hits every state)" sequence)
1976 (:tag "Type (cycling directly to DONE)" type))
1977 "The available interpretation symbols for customizing `org-todo-keywords'.
1978 Interested libraries should add to this list.")
1980 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1981 "List of TODO entry keyword sequences and their interpretation.
1982 \\<org-mode-map>This is a list of sequences.
1984 Each sequence starts with a symbol, either `sequence' or `type',
1985 indicating if the keywords should be interpreted as a sequence of
1986 action steps, or as different types of TODO items. The first
1987 keywords are states requiring action - these states will select a headline
1988 for inclusion into the global TODO list Org-mode produces. If one of
1989 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
1990 signify that no further action is necessary. If \"|\" is not found,
1991 the last keyword is treated as the only DONE state of the sequence.
1993 The command \\[org-todo] cycles an entry through these states, and one
1994 additional state where no keyword is present. For details about this
1995 cycling, see the manual.
1997 TODO keywords and interpretation can also be set on a per-file basis with
1998 the special #+SEQ_TODO and #+TYP_TODO lines.
2000 Each keyword can optionally specify a character for fast state selection
2001 \(in combination with the variable `org-use-fast-todo-selection')
2002 and specifiers for state change logging, using the same syntax
2003 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2004 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2005 indicates to record a time stamp each time this state is selected.
2007 Each keyword may also specify if a timestamp or a note should be
2008 recorded when entering or leaving the state, by adding additional
2009 characters in the parenthesis after the keyword. This looks like this:
2010 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2011 record only the time of the state change. With X and Y being either
2012 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2013 Y when leaving the state if and only if the *target* state does not
2014 define X. You may omit any of the fast-selection key or X or /Y,
2015 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2017 For backward compatibility, this variable may also be just a list
2018 of keywords - in this case the interpretation (sequence or type) will be
2019 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2020 :group 'org-todo
2021 :group 'org-keywords
2022 :type '(choice
2023 (repeat :tag "Old syntax, just keywords"
2024 (string :tag "Keyword"))
2025 (repeat :tag "New syntax"
2026 (cons
2027 (choice
2028 :tag "Interpretation"
2029 ;;Quick and dirty way to see
2030 ;;`org-todo-interpretations'. This takes the
2031 ;;place of item arguments
2032 :convert-widget
2033 (lambda (widget)
2034 (widget-put widget
2035 :args (mapcar
2036 #'(lambda (x)
2037 (widget-convert
2038 (cons 'const x)))
2039 org-todo-interpretation-widgets))
2040 widget))
2041 (repeat
2042 (string :tag "Keyword"))))))
2044 (defvar org-todo-keywords-1 nil
2045 "All TODO and DONE keywords active in a buffer.")
2046 (make-variable-buffer-local 'org-todo-keywords-1)
2047 (defvar org-todo-keywords-for-agenda nil)
2048 (defvar org-done-keywords-for-agenda nil)
2049 (defvar org-drawers-for-agenda nil)
2050 (defvar org-todo-keyword-alist-for-agenda nil)
2051 (defvar org-tag-alist-for-agenda nil)
2052 (defvar org-agenda-contributing-files nil)
2053 (defvar org-not-done-keywords nil)
2054 (make-variable-buffer-local 'org-not-done-keywords)
2055 (defvar org-done-keywords nil)
2056 (make-variable-buffer-local 'org-done-keywords)
2057 (defvar org-todo-heads nil)
2058 (make-variable-buffer-local 'org-todo-heads)
2059 (defvar org-todo-sets nil)
2060 (make-variable-buffer-local 'org-todo-sets)
2061 (defvar org-todo-log-states nil)
2062 (make-variable-buffer-local 'org-todo-log-states)
2063 (defvar org-todo-kwd-alist nil)
2064 (make-variable-buffer-local 'org-todo-kwd-alist)
2065 (defvar org-todo-key-alist nil)
2066 (make-variable-buffer-local 'org-todo-key-alist)
2067 (defvar org-todo-key-trigger nil)
2068 (make-variable-buffer-local 'org-todo-key-trigger)
2070 (defcustom org-todo-interpretation 'sequence
2071 "Controls how TODO keywords are interpreted.
2072 This variable is in principle obsolete and is only used for
2073 backward compatibility, if the interpretation of todo keywords is
2074 not given already in `org-todo-keywords'. See that variable for
2075 more information."
2076 :group 'org-todo
2077 :group 'org-keywords
2078 :type '(choice (const sequence)
2079 (const type)))
2081 (defcustom org-use-fast-todo-selection t
2082 "Non-nil means use the fast todo selection scheme with C-c C-t.
2083 This variable describes if and under what circumstances the cycling
2084 mechanism for TODO keywords will be replaced by a single-key, direct
2085 selection scheme.
2087 When nil, fast selection is never used.
2089 When the symbol `prefix', it will be used when `org-todo' is called with
2090 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2091 in an agenda buffer.
2093 When t, fast selection is used by default. In this case, the prefix
2094 argument forces cycling instead.
2096 In all cases, the special interface is only used if access keys have actually
2097 been assigned by the user, i.e. if keywords in the configuration are followed
2098 by a letter in parenthesis, like TODO(t)."
2099 :group 'org-todo
2100 :type '(choice
2101 (const :tag "Never" nil)
2102 (const :tag "By default" t)
2103 (const :tag "Only with C-u C-c C-t" prefix)))
2105 (defcustom org-provide-todo-statistics t
2106 "Non-nil means update todo statistics after insert and toggle.
2107 ALL-HEADLINES means update todo statistics by including headlines
2108 with no TODO keyword as well, counting them as not done.
2109 A list of TODO keywords means the same, but skip keywords that are
2110 not in this list.
2112 When this is set, todo statistics is updated in the parent of the
2113 current entry each time a todo state is changed."
2114 :group 'org-todo
2115 :type '(choice
2116 (const :tag "Yes, only for TODO entries" t)
2117 (const :tag "Yes, including all entries" 'all-headlines)
2118 (repeat :tag "Yes, for TODOs in this list"
2119 (string :tag "TODO keyword"))
2120 (other :tag "No TODO statistics" nil)))
2122 (defcustom org-hierarchical-todo-statistics t
2123 "Non-nil means TODO statistics covers just direct children.
2124 When nil, all entries in the subtree are considered.
2125 This has only an effect if `org-provide-todo-statistics' is set.
2126 To set this to nil for only a single subtree, use a COOKIE_DATA
2127 property and include the word \"recursive\" into the value."
2128 :group 'org-todo
2129 :type 'boolean)
2131 (defcustom org-after-todo-state-change-hook nil
2132 "Hook which is run after the state of a TODO item was changed.
2133 The new state (a string with a TODO keyword, or nil) is available in the
2134 Lisp variable `state'."
2135 :group 'org-todo
2136 :type 'hook)
2138 (defvar org-blocker-hook nil
2139 "Hook for functions that are allowed to block a state change.
2141 Each function gets as its single argument a property list, see
2142 `org-trigger-hook' for more information about this list.
2144 If any of the functions in this hook returns nil, the state change
2145 is blocked.")
2147 (defvar org-trigger-hook nil
2148 "Hook for functions that are triggered by a state change.
2150 Each function gets as its single argument a property list with at least
2151 the following elements:
2153 (:type type-of-change :position pos-at-entry-start
2154 :from old-state :to new-state)
2156 Depending on the type, more properties may be present.
2158 This mechanism is currently implemented for:
2160 TODO state changes
2161 ------------------
2162 :type todo-state-change
2163 :from previous state (keyword as a string), or nil, or a symbol
2164 'todo' or 'done', to indicate the general type of state.
2165 :to new state, like in :from")
2167 (defcustom org-enforce-todo-dependencies nil
2168 "Non-nil means undone TODO entries will block switching the parent to DONE.
2169 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2170 be blocked if any prior sibling is not yet done.
2171 Finally, if the parent is blocked because of ordered siblings of its own,
2172 the child will also be blocked.
2173 This variable needs to be set before org.el is loaded, and you need to
2174 restart Emacs after a change to make the change effective. The only way
2175 to change is while Emacs is running is through the customize interface."
2176 :set (lambda (var val)
2177 (set var val)
2178 (if val
2179 (add-hook 'org-blocker-hook
2180 'org-block-todo-from-children-or-siblings-or-parent)
2181 (remove-hook 'org-blocker-hook
2182 'org-block-todo-from-children-or-siblings-or-parent)))
2183 :group 'org-todo
2184 :type 'boolean)
2186 (defcustom org-enforce-todo-checkbox-dependencies nil
2187 "Non-nil means unchecked boxes will block switching the parent to DONE.
2188 When this is nil, checkboxes have no influence on switching TODO states.
2189 When non-nil, you first need to check off all check boxes before the TODO
2190 entry can be switched to DONE.
2191 This variable needs to be set before org.el is loaded, and you need to
2192 restart Emacs after a change to make the change effective. The only way
2193 to change is while Emacs is running is through the customize interface."
2194 :set (lambda (var val)
2195 (set var val)
2196 (if val
2197 (add-hook 'org-blocker-hook
2198 'org-block-todo-from-checkboxes)
2199 (remove-hook 'org-blocker-hook
2200 'org-block-todo-from-checkboxes)))
2201 :group 'org-todo
2202 :type 'boolean)
2204 (defcustom org-treat-insert-todo-heading-as-state-change nil
2205 "Non-nil means inserting a TODO heading is treated as state change.
2206 So when the command \\[org-insert-todo-heading] is used, state change
2207 logging will apply if appropriate. When nil, the new TODO item will
2208 be inserted directly, and no logging will take place."
2209 :group 'org-todo
2210 :type 'boolean)
2212 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2213 "Non-nil means switching TODO states with S-cursor counts as state change.
2214 This is the default behavior. However, setting this to nil allows a
2215 convenient way to select a TODO state and bypass any logging associated
2216 with that."
2217 :group 'org-todo
2218 :type 'boolean)
2220 (defcustom org-todo-state-tags-triggers nil
2221 "Tag changes that should be triggered by TODO state changes.
2222 This is a list. Each entry is
2224 (state-change (tag . flag) .......)
2226 State-change can be a string with a state, and empty string to indicate the
2227 state that has no TODO keyword, or it can be one of the symbols `todo'
2228 or `done', meaning any not-done or done state, respectively."
2229 :group 'org-todo
2230 :group 'org-tags
2231 :type '(repeat
2232 (cons (choice :tag "When changing to"
2233 (const :tag "Not-done state" todo)
2234 (const :tag "Done state" done)
2235 (string :tag "State"))
2236 (repeat
2237 (cons :tag "Tag action"
2238 (string :tag "Tag")
2239 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2241 (defcustom org-log-done nil
2242 "Information to record when a task moves to the DONE state.
2244 Possible values are:
2246 nil Don't add anything, just change the keyword
2247 time Add a time stamp to the task
2248 note Prompt for a note and add it with template `org-log-note-headings'
2250 This option can also be set with on a per-file-basis with
2252 #+STARTUP: nologdone
2253 #+STARTUP: logdone
2254 #+STARTUP: lognotedone
2256 You can have local logging settings for a subtree by setting the LOGGING
2257 property to one or more of these keywords."
2258 :group 'org-todo
2259 :group 'org-progress
2260 :type '(choice
2261 (const :tag "No logging" nil)
2262 (const :tag "Record CLOSED timestamp" time)
2263 (const :tag "Record CLOSED timestamp with note." note)))
2265 ;; Normalize old uses of org-log-done.
2266 (cond
2267 ((eq org-log-done t) (setq org-log-done 'time))
2268 ((and (listp org-log-done) (memq 'done org-log-done))
2269 (setq org-log-done 'note)))
2271 (defcustom org-log-reschedule nil
2272 "Information to record when the scheduling date of a tasks is modified.
2274 Possible values are:
2276 nil Don't add anything, just change the date
2277 time Add a time stamp to the task
2278 note Prompt for a note and add it with template `org-log-note-headings'
2280 This option can also be set with on a per-file-basis with
2282 #+STARTUP: nologreschedule
2283 #+STARTUP: logreschedule
2284 #+STARTUP: lognotereschedule"
2285 :group 'org-todo
2286 :group 'org-progress
2287 :type '(choice
2288 (const :tag "No logging" nil)
2289 (const :tag "Record timestamp" time)
2290 (const :tag "Record timestamp with note." note)))
2292 (defcustom org-log-redeadline nil
2293 "Information to record when the deadline date of a tasks is modified.
2295 Possible values are:
2297 nil Don't add anything, just change the date
2298 time Add a time stamp to the task
2299 note Prompt for a note and add it with template `org-log-note-headings'
2301 This option can also be set with on a per-file-basis with
2303 #+STARTUP: nologredeadline
2304 #+STARTUP: logredeadline
2305 #+STARTUP: lognoteredeadline
2307 You can have local logging settings for a subtree by setting the LOGGING
2308 property to one or more of these keywords."
2309 :group 'org-todo
2310 :group 'org-progress
2311 :type '(choice
2312 (const :tag "No logging" nil)
2313 (const :tag "Record timestamp" time)
2314 (const :tag "Record timestamp with note." note)))
2316 (defcustom org-log-note-clock-out nil
2317 "Non-nil means record a note when clocking out of an item.
2318 This can also be configured on a per-file basis by adding one of
2319 the following lines anywhere in the buffer:
2321 #+STARTUP: lognoteclock-out
2322 #+STARTUP: nolognoteclock-out"
2323 :group 'org-todo
2324 :group 'org-progress
2325 :type 'boolean)
2327 (defcustom org-log-done-with-time t
2328 "Non-nil means the CLOSED time stamp will contain date and time.
2329 When nil, only the date will be recorded."
2330 :group 'org-progress
2331 :type 'boolean)
2333 (defcustom org-log-note-headings
2334 '((done . "CLOSING NOTE %t")
2335 (state . "State %-12s from %-12S %t")
2336 (note . "Note taken on %t")
2337 (reschedule . "Rescheduled from %S on %t")
2338 (delschedule . "Not scheduled, was %S on %t")
2339 (redeadline . "New deadline from %S on %t")
2340 (deldeadline . "Removed deadline, was %S on %t")
2341 (refile . "Refiled on %t")
2342 (clock-out . ""))
2343 "Headings for notes added to entries.
2344 The value is an alist, with the car being a symbol indicating the note
2345 context, and the cdr is the heading to be used. The heading may also be the
2346 empty string.
2347 %t in the heading will be replaced by a time stamp.
2348 %T will be an active time stamp instead the default inactive one
2349 %s will be replaced by the new TODO state, in double quotes.
2350 %S will be replaced by the old TODO state, in double quotes.
2351 %u will be replaced by the user name.
2352 %U will be replaced by the full user name.
2354 In fact, it is not a good idea to change the `state' entry, because
2355 agenda log mode depends on the format of these entries."
2356 :group 'org-todo
2357 :group 'org-progress
2358 :type '(list :greedy t
2359 (cons (const :tag "Heading when closing an item" done) string)
2360 (cons (const :tag
2361 "Heading when changing todo state (todo sequence only)"
2362 state) string)
2363 (cons (const :tag "Heading when just taking a note" note) string)
2364 (cons (const :tag "Heading when clocking out" clock-out) string)
2365 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2366 (cons (const :tag "Heading when rescheduling" reschedule) string)
2367 (cons (const :tag "Heading when changing deadline" redeadline) string)
2368 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2369 (cons (const :tag "Heading when refiling" refile) string)))
2371 (unless (assq 'note org-log-note-headings)
2372 (push '(note . "%t") org-log-note-headings))
2374 (defcustom org-log-into-drawer nil
2375 "Non-nil means insert state change notes and time stamps into a drawer.
2376 When nil, state changes notes will be inserted after the headline and
2377 any scheduling and clock lines, but not inside a drawer.
2379 The value of this variable should be the name of the drawer to use.
2380 LOGBOOK is proposed as the default drawer for this purpose, you can
2381 also set this to a string to define the drawer of your choice.
2383 A value of t is also allowed, representing \"LOGBOOK\".
2385 If this variable is set, `org-log-state-notes-insert-after-drawers'
2386 will be ignored.
2388 You can set the property LOG_INTO_DRAWER to overrule this setting for
2389 a subtree."
2390 :group 'org-todo
2391 :group 'org-progress
2392 :type '(choice
2393 (const :tag "Not into a drawer" nil)
2394 (const :tag "LOGBOOK" t)
2395 (string :tag "Other")))
2397 (if (fboundp 'defvaralias)
2398 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2400 (defun org-log-into-drawer ()
2401 "Return the value of `org-log-into-drawer', but let properties overrule.
2402 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2403 used instead of the default value."
2404 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2405 (cond
2406 ((or (not p) (equal p "nil")) org-log-into-drawer)
2407 ((equal p "t") "LOGBOOK")
2408 (t p))))
2410 (defcustom org-log-state-notes-insert-after-drawers nil
2411 "Non-nil means insert state change notes after any drawers in entry.
2412 Only the drawers that *immediately* follow the headline and the
2413 deadline/scheduled line are skipped.
2414 When nil, insert notes right after the heading and perhaps the line
2415 with deadline/scheduling if present.
2417 This variable will have no effect if `org-log-into-drawer' is
2418 set."
2419 :group 'org-todo
2420 :group 'org-progress
2421 :type 'boolean)
2423 (defcustom org-log-states-order-reversed t
2424 "Non-nil means the latest state note will be directly after heading.
2425 When nil, the state change notes will be ordered according to time."
2426 :group 'org-todo
2427 :group 'org-progress
2428 :type 'boolean)
2430 (defcustom org-todo-repeat-to-state nil
2431 "The TODO state to which a repeater should return the repeating task.
2432 By default this is the first task in a TODO sequence, or the previous state
2433 in a TODO_TYP set. But you can specify another task here.
2434 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2435 :group 'org-todo
2436 :type '(choice (const :tag "Head of sequence" nil)
2437 (string :tag "Specific state")))
2439 (defcustom org-log-repeat 'time
2440 "Non-nil means record moving through the DONE state when triggering repeat.
2441 An auto-repeating task is immediately switched back to TODO when
2442 marked DONE. If you are not logging state changes (by adding \"@\"
2443 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2444 record a closing note, there will be no record of the task moving
2445 through DONE. This variable forces taking a note anyway.
2447 nil Don't force a record
2448 time Record a time stamp
2449 note Record a note
2451 This option can also be set with on a per-file-basis with
2453 #+STARTUP: logrepeat
2454 #+STARTUP: lognoterepeat
2455 #+STARTUP: nologrepeat
2457 You can have local logging settings for a subtree by setting the LOGGING
2458 property to one or more of these keywords."
2459 :group 'org-todo
2460 :group 'org-progress
2461 :type '(choice
2462 (const :tag "Don't force a record" nil)
2463 (const :tag "Force recording the DONE state" time)
2464 (const :tag "Force recording a note with the DONE state" note)))
2467 (defgroup org-priorities nil
2468 "Priorities in Org-mode."
2469 :tag "Org Priorities"
2470 :group 'org-todo)
2472 (defcustom org-enable-priority-commands t
2473 "Non-nil means priority commands are active.
2474 When nil, these commands will be disabled, so that you never accidentally
2475 set a priority."
2476 :group 'org-priorities
2477 :type 'boolean)
2479 (defcustom org-highest-priority ?A
2480 "The highest priority of TODO items. A character like ?A, ?B etc.
2481 Must have a smaller ASCII number than `org-lowest-priority'."
2482 :group 'org-priorities
2483 :type 'character)
2485 (defcustom org-lowest-priority ?C
2486 "The lowest priority of TODO items. A character like ?A, ?B etc.
2487 Must have a larger ASCII number than `org-highest-priority'."
2488 :group 'org-priorities
2489 :type 'character)
2491 (defcustom org-default-priority ?B
2492 "The default priority of TODO items.
2493 This is the priority an item gets if no explicit priority is given.
2494 When starting to cycle on an empty priority the first step in the cycle
2495 depends on `org-priority-start-cycle-with-default'. The resulting first
2496 step priority must not exceed the range from `org-highest-priority' to
2497 `org-lowest-priority' which means that `org-default-priority' has to be
2498 in this range exclusive or inclusive the range boundaries. Else the
2499 first step refuses to set the default and the second will fall back
2500 to (depending on the command used) the highest or lowest priority."
2501 :group 'org-priorities
2502 :type 'character)
2504 (defcustom org-priority-start-cycle-with-default t
2505 "Non-nil means start with default priority when starting to cycle.
2506 When this is nil, the first step in the cycle will be (depending on the
2507 command used) one higher or lower than the default priority.
2508 See also `org-default-priority'."
2509 :group 'org-priorities
2510 :type 'boolean)
2512 (defcustom org-get-priority-function nil
2513 "Function to extract the priority from a string.
2514 The string is normally the headline. If this is nil Org computes the
2515 priority from the priority cookie like [#A] in the headline. It returns
2516 an integer, increasing by 1000 for each priority level.
2517 The user can set a different function here, which should take a string
2518 as an argument and return the numeric priority."
2519 :group 'org-priorities
2520 :type 'function)
2522 (defgroup org-time nil
2523 "Options concerning time stamps and deadlines in Org-mode."
2524 :tag "Org Time"
2525 :group 'org)
2527 (defcustom org-insert-labeled-timestamps-at-point nil
2528 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2529 When nil, these labeled time stamps are forces into the second line of an
2530 entry, just after the headline. When scheduling from the global TODO list,
2531 the time stamp will always be forced into the second line."
2532 :group 'org-time
2533 :type 'boolean)
2535 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2536 "Formats for `format-time-string' which are used for time stamps.
2537 It is not recommended to change this constant.")
2539 (defcustom org-time-stamp-rounding-minutes '(0 5)
2540 "Number of minutes to round time stamps to.
2541 These are two values, the first applies when first creating a time stamp.
2542 The second applies when changing it with the commands `S-up' and `S-down'.
2543 When changing the time stamp, this means that it will change in steps
2544 of N minutes, as given by the second value.
2546 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2547 numbers should be factors of 60, so for example 5, 10, 15.
2549 When this is larger than 1, you can still force an exact time stamp by using
2550 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2551 and by using a prefix arg to `S-up/down' to specify the exact number
2552 of minutes to shift."
2553 :group 'org-time
2554 :get #'(lambda (var) ; Make sure both elements are there
2555 (if (integerp (default-value var))
2556 (list (default-value var) 5)
2557 (default-value var)))
2558 :type '(list
2559 (integer :tag "when inserting times")
2560 (integer :tag "when modifying times")))
2562 ;; Normalize old customizations of this variable.
2563 (when (integerp org-time-stamp-rounding-minutes)
2564 (setq org-time-stamp-rounding-minutes
2565 (list org-time-stamp-rounding-minutes
2566 org-time-stamp-rounding-minutes)))
2568 (defcustom org-display-custom-times nil
2569 "Non-nil means overlay custom formats over all time stamps.
2570 The formats are defined through the variable `org-time-stamp-custom-formats'.
2571 To turn this on on a per-file basis, insert anywhere in the file:
2572 #+STARTUP: customtime"
2573 :group 'org-time
2574 :set 'set-default
2575 :type 'sexp)
2576 (make-variable-buffer-local 'org-display-custom-times)
2578 (defcustom org-time-stamp-custom-formats
2579 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2580 "Custom formats for time stamps. See `format-time-string' for the syntax.
2581 These are overlayed over the default ISO format if the variable
2582 `org-display-custom-times' is set. Time like %H:%M should be at the
2583 end of the second format. The custom formats are also honored by export
2584 commands, if custom time display is turned on at the time of export."
2585 :group 'org-time
2586 :type 'sexp)
2588 (defun org-time-stamp-format (&optional long inactive)
2589 "Get the right format for a time string."
2590 (let ((f (if long (cdr org-time-stamp-formats)
2591 (car org-time-stamp-formats))))
2592 (if inactive
2593 (concat "[" (substring f 1 -1) "]")
2594 f)))
2596 (defcustom org-time-clocksum-format "%d:%02d"
2597 "The format string used when creating CLOCKSUM lines.
2598 This is also used when org-mode generates a time duration."
2599 :group 'org-time
2600 :type 'string)
2602 (defcustom org-time-clocksum-use-fractional nil
2603 "If non-nil, \\[org-clock-display] uses fractional times.
2604 org-mode generates a time duration."
2605 :group 'org-time
2606 :type 'boolean)
2608 (defcustom org-time-clocksum-fractional-format "%.2f"
2609 "The format string used when creating CLOCKSUM lines, or when
2610 org-mode generates a time duration."
2611 :group 'org-time
2612 :type 'string)
2614 (defcustom org-deadline-warning-days 14
2615 "No. of days before expiration during which a deadline becomes active.
2616 This variable governs the display in sparse trees and in the agenda.
2617 When 0 or negative, it means use this number (the absolute value of it)
2618 even if a deadline has a different individual lead time specified.
2620 Custom commands can set this variable in the options section."
2621 :group 'org-time
2622 :group 'org-agenda-daily/weekly
2623 :type 'integer)
2625 (defcustom org-read-date-prefer-future t
2626 "Non-nil means assume future for incomplete date input from user.
2627 This affects the following situations:
2628 1. The user gives a month but not a year.
2629 For example, if it is April and you enter \"feb 2\", this will be read
2630 as Feb 2, *next* year. \"May 5\", however, will be this year.
2631 2. The user gives a day, but no month.
2632 For example, if today is the 15th, and you enter \"3\", Org-mode will
2633 read this as the third of *next* month. However, if you enter \"17\",
2634 it will be considered as *this* month.
2636 If you set this variable to the symbol `time', then also the following
2637 will work:
2639 3. If the user gives a time, but no day. If the time is before now,
2640 to will be interpreted as tomorrow.
2642 Currently none of this works for ISO week specifications.
2644 When this option is nil, the current day, month and year will always be
2645 used as defaults.
2647 See also `org-agenda-jump-prefer-future'."
2648 :group 'org-time
2649 :type '(choice
2650 (const :tag "Never" nil)
2651 (const :tag "Check month and day" t)
2652 (const :tag "Check month, day, and time" time)))
2654 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2655 "Should the agenda jump command prefer the future for incomplete dates?
2656 The default is to do the same as configured in `org-read-date-prefer-future'.
2657 But you can also set a deviating value here.
2658 This may t or nil, or the symbol `org-read-date-prefer-future'."
2659 :group 'org-agenda
2660 :group 'org-time
2661 :type '(choice
2662 (const :tag "Use org-read-date-prefer-future"
2663 org-read-date-prefer-future)
2664 (const :tag "Never" nil)
2665 (const :tag "Always" t)))
2667 (defcustom org-read-date-force-compatible-dates t
2668 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2670 Depending on the system Emacs is running on, certain dates cannot
2671 be represented with the type used internally to represent time.
2672 Dates between 1970-1-1 and 2038-1-1 can always be represented
2673 correctly. Some systems allow for earlier dates, some for later,
2674 some for both. One way to find out it to insert any date into an
2675 Org buffer, putting the cursor on the year and hitting S-up and
2676 S-down to test the range.
2678 When this variable is set to t, the date/time prompt will not let
2679 you specify dates outside the 1970-2037 range, so it is certain that
2680 these dates will work in whatever version of Emacs you are
2681 running, and also that you can move a file from one Emacs implementation
2682 to another. WHenever Org is forcing the year for you, it will display
2683 a message and beep.
2685 When this variable is nil, Org will check if the date is
2686 representable in the specific Emacs implementation you are using.
2687 If not, it will force a year, usually the current year, and beep
2688 to remind you. Currently this setting is not recommended because
2689 the likelihood that you will open your Org files in an Emacs that
2690 has limited date range is not negligible.
2692 A workaround for this problem is to use diary sexp dates for time
2693 stamps outside of this range."
2694 :group 'org-time
2695 :type 'boolean)
2697 (defcustom org-read-date-display-live t
2698 "Non-nil means display current interpretation of date prompt live.
2699 This display will be in an overlay, in the minibuffer."
2700 :group 'org-time
2701 :type 'boolean)
2703 (defcustom org-read-date-popup-calendar t
2704 "Non-nil means pop up a calendar when prompting for a date.
2705 In the calendar, the date can be selected with mouse-1. However, the
2706 minibuffer will also be active, and you can simply enter the date as well.
2707 When nil, only the minibuffer will be available."
2708 :group 'org-time
2709 :type 'boolean)
2710 (if (fboundp 'defvaralias)
2711 (defvaralias 'org-popup-calendar-for-date-prompt
2712 'org-read-date-popup-calendar))
2714 (defcustom org-read-date-minibuffer-setup-hook nil
2715 "Hook to be used to set up keys for the date/time interface.
2716 Add key definitions to `minibuffer-local-map', which will be a temporary
2717 copy."
2718 :group 'org-time
2719 :type 'hook)
2721 (defcustom org-extend-today-until 0
2722 "The hour when your day really ends. Must be an integer.
2723 This has influence for the following applications:
2724 - When switching the agenda to \"today\". It it is still earlier than
2725 the time given here, the day recognized as TODAY is actually yesterday.
2726 - When a date is read from the user and it is still before the time given
2727 here, the current date and time will be assumed to be yesterday, 23:59.
2728 Also, timestamps inserted in remember templates follow this rule.
2730 IMPORTANT: This is a feature whose implementation is and likely will
2731 remain incomplete. Really, it is only here because past midnight seems to
2732 be the favorite working time of John Wiegley :-)"
2733 :group 'org-time
2734 :type 'integer)
2736 (defcustom org-edit-timestamp-down-means-later nil
2737 "Non-nil means S-down will increase the time in a time stamp.
2738 When nil, S-up will increase."
2739 :group 'org-time
2740 :type 'boolean)
2742 (defcustom org-calendar-follow-timestamp-change t
2743 "Non-nil means make the calendar window follow timestamp changes.
2744 When a timestamp is modified and the calendar window is visible, it will be
2745 moved to the new date."
2746 :group 'org-time
2747 :type 'boolean)
2749 (defgroup org-tags nil
2750 "Options concerning tags in Org-mode."
2751 :tag "Org Tags"
2752 :group 'org)
2754 (defcustom org-tag-alist nil
2755 "List of tags allowed in Org-mode files.
2756 When this list is nil, Org-mode will base TAG input on what is already in the
2757 buffer.
2758 The value of this variable is an alist, the car of each entry must be a
2759 keyword as a string, the cdr may be a character that is used to select
2760 that tag through the fast-tag-selection interface.
2761 See the manual for details."
2762 :group 'org-tags
2763 :type '(repeat
2764 (choice
2765 (cons (string :tag "Tag name")
2766 (character :tag "Access char"))
2767 (list :tag "Start radio group"
2768 (const :startgroup)
2769 (option (string :tag "Group description")))
2770 (list :tag "End radio group"
2771 (const :endgroup)
2772 (option (string :tag "Group description")))
2773 (const :tag "New line" (:newline)))))
2775 (defcustom org-tag-persistent-alist nil
2776 "List of tags that will always appear in all Org-mode files.
2777 This is in addition to any in buffer settings or customizations
2778 of `org-tag-alist'.
2779 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2780 The value of this variable is an alist, the car of each entry must be a
2781 keyword as a string, the cdr may be a character that is used to select
2782 that tag through the fast-tag-selection interface.
2783 See the manual for details.
2784 To disable these tags on a per-file basis, insert anywhere in the file:
2785 #+STARTUP: noptag"
2786 :group 'org-tags
2787 :type '(repeat
2788 (choice
2789 (cons (string :tag "Tag name")
2790 (character :tag "Access char"))
2791 (const :tag "Start radio group" (:startgroup))
2792 (const :tag "End radio group" (:endgroup))
2793 (const :tag "New line" (:newline)))))
2795 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2796 "If non-nil, always offer completion for all tags of all agenda files.
2797 Instead of customizing this variable directly, you might want to
2798 set it locally for capture buffers, because there no list of
2799 tags in that file can be created dynamically (there are none).
2801 (add-hook 'org-capture-mode-hook
2802 (lambda ()
2803 (set (make-local-variable
2804 'org-complete-tags-always-offer-all-agenda-tags)
2805 t)))"
2806 :group 'org-tags
2807 :type 'boolean)
2809 (defvar org-file-tags nil
2810 "List of tags that can be inherited by all entries in the file.
2811 The tags will be inherited if the variable `org-use-tag-inheritance'
2812 says they should be.
2813 This variable is populated from #+FILETAGS lines.")
2815 (defcustom org-use-fast-tag-selection 'auto
2816 "Non-nil means use fast tag selection scheme.
2817 This is a special interface to select and deselect tags with single keys.
2818 When nil, fast selection is never used.
2819 When the symbol `auto', fast selection is used if and only if selection
2820 characters for tags have been configured, either through the variable
2821 `org-tag-alist' or through a #+TAGS line in the buffer.
2822 When t, fast selection is always used and selection keys are assigned
2823 automatically if necessary."
2824 :group 'org-tags
2825 :type '(choice
2826 (const :tag "Always" t)
2827 (const :tag "Never" nil)
2828 (const :tag "When selection characters are configured" 'auto)))
2830 (defcustom org-fast-tag-selection-single-key nil
2831 "Non-nil means fast tag selection exits after first change.
2832 When nil, you have to press RET to exit it.
2833 During fast tag selection, you can toggle this flag with `C-c'.
2834 This variable can also have the value `expert'. In this case, the window
2835 displaying the tags menu is not even shown, until you press C-c again."
2836 :group 'org-tags
2837 :type '(choice
2838 (const :tag "No" nil)
2839 (const :tag "Yes" t)
2840 (const :tag "Expert" expert)))
2842 (defvar org-fast-tag-selection-include-todo nil
2843 "Non-nil means fast tags selection interface will also offer TODO states.
2844 This is an undocumented feature, you should not rely on it.")
2846 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2847 "The column to which tags should be indented in a headline.
2848 If this number is positive, it specifies the column. If it is negative,
2849 it means that the tags should be flushright to that column. For example,
2850 -80 works well for a normal 80 character screen."
2851 :group 'org-tags
2852 :type 'integer)
2854 (defcustom org-auto-align-tags t
2855 "Non-nil keeps tags aligned when modifying headlines.
2856 Some operations (i.e. demoting) change the length of a headline and
2857 therefore shift the tags around. With this option turned on, after
2858 each such operation the tags are again aligned to `org-tags-column'."
2859 :group 'org-tags
2860 :type 'boolean)
2862 (defcustom org-use-tag-inheritance t
2863 "Non-nil means tags in levels apply also for sublevels.
2864 When nil, only the tags directly given in a specific line apply there.
2865 This may also be a list of tags that should be inherited, or a regexp that
2866 matches tags that should be inherited. Additional control is possible
2867 with the variable `org-tags-exclude-from-inheritance' which gives an
2868 explicit list of tags to be excluded from inheritance., even if the value of
2869 `org-use-tag-inheritance' would select it for inheritance.
2871 If this option is t, a match early-on in a tree can lead to a large
2872 number of matches in the subtree when constructing the agenda or creating
2873 a sparse tree. If you only want to see the first match in a tree during
2874 a search, check out the variable `org-tags-match-list-sublevels'."
2875 :group 'org-tags
2876 :type '(choice
2877 (const :tag "Not" nil)
2878 (const :tag "Always" t)
2879 (repeat :tag "Specific tags" (string :tag "Tag"))
2880 (regexp :tag "Tags matched by regexp")))
2882 (defcustom org-tags-exclude-from-inheritance nil
2883 "List of tags that should never be inherited.
2884 This is a way to exclude a few tags from inheritance. For way to do
2885 the opposite, to actively allow inheritance for selected tags,
2886 see the variable `org-use-tag-inheritance'."
2887 :group 'org-tags
2888 :type '(repeat (string :tag "Tag")))
2890 (defun org-tag-inherit-p (tag)
2891 "Check if TAG is one that should be inherited."
2892 (cond
2893 ((member tag org-tags-exclude-from-inheritance) nil)
2894 ((eq org-use-tag-inheritance t) t)
2895 ((not org-use-tag-inheritance) nil)
2896 ((stringp org-use-tag-inheritance)
2897 (string-match org-use-tag-inheritance tag))
2898 ((listp org-use-tag-inheritance)
2899 (member tag org-use-tag-inheritance))
2900 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2902 (defcustom org-tags-match-list-sublevels t
2903 "Non-nil means list also sublevels of headlines matching a search.
2904 This variable applies to tags/property searches, and also to stuck
2905 projects because this search is based on a tags match as well.
2907 When set to the symbol `indented', sublevels are indented with
2908 leading dots.
2910 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2911 the sublevels of a headline matching a tag search often also match
2912 the same search. Listing all of them can create very long lists.
2913 Setting this variable to nil causes subtrees of a match to be skipped.
2915 This variable is semi-obsolete and probably should always be true. It
2916 is better to limit inheritance to certain tags using the variables
2917 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2918 :group 'org-tags
2919 :type '(choice
2920 (const :tag "No, don't list them" nil)
2921 (const :tag "Yes, do list them" t)
2922 (const :tag "List them, indented with leading dots" indented)))
2924 (defcustom org-tags-sort-function nil
2925 "When set, tags are sorted using this function as a comparator."
2926 :group 'org-tags
2927 :type '(choice
2928 (const :tag "No sorting" nil)
2929 (const :tag "Alphabetical" string<)
2930 (const :tag "Reverse alphabetical" string>)
2931 (function :tag "Custom function" nil)))
2933 (defvar org-tags-history nil
2934 "History of minibuffer reads for tags.")
2935 (defvar org-last-tags-completion-table nil
2936 "The last used completion table for tags.")
2937 (defvar org-after-tags-change-hook nil
2938 "Hook that is run after the tags in a line have changed.")
2940 (defgroup org-properties nil
2941 "Options concerning properties in Org-mode."
2942 :tag "Org Properties"
2943 :group 'org)
2945 (defcustom org-property-format "%-10s %s"
2946 "How property key/value pairs should be formatted by `indent-line'.
2947 When `indent-line' hits a property definition, it will format the line
2948 according to this format, mainly to make sure that the values are
2949 lined-up with respect to each other."
2950 :group 'org-properties
2951 :type 'string)
2953 (defcustom org-use-property-inheritance nil
2954 "Non-nil means properties apply also for sublevels.
2956 This setting is chiefly used during property searches. Turning it on can
2957 cause significant overhead when doing a search, which is why it is not
2958 on by default.
2960 When nil, only the properties directly given in the current entry count.
2961 When t, every property is inherited. The value may also be a list of
2962 properties that should have inheritance, or a regular expression matching
2963 properties that should be inherited.
2965 However, note that some special properties use inheritance under special
2966 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2967 and the properties ending in \"_ALL\" when they are used as descriptor
2968 for valid values of a property.
2970 Note for programmers:
2971 When querying an entry with `org-entry-get', you can control if inheritance
2972 should be used. By default, `org-entry-get' looks only at the local
2973 properties. You can request inheritance by setting the inherit argument
2974 to t (to force inheritance) or to `selective' (to respect the setting
2975 in this variable)."
2976 :group 'org-properties
2977 :type '(choice
2978 (const :tag "Not" nil)
2979 (const :tag "Always" t)
2980 (repeat :tag "Specific properties" (string :tag "Property"))
2981 (regexp :tag "Properties matched by regexp")))
2983 (defun org-property-inherit-p (property)
2984 "Check if PROPERTY is one that should be inherited."
2985 (cond
2986 ((eq org-use-property-inheritance t) t)
2987 ((not org-use-property-inheritance) nil)
2988 ((stringp org-use-property-inheritance)
2989 (string-match org-use-property-inheritance property))
2990 ((listp org-use-property-inheritance)
2991 (member property org-use-property-inheritance))
2992 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2994 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2995 "The default column format, if no other format has been defined.
2996 This variable can be set on the per-file basis by inserting a line
2998 #+COLUMNS: %25ITEM ....."
2999 :group 'org-properties
3000 :type 'string)
3002 (defcustom org-columns-ellipses ".."
3003 "The ellipses to be used when a field in column view is truncated.
3004 When this is the empty string, as many characters as possible are shown,
3005 but then there will be no visual indication that the field has been truncated.
3006 When this is a string of length N, the last N characters of a truncated
3007 field are replaced by this string. If the column is narrower than the
3008 ellipses string, only part of the ellipses string will be shown."
3009 :group 'org-properties
3010 :type 'string)
3012 (defcustom org-columns-modify-value-for-display-function nil
3013 "Function that modifies values for display in column view.
3014 For example, it can be used to cut out a certain part from a time stamp.
3015 The function must take 2 arguments:
3017 column-title The title of the column (*not* the property name)
3018 value The value that should be modified.
3020 The function should return the value that should be displayed,
3021 or nil if the normal value should be used."
3022 :group 'org-properties
3023 :type 'function)
3025 (defcustom org-effort-property "Effort"
3026 "The property that is being used to keep track of effort estimates.
3027 Effort estimates given in this property need to have the format H:MM."
3028 :group 'org-properties
3029 :group 'org-progress
3030 :type '(string :tag "Property"))
3032 (defconst org-global-properties-fixed
3033 '(("VISIBILITY_ALL" . "folded children content all")
3034 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3035 "List of property/value pairs that can be inherited by any entry.
3037 These are fixed values, for the preset properties. The user variable
3038 that can be used to add to this list is `org-global-properties'.
3040 The entries in this list are cons cells where the car is a property
3041 name and cdr is a string with the value. If the value represents
3042 multiple items like an \"_ALL\" property, separate the items by
3043 spaces.")
3045 (defcustom org-global-properties nil
3046 "List of property/value pairs that can be inherited by any entry.
3048 This list will be combined with the constant `org-global-properties-fixed'.
3050 The entries in this list are cons cells where the car is a property
3051 name and cdr is a string with the value.
3053 You can set buffer-local values for the same purpose in the variable
3054 `org-file-properties' this by adding lines like
3056 #+PROPERTY: NAME VALUE"
3057 :group 'org-properties
3058 :type '(repeat
3059 (cons (string :tag "Property")
3060 (string :tag "Value"))))
3062 (defvar org-file-properties nil
3063 "List of property/value pairs that can be inherited by any entry.
3064 Valid for the current buffer.
3065 This variable is populated from #+PROPERTY lines.")
3066 (make-variable-buffer-local 'org-file-properties)
3068 (defgroup org-agenda nil
3069 "Options concerning agenda views in Org-mode."
3070 :tag "Org Agenda"
3071 :group 'org)
3073 (defvar org-category nil
3074 "Variable used by org files to set a category for agenda display.
3075 Such files should use a file variable to set it, for example
3077 # -*- mode: org; org-category: \"ELisp\"
3079 or contain a special line
3081 #+CATEGORY: ELisp
3083 If the file does not specify a category, then file's base name
3084 is used instead.")
3085 (make-variable-buffer-local 'org-category)
3086 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3088 (defcustom org-agenda-files nil
3089 "The files to be used for agenda display.
3090 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3091 \\[org-remove-file]. You can also use customize to edit the list.
3093 If an entry is a directory, all files in that directory that are matched by
3094 `org-agenda-file-regexp' will be part of the file list.
3096 If the value of the variable is not a list but a single file name, then
3097 the list of agenda files is actually stored and maintained in that file, one
3098 agenda file per line. In this file paths can be given relative to
3099 `org-directory'. Tilde expansion and environment variable substitution
3100 are also made."
3101 :group 'org-agenda
3102 :type '(choice
3103 (repeat :tag "List of files and directories" file)
3104 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3106 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3107 "Regular expression to match files for `org-agenda-files'.
3108 If any element in the list in that variable contains a directory instead
3109 of a normal file, all files in that directory that are matched by this
3110 regular expression will be included."
3111 :group 'org-agenda
3112 :type 'regexp)
3114 (defcustom org-agenda-text-search-extra-files nil
3115 "List of extra files to be searched by text search commands.
3116 These files will be search in addition to the agenda files by the
3117 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3118 Note that these files will only be searched for text search commands,
3119 not for the other agenda views like todo lists, tag searches or the weekly
3120 agenda. This variable is intended to list notes and possibly archive files
3121 that should also be searched by these two commands.
3122 In fact, if the first element in the list is the symbol `agenda-archives',
3123 than all archive files of all agenda files will be added to the search
3124 scope."
3125 :group 'org-agenda
3126 :type '(set :greedy t
3127 (const :tag "Agenda Archives" agenda-archives)
3128 (repeat :inline t (file))))
3130 (if (fboundp 'defvaralias)
3131 (defvaralias 'org-agenda-multi-occur-extra-files
3132 'org-agenda-text-search-extra-files))
3134 (defcustom org-agenda-skip-unavailable-files nil
3135 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3136 A nil value means to remove them, after a query, from the list."
3137 :group 'org-agenda
3138 :type 'boolean)
3140 (defcustom org-calendar-to-agenda-key [?c]
3141 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3142 The command `org-calendar-goto-agenda' will be bound to this key. The
3143 default is the character `c' because then `c' can be used to switch back and
3144 forth between agenda and calendar."
3145 :group 'org-agenda
3146 :type 'sexp)
3148 (defcustom org-calendar-agenda-action-key [?k]
3149 "The key to be installed in `calendar-mode-map' for agenda-action.
3150 The command `org-agenda-action' will be bound to this key. The
3151 default is the character `k' because we use the same key in the agenda."
3152 :group 'org-agenda
3153 :type 'sexp)
3155 (defcustom org-calendar-insert-diary-entry-key [?i]
3156 "The key to be installed in `calendar-mode-map' for adding diary entries.
3157 This option is irrelevant until `org-agenda-diary-file' has been configured
3158 to point to an Org-mode file. When that is the case, the command
3159 `org-agenda-diary-entry' will be bound to the key given here, by default
3160 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3161 if you want to continue doing this, you need to change this to a different
3162 key."
3163 :group 'org-agenda
3164 :type 'sexp)
3166 (defcustom org-agenda-diary-file 'diary-file
3167 "File to which to add new entries with the `i' key in agenda and calendar.
3168 When this is the symbol `diary-file', the functionality in the Emacs
3169 calendar will be used to add entries to the `diary-file'. But when this
3170 points to a file, `org-agenda-diary-entry' will be used instead."
3171 :group 'org-agenda
3172 :type '(choice
3173 (const :tag "The standard Emacs diary file" diary-file)
3174 (file :tag "Special Org file diary entries")))
3176 (eval-after-load "calendar"
3177 '(progn
3178 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3179 'org-calendar-goto-agenda)
3180 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3181 'org-agenda-action)
3182 (add-hook 'calendar-mode-hook
3183 (lambda ()
3184 (unless (eq org-agenda-diary-file 'diary-file)
3185 (define-key calendar-mode-map
3186 org-calendar-insert-diary-entry-key
3187 'org-agenda-diary-entry))))))
3189 (defgroup org-latex nil
3190 "Options for embedding LaTeX code into Org-mode."
3191 :tag "Org LaTeX"
3192 :group 'org)
3194 (defcustom org-format-latex-options
3195 '(:foreground default :background default :scale 1.0
3196 :html-foreground "Black" :html-background "Transparent"
3197 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3198 "Options for creating images from LaTeX fragments.
3199 This is a property list with the following properties:
3200 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3201 `default' means use the foreground of the default face.
3202 :background the background color, or \"Transparent\".
3203 `default' means use the background of the default face.
3204 :scale a scaling factor for the size of the images, to get more pixels
3205 :html-foreground, :html-background, :html-scale
3206 the same numbers for HTML export.
3207 :matchers a list indicating which matchers should be used to
3208 find LaTeX fragments. Valid members of this list are:
3209 \"begin\" find environments
3210 \"$1\" find single characters surrounded by $.$
3211 \"$\" find math expressions surrounded by $...$
3212 \"$$\" find math expressions surrounded by $$....$$
3213 \"\\(\" find math expressions surrounded by \\(...\\)
3214 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3215 :group 'org-latex
3216 :type 'plist)
3218 (defcustom org-format-latex-signal-error t
3219 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3220 When nil, just push out a message."
3221 :group 'org-latex
3222 :type 'boolean)
3224 (defcustom org-format-latex-header "\\documentclass{article}
3225 \\usepackage[usenames]{color}
3226 \\usepackage{amsmath}
3227 \\usepackage[mathscr]{eucal}
3228 \\pagestyle{empty} % do not remove
3229 \[PACKAGES]
3230 \[DEFAULT-PACKAGES]
3231 % The settings below are copied from fullpage.sty
3232 \\setlength{\\textwidth}{\\paperwidth}
3233 \\addtolength{\\textwidth}{-3cm}
3234 \\setlength{\\oddsidemargin}{1.5cm}
3235 \\addtolength{\\oddsidemargin}{-2.54cm}
3236 \\setlength{\\evensidemargin}{\\oddsidemargin}
3237 \\setlength{\\textheight}{\\paperheight}
3238 \\addtolength{\\textheight}{-\\headheight}
3239 \\addtolength{\\textheight}{-\\headsep}
3240 \\addtolength{\\textheight}{-\\footskip}
3241 \\addtolength{\\textheight}{-3cm}
3242 \\setlength{\\topmargin}{1.5cm}
3243 \\addtolength{\\topmargin}{-2.54cm}"
3244 "The document header used for processing LaTeX fragments.
3245 It is imperative that this header make sure that no page number
3246 appears on the page. The package defined in the variables
3247 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3248 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3249 will be appended."
3250 :group 'org-latex
3251 :type 'string)
3253 (defvar org-format-latex-header-extra nil)
3255 (defun org-set-packages-alist (var val)
3256 "Set the packages alist and make sure it has 3 elements per entry."
3257 (set var (mapcar (lambda (x)
3258 (if (and (consp x) (= (length x) 2))
3259 (list (car x) (nth 1 x) t)
3261 val)))
3263 (defun org-get-packages-alist (var)
3265 "Get the packages alist and make sure it has 3 elements per entry."
3266 (mapcar (lambda (x)
3267 (if (and (consp x) (= (length x) 2))
3268 (list (car x) (nth 1 x) t)
3270 (default-value var)))
3272 ;; The following variables are defined here because is it also used
3273 ;; when formatting latex fragments. Originally it was part of the
3274 ;; LaTeX exporter, which is why the name includes "export".
3275 (defcustom org-export-latex-default-packages-alist
3276 '(("AUTO" "inputenc" t)
3277 ("T1" "fontenc" t)
3278 ("" "fixltx2e" nil)
3279 ("" "graphicx" t)
3280 ("" "longtable" nil)
3281 ("" "float" nil)
3282 ("" "wrapfig" nil)
3283 ("" "soul" t)
3284 ("" "textcomp" t)
3285 ("" "marvosym" t)
3286 ("" "wasysym" t)
3287 ("" "latexsym" t)
3288 ("" "amssymb" t)
3289 ("" "hyperref" nil)
3290 "\\tolerance=1000"
3292 "Alist of default packages to be inserted in the header.
3293 Change this only if one of the packages here causes an incompatibility
3294 with another package you are using.
3295 The packages in this list are needed by one part or another of Org-mode
3296 to function properly.
3298 - inputenc, fontenc: for basic font and character selection
3299 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3300 for interpreting the entities in `org-entities'. You can skip some of these
3301 packages if you don't use any of the symbols in it.
3302 - graphicx: for including images
3303 - float, wrapfig: for figure placement
3304 - longtable: for long tables
3305 - hyperref: for cross references
3307 Therefore you should not modify this variable unless you know what you
3308 are doing. The one reason to change it anyway is that you might be loading
3309 some other package that conflicts with one of the default packages.
3310 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3311 If SNIPPET-FLAG is t, the package also needs to be included when
3312 compiling LaTeX snippets into images for inclusion into HTML."
3313 :group 'org-export-latex
3314 :set 'org-set-packages-alist
3315 :get 'org-get-packages-alist
3316 :type '(repeat
3317 (choice
3318 (list :tag "options/package pair"
3319 (string :tag "options")
3320 (string :tag "package")
3321 (boolean :tag "Snippet"))
3322 (string :tag "A line of LaTeX"))))
3324 (defcustom org-export-latex-packages-alist nil
3325 "Alist of packages to be inserted in every LaTeX header.
3326 These will be inserted after `org-export-latex-default-packages-alist'.
3327 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3328 SNIPPET-FLAG, when t, indicates that this package is also needed when
3329 turning LaTeX snippets into images for inclusion into HTML.
3330 Make sure that you only list packages here which:
3331 - you want in every file
3332 - do not conflict with the default packages in
3333 `org-export-latex-default-packages-alist'
3334 - do not conflict with the setup in `org-format-latex-header'."
3335 :group 'org-export-latex
3336 :set 'org-set-packages-alist
3337 :get 'org-get-packages-alist
3338 :type '(repeat
3339 (choice
3340 (list :tag "options/package pair"
3341 (string :tag "options")
3342 (string :tag "package")
3343 (boolean :tag "Snippet"))
3344 (string :tag "A line of LaTeX"))))
3347 (defgroup org-appearance nil
3348 "Settings for Org-mode appearance."
3349 :tag "Org Appearance"
3350 :group 'org)
3352 (defcustom org-level-color-stars-only nil
3353 "Non-nil means fontify only the stars in each headline.
3354 When nil, the entire headline is fontified.
3355 Changing it requires restart of `font-lock-mode' to become effective
3356 also in regions already fontified."
3357 :group 'org-appearance
3358 :type 'boolean)
3360 (defcustom org-hide-leading-stars nil
3361 "Non-nil means hide the first N-1 stars in a headline.
3362 This works by using the face `org-hide' for these stars. This
3363 face is white for a light background, and black for a dark
3364 background. You may have to customize the face `org-hide' to
3365 make this work.
3366 Changing it requires restart of `font-lock-mode' to become effective
3367 also in regions already fontified.
3368 You may also set this on a per-file basis by adding one of the following
3369 lines to the buffer:
3371 #+STARTUP: hidestars
3372 #+STARTUP: showstars"
3373 :group 'org-appearance
3374 :type 'boolean)
3376 (defcustom org-hidden-keywords nil
3377 "List of symbols corresponding to keywords to be hidden the org buffer.
3378 For example, a value '(title) for this list will make the document's title
3379 appear in the buffer without the initial #+TITLE: keyword."
3380 :group 'org-appearance
3381 :type '(set (const :tag "#+AUTHOR" author)
3382 (const :tag "#+DATE" date)
3383 (const :tag "#+EMAIL" email)
3384 (const :tag "#+TITLE" title)))
3386 (defcustom org-fontify-done-headline nil
3387 "Non-nil means change the face of a headline if it is marked DONE.
3388 Normally, only the TODO/DONE keyword indicates the state of a headline.
3389 When this is non-nil, the headline after the keyword is set to the
3390 `org-headline-done' as an additional indication."
3391 :group 'org-appearance
3392 :type 'boolean)
3394 (defcustom org-fontify-emphasized-text t
3395 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3396 Changing this variable requires a restart of Emacs to take effect."
3397 :group 'org-appearance
3398 :type 'boolean)
3400 (defcustom org-fontify-whole-heading-line nil
3401 "Non-nil means fontify the whole line for headings.
3402 This is useful when setting a background color for the
3403 org-level-* faces."
3404 :group 'org-appearance
3405 :type 'boolean)
3407 (defcustom org-highlight-latex-fragments-and-specials nil
3408 "Non-nil means fontify what is treated specially by the exporters."
3409 :group 'org-appearance
3410 :type 'boolean)
3412 (defcustom org-hide-emphasis-markers nil
3413 "Non-nil mean font-lock should hide the emphasis marker characters."
3414 :group 'org-appearance
3415 :type 'boolean)
3417 (defcustom org-pretty-entities nil
3418 "Non-nil means show entities as UTF8 characters.
3419 When nil, the \\name form remains in the buffer."
3420 :group 'org-appearance
3421 :type 'boolean)
3423 (defcustom org-pretty-entities-include-sub-superscripts t
3424 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3425 :group 'org-appearance
3426 :type 'boolean)
3428 (defvar org-emph-re nil
3429 "Regular expression for matching emphasis.
3430 After a match, the match groups contain these elements:
3431 0 The match of the full regular expression, including the characters
3432 before and after the proper match
3433 1 The character before the proper match, or empty at beginning of line
3434 2 The proper match, including the leading and trailing markers
3435 3 The leading marker like * or /, indicating the type of highlighting
3436 4 The text between the emphasis markers, not including the markers
3437 5 The character after the match, empty at the end of a line")
3438 (defvar org-verbatim-re nil
3439 "Regular expression for matching verbatim text.")
3440 (defvar org-emphasis-regexp-components) ; defined just below
3441 (defvar org-emphasis-alist) ; defined just below
3442 (defun org-set-emph-re (var val)
3443 "Set variable and compute the emphasis regular expression."
3444 (set var val)
3445 (when (and (boundp 'org-emphasis-alist)
3446 (boundp 'org-emphasis-regexp-components)
3447 org-emphasis-alist org-emphasis-regexp-components)
3448 (let* ((e org-emphasis-regexp-components)
3449 (pre (car e))
3450 (post (nth 1 e))
3451 (border (nth 2 e))
3452 (body (nth 3 e))
3453 (nl (nth 4 e))
3454 (body1 (concat body "*?"))
3455 (markers (mapconcat 'car org-emphasis-alist ""))
3456 (vmarkers (mapconcat
3457 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3458 org-emphasis-alist "")))
3459 ;; make sure special characters appear at the right position in the class
3460 (if (string-match "\\^" markers)
3461 (setq markers (concat (replace-match "" t t markers) "^")))
3462 (if (string-match "-" markers)
3463 (setq markers (concat (replace-match "" t t markers) "-")))
3464 (if (string-match "\\^" vmarkers)
3465 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3466 (if (string-match "-" vmarkers)
3467 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3468 (if (> nl 0)
3469 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3470 (int-to-string nl) "\\}")))
3471 ;; Make the regexp
3472 (setq org-emph-re
3473 (concat "\\([" pre "]\\|^\\)"
3474 "\\("
3475 "\\([" markers "]\\)"
3476 "\\("
3477 "[^" border "]\\|"
3478 "[^" border "]"
3479 body1
3480 "[^" border "]"
3481 "\\)"
3482 "\\3\\)"
3483 "\\([" post "]\\|$\\)"))
3484 (setq org-verbatim-re
3485 (concat "\\([" pre "]\\|^\\)"
3486 "\\("
3487 "\\([" vmarkers "]\\)"
3488 "\\("
3489 "[^" border "]\\|"
3490 "[^" border "]"
3491 body1
3492 "[^" border "]"
3493 "\\)"
3494 "\\3\\)"
3495 "\\([" post "]\\|$\\)")))))
3497 (defcustom org-emphasis-regexp-components
3498 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3499 "Components used to build the regular expression for emphasis.
3500 This is a list with five entries. Terminology: In an emphasis string
3501 like \" *strong word* \", we call the initial space PREMATCH, the final
3502 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3503 and \"trong wor\" is the body. The different components in this variable
3504 specify what is allowed/forbidden in each part:
3506 pre Chars allowed as prematch. Beginning of line will be allowed too.
3507 post Chars allowed as postmatch. End of line will be allowed too.
3508 border The chars *forbidden* as border characters.
3509 body-regexp A regexp like \".\" to match a body character. Don't use
3510 non-shy groups here, and don't allow newline here.
3511 newline The maximum number of newlines allowed in an emphasis exp.
3513 Use customize to modify this, or restart Emacs after changing it."
3514 :group 'org-appearance
3515 :set 'org-set-emph-re
3516 :type '(list
3517 (sexp :tag "Allowed chars in pre ")
3518 (sexp :tag "Allowed chars in post ")
3519 (sexp :tag "Forbidden chars in border ")
3520 (sexp :tag "Regexp for body ")
3521 (integer :tag "number of newlines allowed")
3522 (option (boolean :tag "Please ignore this button"))))
3524 (defcustom org-emphasis-alist
3525 `(("*" bold "<b>" "</b>")
3526 ("/" italic "<i>" "</i>")
3527 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3528 ("=" org-code "<code>" "</code>" verbatim)
3529 ("~" org-verbatim "<code>" "</code>" verbatim)
3530 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3531 "<del>" "</del>")
3533 "Special syntax for emphasized text.
3534 Text starting and ending with a special character will be emphasized, for
3535 example *bold*, _underlined_ and /italic/. This variable sets the marker
3536 characters, the face to be used by font-lock for highlighting in Org-mode
3537 Emacs buffers, and the HTML tags to be used for this.
3538 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3539 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3540 Use customize to modify this, or restart Emacs after changing it."
3541 :group 'org-appearance
3542 :set 'org-set-emph-re
3543 :type '(repeat
3544 (list
3545 (string :tag "Marker character")
3546 (choice
3547 (face :tag "Font-lock-face")
3548 (plist :tag "Face property list"))
3549 (string :tag "HTML start tag")
3550 (string :tag "HTML end tag")
3551 (option (const verbatim)))))
3553 (defvar org-protecting-blocks
3554 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3555 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3556 This is needed for font-lock setup.")
3558 ;;; Miscellaneous options
3560 (defgroup org-completion nil
3561 "Completion in Org-mode."
3562 :tag "Org Completion"
3563 :group 'org)
3565 (defcustom org-completion-use-ido nil
3566 "Non-nil means use ido completion wherever possible.
3567 Note that `ido-mode' must be active for this variable to be relevant.
3568 If you decide to turn this variable on, you might well want to turn off
3569 `org-outline-path-complete-in-steps'.
3570 See also `org-completion-use-iswitchb'."
3571 :group 'org-completion
3572 :type 'boolean)
3574 (defcustom org-completion-use-iswitchb nil
3575 "Non-nil means use iswitchb completion wherever possible.
3576 Note that `iswitchb-mode' must be active for this variable to be relevant.
3577 If you decide to turn this variable on, you might well want to turn off
3578 `org-outline-path-complete-in-steps'.
3579 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3580 :group 'org-completion
3581 :type 'boolean)
3583 (defcustom org-completion-fallback-command 'hippie-expand
3584 "The expansion command called by \\[pcomplete] in normal context.
3585 Normal means, no org-mode-specific context."
3586 :group 'org-completion
3587 :type 'function)
3589 ;;; Functions and variables from their packages
3590 ;; Declared here to avoid compiler warnings
3592 ;; XEmacs only
3593 (defvar outline-mode-menu-heading)
3594 (defvar outline-mode-menu-show)
3595 (defvar outline-mode-menu-hide)
3596 (defvar zmacs-regions) ; XEmacs regions
3598 ;; Emacs only
3599 (defvar mark-active)
3601 ;; Various packages
3602 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3603 (declare-function calendar-forward-day "cal-move" (arg))
3604 (declare-function calendar-goto-date "cal-move" (date))
3605 (declare-function calendar-goto-today "cal-move" ())
3606 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3607 (defvar calc-embedded-close-formula)
3608 (defvar calc-embedded-open-formula)
3609 (declare-function cdlatex-tab "ext:cdlatex" ())
3610 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3611 (defvar font-lock-unfontify-region-function)
3612 (declare-function iswitchb-read-buffer "iswitchb"
3613 (prompt &optional default require-match start matches-set))
3614 (defvar iswitchb-temp-buflist)
3615 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3616 (defvar org-agenda-tags-todo-honor-ignore-options)
3617 (declare-function org-agenda-skip "org-agenda" ())
3618 (declare-function
3619 org-format-agenda-item "org-agenda"
3620 (extra txt &optional category tags dotime noprefix remove-re habitp))
3621 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3622 (declare-function org-agenda-change-all-lines "org-agenda"
3623 (newhead hdmarker &optional fixface just-this))
3624 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3625 (declare-function org-agenda-maybe-redo "org-agenda" ())
3626 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3627 (beg end))
3628 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3629 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3630 "org-agenda" (&optional end))
3631 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3632 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3633 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3634 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3635 (declare-function org-indent-mode "org-indent" (&optional arg))
3636 (declare-function parse-time-string "parse-time" (string))
3637 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3638 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3639 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3640 (defvar remember-data-file)
3641 (defvar texmathp-why)
3642 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3643 (declare-function table--at-cell-p "table" (position &optional object at-column))
3645 (defvar w3m-current-url)
3646 (defvar w3m-current-title)
3648 (defvar org-latex-regexps)
3650 ;;; Autoload and prepare some org modules
3652 ;; Some table stuff that needs to be defined here, because it is used
3653 ;; by the functions setting up org-mode or checking for table context.
3655 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3656 "Detect an org-type or table-type table.")
3657 (defconst org-table-line-regexp "^[ \t]*|"
3658 "Detect an org-type table line.")
3659 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3660 "Detect an org-type table line.")
3661 (defconst org-table-hline-regexp "^[ \t]*|-"
3662 "Detect an org-type table hline.")
3663 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3664 "Detect a table-type table hline.")
3665 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3666 "Detect the first line outside a table when searching from within it.
3667 This works for both table types.")
3669 ;; Autoload the functions in org-table.el that are needed by functions here.
3671 (eval-and-compile
3672 (org-autoload "org-table"
3673 '(org-table-align org-table-begin org-table-blank-field
3674 org-table-convert org-table-convert-region org-table-copy-down
3675 org-table-copy-region org-table-create
3676 org-table-create-or-convert-from-region
3677 org-table-create-with-table.el org-table-current-dline
3678 org-table-cut-region org-table-delete-column org-table-edit-field
3679 org-table-edit-formulas org-table-end org-table-eval-formula
3680 org-table-export org-table-field-info
3681 org-table-get-stored-formulas org-table-goto-column
3682 org-table-hline-and-move org-table-import org-table-insert-column
3683 org-table-insert-hline org-table-insert-row org-table-iterate
3684 org-table-justify-field-maybe org-table-kill-row
3685 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3686 org-table-move-column org-table-move-column-left
3687 org-table-move-column-right org-table-move-row
3688 org-table-move-row-down org-table-move-row-up
3689 org-table-next-field org-table-next-row org-table-paste-rectangle
3690 org-table-previous-field org-table-recalculate
3691 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3692 org-table-toggle-coordinate-overlays
3693 org-table-toggle-formula-debugger org-table-wrap-region
3694 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3695 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3696 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3698 (defun org-at-table-p (&optional table-type)
3699 "Return t if the cursor is inside an org-type table.
3700 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3701 (if org-enable-table-editor
3702 (save-excursion
3703 (beginning-of-line 1)
3704 (looking-at (if table-type org-table-any-line-regexp
3705 org-table-line-regexp)))
3706 nil))
3707 (defsubst org-table-p () (org-at-table-p))
3709 (defun org-at-table.el-p ()
3710 "Return t if and only if we are at a table.el table."
3711 (and (org-at-table-p 'any)
3712 (save-excursion
3713 (goto-char (org-table-begin 'any))
3714 (looking-at org-table1-hline-regexp))))
3715 (defun org-table-recognize-table.el ()
3716 "If there is a table.el table nearby, recognize it and move into it."
3717 (if org-table-tab-recognizes-table.el
3718 (if (org-at-table.el-p)
3719 (progn
3720 (beginning-of-line 1)
3721 (if (looking-at org-table-dataline-regexp)
3723 (if (looking-at org-table1-hline-regexp)
3724 (progn
3725 (beginning-of-line 2)
3726 (if (looking-at org-table-any-border-regexp)
3727 (beginning-of-line -1)))))
3728 (if (re-search-forward "|" (org-table-end t) t)
3729 (progn
3730 (require 'table)
3731 (if (table--at-cell-p (point))
3733 (message "recognizing table.el table...")
3734 (table-recognize-table)
3735 (message "recognizing table.el table...done")))
3736 (error "This should not happen"))
3738 nil)
3739 nil))
3741 (defun org-at-table-hline-p ()
3742 "Return t if the cursor is inside a hline in a table."
3743 (if org-enable-table-editor
3744 (save-excursion
3745 (beginning-of-line 1)
3746 (looking-at org-table-hline-regexp))
3747 nil))
3749 (defvar org-table-clean-did-remove-column nil)
3751 (defun org-table-map-tables (function &optional quietly)
3752 "Apply FUNCTION to the start of all tables in the buffer."
3753 (save-excursion
3754 (save-restriction
3755 (widen)
3756 (goto-char (point-min))
3757 (while (re-search-forward org-table-any-line-regexp nil t)
3758 (unless quietly
3759 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3760 (beginning-of-line 1)
3761 (when (looking-at org-table-line-regexp)
3762 (save-excursion (funcall function))
3763 (or (looking-at org-table-line-regexp)
3764 (forward-char 1)))
3765 (re-search-forward org-table-any-border-regexp nil 1))))
3766 (unless quietly (message "Mapping tables: done")))
3768 ;; Declare and autoload functions from org-exp.el & Co
3770 (declare-function org-default-export-plist "org-exp")
3771 (declare-function org-infile-export-plist "org-exp")
3772 (declare-function org-get-current-options "org-exp")
3773 (eval-and-compile
3774 (org-autoload "org-exp"
3775 '(org-export org-export-visible
3776 org-insert-export-options-template
3777 org-table-clean-before-export))
3778 (org-autoload "org-ascii"
3779 '(org-export-as-ascii org-export-ascii-preprocess
3780 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3781 org-export-region-as-ascii))
3782 (org-autoload "org-latex"
3783 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3784 org-replace-region-by-latex org-export-region-as-latex
3785 org-export-as-latex org-export-as-pdf
3786 org-export-as-pdf-and-open))
3787 (org-autoload "org-html"
3788 '(org-export-as-html-and-open
3789 org-export-as-html-batch org-export-as-html-to-buffer
3790 org-replace-region-by-html org-export-region-as-html
3791 org-export-as-html))
3792 (org-autoload "org-docbook"
3793 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3794 org-replace-region-by-docbook org-export-region-as-docbook
3795 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3796 org-export-as-docbook))
3797 (org-autoload "org-icalendar"
3798 '(org-export-icalendar-this-file
3799 org-export-icalendar-all-agenda-files
3800 org-export-icalendar-combine-agenda-files))
3801 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3802 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3804 ;; Declare and autoload functions from org-agenda.el
3806 (eval-and-compile
3807 (org-autoload "org-agenda"
3808 '(org-agenda org-agenda-list org-search-view
3809 org-todo-list org-tags-view org-agenda-list-stuck-projects
3810 org-diary org-agenda-to-appt
3811 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3813 ;; Autoload org-remember
3815 (eval-and-compile
3816 (org-autoload "org-remember"
3817 '(org-remember-insinuate org-remember-annotation
3818 org-remember-apply-template org-remember org-remember-handler)))
3820 (eval-and-compile
3821 (org-autoload "org-capture"
3822 '(org-capture org-capture-insert-template-here
3823 org-capture-import-remember-templates)))
3825 ;; Autoload org-clock.el
3827 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3828 (beg end))
3829 (declare-function org-clock-update-mode-line "org-clock" ())
3830 (declare-function org-resolve-clocks "org-clock"
3831 (&optional also-non-dangling-p prompt last-valid))
3832 (defvar org-clock-start-time)
3833 (defvar org-clock-marker (make-marker)
3834 "Marker recording the last clock-in.")
3835 (defvar org-clock-hd-marker (make-marker)
3836 "Marker recording the last clock-in, but the headline position.")
3837 (defvar org-clock-heading ""
3838 "The heading of the current clock entry.")
3839 (defun org-clock-is-active ()
3840 "Return non-nil if clock is currently running.
3841 The return value is actually the clock marker."
3842 (marker-buffer org-clock-marker))
3844 (eval-and-compile
3845 (org-autoload
3846 "org-clock"
3847 '(org-clock-in org-clock-out org-clock-cancel
3848 org-clock-goto org-clock-sum org-clock-display
3849 org-clock-remove-overlays org-clock-report
3850 org-clocktable-shift org-dblock-write:clocktable
3851 org-get-clocktable org-resolve-clocks)))
3853 (defun org-clock-update-time-maybe ()
3854 "If this is a CLOCK line, update it and return t.
3855 Otherwise, return nil."
3856 (interactive)
3857 (save-excursion
3858 (beginning-of-line 1)
3859 (skip-chars-forward " \t")
3860 (when (looking-at org-clock-string)
3861 (let ((re (concat "[ \t]*" org-clock-string
3862 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3863 "\\([ \t]*=>.*\\)?\\)?"))
3864 ts te h m s neg)
3865 (cond
3866 ((not (looking-at re))
3867 nil)
3868 ((not (match-end 2))
3869 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3870 (> org-clock-marker (point))
3871 (<= org-clock-marker (point-at-eol)))
3872 ;; The clock is running here
3873 (setq org-clock-start-time
3874 (apply 'encode-time
3875 (org-parse-time-string (match-string 1))))
3876 (org-clock-update-mode-line)))
3878 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3879 (end-of-line 1)
3880 (setq ts (match-string 1)
3881 te (match-string 3))
3882 (setq s (- (org-float-time
3883 (apply 'encode-time (org-parse-time-string te)))
3884 (org-float-time
3885 (apply 'encode-time (org-parse-time-string ts))))
3886 neg (< s 0)
3887 s (abs s)
3888 h (floor (/ s 3600))
3889 s (- s (* 3600 h))
3890 m (floor (/ s 60))
3891 s (- s (* 60 s)))
3892 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3893 t))))))
3895 (defun org-check-running-clock ()
3896 "Check if the current buffer contains the running clock.
3897 If yes, offer to stop it and to save the buffer with the changes."
3898 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3899 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3900 (buffer-name))))
3901 (org-clock-out)
3902 (when (y-or-n-p "Save changed buffer?")
3903 (save-buffer))))
3905 (defun org-clocktable-try-shift (dir n)
3906 "Check if this line starts a clock table, if yes, shift the time block."
3907 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
3908 (org-clocktable-shift dir n)))
3910 ;; Autoload org-timer.el
3912 (eval-and-compile
3913 (org-autoload
3914 "org-timer"
3915 '(org-timer-start org-timer org-timer-item
3916 org-timer-change-times-in-region
3917 org-timer-set-timer
3918 org-timer-reset-timers
3919 org-timer-show-remaining-time)))
3921 ;; Autoload org-feed.el
3923 (eval-and-compile
3924 (org-autoload
3925 "org-feed"
3926 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3929 ;; Autoload org-indent.el
3931 ;; Define the variable already here, to make sure we have it.
3932 (defvar org-indent-mode nil
3933 "Non-nil if Org-Indent mode is enabled.
3934 Use the command `org-indent-mode' to change this variable.")
3936 (eval-and-compile
3937 (org-autoload
3938 "org-indent"
3939 '(org-indent-mode)))
3941 ;; Autoload org-mobile.el
3943 (eval-and-compile
3944 (org-autoload
3945 "org-mobile"
3946 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3948 ;; Autoload archiving code
3949 ;; The stuff that is needed for cycling and tags has to be defined here.
3951 (defgroup org-archive nil
3952 "Options concerning archiving in Org-mode."
3953 :tag "Org Archive"
3954 :group 'org-structure)
3956 (defcustom org-archive-location "%s_archive::"
3957 "The location where subtrees should be archived.
3959 The value of this variable is a string, consisting of two parts,
3960 separated by a double-colon. The first part is a filename and
3961 the second part is a headline.
3963 When the filename is omitted, archiving happens in the same file.
3964 %s in the filename will be replaced by the current file
3965 name (without the directory part). Archiving to a different file
3966 is useful to keep archived entries from contributing to the
3967 Org-mode Agenda.
3969 The archived entries will be filed as subtrees of the specified
3970 headline. When the headline is omitted, the subtrees are simply
3971 filed away at the end of the file, as top-level entries. Also in
3972 the heading you can use %s to represent the file name, this can be
3973 useful when using the same archive for a number of different files.
3975 Here are a few examples:
3976 \"%s_archive::\"
3977 If the current file is Projects.org, archive in file
3978 Projects.org_archive, as top-level trees. This is the default.
3980 \"::* Archived Tasks\"
3981 Archive in the current file, under the top-level headline
3982 \"* Archived Tasks\".
3984 \"~/org/archive.org::\"
3985 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3987 \"~/org/archive.org::From %s\"
3988 Archive in file ~/org/archive.org (absolute path), under headlines
3989 \"From FILENAME\" where file name is the current file name.
3991 \"basement::** Finished Tasks\"
3992 Archive in file ./basement (relative path), as level 3 trees
3993 below the level 2 heading \"** Finished Tasks\".
3995 You may set this option on a per-file basis by adding to the buffer a
3996 line like
3998 #+ARCHIVE: basement::** Finished Tasks
4000 You may also define it locally for a subtree by setting an ARCHIVE property
4001 in the entry. If such a property is found in an entry, or anywhere up
4002 the hierarchy, it will be used."
4003 :group 'org-archive
4004 :type 'string)
4006 (defcustom org-archive-tag "ARCHIVE"
4007 "The tag that marks a subtree as archived.
4008 An archived subtree does not open during visibility cycling, and does
4009 not contribute to the agenda listings.
4010 After changing this, font-lock must be restarted in the relevant buffers to
4011 get the proper fontification."
4012 :group 'org-archive
4013 :group 'org-keywords
4014 :type 'string)
4016 (defcustom org-agenda-skip-archived-trees t
4017 "Non-nil means the agenda will skip any items located in archived trees.
4018 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4019 variable is no longer recommended, you should leave it at the value t.
4020 Instead, use the key `v' to cycle the archives-mode in the agenda."
4021 :group 'org-archive
4022 :group 'org-agenda-skip
4023 :type 'boolean)
4025 (defcustom org-columns-skip-archived-trees t
4026 "Non-nil means ignore archived trees when creating column view."
4027 :group 'org-archive
4028 :group 'org-properties
4029 :type 'boolean)
4031 (defcustom org-cycle-open-archived-trees nil
4032 "Non-nil means `org-cycle' will open archived trees.
4033 An archived tree is a tree marked with the tag ARCHIVE.
4034 When nil, archived trees will stay folded. You can still open them with
4035 normal outline commands like `show-all', but not with the cycling commands."
4036 :group 'org-archive
4037 :group 'org-cycle
4038 :type 'boolean)
4040 (defcustom org-sparse-tree-open-archived-trees nil
4041 "Non-nil means sparse tree construction shows matches in archived trees.
4042 When nil, matches in these trees are highlighted, but the trees are kept in
4043 collapsed state."
4044 :group 'org-archive
4045 :group 'org-sparse-trees
4046 :type 'boolean)
4048 (defun org-cycle-hide-archived-subtrees (state)
4049 "Re-hide all archived subtrees after a visibility state change."
4050 (when (and (not org-cycle-open-archived-trees)
4051 (not (memq state '(overview folded))))
4052 (save-excursion
4053 (let* ((globalp (memq state '(contents all)))
4054 (beg (if globalp (point-min) (point)))
4055 (end (if globalp (point-max) (org-end-of-subtree t))))
4056 (org-hide-archived-subtrees beg end)
4057 (goto-char beg)
4058 (if (looking-at (concat ".*:" org-archive-tag ":"))
4059 (message "%s" (substitute-command-keys
4060 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4062 (defun org-force-cycle-archived ()
4063 "Cycle subtree even if it is archived."
4064 (interactive)
4065 (setq this-command 'org-cycle)
4066 (let ((org-cycle-open-archived-trees t))
4067 (call-interactively 'org-cycle)))
4069 (defun org-hide-archived-subtrees (beg end)
4070 "Re-hide all archived subtrees after a visibility state change."
4071 (save-excursion
4072 (let* ((re (concat ":" org-archive-tag ":")))
4073 (goto-char beg)
4074 (while (re-search-forward re end t)
4075 (when (org-on-heading-p)
4076 (org-flag-subtree t)
4077 (org-end-of-subtree t))))))
4079 (defun org-flag-subtree (flag)
4080 (save-excursion
4081 (org-back-to-heading t)
4082 (outline-end-of-heading)
4083 (outline-flag-region (point)
4084 (progn (org-end-of-subtree t) (point))
4085 flag)))
4087 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4089 (eval-and-compile
4090 (org-autoload "org-archive"
4091 '(org-add-archive-files org-archive-subtree
4092 org-archive-to-archive-sibling org-toggle-archive-tag
4093 org-archive-subtree-default
4094 org-archive-subtree-default-with-confirmation)))
4096 ;; Autoload Column View Code
4098 (declare-function org-columns-number-to-string "org-colview")
4099 (declare-function org-columns-get-format-and-top-level "org-colview")
4100 (declare-function org-columns-compute "org-colview")
4102 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4103 '(org-columns-number-to-string org-columns-get-format-and-top-level
4104 org-columns-compute org-agenda-columns org-columns-remove-overlays
4105 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4107 ;; Autoload ID code
4109 (declare-function org-id-store-link "org-id")
4110 (declare-function org-id-locations-load "org-id")
4111 (declare-function org-id-locations-save "org-id")
4112 (defvar org-id-track-globally)
4113 (org-autoload "org-id"
4114 '(org-id-get-create org-id-new org-id-copy org-id-get
4115 org-id-get-with-outline-path-completion
4116 org-id-get-with-outline-drilling org-id-store-link
4117 org-id-goto org-id-find org-id-store-link))
4119 ;; Autoload Plotting Code
4121 (org-autoload "org-plot"
4122 '(org-plot/gnuplot))
4124 ;;; Variables for pre-computed regular expressions, all buffer local
4126 (defvar org-drawer-regexp nil
4127 "Matches first line of a hidden block.")
4128 (make-variable-buffer-local 'org-drawer-regexp)
4129 (defvar org-todo-regexp nil
4130 "Matches any of the TODO state keywords.")
4131 (make-variable-buffer-local 'org-todo-regexp)
4132 (defvar org-not-done-regexp nil
4133 "Matches any of the TODO state keywords except the last one.")
4134 (make-variable-buffer-local 'org-not-done-regexp)
4135 (defvar org-not-done-heading-regexp nil
4136 "Matches a TODO headline that is not done.")
4137 (make-variable-buffer-local 'org-not-done-regexp)
4138 (defvar org-todo-line-regexp nil
4139 "Matches a headline and puts TODO state into group 2 if present.")
4140 (make-variable-buffer-local 'org-todo-line-regexp)
4141 (defvar org-complex-heading-regexp nil
4142 "Matches a headline and puts everything into groups:
4143 group 1: the stars
4144 group 2: The todo keyword, maybe
4145 group 3: Priority cookie
4146 group 4: True headline
4147 group 5: Tags")
4148 (make-variable-buffer-local 'org-complex-heading-regexp)
4149 (defvar org-complex-heading-regexp-format nil
4150 "Printf format to make regexp to match an exact headline.
4151 This regexp will match the headline of any node which hase the exact
4152 headline text that is put into the format, but may have any TODO state,
4153 priority and tags.")
4154 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4155 (defvar org-todo-line-tags-regexp nil
4156 "Matches a headline and puts TODO state into group 2 if present.
4157 Also put tags into group 4 if tags are present.")
4158 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4159 (defvar org-nl-done-regexp nil
4160 "Matches newline followed by a headline with the DONE keyword.")
4161 (make-variable-buffer-local 'org-nl-done-regexp)
4162 (defvar org-looking-at-done-regexp nil
4163 "Matches the DONE keyword a point.")
4164 (make-variable-buffer-local 'org-looking-at-done-regexp)
4165 (defvar org-ds-keyword-length 12
4166 "Maximum length of the Deadline and SCHEDULED keywords.")
4167 (make-variable-buffer-local 'org-ds-keyword-length)
4168 (defvar org-deadline-regexp nil
4169 "Matches the DEADLINE keyword.")
4170 (make-variable-buffer-local 'org-deadline-regexp)
4171 (defvar org-deadline-time-regexp nil
4172 "Matches the DEADLINE keyword together with a time stamp.")
4173 (make-variable-buffer-local 'org-deadline-time-regexp)
4174 (defvar org-deadline-line-regexp nil
4175 "Matches the DEADLINE keyword and the rest of the line.")
4176 (make-variable-buffer-local 'org-deadline-line-regexp)
4177 (defvar org-scheduled-regexp nil
4178 "Matches the SCHEDULED keyword.")
4179 (make-variable-buffer-local 'org-scheduled-regexp)
4180 (defvar org-scheduled-time-regexp nil
4181 "Matches the SCHEDULED keyword together with a time stamp.")
4182 (make-variable-buffer-local 'org-scheduled-time-regexp)
4183 (defvar org-closed-time-regexp nil
4184 "Matches the CLOSED keyword together with a time stamp.")
4185 (make-variable-buffer-local 'org-closed-time-regexp)
4187 (defvar org-keyword-time-regexp nil
4188 "Matches any of the 4 keywords, together with the time stamp.")
4189 (make-variable-buffer-local 'org-keyword-time-regexp)
4190 (defvar org-keyword-time-not-clock-regexp nil
4191 "Matches any of the 3 keywords, together with the time stamp.")
4192 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4193 (defvar org-maybe-keyword-time-regexp nil
4194 "Matches a timestamp, possibly preceded by a keyword.")
4195 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4196 (defvar org-planning-or-clock-line-re nil
4197 "Matches a line with planning or clock info.")
4198 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4199 (defvar org-all-time-keywords nil
4200 "List of time keywords.")
4201 (make-variable-buffer-local 'org-all-time-keywords)
4203 (defconst org-plain-time-of-day-regexp
4204 (concat
4205 "\\(\\<[012]?[0-9]"
4206 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4207 "\\(--?"
4208 "\\(\\<[012]?[0-9]"
4209 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4210 "\\)?")
4211 "Regular expression to match a plain time or time range.
4212 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4213 groups carry important information:
4214 0 the full match
4215 1 the first time, range or not
4216 8 the second time, if it is a range.")
4218 (defconst org-plain-time-extension-regexp
4219 (concat
4220 "\\(\\<[012]?[0-9]"
4221 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4222 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4223 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4224 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4225 groups carry important information:
4226 0 the full match
4227 7 hours of duration
4228 9 minutes of duration")
4230 (defconst org-stamp-time-of-day-regexp
4231 (concat
4232 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4233 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4234 "\\(--?"
4235 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4236 "Regular expression to match a timestamp time or time range.
4237 After a match, the following groups carry important information:
4238 0 the full match
4239 1 date plus weekday, for back referencing to make sure both times are on the same day
4240 2 the first time, range or not
4241 4 the second time, if it is a range.")
4243 (defconst org-startup-options
4244 '(("fold" org-startup-folded t)
4245 ("overview" org-startup-folded t)
4246 ("nofold" org-startup-folded nil)
4247 ("showall" org-startup-folded nil)
4248 ("showeverything" org-startup-folded showeverything)
4249 ("content" org-startup-folded content)
4250 ("indent" org-startup-indented t)
4251 ("noindent" org-startup-indented nil)
4252 ("hidestars" org-hide-leading-stars t)
4253 ("showstars" org-hide-leading-stars nil)
4254 ("odd" org-odd-levels-only t)
4255 ("oddeven" org-odd-levels-only nil)
4256 ("align" org-startup-align-all-tables t)
4257 ("noalign" org-startup-align-all-tables nil)
4258 ("inlineimages" org-startup-with-inline-images t)
4259 ("noinlineimages" org-startup-with-inline-images nil)
4260 ("customtime" org-display-custom-times t)
4261 ("logdone" org-log-done time)
4262 ("lognotedone" org-log-done note)
4263 ("nologdone" org-log-done nil)
4264 ("lognoteclock-out" org-log-note-clock-out t)
4265 ("nolognoteclock-out" org-log-note-clock-out nil)
4266 ("logrepeat" org-log-repeat state)
4267 ("lognoterepeat" org-log-repeat note)
4268 ("nologrepeat" org-log-repeat nil)
4269 ("logreschedule" org-log-reschedule time)
4270 ("lognotereschedule" org-log-reschedule note)
4271 ("nologreschedule" org-log-reschedule nil)
4272 ("logredeadline" org-log-redeadline time)
4273 ("lognoteredeadline" org-log-redeadline note)
4274 ("nologredeadline" org-log-redeadline nil)
4275 ("logrefile" org-log-refile time)
4276 ("lognoterefile" org-log-refile note)
4277 ("nologrefile" org-log-refile nil)
4278 ("fninline" org-footnote-define-inline t)
4279 ("nofninline" org-footnote-define-inline nil)
4280 ("fnlocal" org-footnote-section nil)
4281 ("fnauto" org-footnote-auto-label t)
4282 ("fnprompt" org-footnote-auto-label nil)
4283 ("fnconfirm" org-footnote-auto-label confirm)
4284 ("fnplain" org-footnote-auto-label plain)
4285 ("fnadjust" org-footnote-auto-adjust t)
4286 ("nofnadjust" org-footnote-auto-adjust nil)
4287 ("constcgs" constants-unit-system cgs)
4288 ("constSI" constants-unit-system SI)
4289 ("noptag" org-tag-persistent-alist nil)
4290 ("hideblocks" org-hide-block-startup t)
4291 ("nohideblocks" org-hide-block-startup nil)
4292 ("beamer" org-startup-with-beamer-mode t)
4293 ("entitiespretty" org-pretty-entities t)
4294 ("entitiesplain" org-pretty-entities nil))
4295 "Variable associated with STARTUP options for org-mode.
4296 Each element is a list of three items: The startup options as written
4297 in the #+STARTUP line, the corresponding variable, and the value to
4298 set this variable to if the option is found. An optional forth element PUSH
4299 means to push this value onto the list in the variable.")
4301 (defun org-set-regexps-and-options ()
4302 "Precompute regular expressions for current buffer."
4303 (when (org-mode-p)
4304 (org-set-local 'org-todo-kwd-alist nil)
4305 (org-set-local 'org-todo-key-alist nil)
4306 (org-set-local 'org-todo-key-trigger nil)
4307 (org-set-local 'org-todo-keywords-1 nil)
4308 (org-set-local 'org-done-keywords nil)
4309 (org-set-local 'org-todo-heads nil)
4310 (org-set-local 'org-todo-sets nil)
4311 (org-set-local 'org-todo-log-states nil)
4312 (org-set-local 'org-file-properties nil)
4313 (org-set-local 'org-file-tags nil)
4314 (let ((re (org-make-options-regexp
4315 '("CATEGORY" "TODO" "COLUMNS"
4316 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4317 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4318 "OPTIONS")
4319 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4320 (splitre "[ \t]+")
4321 (scripts org-use-sub-superscripts)
4322 kwds kws0 kwsa key log value cat arch tags const links hw dws
4323 tail sep kws1 prio props ftags drawers beamer-p
4324 ext-setup-or-nil setup-contents (start 0))
4325 (save-excursion
4326 (save-restriction
4327 (widen)
4328 (goto-char (point-min))
4329 (while (or (and ext-setup-or-nil
4330 (string-match re ext-setup-or-nil start)
4331 (setq start (match-end 0)))
4332 (and (setq ext-setup-or-nil nil start 0)
4333 (re-search-forward re nil t)))
4334 (setq key (upcase (match-string 1 ext-setup-or-nil))
4335 value (org-match-string-no-properties 2 ext-setup-or-nil))
4336 (if (stringp value) (setq value (org-trim value)))
4337 (cond
4338 ((equal key "CATEGORY")
4339 (setq cat value))
4340 ((member key '("SEQ_TODO" "TODO"))
4341 (push (cons 'sequence (org-split-string value splitre)) kwds))
4342 ((equal key "TYP_TODO")
4343 (push (cons 'type (org-split-string value splitre)) kwds))
4344 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4345 ;; general TODO-like setup
4346 (push (cons (intern (downcase (match-string 1 key)))
4347 (org-split-string value splitre)) kwds))
4348 ((equal key "TAGS")
4349 (setq tags (append tags (if tags '("\\n") nil)
4350 (org-split-string value splitre))))
4351 ((equal key "COLUMNS")
4352 (org-set-local 'org-columns-default-format value))
4353 ((equal key "LINK")
4354 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4355 (push (cons (match-string 1 value)
4356 (org-trim (match-string 2 value)))
4357 links)))
4358 ((equal key "PRIORITIES")
4359 (setq prio (org-split-string value " +")))
4360 ((equal key "PROPERTY")
4361 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4362 (push (cons (match-string 1 value) (match-string 2 value))
4363 props)))
4364 ((equal key "FILETAGS")
4365 (when (string-match "\\S-" value)
4366 (setq ftags
4367 (append
4368 ftags
4369 (apply 'append
4370 (mapcar (lambda (x) (org-split-string x ":"))
4371 (org-split-string value)))))))
4372 ((equal key "DRAWERS")
4373 (setq drawers (org-split-string value splitre)))
4374 ((equal key "CONSTANTS")
4375 (setq const (append const (org-split-string value splitre))))
4376 ((equal key "STARTUP")
4377 (let ((opts (org-split-string value splitre))
4378 l var val)
4379 (while (setq l (pop opts))
4380 (when (setq l (assoc l org-startup-options))
4381 (setq var (nth 1 l) val (nth 2 l))
4382 (if (not (nth 3 l))
4383 (set (make-local-variable var) val)
4384 (if (not (listp (symbol-value var)))
4385 (set (make-local-variable var) nil))
4386 (set (make-local-variable var) (symbol-value var))
4387 (add-to-list var val))))))
4388 ((equal key "ARCHIVE")
4389 (setq arch value)
4390 (remove-text-properties 0 (length arch)
4391 '(face t fontified t) arch))
4392 ((equal key "LATEX_CLASS")
4393 (setq beamer-p (equal value "beamer")))
4394 ((equal key "OPTIONS")
4395 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4396 (setq scripts (read (match-string 2 value)))))
4397 ((equal key "SETUPFILE")
4398 (setq setup-contents (org-file-contents
4399 (expand-file-name
4400 (org-remove-double-quotes value))
4401 'noerror))
4402 (if (not ext-setup-or-nil)
4403 (setq ext-setup-or-nil setup-contents start 0)
4404 (setq ext-setup-or-nil
4405 (concat (substring ext-setup-or-nil 0 start)
4406 "\n" setup-contents "\n"
4407 (substring ext-setup-or-nil start)))))
4408 ))))
4409 (org-set-local 'org-use-sub-superscripts scripts)
4410 (when cat
4411 (org-set-local 'org-category (intern cat))
4412 (push (cons "CATEGORY" cat) props))
4413 (when prio
4414 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4415 (setq prio (mapcar 'string-to-char prio))
4416 (org-set-local 'org-highest-priority (nth 0 prio))
4417 (org-set-local 'org-lowest-priority (nth 1 prio))
4418 (org-set-local 'org-default-priority (nth 2 prio)))
4419 (and props (org-set-local 'org-file-properties (nreverse props)))
4420 (and ftags (org-set-local 'org-file-tags
4421 (mapcar 'org-add-prop-inherited ftags)))
4422 (and drawers (org-set-local 'org-drawers drawers))
4423 (and arch (org-set-local 'org-archive-location arch))
4424 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4425 ;; Process the TODO keywords
4426 (unless kwds
4427 ;; Use the global values as if they had been given locally.
4428 (setq kwds (default-value 'org-todo-keywords))
4429 (if (stringp (car kwds))
4430 (setq kwds (list (cons org-todo-interpretation
4431 (default-value 'org-todo-keywords)))))
4432 (setq kwds (reverse kwds)))
4433 (setq kwds (nreverse kwds))
4434 (let (inter kws kw)
4435 (while (setq kws (pop kwds))
4436 (let ((kws (or
4437 (run-hook-with-args-until-success
4438 'org-todo-setup-filter-hook kws)
4439 kws)))
4440 (setq inter (pop kws) sep (member "|" kws)
4441 kws0 (delete "|" (copy-sequence kws))
4442 kwsa nil
4443 kws1 (mapcar
4444 (lambda (x)
4445 ;; 1 2
4446 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4447 (progn
4448 (setq kw (match-string 1 x)
4449 key (and (match-end 2) (match-string 2 x))
4450 log (org-extract-log-state-settings x))
4451 (push (cons kw (and key (string-to-char key))) kwsa)
4452 (and log (push log org-todo-log-states))
4454 (error "Invalid TODO keyword %s" x)))
4455 kws0)
4456 kwsa (if kwsa (append '((:startgroup))
4457 (nreverse kwsa)
4458 '((:endgroup))))
4459 hw (car kws1)
4460 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4461 tail (list inter hw (car dws) (org-last dws))))
4462 (add-to-list 'org-todo-heads hw 'append)
4463 (push kws1 org-todo-sets)
4464 (setq org-done-keywords (append org-done-keywords dws nil))
4465 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4466 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4467 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4468 (setq org-todo-sets (nreverse org-todo-sets)
4469 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4470 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4471 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4472 ;; Process the constants
4473 (when const
4474 (let (e cst)
4475 (while (setq e (pop const))
4476 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4477 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4478 (setq org-table-formula-constants-local cst)))
4480 ;; Process the tags.
4481 (when tags
4482 (let (e tgs)
4483 (while (setq e (pop tags))
4484 (cond
4485 ((equal e "{") (push '(:startgroup) tgs))
4486 ((equal e "}") (push '(:endgroup) tgs))
4487 ((equal e "\\n") (push '(:newline) tgs))
4488 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4489 (push (cons (match-string 1 e)
4490 (string-to-char (match-string 2 e)))
4491 tgs))
4492 (t (push (list e) tgs))))
4493 (org-set-local 'org-tag-alist nil)
4494 (while (setq e (pop tgs))
4495 (or (and (stringp (car e))
4496 (assoc (car e) org-tag-alist))
4497 (push e org-tag-alist)))))
4499 ;; Compute the regular expressions and other local variables
4500 (if (not org-done-keywords)
4501 (setq org-done-keywords (and org-todo-keywords-1
4502 (list (org-last org-todo-keywords-1)))))
4503 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4504 (length org-scheduled-string)
4505 (length org-clock-string)
4506 (length org-closed-string)))
4507 org-drawer-regexp
4508 (concat "^[ \t]*:\\("
4509 (mapconcat 'regexp-quote org-drawers "\\|")
4510 "\\):[ \t]*$")
4511 org-not-done-keywords
4512 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4513 org-todo-regexp
4514 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4515 "\\|") "\\)\\>")
4516 org-not-done-regexp
4517 (concat "\\<\\("
4518 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4519 "\\)\\>")
4520 org-not-done-heading-regexp
4521 (concat "^\\(\\*+\\)[ \t]+\\("
4522 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4523 "\\)\\>")
4524 org-todo-line-regexp
4525 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4526 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4527 "\\)\\>\\)?[ \t]*\\(.*\\)")
4528 org-complex-heading-regexp
4529 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4530 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4531 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4532 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
4533 org-complex-heading-regexp-format
4534 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4535 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4536 "\\)\\>\\)?"
4537 "\\(?:[ \t]*\\(\\[#.\\]\\)\\)?"
4538 "\\(?:[ \t]*\\(?:\\[[0-9%%/]+\\]\\)\\)?" ;; stats cookie
4539 "[ \t]*\\(%s\\)"
4540 "\\(?:[ \t]*\\(?:\\[[0-9%%/]+\\]\\)\\)?" ;; stats cookie
4541 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?[ \t]*$")
4542 org-nl-done-regexp
4543 (concat "\n\\*+[ \t]+"
4544 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4545 "\\)" "\\>")
4546 org-todo-line-tags-regexp
4547 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4548 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4549 (org-re
4550 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@#%]+:[ \t]*\\)?$\\)"))
4551 org-looking-at-done-regexp
4552 (concat "^" "\\(?:"
4553 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4554 "\\>")
4555 org-deadline-regexp (concat "\\<" org-deadline-string)
4556 org-deadline-time-regexp
4557 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4558 org-deadline-line-regexp
4559 (concat "\\<\\(" org-deadline-string "\\).*")
4560 org-scheduled-regexp
4561 (concat "\\<" org-scheduled-string)
4562 org-scheduled-time-regexp
4563 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4564 org-closed-time-regexp
4565 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4566 org-keyword-time-regexp
4567 (concat "\\<\\(" org-scheduled-string
4568 "\\|" org-deadline-string
4569 "\\|" org-closed-string
4570 "\\|" org-clock-string "\\)"
4571 " *[[<]\\([^]>]+\\)[]>]")
4572 org-keyword-time-not-clock-regexp
4573 (concat "\\<\\(" org-scheduled-string
4574 "\\|" org-deadline-string
4575 "\\|" org-closed-string
4576 "\\)"
4577 " *[[<]\\([^]>]+\\)[]>]")
4578 org-maybe-keyword-time-regexp
4579 (concat "\\(\\<\\(" org-scheduled-string
4580 "\\|" org-deadline-string
4581 "\\|" org-closed-string
4582 "\\|" org-clock-string "\\)\\)?"
4583 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4584 org-planning-or-clock-line-re
4585 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4586 "\\|" org-deadline-string
4587 "\\|" org-closed-string "\\|" org-clock-string
4588 "\\)\\>\\)")
4589 org-all-time-keywords
4590 (mapcar (lambda (w) (substring w 0 -1))
4591 (list org-scheduled-string org-deadline-string
4592 org-clock-string org-closed-string))
4594 (org-compute-latex-and-specials-regexp)
4595 (org-set-font-lock-defaults))))
4597 (defun org-file-contents (file &optional noerror)
4598 "Return the contents of FILE, as a string."
4599 (if (or (not file)
4600 (not (file-readable-p file)))
4601 (if noerror
4602 (progn
4603 (message "Cannot read file \"%s\"" file)
4604 (ding) (sit-for 2)
4606 (error "Cannot read file \"%s\"" file))
4607 (with-temp-buffer
4608 (insert-file-contents file)
4609 (buffer-string))))
4611 (defun org-extract-log-state-settings (x)
4612 "Extract the log state setting from a TODO keyword string.
4613 This will extract info from a string like \"WAIT(w@/!)\"."
4614 (let (kw key log1 log2)
4615 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4616 (setq kw (match-string 1 x)
4617 key (and (match-end 2) (match-string 2 x))
4618 log1 (and (match-end 3) (match-string 3 x))
4619 log2 (and (match-end 4) (match-string 4 x)))
4620 (and (or log1 log2)
4621 (list kw
4622 (and log1 (if (equal log1 "!") 'time 'note))
4623 (and log2 (if (equal log2 "!") 'time 'note)))))))
4625 (defun org-remove-keyword-keys (list)
4626 "Remove a pair of parenthesis at the end of each string in LIST."
4627 (mapcar (lambda (x)
4628 (if (string-match "(.*)$" x)
4629 (substring x 0 (match-beginning 0))
4631 list))
4633 (defun org-assign-fast-keys (alist)
4634 "Assign fast keys to a keyword-key alist.
4635 Respect keys that are already there."
4636 (let (new e (alt ?0))
4637 (while (setq e (pop alist))
4638 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4639 (cdr e)) ;; Key already assigned.
4640 (push e new)
4641 (let ((clist (string-to-list (downcase (car e))))
4642 (used (append new alist)))
4643 (when (= (car clist) ?@)
4644 (pop clist))
4645 (while (and clist (rassoc (car clist) used))
4646 (pop clist))
4647 (unless clist
4648 (while (rassoc alt used)
4649 (incf alt)))
4650 (push (cons (car e) (or (car clist) alt)) new))))
4651 (nreverse new)))
4653 ;;; Some variables used in various places
4655 (defvar org-window-configuration nil
4656 "Used in various places to store a window configuration.")
4657 (defvar org-selected-window nil
4658 "Used in various places to store a window configuration.")
4659 (defvar org-finish-function nil
4660 "Function to be called when `C-c C-c' is used.
4661 This is for getting out of special buffers like remember.")
4664 ;; FIXME: Occasionally check by commenting these, to make sure
4665 ;; no other functions uses these, forgetting to let-bind them.
4666 (defvar entry)
4667 (defvar last-state)
4668 (defvar date)
4670 ;; Defined somewhere in this file, but used before definition.
4671 (defvar org-entities) ;; defined in org-entities.el
4672 (defvar org-struct-menu)
4673 (defvar org-org-menu)
4674 (defvar org-tbl-menu)
4676 ;;;; Define the Org-mode
4678 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4679 (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"))
4682 ;; We use a before-change function to check if a table might need
4683 ;; an update.
4684 (defvar org-table-may-need-update t
4685 "Indicates that a table might need an update.
4686 This variable is set by `org-before-change-function'.
4687 `org-table-align' sets it back to nil.")
4688 (defun org-before-change-function (beg end)
4689 "Every change indicates that a table might need an update."
4690 (setq org-table-may-need-update t))
4691 (defvar org-mode-map)
4692 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4693 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4694 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4695 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4696 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4697 (defvar org-table-buffer-is-an nil)
4698 (defconst org-outline-regexp "\\*+ ")
4700 ;;;###autoload
4701 (define-derived-mode org-mode outline-mode "Org"
4702 "Outline-based notes management and organizer, alias
4703 \"Carsten's outline-mode for keeping track of everything.\"
4705 Org-mode develops organizational tasks around a NOTES file which
4706 contains information about projects as plain text. Org-mode is
4707 implemented on top of outline-mode, which is ideal to keep the content
4708 of large files well structured. It supports ToDo items, deadlines and
4709 time stamps, which magically appear in the diary listing of the Emacs
4710 calendar. Tables are easily created with a built-in table editor.
4711 Plain text URL-like links connect to websites, emails (VM), Usenet
4712 messages (Gnus), BBDB entries, and any files related to the project.
4713 For printing and sharing of notes, an Org-mode file (or a part of it)
4714 can be exported as a structured ASCII or HTML file.
4716 The following commands are available:
4718 \\{org-mode-map}"
4720 ;; Get rid of Outline menus, they are not needed
4721 ;; Need to do this here because define-derived-mode sets up
4722 ;; the keymap so late. Still, it is a waste to call this each time
4723 ;; we switch another buffer into org-mode.
4724 (if (featurep 'xemacs)
4725 (when (boundp 'outline-mode-menu-heading)
4726 ;; Assume this is Greg's port, it uses easymenu
4727 (easy-menu-remove outline-mode-menu-heading)
4728 (easy-menu-remove outline-mode-menu-show)
4729 (easy-menu-remove outline-mode-menu-hide))
4730 (define-key org-mode-map [menu-bar headings] 'undefined)
4731 (define-key org-mode-map [menu-bar hide] 'undefined)
4732 (define-key org-mode-map [menu-bar show] 'undefined))
4734 (org-load-modules-maybe)
4735 (easy-menu-add org-org-menu)
4736 (easy-menu-add org-tbl-menu)
4737 (org-install-agenda-files-menu)
4738 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4739 (add-to-invisibility-spec '(org-cwidth))
4740 (add-to-invisibility-spec '(org-hide-block . t))
4741 (when (featurep 'xemacs)
4742 (org-set-local 'line-move-ignore-invisible t))
4743 (org-set-local 'outline-regexp org-outline-regexp)
4744 (org-set-local 'outline-level 'org-outline-level)
4745 (when (and org-ellipsis
4746 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4747 (fboundp 'make-glyph-code))
4748 (unless org-display-table
4749 (setq org-display-table (make-display-table)))
4750 (set-display-table-slot
4751 org-display-table 4
4752 (vconcat (mapcar
4753 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4754 org-ellipsis)))
4755 (if (stringp org-ellipsis) org-ellipsis "..."))))
4756 (setq buffer-display-table org-display-table))
4757 (org-set-regexps-and-options)
4758 (when (and org-tag-faces (not org-tags-special-faces-re))
4759 ;; tag faces set outside customize.... force initialization.
4760 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4761 ;; Calc embedded
4762 (org-set-local 'calc-embedded-open-mode "# ")
4763 (modify-syntax-entry ?@ "w")
4764 (if org-startup-truncated (setq truncate-lines t))
4765 (org-set-local 'font-lock-unfontify-region-function
4766 'org-unfontify-region)
4767 ;; Activate before-change-function
4768 (org-set-local 'org-table-may-need-update t)
4769 (org-add-hook 'before-change-functions 'org-before-change-function nil
4770 'local)
4771 ;; Check for running clock before killing a buffer
4772 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4773 ;; Paragraphs and auto-filling
4774 (org-set-autofill-regexps)
4775 (setq indent-line-function 'org-indent-line-function)
4776 (org-update-radio-target-regexp)
4777 ;; Beginning/end of defun
4778 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
4779 (org-set-local 'end-of-defun-function 'org-end-of-defun)
4780 ;; Next error for sparse trees
4781 (org-set-local 'next-error-function 'org-occur-next-match)
4782 ;; Make sure dependence stuff works reliably, even for users who set it
4783 ;; too late :-(
4784 (if org-enforce-todo-dependencies
4785 (add-hook 'org-blocker-hook
4786 'org-block-todo-from-children-or-siblings-or-parent)
4787 (remove-hook 'org-blocker-hook
4788 'org-block-todo-from-children-or-siblings-or-parent))
4789 (if org-enforce-todo-checkbox-dependencies
4790 (add-hook 'org-blocker-hook
4791 'org-block-todo-from-checkboxes)
4792 (remove-hook 'org-blocker-hook
4793 'org-block-todo-from-checkboxes))
4795 ;; Comment characters
4796 (org-set-local 'comment-start "#")
4797 (org-set-local 'comment-padding " ")
4799 ;; Align options lines
4800 (org-set-local
4801 'align-mode-rules-list
4802 '((org-in-buffer-settings
4803 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4804 (modes . '(org-mode)))))
4806 ;; Imenu
4807 (org-set-local 'imenu-create-index-function
4808 'org-imenu-get-tree)
4810 ;; Make isearch reveal context
4811 (if (or (featurep 'xemacs)
4812 (not (boundp 'outline-isearch-open-invisible-function)))
4813 ;; Emacs 21 and XEmacs make use of the hook
4814 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4815 ;; Emacs 22 deals with this through a special variable
4816 (org-set-local 'outline-isearch-open-invisible-function
4817 (lambda (&rest ignore) (org-show-context 'isearch))))
4819 ;; Turn on org-beamer-mode?
4820 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4822 ;; Setup the pcomplete hooks
4823 (set (make-local-variable 'pcomplete-command-completion-function)
4824 'org-pcomplete-initial)
4825 (set (make-local-variable 'pcomplete-command-name-function)
4826 'org-command-at-point)
4827 (set (make-local-variable 'pcomplete-default-completion-function)
4828 'ignore)
4829 (set (make-local-variable 'pcomplete-parse-arguments-function)
4830 'org-parse-arguments)
4831 (set (make-local-variable 'pcomplete-termination-string) "")
4832 (set (make-local-variable 'face-remapping-alist)
4833 '((default org-default)))
4835 ;; If empty file that did not turn on org-mode automatically, make it to.
4836 (if (and org-insert-mode-line-in-empty-file
4837 (org-called-interactively-p 'any)
4838 (= (point-min) (point-max)))
4839 (insert "# -*- mode: org -*-\n\n"))
4840 (unless org-inhibit-startup
4841 (when org-startup-align-all-tables
4842 (let ((bmp (buffer-modified-p)))
4843 (org-table-map-tables 'org-table-align 'quietly)
4844 (set-buffer-modified-p bmp)))
4845 (when org-startup-with-inline-images
4846 (org-display-inline-images))
4847 (when org-startup-indented
4848 (require 'org-indent)
4849 (org-indent-mode 1))
4850 (unless org-inhibit-startup-visibility-stuff
4851 (org-set-startup-visibility))))
4853 (when (fboundp 'abbrev-table-put)
4854 (abbrev-table-put org-mode-abbrev-table
4855 :parents (list text-mode-abbrev-table)))
4857 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4859 (defun org-current-time ()
4860 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4861 (if (> (car org-time-stamp-rounding-minutes) 1)
4862 (let ((r (car org-time-stamp-rounding-minutes))
4863 (time (decode-time)))
4864 (apply 'encode-time
4865 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4866 (nthcdr 2 time))))
4867 (current-time)))
4869 (defun org-today ()
4870 "Return today date, considering `org-extend-today-until'."
4871 (time-to-days
4872 (time-subtract (current-time)
4873 (list 0 (* 3600 org-extend-today-until) 0))))
4875 ;;;; Font-Lock stuff, including the activators
4877 (defvar org-mouse-map (make-sparse-keymap))
4878 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
4879 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
4880 (when org-mouse-1-follows-link
4881 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4882 (when org-tab-follows-link
4883 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4884 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4886 (require 'font-lock)
4888 (defconst org-non-link-chars "]\t\n\r<>")
4889 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4890 "shell" "elisp" "doi" "message"))
4891 (defvar org-link-types-re nil
4892 "Matches a link that has a url-like prefix like \"http:\"")
4893 (defvar org-link-re-with-space nil
4894 "Matches a link with spaces, optional angular brackets around it.")
4895 (defvar org-link-re-with-space2 nil
4896 "Matches a link with spaces, optional angular brackets around it.")
4897 (defvar org-link-re-with-space3 nil
4898 "Matches a link with spaces, only for internal part in bracket links.")
4899 (defvar org-angle-link-re nil
4900 "Matches link with angular brackets, spaces are allowed.")
4901 (defvar org-plain-link-re nil
4902 "Matches plain link, without spaces.")
4903 (defvar org-bracket-link-regexp nil
4904 "Matches a link in double brackets.")
4905 (defvar org-bracket-link-analytic-regexp nil
4906 "Regular expression used to analyze links.
4907 Here is what the match groups contain after a match:
4908 1: http:
4909 2: http
4910 3: path
4911 4: [desc]
4912 5: desc")
4913 (defvar org-bracket-link-analytic-regexp++ nil
4914 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
4915 (defvar org-any-link-re nil
4916 "Regular expression matching any link.")
4918 (defcustom org-match-sexp-depth 3
4919 "Number of stacked braces for sub/superscript matching.
4920 This has to be set before loading org.el to be effective."
4921 :group 'org-export-translation ; ??????????????????????????/
4922 :type 'integer)
4924 (defun org-create-multibrace-regexp (left right n)
4925 "Create a regular expression which will match a balanced sexp.
4926 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
4927 as single character strings.
4928 The regexp returned will match the entire expression including the
4929 delimiters. It will also define a single group which contains the
4930 match except for the outermost delimiters. The maximum depth of
4931 stacked delimiters is N. Escaping delimiters is not possible."
4932 (let* ((nothing (concat "[^" left right "]*?"))
4933 (or "\\|")
4934 (re nothing)
4935 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
4936 (while (> n 1)
4937 (setq n (1- n)
4938 re (concat re or next)
4939 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
4940 (concat left "\\(" re "\\)" right)))
4942 (defvar org-match-substring-regexp
4943 (concat
4944 "\\([^\\]\\)\\([_^]\\)\\("
4945 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
4946 "\\|"
4947 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
4948 "\\|"
4949 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
4950 "The regular expression matching a sub- or superscript.")
4952 (defvar org-match-substring-with-braces-regexp
4953 (concat
4954 "\\([^\\]\\)\\([_^]\\)\\("
4955 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
4956 "\\)")
4957 "The regular expression matching a sub- or superscript, forcing braces.")
4959 (defun org-make-link-regexps ()
4960 "Update the link regular expressions.
4961 This should be called after the variable `org-link-types' has changed."
4962 (setq org-link-types-re
4963 (concat
4964 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
4965 org-link-re-with-space
4966 (concat
4967 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4968 "\\([^" org-non-link-chars " ]"
4969 "[^" org-non-link-chars "]*"
4970 "[^" org-non-link-chars " ]\\)>?")
4971 org-link-re-with-space2
4972 (concat
4973 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4974 "\\([^" org-non-link-chars " ]"
4975 "[^\t\n\r]*"
4976 "[^" org-non-link-chars " ]\\)>?")
4977 org-link-re-with-space3
4978 (concat
4979 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4980 "\\([^" org-non-link-chars " ]"
4981 "[^\t\n\r]*\\)")
4982 org-angle-link-re
4983 (concat
4984 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4985 "\\([^" org-non-link-chars " ]"
4986 "[^" org-non-link-chars "]*"
4987 "\\)>")
4988 org-plain-link-re
4989 (concat
4990 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4991 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4992 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4993 org-bracket-link-regexp
4994 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4995 org-bracket-link-analytic-regexp
4996 (concat
4997 "\\[\\["
4998 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
4999 "\\([^]]+\\)"
5000 "\\]"
5001 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5002 "\\]")
5003 org-bracket-link-analytic-regexp++
5004 (concat
5005 "\\[\\["
5006 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5007 "\\([^]]+\\)"
5008 "\\]"
5009 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5010 "\\]")
5011 org-any-link-re
5012 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5013 org-angle-link-re "\\)\\|\\("
5014 org-plain-link-re "\\)")))
5016 (org-make-link-regexps)
5018 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5019 "Regular expression for fast time stamp matching.")
5020 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?\\)[]>]"
5021 "Regular expression for fast time stamp matching.")
5022 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5023 "Regular expression matching time strings for analysis.
5024 This one does not require the space after the date, so it can be used
5025 on a string that terminates immediately after the date.")
5026 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5027 "Regular expression matching time strings for analysis.")
5028 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5029 "Regular expression matching time stamps, with groups.")
5030 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5031 "Regular expression matching time stamps (also [..]), with groups.")
5032 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5033 "Regular expression matching a time stamp range.")
5034 (defconst org-tr-regexp-both
5035 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5036 "Regular expression matching a time stamp range.")
5037 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5038 org-ts-regexp "\\)?")
5039 "Regular expression matching a time stamp or time stamp range.")
5040 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5041 org-ts-regexp-both "\\)?")
5042 "Regular expression matching a time stamp or time stamp range.
5043 The time stamps may be either active or inactive.")
5045 (defvar org-emph-face nil)
5047 (defun org-do-emphasis-faces (limit)
5048 "Run through the buffer and add overlays to links."
5049 (let (rtn a)
5050 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5051 (if (not (= (char-after (match-beginning 3))
5052 (char-after (match-beginning 4))))
5053 (progn
5054 (setq rtn t)
5055 (setq a (assoc (match-string 3) org-emphasis-alist))
5056 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5057 'face
5058 (nth 1 a))
5059 (and (nth 4 a)
5060 (org-remove-flyspell-overlays-in
5061 (match-beginning 0) (match-end 0)))
5062 (add-text-properties (match-beginning 2) (match-end 2)
5063 '(font-lock-multiline t org-emphasis t))
5064 (when org-hide-emphasis-markers
5065 (add-text-properties (match-end 4) (match-beginning 5)
5066 '(invisible org-link))
5067 (add-text-properties (match-beginning 3) (match-end 3)
5068 '(invisible org-link)))))
5069 (backward-char 1))
5070 rtn))
5072 (defun org-emphasize (&optional char)
5073 "Insert or change an emphasis, i.e. a font like bold or italic.
5074 If there is an active region, change that region to a new emphasis.
5075 If there is no region, just insert the marker characters and position
5076 the cursor between them.
5077 CHAR should be either the marker character, or the first character of the
5078 HTML tag associated with that emphasis. If CHAR is a space, the means
5079 to remove the emphasis of the selected region.
5080 If char is not given (for example in an interactive call) it
5081 will be prompted for."
5082 (interactive)
5083 (let ((eal org-emphasis-alist) e det
5084 (erc org-emphasis-regexp-components)
5085 (prompt "")
5086 (string "") beg end move tag c s)
5087 (if (org-region-active-p)
5088 (setq beg (region-beginning) end (region-end)
5089 string (buffer-substring beg end))
5090 (setq move t))
5092 (while (setq e (pop eal))
5093 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5094 c (aref tag 0))
5095 (push (cons c (string-to-char (car e))) det)
5096 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5097 (substring tag 1)))))
5098 (setq det (nreverse det))
5099 (unless char
5100 (message "%s" (concat "Emphasis marker or tag:" prompt))
5101 (setq char (read-char-exclusive)))
5102 (setq char (or (cdr (assoc char det)) char))
5103 (if (equal char ?\ )
5104 (setq s "" move nil)
5105 (unless (assoc (char-to-string char) org-emphasis-alist)
5106 (error "No such emphasis marker: \"%c\"" char))
5107 (setq s (char-to-string char)))
5108 (while (and (> (length string) 1)
5109 (equal (substring string 0 1) (substring string -1))
5110 (assoc (substring string 0 1) org-emphasis-alist))
5111 (setq string (substring string 1 -1)))
5112 (setq string (concat s string s))
5113 (if beg (delete-region beg end))
5114 (unless (or (bolp)
5115 (string-match (concat "[" (nth 0 erc) "\n]")
5116 (char-to-string (char-before (point)))))
5117 (insert " "))
5118 (unless (or (eobp)
5119 (string-match (concat "[" (nth 1 erc) "\n]")
5120 (char-to-string (char-after (point)))))
5121 (insert " ") (backward-char 1))
5122 (insert string)
5123 (and move (backward-char 1))))
5125 (defconst org-nonsticky-props
5126 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5128 (defsubst org-rear-nonsticky-at (pos)
5129 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5131 (defun org-activate-plain-links (limit)
5132 "Run through the buffer and add overlays to links."
5133 (catch 'exit
5134 (let (f)
5135 (if (re-search-forward org-plain-link-re limit t)
5136 (progn
5137 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5138 (setq f (get-text-property (match-beginning 0) 'face))
5139 (if (or (eq f 'org-tag)
5140 (and (listp f) (memq 'org-tag f)))
5142 (add-text-properties (match-beginning 0) (match-end 0)
5143 (list 'mouse-face 'highlight
5144 'face 'org-link
5145 'keymap org-mouse-map))
5146 (org-rear-nonsticky-at (match-end 0)))
5147 t)))))
5149 (defun org-activate-code (limit)
5150 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
5151 (progn
5152 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5153 (remove-text-properties (match-beginning 0) (match-end 0)
5154 '(display t invisible t intangible t))
5155 t)))
5157 (defcustom org-src-fontify-natively nil
5158 "When non-nil, fontify code in code blocks."
5159 :type 'boolean
5160 :group 'org-appearance
5161 :group 'org-babel)
5163 (defun org-fontify-meta-lines-and-blocks (limit)
5164 (condition-case nil
5165 (org-fontify-meta-lines-and-blocks-1 limit)
5166 (error (message "org-mode fontification error"))))
5168 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5169 "Fontify #+ lines and blocks, in the correct ways."
5170 (let ((case-fold-search t))
5171 (if (re-search-forward
5172 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5173 limit t)
5174 (let ((beg (match-beginning 0))
5175 (block-start (match-end 0))
5176 (block-end nil)
5177 (lang (match-string 7))
5178 (beg1 (line-beginning-position 2))
5179 (dc1 (downcase (match-string 2)))
5180 (dc3 (downcase (match-string 3)))
5181 end end1 quoting block-type ovl)
5182 (cond
5183 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5184 ;; a single line of backend-specific content
5185 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5186 (remove-text-properties (match-beginning 0) (match-end 0)
5187 '(display t invisible t intangible t))
5188 (add-text-properties (match-beginning 1) (match-end 3)
5189 '(font-lock-fontified t face org-meta-line))
5190 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5191 '(font-lock-fontified t face org-block))
5192 ; for backend-specific code
5194 ((and (match-end 4) (equal dc3 "begin"))
5195 ;; Truly a block
5196 (setq block-type (downcase (match-string 5))
5197 quoting (member block-type org-protecting-blocks))
5198 (when (re-search-forward
5199 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5200 nil t) ;; on purpose, we look further than LIMIT
5201 (setq end (match-end 0) end1 (1- (match-beginning 0)))
5202 (setq block-end (match-beginning 0))
5203 (when quoting
5204 (remove-text-properties beg end
5205 '(display t invisible t intangible t)))
5206 (add-text-properties
5207 beg end
5208 '(font-lock-fontified t font-lock-multiline t))
5209 (add-text-properties beg beg1 '(face org-meta-line))
5210 (add-text-properties end1 (+ end 1) '(face org-meta-line))
5211 ; for end_src
5212 (cond
5213 ((and lang (not (string= lang "")) org-src-fontify-natively)
5214 (org-src-font-lock-fontify-block lang block-start block-end)
5215 ;; remove old background overlays
5216 (mapc (lambda (ov)
5217 (if (eq (overlay-get ov 'face) 'org-block-background)
5218 (delete-overlay ov)))
5219 (overlays-at (/ (+ beg1 block-end) 2)))
5220 ;; add a background overlay
5221 (setq ovl (make-overlay beg1 block-end))
5222 (overlay-put ovl 'face 'org-block-background)
5223 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5224 (quoting
5225 (add-text-properties beg1 (+ end1 1) '(face org-block)))
5226 ; end of source block
5227 ((not org-fontify-quote-and-verse-blocks))
5228 ((string= block-type "quote")
5229 (add-text-properties beg1 (1+ end1) '(face org-quote)))
5230 ((string= block-type "verse")
5231 (add-text-properties beg1 (1+ end1) '(face org-verse))))
5232 (add-text-properties beg beg1 '(face org-block-begin-line))
5233 (add-text-properties (1+ end) (1+ end1) '(face org-block-end-line))
5235 ((member dc1 '("title:" "author:" "email:" "date:"))
5236 (add-text-properties
5237 beg (match-end 3)
5238 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5239 '(font-lock-fontified t invisible t)
5240 '(font-lock-fontified t face org-document-info-keyword)))
5241 (add-text-properties
5242 (match-beginning 6) (match-end 6)
5243 (if (string-equal dc1 "title:")
5244 '(font-lock-fontified t face org-document-title)
5245 '(font-lock-fontified t face org-document-info))))
5246 ((not (member (char-after beg) '(?\ ?\t)))
5247 ;; just any other in-buffer setting, but not indented
5248 (add-text-properties
5249 beg (1+ (match-end 0))
5250 '(font-lock-fontified t face org-meta-line))
5252 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5253 "orgtbl:" "tblfm:" "tblname:" "result:"
5254 "results:" "source:" "srcname:" "call:"
5255 "data:" "header:" "headers:"))
5256 (and (match-end 4) (equal dc3 "attr")))
5257 (add-text-properties
5258 beg (match-end 0)
5259 '(font-lock-fontified t face org-meta-line))
5261 ((member dc3 '(" " ""))
5262 (add-text-properties
5263 beg (match-end 0)
5264 '(font-lock-fontified t face font-lock-comment-face)))
5265 (t nil))))))
5267 (defun org-activate-angle-links (limit)
5268 "Run through the buffer and add overlays to links."
5269 (if (re-search-forward org-angle-link-re limit t)
5270 (progn
5271 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5272 (add-text-properties (match-beginning 0) (match-end 0)
5273 (list 'mouse-face 'highlight
5274 'keymap org-mouse-map))
5275 (org-rear-nonsticky-at (match-end 0))
5276 t)))
5278 (defun org-activate-footnote-links (limit)
5279 "Run through the buffer and add overlays to footnotes."
5280 (let ((fn (org-footnote-next-reference-or-definition limit)))
5281 (when fn
5282 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5283 (org-remove-flyspell-overlays-in beg end)
5284 (add-text-properties beg end
5285 (list 'mouse-face 'highlight
5286 'keymap org-mouse-map
5287 'help-echo
5288 (if (= (point-at-bol) beg)
5289 "Footnote definition"
5290 "Footnote reference")
5291 'font-lock-fontified t
5292 'font-lock-multiline t
5293 'face 'org-footnote))))))
5295 (defun org-activate-bracket-links (limit)
5296 "Run through the buffer and add overlays to bracketed links."
5297 (if (re-search-forward org-bracket-link-regexp limit t)
5298 (let* ((help (concat "LINK: "
5299 (org-match-string-no-properties 1)))
5300 ;; FIXME: above we should remove the escapes.
5301 ;; but that requires another match, protecting match data,
5302 ;; a lot of overhead for font-lock.
5303 (ip (org-maybe-intangible
5304 (list 'invisible 'org-link
5305 'keymap org-mouse-map 'mouse-face 'highlight
5306 'font-lock-multiline t 'help-echo help)))
5307 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5308 'font-lock-multiline t 'help-echo help)))
5309 ;; We need to remove the invisible property here. Table narrowing
5310 ;; may have made some of this invisible.
5311 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5312 (remove-text-properties (match-beginning 0) (match-end 0)
5313 '(invisible nil))
5314 (if (match-end 3)
5315 (progn
5316 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5317 (org-rear-nonsticky-at (match-beginning 3))
5318 (add-text-properties (match-beginning 3) (match-end 3) vp)
5319 (org-rear-nonsticky-at (match-end 3))
5320 (add-text-properties (match-end 3) (match-end 0) ip)
5321 (org-rear-nonsticky-at (match-end 0)))
5322 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5323 (org-rear-nonsticky-at (match-beginning 1))
5324 (add-text-properties (match-beginning 1) (match-end 1) vp)
5325 (org-rear-nonsticky-at (match-end 1))
5326 (add-text-properties (match-end 1) (match-end 0) ip)
5327 (org-rear-nonsticky-at (match-end 0)))
5328 t)))
5330 (defun org-activate-dates (limit)
5331 "Run through the buffer and add overlays to dates."
5332 (if (re-search-forward org-tsr-regexp-both limit t)
5333 (progn
5334 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5335 (add-text-properties (match-beginning 0) (match-end 0)
5336 (list 'mouse-face 'highlight
5337 'keymap org-mouse-map))
5338 (org-rear-nonsticky-at (match-end 0))
5339 (when org-display-custom-times
5340 (if (match-end 3)
5341 (org-display-custom-time (match-beginning 3) (match-end 3)))
5342 (org-display-custom-time (match-beginning 1) (match-end 1)))
5343 t)))
5345 (defvar org-target-link-regexp nil
5346 "Regular expression matching radio targets in plain text.")
5347 (make-variable-buffer-local 'org-target-link-regexp)
5348 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5349 "Regular expression matching a link target.")
5350 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5351 "Regular expression matching a radio target.")
5352 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5353 "Regular expression matching any target.")
5355 (defun org-activate-target-links (limit)
5356 "Run through the buffer and add overlays to target matches."
5357 (when org-target-link-regexp
5358 (let ((case-fold-search t))
5359 (if (re-search-forward org-target-link-regexp limit t)
5360 (progn
5361 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5362 (add-text-properties (match-beginning 0) (match-end 0)
5363 (list 'mouse-face 'highlight
5364 'keymap org-mouse-map
5365 'help-echo "Radio target link"
5366 'org-linked-text t))
5367 (org-rear-nonsticky-at (match-end 0))
5368 t)))))
5370 (defun org-update-radio-target-regexp ()
5371 "Find all radio targets in this file and update the regular expression."
5372 (interactive)
5373 (when (memq 'radio org-activate-links)
5374 (setq org-target-link-regexp
5375 (org-make-target-link-regexp (org-all-targets 'radio)))
5376 (org-restart-font-lock)))
5378 (defun org-hide-wide-columns (limit)
5379 (let (s e)
5380 (setq s (text-property-any (point) (or limit (point-max))
5381 'org-cwidth t))
5382 (when s
5383 (setq e (next-single-property-change s 'org-cwidth))
5384 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5385 (goto-char e)
5386 t)))
5388 (defvar org-latex-and-specials-regexp nil
5389 "Regular expression for highlighting export special stuff.")
5390 (defvar org-match-substring-regexp)
5391 (defvar org-match-substring-with-braces-regexp)
5393 ;; This should be with the exporter code, but we also use if for font-locking
5394 (defconst org-export-html-special-string-regexps
5395 '(("\\\\-" . "&shy;")
5396 ("---\\([^-]\\)" . "&mdash;\\1")
5397 ("--\\([^-]\\)" . "&ndash;\\1")
5398 ("\\.\\.\\." . "&hellip;"))
5399 "Regular expressions for special string conversion.")
5402 (defun org-compute-latex-and-specials-regexp ()
5403 "Compute regular expression for stuff treated specially by exporters."
5404 (if (not org-highlight-latex-fragments-and-specials)
5405 (org-set-local 'org-latex-and-specials-regexp nil)
5406 (require 'org-exp)
5407 (let*
5408 ((matchers (plist-get org-format-latex-options :matchers))
5409 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5410 org-latex-regexps)))
5411 (org-export-allow-BIND nil)
5412 (options (org-combine-plists (org-default-export-plist)
5413 (org-infile-export-plist)))
5414 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5415 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5416 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5417 (org-export-html-expand (plist-get options :expand-quoted-html))
5418 (org-export-with-special-strings (plist-get options :special-strings))
5419 (re-sub
5420 (cond
5421 ((equal org-export-with-sub-superscripts '{})
5422 (list org-match-substring-with-braces-regexp))
5423 (org-export-with-sub-superscripts
5424 (list org-match-substring-regexp))
5425 (t nil)))
5426 (re-latex
5427 (if org-export-with-LaTeX-fragments
5428 (mapcar (lambda (x) (nth 1 x)) latexs)))
5429 (re-macros
5430 (if org-export-with-TeX-macros
5431 (list (concat "\\\\"
5432 (regexp-opt
5433 (append
5435 (delq nil
5436 (mapcar 'car-safe
5437 (append org-entities-user
5438 org-entities)))
5439 (if (boundp 'org-latex-entities)
5440 (mapcar (lambda (x)
5441 (or (car-safe x) x))
5442 org-latex-entities)
5443 nil))
5444 'words))) ; FIXME
5446 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5447 (re-special (if org-export-with-special-strings
5448 (mapcar (lambda (x) (car x))
5449 org-export-html-special-string-regexps)))
5450 (re-rest
5451 (delq nil
5452 (list
5453 (if org-export-html-expand "@<[^>\n]+>")
5454 ))))
5455 (org-set-local
5456 'org-latex-and-specials-regexp
5457 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5458 re-rest) "\\|")))))
5460 (defun org-do-latex-and-special-faces (limit)
5461 "Run through the buffer and add overlays to links."
5462 (when org-latex-and-specials-regexp
5463 (let (rtn d)
5464 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5465 limit t))
5466 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5467 'face))
5468 '(org-code org-verbatim underline)))
5469 (progn
5470 (setq rtn t
5471 d (cond ((member (char-after (1+ (match-beginning 0)))
5472 '(?_ ?^)) 1)
5473 (t 0)))
5474 (font-lock-prepend-text-property
5475 (+ d (match-beginning 0)) (match-end 0)
5476 'face 'org-latex-and-export-specials)
5477 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5478 '(font-lock-multiline t)))))
5479 rtn)))
5481 (defun org-restart-font-lock ()
5482 "Restart `font-lock-mode', to force refontification."
5483 (when (and (boundp 'font-lock-mode) font-lock-mode)
5484 (font-lock-mode -1)
5485 (font-lock-mode 1)))
5487 (defun org-all-targets (&optional radio)
5488 "Return a list of all targets in this file.
5489 With optional argument RADIO, only find radio targets."
5490 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5491 rtn)
5492 (save-excursion
5493 (goto-char (point-min))
5494 (while (re-search-forward re nil t)
5495 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5496 rtn)))
5498 (defun org-make-target-link-regexp (targets)
5499 "Make regular expression matching all strings in TARGETS.
5500 The regular expression finds the targets also if there is a line break
5501 between words."
5502 (and targets
5503 (concat
5504 "\\<\\("
5505 (mapconcat
5506 (lambda (x)
5507 (setq x (regexp-quote x))
5508 (while (string-match " +" x)
5509 (setq x (replace-match "\\s-+" t t x)))
5511 targets
5512 "\\|")
5513 "\\)\\>")))
5515 (defun org-activate-tags (limit)
5516 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5517 (progn
5518 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5519 (add-text-properties (match-beginning 1) (match-end 1)
5520 (list 'mouse-face 'highlight
5521 'keymap org-mouse-map))
5522 (org-rear-nonsticky-at (match-end 1))
5523 t)))
5525 (defun org-outline-level ()
5526 "Compute the outline level of the heading at point.
5527 This function assumes that the cursor is at the beginning of a line matched
5528 by `outline-regexp'. Otherwise it returns garbage.
5529 If this is called at a normal headline, the level is the number of stars.
5530 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5531 (save-excursion
5532 (looking-at outline-regexp)
5533 (1- (- (match-end 0) (match-beginning 0)))))
5535 (defvar org-font-lock-keywords nil)
5537 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5538 "Regular expression matching a property line.")
5540 (defvar org-font-lock-hook nil
5541 "Functions to be called for special font lock stuff.")
5543 (defvar org-font-lock-set-keywords-hook nil
5544 "Functions that can manipulate `org-font-lock-extra-keywords'.
5545 This is calles after `org-font-lock-extra-keywords' is defined, but before
5546 it is installed to be used by font lock. This can be useful if something
5547 needs to be inserted at a specific position in the font-lock sequence.")
5549 (defun org-font-lock-hook (limit)
5550 (run-hook-with-args 'org-font-lock-hook limit))
5552 (defun org-set-font-lock-defaults ()
5553 (let* ((em org-fontify-emphasized-text)
5554 (lk org-activate-links)
5555 (org-font-lock-extra-keywords
5556 (list
5557 ;; Call the hook
5558 '(org-font-lock-hook)
5559 ;; Headlines
5560 `(,(if org-fontify-whole-heading-line
5561 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5562 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5563 (1 (org-get-level-face 1))
5564 (2 (org-get-level-face 2))
5565 (3 (org-get-level-face 3)))
5566 ;; Table lines
5567 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5568 (1 'org-table t))
5569 ;; Table internals
5570 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5571 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5572 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5573 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5574 ;; Drawers
5575 (list org-drawer-regexp '(0 'org-special-keyword t))
5576 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5577 ;; Properties
5578 (list org-property-re
5579 '(1 'org-special-keyword t)
5580 '(3 'org-property-value t))
5581 ;; Links
5582 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5583 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5584 (if (memq 'plain lk) '(org-activate-plain-links))
5585 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5586 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5587 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5588 (if (memq 'footnote lk) '(org-activate-footnote-links))
5589 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5590 '(org-hide-wide-columns (0 nil append))
5591 ;; TODO lines
5592 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
5593 '(1 (org-get-todo-face 1) t))
5594 ;; DONE
5595 (if org-fontify-done-headline
5596 (list (concat "^[*]+ +\\<\\("
5597 (mapconcat 'regexp-quote org-done-keywords "\\|")
5598 "\\)\\(.*\\)")
5599 '(2 'org-headline-done t))
5600 nil)
5601 ;; Priorities
5602 '(org-font-lock-add-priority-faces)
5603 ;; Tags
5604 '(org-font-lock-add-tag-faces)
5605 ;; Special keywords
5606 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5607 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5608 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5609 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5610 ;; Emphasis
5611 (if em
5612 (if (featurep 'xemacs)
5613 '(org-do-emphasis-faces (0 nil append))
5614 '(org-do-emphasis-faces)))
5615 ;; Checkboxes
5616 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5617 1 'org-checkbox prepend)
5618 (if (cdr (assq 'checkbox org-list-automatic-rules))
5619 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5620 (0 (org-get-checkbox-statistics-face) t)))
5621 ;; Description list items
5622 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5623 1 'bold prepend)
5624 ;; ARCHIVEd headings
5625 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5626 '(1 'org-archived prepend))
5627 ;; Specials
5628 '(org-do-latex-and-special-faces)
5629 '(org-fontify-entities)
5630 '(org-raise-scripts)
5631 ;; Code
5632 '(org-activate-code (1 'org-code t))
5633 ;; COMMENT
5634 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5635 "\\|" org-quote-string "\\)\\>")
5636 '(1 'org-special-keyword t))
5637 '("^#.*" (0 'font-lock-comment-face t))
5638 ;; Blocks and meta lines
5639 '(org-fontify-meta-lines-and-blocks)
5641 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5642 (run-hooks 'org-font-lock-set-keywords-hook)
5643 ;; Now set the full font-lock-keywords
5644 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5645 (org-set-local 'font-lock-defaults
5646 '(org-font-lock-keywords t nil nil backward-paragraph))
5647 (kill-local-variable 'font-lock-keywords) nil))
5649 (defun org-toggle-pretty-entities ()
5650 "Toggle the composition display of entities as UTF8 characters."
5651 (interactive)
5652 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5653 (org-restart-font-lock)
5654 (if org-pretty-entities
5655 (message "Entities are displayed as UTF8 characers")
5656 (save-restriction
5657 (widen)
5658 (org-decompose-region (point-min) (point-max))
5659 (message "Entities are displayed plain"))))
5661 (defun org-fontify-entities (limit)
5662 "Find an entity to fontify."
5663 (let (ee)
5664 (when org-pretty-entities
5665 (catch 'match
5666 (while (re-search-forward
5667 "\\\\\\([a-zA-Z][a-zA-Z0-9]*\\)\\($\\|[^[:alnum:]\n]\\)"
5668 limit t)
5669 (if (and (not (org-in-indented-comment-line))
5670 (setq ee (org-entity-get (match-string 1)))
5671 (= (length (nth 6 ee)) 1))
5672 (progn
5673 (add-text-properties
5674 (match-beginning 0) (match-end 1)
5675 (list 'font-lock-fontified t))
5676 (compose-region (match-beginning 0) (match-end 1)
5677 (nth 6 ee) nil)
5678 (backward-char 1)
5679 (throw 'match t))))
5680 nil))))
5682 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5683 "Fontify string S like in Org-mode."
5684 (with-temp-buffer
5685 (insert s)
5686 (let ((org-odd-levels-only odd-levels))
5687 (org-mode)
5688 (font-lock-fontify-buffer)
5689 (buffer-string))))
5691 (defvar org-m nil)
5692 (defvar org-l nil)
5693 (defvar org-f nil)
5694 (defun org-get-level-face (n)
5695 "Get the right face for match N in font-lock matching of headlines."
5696 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5697 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5698 (if org-cycle-level-faces
5699 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5700 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5701 (cond
5702 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5703 ((eq n 2) org-f)
5704 (t (if org-level-color-stars-only nil org-f))))
5707 (defun org-get-todo-face (kwd)
5708 "Get the right face for a TODO keyword KWD.
5709 If KWD is a number, get the corresponding match group."
5710 (if (numberp kwd) (setq kwd (match-string kwd)))
5711 (or (org-face-from-face-or-color
5712 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5713 (and (member kwd org-done-keywords) 'org-done)
5714 'org-todo))
5716 (defun org-face-from-face-or-color (context inherit face-or-color)
5717 "Create a face list that inherits INHERIT, but sets the foreground color.
5718 When FACE-OR-COLOR is not a string, just return it."
5719 (if (stringp face-or-color)
5720 (list :inherit inherit
5721 (cdr (assoc context org-faces-easy-properties))
5722 face-or-color)
5723 face-or-color))
5725 (defun org-font-lock-add-tag-faces (limit)
5726 "Add the special tag faces."
5727 (when (and org-tag-faces org-tags-special-faces-re)
5728 (while (re-search-forward org-tags-special-faces-re limit t)
5729 (add-text-properties (match-beginning 1) (match-end 1)
5730 (list 'face (org-get-tag-face 1)
5731 'font-lock-fontified t))
5732 (backward-char 1))))
5734 (defun org-font-lock-add-priority-faces (limit)
5735 "Add the special priority faces."
5736 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5737 (add-text-properties
5738 (match-beginning 0) (match-end 0)
5739 (list 'face (or (org-face-from-face-or-color
5740 'priority 'org-special-keyword
5741 (cdr (assoc (char-after (match-beginning 1))
5742 org-priority-faces)))
5743 'org-special-keyword)
5744 'font-lock-fontified t))))
5746 (defun org-get-tag-face (kwd)
5747 "Get the right face for a TODO keyword KWD.
5748 If KWD is a number, get the corresponding match group."
5749 (if (numberp kwd) (setq kwd (match-string kwd)))
5750 (or (org-face-from-face-or-color
5751 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5752 'org-tag))
5754 (defun org-unfontify-region (beg end &optional maybe_loudly)
5755 "Remove fontification and activation overlays from links."
5756 (font-lock-default-unfontify-region beg end)
5757 (let* ((buffer-undo-list t)
5758 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5759 (inhibit-modification-hooks t)
5760 deactivate-mark buffer-file-name buffer-file-truename)
5761 (org-decompose-region beg end)
5762 (remove-text-properties
5763 beg end
5764 (if org-indent-mode
5765 ;; also remove line-prefix and wrap-prefix properties
5766 '(mouse-face t keymap t org-linked-text t
5767 invisible t intangible t
5768 line-prefix t wrap-prefix t
5769 org-no-flyspell t org-emphasis t)
5770 '(mouse-face t keymap t org-linked-text t
5771 invisible t intangible t
5772 org-no-flyspell t org-emphasis t)))
5773 (org-remove-font-lock-display-properties beg end)))
5775 (defconst org-script-display '(((raise -0.3) (height 0.7))
5776 ((raise 0.3) (height 0.7))
5777 ((raise -0.5))
5778 ((raise 0.5)))
5779 "Display properties for showing superscripts and subscripts.")
5781 (defun org-remove-font-lock-display-properties (beg end)
5782 "Remove specific display properties that have been added by font lock.
5783 The will remove the raise properties that are used to show superscripts
5784 and subscripts."
5785 (let (next prop)
5786 (while (< beg end)
5787 (setq next (next-single-property-change beg 'display nil end)
5788 prop (get-text-property beg 'display))
5789 (if (member prop org-script-display)
5790 (put-text-property beg next 'display nil))
5791 (setq beg next))))
5793 (defun org-raise-scripts (limit)
5794 "Add raise properties to sub/superscripts."
5795 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
5796 (if (re-search-forward
5797 (if (eq org-use-sub-superscripts t)
5798 org-match-substring-regexp
5799 org-match-substring-with-braces-regexp)
5800 limit t)
5801 (let* ((pos (point)) table-p comment-p
5802 (mpos (match-beginning 3))
5803 (emph-p (get-text-property mpos 'org-emphasis))
5804 (link-p (get-text-property mpos 'mouse-face))
5805 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
5806 (goto-char (point-at-bol))
5807 (setq table-p (org-looking-at-p org-table-dataline-regexp)
5808 comment-p (org-looking-at-p "[ \t]*#"))
5809 (goto-char pos)
5810 ;; FIXME: Should we go back one character here, for a_b^c
5811 ;; (goto-char (1- pos)) ;????????????????????
5812 (if (or comment-p emph-p link-p keyw-p)
5814 (put-text-property (match-beginning 3) (match-end 0)
5815 'display
5816 (if (equal (char-after (match-beginning 2)) ?^)
5817 (nth (if table-p 3 1) org-script-display)
5818 (nth (if table-p 2 0) org-script-display)))
5819 (add-text-properties (match-beginning 2) (match-end 2)
5820 (list 'invisible t
5821 'org-dwidth t 'org-dwidth-n 1))
5822 (if (and (eq (char-after (match-beginning 3)) ?{)
5823 (eq (char-before (match-end 3)) ?}))
5824 (progn
5825 (add-text-properties
5826 (match-beginning 3) (1+ (match-beginning 3))
5827 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
5828 (add-text-properties
5829 (1- (match-end 3)) (match-end 3)
5830 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
5831 t)))))
5833 ;;;; Visibility cycling, including org-goto and indirect buffer
5835 ;;; Cycling
5837 (defvar org-cycle-global-status nil)
5838 (make-variable-buffer-local 'org-cycle-global-status)
5839 (defvar org-cycle-subtree-status nil)
5840 (make-variable-buffer-local 'org-cycle-subtree-status)
5842 ;;;###autoload
5844 (defvar org-inlinetask-min-level)
5846 (defun org-cycle (&optional arg)
5847 "TAB-action and visibility cycling for Org-mode.
5849 This is the command invoked in Org-mode by the TAB key. Its main purpose
5850 is outline visibility cycling, but it also invokes other actions
5851 in special contexts.
5853 - When this function is called with a prefix argument, rotate the entire
5854 buffer through 3 states (global cycling)
5855 1. OVERVIEW: Show only top-level headlines.
5856 2. CONTENTS: Show all headlines of all levels, but no body text.
5857 3. SHOW ALL: Show everything.
5858 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5859 determined by the variable `org-startup-folded', and by any VISIBILITY
5860 properties in the buffer.
5861 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5862 including any drawers.
5864 - When inside a table, re-align the table and move to the next field.
5866 - When point is at the beginning of a headline, rotate the subtree started
5867 by this line through 3 different states (local cycling)
5868 1. FOLDED: Only the main headline is shown.
5869 2. CHILDREN: The main headline and the direct children are shown.
5870 From this state, you can move to one of the children
5871 and zoom in further.
5872 3. SUBTREE: Show the entire subtree, including body text.
5873 If there is no subtree, switch directly from CHILDREN to FOLDED.
5875 - When point is at the beginning of an empty headline and the variable
5876 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5877 of the headline by demoting and promoting it to likely levels. This
5878 speeds up creation document structure by pressing TAB once or several
5879 times right after creating a new headline.
5881 - When there is a numeric prefix, go up to a heading with level ARG, do
5882 a `show-subtree' and return to the previous cursor position. If ARG
5883 is negative, go up that many levels.
5885 - When point is not at the beginning of a headline, execute the global
5886 binding for TAB, which is re-indenting the line. See the option
5887 `org-cycle-emulate-tab' for details.
5889 - Special case: if point is at the beginning of the buffer and there is
5890 no headline in line 1, this function will act as if called with prefix arg
5891 (C-u TAB, same as S-TAB) also when called without prefix arg.
5892 But only if also the variable `org-cycle-global-at-bob' is t."
5893 (interactive "P")
5894 (org-load-modules-maybe)
5895 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5896 (and org-cycle-level-after-item/entry-creation
5897 (or (org-cycle-level)
5898 (org-cycle-item-indentation))))
5899 (let* ((limit-level
5900 (or org-cycle-max-level
5901 (and (boundp 'org-inlinetask-min-level)
5902 org-inlinetask-min-level
5903 (1- org-inlinetask-min-level))))
5904 (nstars (and limit-level
5905 (if org-odd-levels-only
5906 (and limit-level (1- (* limit-level 2)))
5907 limit-level)))
5908 (outline-regexp
5909 (if (not (org-mode-p))
5910 outline-regexp
5911 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
5912 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
5913 (not (looking-at outline-regexp))))
5914 (org-cycle-hook
5915 (if bob-special
5916 (delq 'org-optimize-window-after-visibility-change
5917 (copy-sequence org-cycle-hook))
5918 org-cycle-hook))
5919 (pos (point)))
5921 (if (or bob-special (equal arg '(4)))
5922 ;; special case: use global cycling
5923 (setq arg t))
5925 (cond
5927 ((equal arg '(16))
5928 (setq last-command 'dummy)
5929 (org-set-startup-visibility)
5930 (message "Startup visibility, plus VISIBILITY properties"))
5932 ((equal arg '(64))
5933 (show-all)
5934 (message "Entire buffer visible, including drawers"))
5936 ;; Table: enter it or move to the next field.
5937 ((org-at-table-p 'any)
5938 (if (org-at-table.el-p)
5939 (message "Use C-c ' to edit table.el tables")
5940 (if arg (org-table-edit-field t)
5941 (org-table-justify-field-maybe)
5942 (call-interactively 'org-table-next-field))))
5944 ((run-hook-with-args-until-success
5945 'org-tab-after-check-for-table-hook))
5947 ;; Global cycling: delegate to `org-cycle-internal-global'.
5948 ((eq arg t) (org-cycle-internal-global))
5950 ;; Drawers: delegate to `org-flag-drawer'.
5951 ((and org-drawers org-drawer-regexp
5952 (save-excursion
5953 (beginning-of-line 1)
5954 (looking-at org-drawer-regexp)))
5955 (org-flag-drawer ; toggle block visibility
5956 (not (get-char-property (match-end 0) 'invisible))))
5958 ;; Show-subtree, ARG levels up from here.
5959 ((integerp arg)
5960 (save-excursion
5961 (org-back-to-heading)
5962 (outline-up-heading (if (< arg 0) (- arg)
5963 (- (funcall outline-level) arg)))
5964 (org-show-subtree)))
5966 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
5967 ((and (featurep 'org-inlinetask)
5968 (org-inlinetask-at-task-p)
5969 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5970 (org-inlinetask-toggle-visibility))
5972 ;; At an item/headline: delegate to `org-cycle-internal-local'.
5973 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
5974 (save-excursion (beginning-of-line 1)
5975 (looking-at outline-regexp)))
5976 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5977 (org-cycle-internal-local))
5979 ;; From there: TAB emulation and template completion.
5980 (buffer-read-only (org-back-to-heading))
5982 ((run-hook-with-args-until-success
5983 'org-tab-after-check-for-cycling-hook))
5985 ((org-try-structure-completion))
5987 ((org-try-cdlatex-tab))
5989 ((run-hook-with-args-until-success
5990 'org-tab-before-tab-emulation-hook))
5992 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5993 (or (not (bolp))
5994 (not (looking-at outline-regexp))))
5995 (call-interactively (global-key-binding "\t")))
5997 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5998 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5999 (or (and (eq org-cycle-emulate-tab 'white)
6000 (= (match-end 0) (point-at-eol)))
6001 (and (eq org-cycle-emulate-tab 'whitestart)
6002 (>= (match-end 0) pos))))
6004 (eq org-cycle-emulate-tab t))
6005 (call-interactively (global-key-binding "\t")))
6007 (t (save-excursion
6008 (org-back-to-heading)
6009 (org-cycle)))))))
6011 (defun org-cycle-internal-global ()
6012 "Do the global cycling action."
6013 (cond
6014 ((and (eq last-command this-command)
6015 (eq org-cycle-global-status 'overview))
6016 ;; We just created the overview - now do table of contents
6017 ;; This can be slow in very large buffers, so indicate action
6018 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6019 (message "CONTENTS...")
6020 (org-content)
6021 (message "CONTENTS...done")
6022 (setq org-cycle-global-status 'contents)
6023 (run-hook-with-args 'org-cycle-hook 'contents))
6025 ((and (eq last-command this-command)
6026 (eq org-cycle-global-status 'contents))
6027 ;; We just showed the table of contents - now show everything
6028 (run-hook-with-args 'org-pre-cycle-hook 'all)
6029 (show-all)
6030 (message "SHOW ALL")
6031 (setq org-cycle-global-status 'all)
6032 (run-hook-with-args 'org-cycle-hook 'all))
6035 ;; Default action: go to overview
6036 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6037 (org-overview)
6038 (message "OVERVIEW")
6039 (setq org-cycle-global-status 'overview)
6040 (run-hook-with-args 'org-cycle-hook 'overview))))
6042 (defun org-cycle-internal-local ()
6043 "Do the local cycling action."
6044 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6045 ;; First, determine end of headline (EOH), end of subtree or item
6046 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6047 (save-excursion
6048 (if (org-at-item-p)
6049 (progn
6050 (beginning-of-line)
6051 (setq struct (org-list-struct))
6052 (setq eoh (point-at-eol))
6053 (setq eos (org-list-get-item-end-before-blank (point) struct))
6054 (setq has-children (org-list-has-child-p (point) struct)))
6055 (org-back-to-heading)
6056 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6057 (setq eos (save-excursion
6058 (org-end-of-subtree t)
6059 (unless (eobp)
6060 (skip-chars-forward " \t\n"))
6061 (if (eobp) (point) (1- (point)))))
6062 (setq has-children
6063 (or (save-excursion
6064 (let ((level (funcall outline-level)))
6065 (outline-next-heading)
6066 (and (org-at-heading-p t)
6067 (> (funcall outline-level) level))))
6068 (save-excursion
6069 (org-list-search-forward (org-item-beginning-re) eos t)))))
6070 ;; Determine end invisible part of buffer (EOL)
6071 (beginning-of-line 2)
6072 ;; XEmacs doesn't have `next-single-char-property-change'
6073 (if (featurep 'xemacs)
6074 (while (and (not (eobp)) ;; this is like `next-line'
6075 (get-char-property (1- (point)) 'invisible))
6076 (beginning-of-line 2))
6077 (while (and (not (eobp)) ;; this is like `next-line'
6078 (get-char-property (1- (point)) 'invisible))
6079 (goto-char (next-single-char-property-change (point) 'invisible))
6080 (and (eolp) (beginning-of-line 2))))
6081 (setq eol (point)))
6082 ;; Find out what to do next and set `this-command'
6083 (cond
6084 ((= eos eoh)
6085 ;; Nothing is hidden behind this heading
6086 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6087 (message "EMPTY ENTRY")
6088 (setq org-cycle-subtree-status nil)
6089 (save-excursion
6090 (goto-char eos)
6091 (outline-next-heading)
6092 (if (outline-invisible-p) (org-flag-heading nil))))
6093 ((and (or (>= eol eos)
6094 (not (string-match "\\S-" (buffer-substring eol eos))))
6095 (or has-children
6096 (not (setq children-skipped
6097 org-cycle-skip-children-state-if-no-children))))
6098 ;; Entire subtree is hidden in one line: children view
6099 (run-hook-with-args 'org-pre-cycle-hook 'children)
6100 (if (org-at-item-p)
6101 (org-list-set-item-visibility (point-at-bol) struct 'children)
6102 (org-show-entry)
6103 (show-children)
6104 ;; Fold every list in subtree to top-level items.
6105 (when (eq org-cycle-include-plain-lists 'integrate)
6106 (save-excursion
6107 (org-back-to-heading)
6108 (while (org-list-search-forward (org-item-beginning-re) eos t)
6109 (beginning-of-line 1)
6110 (let* ((struct (org-list-struct))
6111 (prevs (org-list-prevs-alist struct))
6112 (end (org-list-get-bottom-point struct)))
6113 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6114 (org-list-get-all-items (point) struct prevs))
6115 (goto-char end))))))
6116 (message "CHILDREN")
6117 (save-excursion
6118 (goto-char eos)
6119 (outline-next-heading)
6120 (if (outline-invisible-p) (org-flag-heading nil)))
6121 (setq org-cycle-subtree-status 'children)
6122 (run-hook-with-args 'org-cycle-hook 'children))
6123 ((or children-skipped
6124 (and (eq last-command this-command)
6125 (eq org-cycle-subtree-status 'children)))
6126 ;; We just showed the children, or no children are there,
6127 ;; now show everything.
6128 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6129 (outline-flag-region eoh eos nil)
6130 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6131 (setq org-cycle-subtree-status 'subtree)
6132 (run-hook-with-args 'org-cycle-hook 'subtree))
6134 ;; Default action: hide the subtree.
6135 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6136 (outline-flag-region eoh eos t)
6137 (message "FOLDED")
6138 (setq org-cycle-subtree-status 'folded)
6139 (run-hook-with-args 'org-cycle-hook 'folded)))))
6141 ;;;###autoload
6142 (defun org-global-cycle (&optional arg)
6143 "Cycle the global visibility. For details see `org-cycle'.
6144 With \\[universal-argument] prefix arg, switch to startup visibility.
6145 With a numeric prefix, show all headlines up to that level."
6146 (interactive "P")
6147 (let ((org-cycle-include-plain-lists
6148 (if (org-mode-p) org-cycle-include-plain-lists nil)))
6149 (cond
6150 ((integerp arg)
6151 (show-all)
6152 (hide-sublevels arg)
6153 (setq org-cycle-global-status 'contents))
6154 ((equal arg '(4))
6155 (org-set-startup-visibility)
6156 (message "Startup visibility, plus VISIBILITY properties."))
6158 (org-cycle '(4))))))
6160 (defun org-set-startup-visibility ()
6161 "Set the visibility required by startup options and properties."
6162 (cond
6163 ((eq org-startup-folded t)
6164 (org-cycle '(4)))
6165 ((eq org-startup-folded 'content)
6166 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6167 (org-cycle '(4)) (org-cycle '(4)))))
6168 (unless (eq org-startup-folded 'showeverything)
6169 (if org-hide-block-startup (org-hide-block-all))
6170 (org-set-visibility-according-to-property 'no-cleanup)
6171 (org-cycle-hide-archived-subtrees 'all)
6172 (org-cycle-hide-drawers 'all)
6173 (org-cycle-show-empty-lines t)))
6175 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6176 "Switch subtree visibilities according to :VISIBILITY: property."
6177 (interactive)
6178 (let (org-show-entry-below state)
6179 (save-excursion
6180 (goto-char (point-min))
6181 (while (re-search-forward
6182 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6183 nil t)
6184 (setq state (match-string 1))
6185 (save-excursion
6186 (org-back-to-heading t)
6187 (hide-subtree)
6188 (org-reveal)
6189 (cond
6190 ((equal state '("fold" "folded"))
6191 (hide-subtree))
6192 ((equal state "children")
6193 (org-show-hidden-entry)
6194 (show-children))
6195 ((equal state "content")
6196 (save-excursion
6197 (save-restriction
6198 (org-narrow-to-subtree)
6199 (org-content))))
6200 ((member state '("all" "showall"))
6201 (show-subtree)))))
6202 (unless no-cleanup
6203 (org-cycle-hide-archived-subtrees 'all)
6204 (org-cycle-hide-drawers 'all)
6205 (org-cycle-show-empty-lines 'all)))))
6207 (defun org-overview ()
6208 "Switch to overview mode, showing only top-level headlines.
6209 Really, this shows all headlines with level equal or greater than the level
6210 of the first headline in the buffer. This is important, because if the
6211 first headline is not level one, then (hide-sublevels 1) gives confusing
6212 results."
6213 (interactive)
6214 (let ((level (save-excursion
6215 (goto-char (point-min))
6216 (if (re-search-forward (concat "^" outline-regexp) nil t)
6217 (progn
6218 (goto-char (match-beginning 0))
6219 (funcall outline-level))))))
6220 (and level (hide-sublevels level))))
6222 (defun org-content (&optional arg)
6223 "Show all headlines in the buffer, like a table of contents.
6224 With numerical argument N, show content up to level N."
6225 (interactive "P")
6226 (save-excursion
6227 ;; Visit all headings and show their offspring
6228 (and (integerp arg) (org-overview))
6229 (goto-char (point-max))
6230 (catch 'exit
6231 (while (and (progn (condition-case nil
6232 (outline-previous-visible-heading 1)
6233 (error (goto-char (point-min))))
6235 (looking-at outline-regexp))
6236 (if (integerp arg)
6237 (show-children (1- arg))
6238 (show-branches))
6239 (if (bobp) (throw 'exit nil))))))
6242 (defun org-optimize-window-after-visibility-change (state)
6243 "Adjust the window after a change in outline visibility.
6244 This function is the default value of the hook `org-cycle-hook'."
6245 (when (get-buffer-window (current-buffer))
6246 (cond
6247 ((eq state 'content) nil)
6248 ((eq state 'all) nil)
6249 ((eq state 'folded) nil)
6250 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6251 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6253 (defun org-remove-empty-overlays-at (pos)
6254 "Remove outline overlays that do not contain non-white stuff."
6255 (mapc
6256 (lambda (o)
6257 (and (eq 'outline (overlay-get o 'invisible))
6258 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6259 (overlay-end o))))
6260 (delete-overlay o)))
6261 (overlays-at pos)))
6263 (defun org-clean-visibility-after-subtree-move ()
6264 "Fix visibility issues after moving a subtree."
6265 ;; First, find a reasonable region to look at:
6266 ;; Start two siblings above, end three below
6267 (let* ((beg (save-excursion
6268 (and (org-get-last-sibling)
6269 (org-get-last-sibling))
6270 (point)))
6271 (end (save-excursion
6272 (and (org-get-next-sibling)
6273 (org-get-next-sibling)
6274 (org-get-next-sibling))
6275 (if (org-at-heading-p)
6276 (point-at-eol)
6277 (point))))
6278 (level (looking-at "\\*+"))
6279 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6280 (save-excursion
6281 (save-restriction
6282 (narrow-to-region beg end)
6283 (when re
6284 ;; Properly fold already folded siblings
6285 (goto-char (point-min))
6286 (while (re-search-forward re nil t)
6287 (if (and (not (outline-invisible-p))
6288 (save-excursion
6289 (goto-char (point-at-eol)) (outline-invisible-p)))
6290 (hide-entry))))
6291 (org-cycle-show-empty-lines 'overview)
6292 (org-cycle-hide-drawers 'overview)))))
6294 (defun org-cycle-show-empty-lines (state)
6295 "Show empty lines above all visible headlines.
6296 The region to be covered depends on STATE when called through
6297 `org-cycle-hook'. Lisp program can use t for STATE to get the
6298 entire buffer covered. Note that an empty line is only shown if there
6299 are at least `org-cycle-separator-lines' empty lines before the headline."
6300 (when (not (= org-cycle-separator-lines 0))
6301 (save-excursion
6302 (let* ((n (abs org-cycle-separator-lines))
6303 (re (cond
6304 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6305 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6306 (t (let ((ns (number-to-string (- n 2))))
6307 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6308 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6309 beg end b e)
6310 (cond
6311 ((memq state '(overview contents t))
6312 (setq beg (point-min) end (point-max)))
6313 ((memq state '(children folded))
6314 (setq beg (point) end (progn (org-end-of-subtree t t)
6315 (beginning-of-line 2)
6316 (point)))))
6317 (when beg
6318 (goto-char beg)
6319 (while (re-search-forward re end t)
6320 (unless (get-char-property (match-end 1) 'invisible)
6321 (setq e (match-end 1))
6322 (if (< org-cycle-separator-lines 0)
6323 (setq b (save-excursion
6324 (goto-char (match-beginning 0))
6325 (org-back-over-empty-lines)
6326 (if (save-excursion
6327 (goto-char (max (point-min) (1- (point))))
6328 (org-on-heading-p))
6329 (1- (point))
6330 (point))))
6331 (setq b (match-beginning 1)))
6332 (outline-flag-region b e nil)))))))
6333 ;; Never hide empty lines at the end of the file.
6334 (save-excursion
6335 (goto-char (point-max))
6336 (outline-previous-heading)
6337 (outline-end-of-heading)
6338 (if (and (looking-at "[ \t\n]+")
6339 (= (match-end 0) (point-max)))
6340 (outline-flag-region (point) (match-end 0) nil))))
6342 (defun org-show-empty-lines-in-parent ()
6343 "Move to the parent and re-show empty lines before visible headlines."
6344 (save-excursion
6345 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6346 (org-cycle-show-empty-lines context))))
6348 (defun org-files-list ()
6349 "Return `org-agenda-files' list, plus all open org-mode files.
6350 This is useful for operations that need to scan all of a user's
6351 open and agenda-wise Org files."
6352 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6353 (dolist (buf (buffer-list))
6354 (with-current-buffer buf
6355 (if (and (org-mode-p) (buffer-file-name))
6356 (let ((file (expand-file-name (buffer-file-name))))
6357 (unless (member file files)
6358 (push file files))))))
6359 files))
6361 (defsubst org-entry-beginning-position ()
6362 "Return the beginning position of the current entry."
6363 (save-excursion (outline-back-to-heading t) (point)))
6365 (defsubst org-entry-end-position ()
6366 "Return the end position of the current entry."
6367 (save-excursion (outline-next-heading) (point)))
6369 (defun org-cycle-hide-drawers (state)
6370 "Re-hide all drawers after a visibility state change."
6371 (when (and (org-mode-p)
6372 (not (memq state '(overview folded contents))))
6373 (save-excursion
6374 (let* ((globalp (memq state '(contents all)))
6375 (beg (if globalp (point-min) (point)))
6376 (end (if globalp (point-max)
6377 (if (eq state 'children)
6378 (save-excursion (outline-next-heading) (point))
6379 (org-end-of-subtree t)))))
6380 (goto-char beg)
6381 (while (re-search-forward org-drawer-regexp end t)
6382 (org-flag-drawer t))))))
6384 (defun org-flag-drawer (flag)
6385 (save-excursion
6386 (beginning-of-line 1)
6387 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6388 (let ((b (match-end 0))
6389 (outline-regexp org-outline-regexp))
6390 (if (re-search-forward
6391 "^[ \t]*:END:"
6392 (save-excursion (outline-next-heading) (point)) t)
6393 (outline-flag-region b (point-at-eol) flag)
6394 (error ":END: line missing at position %s" b))))))
6396 (defun org-subtree-end-visible-p ()
6397 "Is the end of the current subtree visible?"
6398 (pos-visible-in-window-p
6399 (save-excursion (org-end-of-subtree t) (point))))
6401 (defun org-first-headline-recenter (&optional N)
6402 "Move cursor to the first headline and recenter the headline.
6403 Optional argument N means put the headline into the Nth line of the window."
6404 (goto-char (point-min))
6405 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
6406 (beginning-of-line)
6407 (recenter (prefix-numeric-value N))))
6409 ;;; Saving and restoring visibility
6411 (defun org-outline-overlay-data (&optional use-markers)
6412 "Return a list of the locations of all outline overlays.
6413 These are overlays with the `invisible' property value `outline'.
6414 The return value is a list of cons cells, with start and stop
6415 positions for each overlay.
6416 If USE-MARKERS is set, return the positions as markers."
6417 (let (beg end)
6418 (save-excursion
6419 (save-restriction
6420 (widen)
6421 (delq nil
6422 (mapcar (lambda (o)
6423 (when (eq (overlay-get o 'invisible) 'outline)
6424 (setq beg (overlay-start o)
6425 end (overlay-end o))
6426 (and beg end (> end beg)
6427 (if use-markers
6428 (cons (move-marker (make-marker) beg)
6429 (move-marker (make-marker) end))
6430 (cons beg end)))))
6431 (overlays-in (point-min) (point-max))))))))
6433 (defun org-set-outline-overlay-data (data)
6434 "Create visibility overlays for all positions in DATA.
6435 DATA should have been made by `org-outline-overlay-data'."
6436 (let (o)
6437 (save-excursion
6438 (save-restriction
6439 (widen)
6440 (show-all)
6441 (mapc (lambda (c)
6442 (setq o (make-overlay (car c) (cdr c)))
6443 (overlay-put o 'invisible 'outline))
6444 data)))))
6446 ;;; Folding of blocks
6448 (defconst org-block-regexp
6449 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
6450 "Regular expression for hiding blocks.")
6452 (defvar org-hide-block-overlays nil
6453 "Overlays hiding blocks.")
6454 (make-variable-buffer-local 'org-hide-block-overlays)
6456 (defun org-block-map (function &optional start end)
6457 "Call FUNCTION at the head of all source blocks in the current buffer.
6458 Optional arguments START and END can be used to limit the range."
6459 (let ((start (or start (point-min)))
6460 (end (or end (point-max))))
6461 (save-excursion
6462 (goto-char start)
6463 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6464 (save-excursion
6465 (save-match-data
6466 (goto-char (match-beginning 0))
6467 (funcall function)))))))
6469 (defun org-hide-block-toggle-all ()
6470 "Toggle the visibility of all blocks in the current buffer."
6471 (org-block-map #'org-hide-block-toggle))
6473 (defun org-hide-block-all ()
6474 "Fold all blocks in the current buffer."
6475 (interactive)
6476 (org-show-block-all)
6477 (org-block-map #'org-hide-block-toggle-maybe))
6479 (defun org-show-block-all ()
6480 "Unfold all blocks in the current buffer."
6481 (interactive)
6482 (mapc 'delete-overlay org-hide-block-overlays)
6483 (setq org-hide-block-overlays nil))
6485 (defun org-hide-block-toggle-maybe ()
6486 "Toggle visibility of block at point."
6487 (interactive)
6488 (let ((case-fold-search t))
6489 (if (save-excursion
6490 (beginning-of-line 1)
6491 (looking-at org-block-regexp))
6492 (progn (org-hide-block-toggle)
6493 t) ;; to signal that we took action
6494 nil))) ;; to signal that we did not
6496 (defun org-hide-block-toggle (&optional force)
6497 "Toggle the visibility of the current block."
6498 (interactive)
6499 (save-excursion
6500 (beginning-of-line)
6501 (if (re-search-forward org-block-regexp nil t)
6502 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6503 (end (match-end 0)) ;; end of entire body
6505 (if (memq t (mapcar (lambda (overlay)
6506 (eq (overlay-get overlay 'invisible)
6507 'org-hide-block))
6508 (overlays-at start)))
6509 (if (or (not force) (eq force 'off))
6510 (mapc (lambda (ov)
6511 (when (member ov org-hide-block-overlays)
6512 (setq org-hide-block-overlays
6513 (delq ov org-hide-block-overlays)))
6514 (when (eq (overlay-get ov 'invisible)
6515 'org-hide-block)
6516 (delete-overlay ov)))
6517 (overlays-at start)))
6518 (setq ov (make-overlay start end))
6519 (overlay-put ov 'invisible 'org-hide-block)
6520 ;; make the block accessible to isearch
6521 (overlay-put
6522 ov 'isearch-open-invisible
6523 (lambda (ov)
6524 (when (member ov org-hide-block-overlays)
6525 (setq org-hide-block-overlays
6526 (delq ov org-hide-block-overlays)))
6527 (when (eq (overlay-get ov 'invisible)
6528 'org-hide-block)
6529 (delete-overlay ov))))
6530 (push ov org-hide-block-overlays)))
6531 (error "Not looking at a source block"))))
6533 ;; org-tab-after-check-for-cycling-hook
6534 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6535 ;; Remove overlays when changing major mode
6536 (add-hook 'org-mode-hook
6537 (lambda () (org-add-hook 'change-major-mode-hook
6538 'org-show-block-all 'append 'local)))
6540 ;;; Org-goto
6542 (defvar org-goto-window-configuration nil)
6543 (defvar org-goto-marker nil)
6544 (defvar org-goto-map
6545 (let ((map (make-sparse-keymap)))
6546 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6547 (while (setq cmd (pop cmds))
6548 (substitute-key-definition cmd cmd map global-map)))
6549 (suppress-keymap map)
6550 (org-defkey map "\C-m" 'org-goto-ret)
6551 (org-defkey map [(return)] 'org-goto-ret)
6552 (org-defkey map [(left)] 'org-goto-left)
6553 (org-defkey map [(right)] 'org-goto-right)
6554 (org-defkey map [(control ?g)] 'org-goto-quit)
6555 (org-defkey map "\C-i" 'org-cycle)
6556 (org-defkey map [(tab)] 'org-cycle)
6557 (org-defkey map [(down)] 'outline-next-visible-heading)
6558 (org-defkey map [(up)] 'outline-previous-visible-heading)
6559 (if org-goto-auto-isearch
6560 (if (fboundp 'define-key-after)
6561 (define-key-after map [t] 'org-goto-local-auto-isearch)
6562 nil)
6563 (org-defkey map "q" 'org-goto-quit)
6564 (org-defkey map "n" 'outline-next-visible-heading)
6565 (org-defkey map "p" 'outline-previous-visible-heading)
6566 (org-defkey map "f" 'outline-forward-same-level)
6567 (org-defkey map "b" 'outline-backward-same-level)
6568 (org-defkey map "u" 'outline-up-heading))
6569 (org-defkey map "/" 'org-occur)
6570 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6571 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6572 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6573 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6574 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6575 map))
6577 (defconst org-goto-help
6578 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6579 RET=jump to location [Q]uit and return to previous location
6580 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6582 (defvar org-goto-start-pos) ; dynamically scoped parameter
6584 ;; FIXME: Docstring does not mention both interfaces
6585 (defun org-goto (&optional alternative-interface)
6586 "Look up a different location in the current file, keeping current visibility.
6588 When you want look-up or go to a different location in a document, the
6589 fastest way is often to fold the entire buffer and then dive into the tree.
6590 This method has the disadvantage, that the previous location will be folded,
6591 which may not be what you want.
6593 This command works around this by showing a copy of the current buffer
6594 in an indirect buffer, in overview mode. You can dive into the tree in
6595 that copy, use org-occur and incremental search to find a location.
6596 When pressing RET or `Q', the command returns to the original buffer in
6597 which the visibility is still unchanged. After RET is will also jump to
6598 the location selected in the indirect buffer and expose the headline
6599 hierarchy above."
6600 (interactive "P")
6601 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6602 (org-refile-use-outline-path t)
6603 (org-refile-target-verify-function nil)
6604 (interface
6605 (if (not alternative-interface)
6606 org-goto-interface
6607 (if (eq org-goto-interface 'outline)
6608 'outline-path-completion
6609 'outline)))
6610 (org-goto-start-pos (point))
6611 (selected-point
6612 (if (eq interface 'outline)
6613 (car (org-get-location (current-buffer) org-goto-help))
6614 (let ((pa (org-refile-get-location "Goto")))
6615 (org-refile-check-position pa)
6616 (nth 3 pa)))))
6617 (if selected-point
6618 (progn
6619 (org-mark-ring-push org-goto-start-pos)
6620 (goto-char selected-point)
6621 (if (or (outline-invisible-p) (org-invisible-p2))
6622 (org-show-context 'org-goto)))
6623 (message "Quit"))))
6625 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6626 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6627 (defvar org-goto-local-auto-isearch-map) ; defined below
6629 (defun org-get-location (buf help)
6630 "Let the user select a location in the Org-mode buffer BUF.
6631 This function uses a recursive edit. It returns the selected position
6632 or nil."
6633 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6634 (isearch-hide-immediately nil)
6635 (isearch-search-fun-function
6636 (lambda () 'org-goto-local-search-headings))
6637 (org-goto-selected-point org-goto-exit-command)
6638 (pop-up-frames nil)
6639 (special-display-buffer-names nil)
6640 (special-display-regexps nil)
6641 (special-display-function nil))
6642 (save-excursion
6643 (save-window-excursion
6644 (delete-other-windows)
6645 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6646 (switch-to-buffer
6647 (condition-case nil
6648 (make-indirect-buffer (current-buffer) "*org-goto*")
6649 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6650 (with-output-to-temp-buffer "*Help*"
6651 (princ help))
6652 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6653 (setq buffer-read-only nil)
6654 (let ((org-startup-truncated t)
6655 (org-startup-folded nil)
6656 (org-startup-align-all-tables nil))
6657 (org-mode)
6658 (org-overview))
6659 (setq buffer-read-only t)
6660 (if (and (boundp 'org-goto-start-pos)
6661 (integer-or-marker-p org-goto-start-pos))
6662 (let ((org-show-hierarchy-above t)
6663 (org-show-siblings t)
6664 (org-show-following-heading t))
6665 (goto-char org-goto-start-pos)
6666 (and (outline-invisible-p) (org-show-context)))
6667 (goto-char (point-min)))
6668 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6669 (message "Select location and press RET")
6670 (use-local-map org-goto-map)
6671 (recursive-edit)
6673 (kill-buffer "*org-goto*")
6674 (cons org-goto-selected-point org-goto-exit-command)))
6676 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6677 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6678 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6679 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6681 (defun org-goto-local-search-headings (string bound noerror)
6682 "Search and make sure that any matches are in headlines."
6683 (catch 'return
6684 (while (if isearch-forward
6685 (search-forward string bound noerror)
6686 (search-backward string bound noerror))
6687 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6688 (and (member :headline context)
6689 (not (member :tags context))))
6690 (throw 'return (point))))))
6692 (defun org-goto-local-auto-isearch ()
6693 "Start isearch."
6694 (interactive)
6695 (goto-char (point-min))
6696 (let ((keys (this-command-keys)))
6697 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6698 (isearch-mode t)
6699 (isearch-process-search-char (string-to-char keys)))))
6701 (defun org-goto-ret (&optional arg)
6702 "Finish `org-goto' by going to the new location."
6703 (interactive "P")
6704 (setq org-goto-selected-point (point)
6705 org-goto-exit-command 'return)
6706 (throw 'exit nil))
6708 (defun org-goto-left ()
6709 "Finish `org-goto' by going to the new location."
6710 (interactive)
6711 (if (org-on-heading-p)
6712 (progn
6713 (beginning-of-line 1)
6714 (setq org-goto-selected-point (point)
6715 org-goto-exit-command 'left)
6716 (throw 'exit nil))
6717 (error "Not on a heading")))
6719 (defun org-goto-right ()
6720 "Finish `org-goto' by going to the new location."
6721 (interactive)
6722 (if (org-on-heading-p)
6723 (progn
6724 (setq org-goto-selected-point (point)
6725 org-goto-exit-command 'right)
6726 (throw 'exit nil))
6727 (error "Not on a heading")))
6729 (defun org-goto-quit ()
6730 "Finish `org-goto' without cursor motion."
6731 (interactive)
6732 (setq org-goto-selected-point nil)
6733 (setq org-goto-exit-command 'quit)
6734 (throw 'exit nil))
6736 ;;; Indirect buffer display of subtrees
6738 (defvar org-indirect-dedicated-frame nil
6739 "This is the frame being used for indirect tree display.")
6740 (defvar org-last-indirect-buffer nil)
6742 (defun org-tree-to-indirect-buffer (&optional arg)
6743 "Create indirect buffer and narrow it to current subtree.
6744 With numerical prefix ARG, go up to this level and then take that tree.
6745 If ARG is negative, go up that many levels.
6746 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6747 indirect buffer previously made with this command, to avoid proliferation of
6748 indirect buffers. However, when you call the command with a \
6749 \\[universal-argument] prefix, or
6750 when `org-indirect-buffer-display' is `new-frame', the last buffer
6751 is kept so that you can work with several indirect buffers at the same time.
6752 If `org-indirect-buffer-display' is `dedicated-frame', the \
6753 \\[universal-argument] prefix also
6754 requests that a new frame be made for the new buffer, so that the dedicated
6755 frame is not changed."
6756 (interactive "P")
6757 (let ((cbuf (current-buffer))
6758 (cwin (selected-window))
6759 (pos (point))
6760 beg end level heading ibuf)
6761 (save-excursion
6762 (org-back-to-heading t)
6763 (when (numberp arg)
6764 (setq level (org-outline-level))
6765 (if (< arg 0) (setq arg (+ level arg)))
6766 (while (> (setq level (org-outline-level)) arg)
6767 (outline-up-heading 1 t)))
6768 (setq beg (point)
6769 heading (org-get-heading))
6770 (org-end-of-subtree t t)
6771 (if (org-on-heading-p) (backward-char 1))
6772 (setq end (point)))
6773 (if (and (buffer-live-p org-last-indirect-buffer)
6774 (not (eq org-indirect-buffer-display 'new-frame))
6775 (not arg))
6776 (kill-buffer org-last-indirect-buffer))
6777 (setq ibuf (org-get-indirect-buffer cbuf)
6778 org-last-indirect-buffer ibuf)
6779 (cond
6780 ((or (eq org-indirect-buffer-display 'new-frame)
6781 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6782 (select-frame (make-frame))
6783 (delete-other-windows)
6784 (switch-to-buffer ibuf)
6785 (org-set-frame-title heading))
6786 ((eq org-indirect-buffer-display 'dedicated-frame)
6787 (raise-frame
6788 (select-frame (or (and org-indirect-dedicated-frame
6789 (frame-live-p org-indirect-dedicated-frame)
6790 org-indirect-dedicated-frame)
6791 (setq org-indirect-dedicated-frame (make-frame)))))
6792 (delete-other-windows)
6793 (switch-to-buffer ibuf)
6794 (org-set-frame-title (concat "Indirect: " heading)))
6795 ((eq org-indirect-buffer-display 'current-window)
6796 (switch-to-buffer ibuf))
6797 ((eq org-indirect-buffer-display 'other-window)
6798 (pop-to-buffer ibuf))
6799 (t (error "Invalid value")))
6800 (if (featurep 'xemacs)
6801 (save-excursion (org-mode) (turn-on-font-lock)))
6802 (narrow-to-region beg end)
6803 (show-all)
6804 (goto-char pos)
6805 (and (window-live-p cwin) (select-window cwin))))
6807 (defun org-get-indirect-buffer (&optional buffer)
6808 (setq buffer (or buffer (current-buffer)))
6809 (let ((n 1) (base (buffer-name buffer)) bname)
6810 (while (buffer-live-p
6811 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6812 (setq n (1+ n)))
6813 (condition-case nil
6814 (make-indirect-buffer buffer bname 'clone)
6815 (error (make-indirect-buffer buffer bname)))))
6817 (defun org-set-frame-title (title)
6818 "Set the title of the current frame to the string TITLE."
6819 ;; FIXME: how to name a single frame in XEmacs???
6820 (unless (featurep 'xemacs)
6821 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6823 ;;;; Structure editing
6825 ;;; Inserting headlines
6827 (defun org-previous-line-empty-p ()
6828 (save-excursion
6829 (and (not (bobp))
6830 (or (beginning-of-line 0) t)
6831 (save-match-data
6832 (looking-at "[ \t]*$")))))
6834 (defun org-insert-heading (&optional force-heading invisible-ok)
6835 "Insert a new heading or item with same depth at point.
6836 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6837 If point is at the beginning of a headline, insert a sibling before the
6838 current headline. If point is not at the beginning, split the line,
6839 create the new headline with the text in the current line after point
6840 \(but see also the variable `org-M-RET-may-split-line').
6842 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6843 This is important for non-interactive uses of the command."
6844 (interactive "P")
6845 (if (or (= (buffer-size) 0)
6846 (and (not (save-excursion
6847 (and (ignore-errors (org-back-to-heading invisible-ok))
6848 (org-on-heading-p))))
6849 (not (org-in-item-p))))
6850 (progn
6851 (insert "\n* ")
6852 (run-hooks 'org-insert-heading-hook))
6853 (when (or force-heading (not (org-insert-item)))
6854 (let* ((empty-line-p nil)
6855 (level nil)
6856 (on-heading (org-on-heading-p))
6857 (head (save-excursion
6858 (condition-case nil
6859 (progn
6860 (org-back-to-heading invisible-ok)
6861 (when (and (not on-heading)
6862 (featurep 'org-inlinetask)
6863 (integerp org-inlinetask-min-level)
6864 (>= (length (match-string 0))
6865 org-inlinetask-min-level))
6866 ;; Find a heading level before the inline task
6867 (while (and (setq level (org-up-heading-safe))
6868 (>= level org-inlinetask-min-level)))
6869 (if (org-on-heading-p)
6870 (org-back-to-heading invisible-ok)
6871 (error "This should not happen")))
6872 (setq empty-line-p (org-previous-line-empty-p))
6873 (match-string 0))
6874 (error "*"))))
6875 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6876 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6877 pos hide-previous previous-pos)
6878 (cond
6879 ((and (org-on-heading-p) (bolp)
6880 (or (bobp)
6881 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
6882 ;; insert before the current line
6883 (open-line (if blank 2 1)))
6884 ((and (bolp)
6885 (not org-insert-heading-respect-content)
6886 (or (bobp)
6887 (save-excursion
6888 (backward-char 1) (not (outline-invisible-p)))))
6889 ;; insert right here
6890 nil)
6892 ;; somewhere in the line
6893 (save-excursion
6894 (setq previous-pos (point-at-bol))
6895 (end-of-line)
6896 (setq hide-previous (outline-invisible-p)))
6897 (and org-insert-heading-respect-content (org-show-subtree))
6898 (let ((split
6899 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6900 (save-excursion
6901 (let ((p (point)))
6902 (goto-char (point-at-bol))
6903 (and (looking-at org-complex-heading-regexp)
6904 (> p (match-beginning 4)))))))
6905 tags pos)
6906 (cond
6907 (org-insert-heading-respect-content
6908 (org-end-of-subtree nil t)
6909 (when (featurep 'org-inlinetask)
6910 (while (and (not (eobp))
6911 (looking-at "\\(\\*+\\)[ \t]+")
6912 (>= (length (match-string 1))
6913 org-inlinetask-min-level))
6914 (org-end-of-subtree nil t)))
6915 (or (bolp) (newline))
6916 (or (org-previous-line-empty-p)
6917 (and blank (newline)))
6918 (open-line 1))
6919 ((org-on-heading-p)
6920 (when hide-previous
6921 (show-children)
6922 (org-show-entry))
6923 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
6924 (setq tags (and (match-end 2) (match-string 2)))
6925 (and (match-end 1)
6926 (delete-region (match-beginning 1) (match-end 1)))
6927 (setq pos (point-at-bol))
6928 (or split (end-of-line 1))
6929 (delete-horizontal-space)
6930 (if (string-match "\\`\\*+\\'"
6931 (buffer-substring (point-at-bol) (point)))
6932 (insert " "))
6933 (newline (if blank 2 1))
6934 (when tags
6935 (save-excursion
6936 (goto-char pos)
6937 (end-of-line 1)
6938 (insert " " tags)
6939 (org-set-tags nil 'align))))
6941 (or split (end-of-line 1))
6942 (newline (if blank 2 1)))))))
6943 (insert head) (just-one-space)
6944 (setq pos (point))
6945 (end-of-line 1)
6946 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6947 (when (and org-insert-heading-respect-content hide-previous)
6948 (save-excursion
6949 (goto-char previous-pos)
6950 (hide-subtree)))
6951 (run-hooks 'org-insert-heading-hook)))))
6953 (defun org-get-heading (&optional no-tags)
6954 "Return the heading of the current entry, without the stars."
6955 (save-excursion
6956 (org-back-to-heading t)
6957 (if (looking-at
6958 (if no-tags
6959 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@#%]+:[ \t]*\\)?$")
6960 "\\*+[ \t]+\\([^\r\n]*\\)"))
6961 (match-string 1) "")))
6963 (defun org-heading-components ()
6964 "Return the components of the current heading.
6965 This is a list with the following elements:
6966 - the level as an integer
6967 - the reduced level, different if `org-odd-levels-only' is set.
6968 - the TODO keyword, or nil
6969 - the priority character, like ?A, or nil if no priority is given
6970 - the headline text itself, or the tags string if no headline text
6971 - the tags string, or nil."
6972 (save-excursion
6973 (org-back-to-heading t)
6974 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6975 (list (length (match-string 1))
6976 (org-reduced-level (length (match-string 1)))
6977 (org-match-string-no-properties 2)
6978 (and (match-end 3) (aref (match-string 3) 2))
6979 (org-match-string-no-properties 4)
6980 (org-match-string-no-properties 5)))))
6982 (defun org-get-entry ()
6983 "Get the entry text, after heading, entire subtree."
6984 (save-excursion
6985 (org-back-to-heading t)
6986 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6988 (defun org-insert-heading-after-current ()
6989 "Insert a new heading with same level as current, after current subtree."
6990 (interactive)
6991 (org-back-to-heading)
6992 (org-insert-heading)
6993 (org-move-subtree-down)
6994 (end-of-line 1))
6996 (defun org-insert-heading-respect-content ()
6997 (interactive)
6998 (let ((org-insert-heading-respect-content t))
6999 (org-insert-heading t)))
7001 (defun org-insert-todo-heading-respect-content (&optional force-state)
7002 (interactive "P")
7003 (let ((org-insert-heading-respect-content t))
7004 (org-insert-todo-heading force-state t)))
7006 (defun org-insert-todo-heading (arg &optional force-heading)
7007 "Insert a new heading with the same level and TODO state as current heading.
7008 If the heading has no TODO state, or if the state is DONE, use the first
7009 state (TODO by default). Also with prefix arg, force first state."
7010 (interactive "P")
7011 (when (or force-heading (not (org-insert-item 'checkbox)))
7012 (org-insert-heading force-heading)
7013 (save-excursion
7014 (org-back-to-heading)
7015 (outline-previous-heading)
7016 (looking-at org-todo-line-regexp))
7017 (let*
7018 ((new-mark-x
7019 (if (or arg
7020 (not (match-beginning 2))
7021 (member (match-string 2) org-done-keywords))
7022 (car org-todo-keywords-1)
7023 (match-string 2)))
7024 (new-mark
7026 (run-hook-with-args-until-success
7027 'org-todo-get-default-hook new-mark-x nil)
7028 new-mark-x)))
7029 (beginning-of-line 1)
7030 (and (looking-at "\\*+ ") (goto-char (match-end 0))
7031 (if org-treat-insert-todo-heading-as-state-change
7032 (org-todo new-mark)
7033 (insert new-mark " "))))
7034 (when org-provide-todo-statistics
7035 (org-update-parent-todo-statistics))))
7037 (defun org-insert-subheading (arg)
7038 "Insert a new subheading and demote it.
7039 Works for outline headings and for plain lists alike."
7040 (interactive "P")
7041 (org-insert-heading arg)
7042 (cond
7043 ((org-on-heading-p) (org-do-demote))
7044 ((org-at-item-p) (org-indent-item))))
7046 (defun org-insert-todo-subheading (arg)
7047 "Insert a new subheading with TODO keyword or checkbox and demote it.
7048 Works for outline headings and for plain lists alike."
7049 (interactive "P")
7050 (org-insert-todo-heading arg)
7051 (cond
7052 ((org-on-heading-p) (org-do-demote))
7053 ((org-at-item-p) (org-indent-item))))
7055 ;;; Promotion and Demotion
7057 (defvar org-after-demote-entry-hook nil
7058 "Hook run after an entry has been demoted.
7059 The cursor will be at the beginning of the entry.
7060 When a subtree is being demoted, the hook will be called for each node.")
7062 (defvar org-after-promote-entry-hook nil
7063 "Hook run after an entry has been promoted.
7064 The cursor will be at the beginning of the entry.
7065 When a subtree is being promoted, the hook will be called for each node.")
7067 (defun org-promote-subtree ()
7068 "Promote the entire subtree.
7069 See also `org-promote'."
7070 (interactive)
7071 (save-excursion
7072 (org-with-limited-levels (org-map-tree 'org-promote)))
7073 (org-fix-position-after-promote))
7075 (defun org-demote-subtree ()
7076 "Demote the entire subtree. See `org-demote'.
7077 See also `org-promote'."
7078 (interactive)
7079 (save-excursion
7080 (org-with-limited-levels (org-map-tree 'org-demote)))
7081 (org-fix-position-after-promote))
7084 (defun org-do-promote ()
7085 "Promote the current heading higher up the tree.
7086 If the region is active in `transient-mark-mode', promote all headings
7087 in the region."
7088 (interactive)
7089 (save-excursion
7090 (if (org-region-active-p)
7091 (org-map-region 'org-promote (region-beginning) (region-end))
7092 (org-promote)))
7093 (org-fix-position-after-promote))
7095 (defun org-do-demote ()
7096 "Demote the current heading lower down the tree.
7097 If the region is active in `transient-mark-mode', demote all headings
7098 in the region."
7099 (interactive)
7100 (save-excursion
7101 (if (org-region-active-p)
7102 (org-map-region 'org-demote (region-beginning) (region-end))
7103 (org-demote)))
7104 (org-fix-position-after-promote))
7106 (defun org-fix-position-after-promote ()
7107 "Make sure that after pro/demotion cursor position is right."
7108 (let ((pos (point)))
7109 (when (save-excursion
7110 (beginning-of-line 1)
7111 (looking-at org-todo-line-regexp)
7112 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7113 (cond ((eobp) (insert " "))
7114 ((eolp) (insert " "))
7115 ((equal (char-after) ?\ ) (forward-char 1))))))
7117 (defun org-current-level ()
7118 "Return the level of the current entry, or nil if before the first headline.
7119 The level is the number of stars at the beginning of the headline."
7120 (save-excursion
7121 (org-with-limited-levels
7122 (ignore-errors
7123 (org-back-to-heading t)
7124 (funcall outline-level)))))
7126 (defun org-get-previous-line-level ()
7127 "Return the outline depth of the last headline before the current line.
7128 Returns 0 for the first headline in the buffer, and nil if before the
7129 first headline."
7130 (let ((current-level (org-current-level))
7131 (prev-level (when (> (line-number-at-pos) 1)
7132 (save-excursion
7133 (beginning-of-line 0)
7134 (org-current-level)))))
7135 (cond ((null current-level) nil) ; Before first headline
7136 ((null prev-level) 0) ; At first headline
7137 (prev-level))))
7139 (defun org-reduced-level (l)
7140 "Compute the effective level of a heading.
7141 This takes into account the setting of `org-odd-levels-only'."
7142 (cond
7143 ((zerop l) 0)
7144 (org-odd-levels-only (1+ (floor (/ l 2))))
7145 (t l)))
7147 (defun org-level-increment ()
7148 "Return the number of stars that will be added or removed at a
7149 time to headlines when structure editing, based on the value of
7150 `org-odd-levels-only'."
7151 (if org-odd-levels-only 2 1))
7153 (defun org-get-valid-level (level &optional change)
7154 "Rectify a level change under the influence of `org-odd-levels-only'
7155 LEVEL is a current level, CHANGE is by how much the level should be
7156 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7157 even level numbers will become the next higher odd number."
7158 (if org-odd-levels-only
7159 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7160 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7161 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7162 (max 1 (+ level (or change 0)))))
7164 (if (boundp 'define-obsolete-function-alias)
7165 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7166 (define-obsolete-function-alias 'org-get-legal-level
7167 'org-get-valid-level)
7168 (define-obsolete-function-alias 'org-get-legal-level
7169 'org-get-valid-level "23.1")))
7171 (defun org-promote ()
7172 "Promote the current heading higher up the tree.
7173 If the region is active in `transient-mark-mode', promote all headings
7174 in the region."
7175 (org-back-to-heading t)
7176 (let* ((level (save-match-data (funcall outline-level)))
7177 (after-change-functions (remove 'flyspell-after-change-function
7178 after-change-functions))
7179 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7180 (diff (abs (- level (length up-head) -1))))
7181 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7182 (replace-match up-head nil t)
7183 ;; Fixup tag positioning
7184 (and org-auto-align-tags (org-set-tags nil t))
7185 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7186 (run-hooks 'org-after-promote-entry-hook)))
7188 (defun org-demote ()
7189 "Demote the current heading lower down the tree.
7190 If the region is active in `transient-mark-mode', demote all headings
7191 in the region."
7192 (org-back-to-heading t)
7193 (let* ((level (save-match-data (funcall outline-level)))
7194 (after-change-functions (remove 'flyspell-after-change-function
7195 after-change-functions))
7196 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7197 (diff (abs (- level (length down-head) -1))))
7198 (replace-match down-head nil t)
7199 ;; Fixup tag positioning
7200 (and org-auto-align-tags (org-set-tags nil t))
7201 (if org-adapt-indentation (org-fixup-indentation diff))
7202 (run-hooks 'org-after-demote-entry-hook)))
7204 (defun org-cycle-level ()
7205 "Cycle the level of an empty headline through possible states.
7206 This goes first to child, then to parent, level, then up the hierarchy.
7207 After top level, it switches back to sibling level."
7208 (interactive)
7209 (let ((org-adapt-indentation nil))
7210 (when (org-point-at-end-of-empty-headline)
7211 (setq this-command 'org-cycle-level) ; Only needed for caching
7212 (let ((cur-level (org-current-level))
7213 (prev-level (org-get-previous-line-level)))
7214 (cond
7215 ;; If first headline in file, promote to top-level.
7216 ((= prev-level 0)
7217 (loop repeat (/ (- cur-level 1) (org-level-increment))
7218 do (org-do-promote)))
7219 ;; If same level as prev, demote one.
7220 ((= prev-level cur-level)
7221 (org-do-demote))
7222 ;; If parent is top-level, promote to top level if not already.
7223 ((= prev-level 1)
7224 (loop repeat (/ (- cur-level 1) (org-level-increment))
7225 do (org-do-promote)))
7226 ;; If top-level, return to prev-level.
7227 ((= cur-level 1)
7228 (loop repeat (/ (- prev-level 1) (org-level-increment))
7229 do (org-do-demote)))
7230 ;; If less than prev-level, promote one.
7231 ((< cur-level prev-level)
7232 (org-do-promote))
7233 ;; If deeper than prev-level, promote until higher than
7234 ;; prev-level.
7235 ((> cur-level prev-level)
7236 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7237 do (org-do-promote))))
7238 t))))
7240 (defun org-map-tree (fun)
7241 "Call FUN for every heading underneath the current one."
7242 (org-back-to-heading)
7243 (let ((level (funcall outline-level)))
7244 (save-excursion
7245 (funcall fun)
7246 (while (and (progn
7247 (outline-next-heading)
7248 (> (funcall outline-level) level))
7249 (not (eobp)))
7250 (funcall fun)))))
7252 (defun org-map-region (fun beg end)
7253 "Call FUN for every heading between BEG and END."
7254 (let ((org-ignore-region t))
7255 (save-excursion
7256 (setq end (copy-marker end))
7257 (goto-char beg)
7258 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
7259 (< (point) end))
7260 (funcall fun))
7261 (while (and (progn
7262 (outline-next-heading)
7263 (< (point) end))
7264 (not (eobp)))
7265 (funcall fun)))))
7267 (defun org-fixup-indentation (diff)
7268 "Change the indentation in the current entry by DIFF.
7269 However, if any line in the current entry has no indentation, or if it
7270 would end up with no indentation after the change, nothing at all is done."
7271 (save-excursion
7272 (let ((end (save-excursion (outline-next-heading)
7273 (point-marker)))
7274 (prohibit (if (> diff 0)
7275 "^\\S-"
7276 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7277 col)
7278 (unless (save-excursion (end-of-line 1)
7279 (re-search-forward prohibit end t))
7280 (while (and (< (point) end)
7281 (re-search-forward "^[ \t]+" end t))
7282 (goto-char (match-end 0))
7283 (setq col (current-column))
7284 (if (< diff 0) (replace-match ""))
7285 (org-indent-to-column (+ diff col))))
7286 (move-marker end nil))))
7288 (defun org-convert-to-odd-levels ()
7289 "Convert an org-mode file with all levels allowed to one with odd levels.
7290 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7291 level 5 etc."
7292 (interactive)
7293 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7294 (let ((outline-regexp org-outline-regexp)
7295 (outline-level 'org-outline-level)
7296 (org-odd-levels-only nil) n)
7297 (save-excursion
7298 (goto-char (point-min))
7299 (while (re-search-forward "^\\*\\*+ " nil t)
7300 (setq n (- (length (match-string 0)) 2))
7301 (while (>= (setq n (1- n)) 0)
7302 (org-demote))
7303 (end-of-line 1))))))
7305 (defun org-convert-to-oddeven-levels ()
7306 "Convert an org-mode file with only odd levels to one with odd/even levels.
7307 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7308 file contains a section with an even level, conversion would
7309 destroy the structure of the file. An error is signaled in this
7310 case."
7311 (interactive)
7312 (goto-char (point-min))
7313 ;; First check if there are no even levels
7314 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7315 (org-show-context t)
7316 (error "Not all levels are odd in this file. Conversion not possible"))
7317 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7318 (let ((outline-regexp org-outline-regexp)
7319 (outline-level 'org-outline-level)
7320 (org-odd-levels-only nil) n)
7321 (save-excursion
7322 (goto-char (point-min))
7323 (while (re-search-forward "^\\*\\*+ " nil t)
7324 (setq n (/ (1- (length (match-string 0))) 2))
7325 (while (>= (setq n (1- n)) 0)
7326 (org-promote))
7327 (end-of-line 1))))))
7329 (defun org-tr-level (n)
7330 "Make N odd if required."
7331 (if org-odd-levels-only (1+ (/ n 2)) n))
7333 ;;; Vertical tree motion, cutting and pasting of subtrees
7335 (defun org-move-subtree-up (&optional arg)
7336 "Move the current subtree up past ARG headlines of the same level."
7337 (interactive "p")
7338 (org-move-subtree-down (- (prefix-numeric-value arg))))
7340 (defun org-move-subtree-down (&optional arg)
7341 "Move the current subtree down past ARG headlines of the same level."
7342 (interactive "p")
7343 (setq arg (prefix-numeric-value arg))
7344 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7345 'org-get-last-sibling))
7346 (ins-point (make-marker))
7347 (cnt (abs arg))
7348 (col (current-column))
7349 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7350 ;; Select the tree
7351 (org-back-to-heading)
7352 (setq beg0 (point))
7353 (save-excursion
7354 (setq ne-beg (org-back-over-empty-lines))
7355 (setq beg (point)))
7356 (save-match-data
7357 (save-excursion (outline-end-of-heading)
7358 (setq folded (outline-invisible-p)))
7359 (outline-end-of-subtree))
7360 (outline-next-heading)
7361 (setq ne-end (org-back-over-empty-lines))
7362 (setq end (point))
7363 (goto-char beg0)
7364 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7365 ;; include less whitespace
7366 (save-excursion
7367 (goto-char beg)
7368 (forward-line (- ne-beg ne-end))
7369 (setq beg (point))))
7370 ;; Find insertion point, with error handling
7371 (while (> cnt 0)
7372 (or (and (funcall movfunc) (looking-at outline-regexp))
7373 (progn (goto-char beg0)
7374 (error "Cannot move past superior level or buffer limit")))
7375 (setq cnt (1- cnt)))
7376 (if (> arg 0)
7377 ;; Moving forward - still need to move over subtree
7378 (progn (org-end-of-subtree t t)
7379 (save-excursion
7380 (org-back-over-empty-lines)
7381 (or (bolp) (newline)))))
7382 (setq ne-ins (org-back-over-empty-lines))
7383 (move-marker ins-point (point))
7384 (setq txt (buffer-substring beg end))
7385 (org-save-markers-in-region beg end)
7386 (delete-region beg end)
7387 (org-remove-empty-overlays-at beg)
7388 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7389 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7390 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7391 (let ((bbb (point)))
7392 (insert-before-markers txt)
7393 (org-reinstall-markers-in-region bbb)
7394 (move-marker ins-point bbb))
7395 (or (bolp) (insert "\n"))
7396 (setq ins-end (point))
7397 (goto-char ins-point)
7398 (org-skip-whitespace)
7399 (when (and (< arg 0)
7400 (org-first-sibling-p)
7401 (> ne-ins ne-beg))
7402 ;; Move whitespace back to beginning
7403 (save-excursion
7404 (goto-char ins-end)
7405 (let ((kill-whole-line t))
7406 (kill-line (- ne-ins ne-beg)) (point)))
7407 (insert (make-string (- ne-ins ne-beg) ?\n)))
7408 (move-marker ins-point nil)
7409 (if folded
7410 (hide-subtree)
7411 (org-show-entry)
7412 (show-children)
7413 (org-cycle-hide-drawers 'children))
7414 (org-clean-visibility-after-subtree-move)
7415 ;; move back to the initial column we were at
7416 (move-to-column col)))
7418 (defvar org-subtree-clip ""
7419 "Clipboard for cut and paste of subtrees.
7420 This is actually only a copy of the kill, because we use the normal kill
7421 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7423 (defvar org-subtree-clip-folded nil
7424 "Was the last copied subtree folded?
7425 This is used to fold the tree back after pasting.")
7427 (defun org-cut-subtree (&optional n)
7428 "Cut the current subtree into the clipboard.
7429 With prefix arg N, cut this many sequential subtrees.
7430 This is a short-hand for marking the subtree and then cutting it."
7431 (interactive "p")
7432 (org-copy-subtree n 'cut))
7434 (defun org-copy-subtree (&optional n cut force-store-markers)
7435 "Cut the current subtree into the clipboard.
7436 With prefix arg N, cut this many sequential subtrees.
7437 This is a short-hand for marking the subtree and then copying it.
7438 If CUT is non-nil, actually cut the subtree.
7439 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7440 of some markers in the region, even if CUT is non-nil. This is
7441 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7442 (interactive "p")
7443 (let (beg end folded (beg0 (point)))
7444 (if (org-called-interactively-p 'any)
7445 (org-back-to-heading nil) ; take what looks like a subtree
7446 (org-back-to-heading t)) ; take what is really there
7447 (org-back-over-empty-lines)
7448 (setq beg (point))
7449 (skip-chars-forward " \t\r\n")
7450 (save-match-data
7451 (save-excursion (outline-end-of-heading)
7452 (setq folded (outline-invisible-p)))
7453 (condition-case nil
7454 (org-forward-same-level (1- n) t)
7455 (error nil))
7456 (org-end-of-subtree t t))
7457 (org-back-over-empty-lines)
7458 (setq end (point))
7459 (goto-char beg0)
7460 (when (> end beg)
7461 (setq org-subtree-clip-folded folded)
7462 (when (or cut force-store-markers)
7463 (org-save-markers-in-region beg end))
7464 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7465 (setq org-subtree-clip (current-kill 0))
7466 (message "%s: Subtree(s) with %d characters"
7467 (if cut "Cut" "Copied")
7468 (length org-subtree-clip)))))
7470 (defun org-paste-subtree (&optional level tree for-yank)
7471 "Paste the clipboard as a subtree, with modification of headline level.
7472 The entire subtree is promoted or demoted in order to match a new headline
7473 level.
7475 If the cursor is at the beginning of a headline, the same level as
7476 that headline is used to paste the tree
7478 If not, the new level is derived from the *visible* headings
7479 before and after the insertion point, and taken to be the inferior headline
7480 level of the two. So if the previous visible heading is level 3 and the
7481 next is level 4 (or vice versa), level 4 will be used for insertion.
7482 This makes sure that the subtree remains an independent subtree and does
7483 not swallow low level entries.
7485 You can also force a different level, either by using a numeric prefix
7486 argument, or by inserting the heading marker by hand. For example, if the
7487 cursor is after \"*****\", then the tree will be shifted to level 5.
7489 If optional TREE is given, use this text instead of the kill ring.
7491 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7492 move back over whitespace before inserting, and move point to the end of
7493 the inserted text when done."
7494 (interactive "P")
7495 (setq tree (or tree (and kill-ring (current-kill 0))))
7496 (unless (org-kill-is-subtree-p tree)
7497 (error "%s"
7498 (substitute-command-keys
7499 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7500 (let* ((visp (not (outline-invisible-p)))
7501 (txt tree)
7502 (^re (concat "^\\(" outline-regexp "\\)"))
7503 (re (concat "\\(" outline-regexp "\\)"))
7504 (^re_ (concat "\\(\\*+\\)[ \t]*"))
7506 (old-level (if (string-match ^re txt)
7507 (- (match-end 0) (match-beginning 0) 1)
7508 -1))
7509 (force-level (cond (level (prefix-numeric-value level))
7510 ((and (looking-at "[ \t]*$")
7511 (string-match
7512 ^re_ (buffer-substring
7513 (point-at-bol) (point))))
7514 (- (match-end 1) (match-beginning 1)))
7515 ((and (bolp)
7516 (looking-at org-outline-regexp))
7517 (- (match-end 0) (point) 1))
7518 (t nil)))
7519 (previous-level (save-excursion
7520 (condition-case nil
7521 (progn
7522 (outline-previous-visible-heading 1)
7523 (if (looking-at re)
7524 (- (match-end 0) (match-beginning 0) 1)
7526 (error 1))))
7527 (next-level (save-excursion
7528 (condition-case nil
7529 (progn
7530 (or (looking-at outline-regexp)
7531 (outline-next-visible-heading 1))
7532 (if (looking-at re)
7533 (- (match-end 0) (match-beginning 0) 1)
7535 (error 1))))
7536 (new-level (or force-level (max previous-level next-level)))
7537 (shift (if (or (= old-level -1)
7538 (= new-level -1)
7539 (= old-level new-level))
7541 (- new-level old-level)))
7542 (delta (if (> shift 0) -1 1))
7543 (func (if (> shift 0) 'org-demote 'org-promote))
7544 (org-odd-levels-only nil)
7545 beg end newend)
7546 ;; Remove the forced level indicator
7547 (if force-level
7548 (delete-region (point-at-bol) (point)))
7549 ;; Paste
7550 (beginning-of-line 1)
7551 (unless for-yank (org-back-over-empty-lines))
7552 (setq beg (point))
7553 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7554 (insert-before-markers txt)
7555 (unless (string-match "\n\\'" txt) (insert "\n"))
7556 (setq newend (point))
7557 (org-reinstall-markers-in-region beg)
7558 (setq end (point))
7559 (goto-char beg)
7560 (skip-chars-forward " \t\n\r")
7561 (setq beg (point))
7562 (if (and (outline-invisible-p) visp)
7563 (save-excursion (outline-show-heading)))
7564 ;; Shift if necessary
7565 (unless (= shift 0)
7566 (save-restriction
7567 (narrow-to-region beg end)
7568 (while (not (= shift 0))
7569 (org-map-region func (point-min) (point-max))
7570 (setq shift (+ delta shift)))
7571 (goto-char (point-min))
7572 (setq newend (point-max))))
7573 (when (or (org-called-interactively-p 'interactive) for-yank)
7574 (message "Clipboard pasted as level %d subtree" new-level))
7575 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7576 kill-ring
7577 (eq org-subtree-clip (current-kill 0))
7578 org-subtree-clip-folded)
7579 ;; The tree was folded before it was killed/copied
7580 (hide-subtree))
7581 (and for-yank (goto-char newend))))
7583 (defun org-kill-is-subtree-p (&optional txt)
7584 "Check if the current kill is an outline subtree, or a set of trees.
7585 Returns nil if kill does not start with a headline, or if the first
7586 headline level is not the largest headline level in the tree.
7587 So this will actually accept several entries of equal levels as well,
7588 which is OK for `org-paste-subtree'.
7589 If optional TXT is given, check this string instead of the current kill."
7590 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7591 (start-level (and kill
7592 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
7593 org-outline-regexp "\\)")
7594 kill)
7595 (- (match-end 2) (match-beginning 2) 1)))
7596 (re (concat "^" org-outline-regexp))
7597 (start (1+ (or (match-beginning 2) -1))))
7598 (if (not start-level)
7599 (progn
7600 nil) ;; does not even start with a heading
7601 (catch 'exit
7602 (while (setq start (string-match re kill (1+ start)))
7603 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7604 (throw 'exit nil)))
7605 t))))
7607 (defvar org-markers-to-move nil
7608 "Markers that should be moved with a cut-and-paste operation.
7609 Those markers are stored together with their positions relative to
7610 the start of the region.")
7612 (defun org-save-markers-in-region (beg end)
7613 "Check markers in region.
7614 If these markers are between BEG and END, record their position relative
7615 to BEG, so that after moving the block of text, we can put the markers back
7616 into place.
7617 This function gets called just before an entry or tree gets cut from the
7618 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7619 called immediately, to move the markers with the entries."
7620 (setq org-markers-to-move nil)
7621 (when (featurep 'org-clock)
7622 (org-clock-save-markers-for-cut-and-paste beg end))
7623 (when (featurep 'org-agenda)
7624 (org-agenda-save-markers-for-cut-and-paste beg end)))
7626 (defun org-check-and-save-marker (marker beg end)
7627 "Check if MARKER is between BEG and END.
7628 If yes, remember the marker and the distance to BEG."
7629 (when (and (marker-buffer marker)
7630 (equal (marker-buffer marker) (current-buffer)))
7631 (if (and (>= marker beg) (< marker end))
7632 (push (cons marker (- marker beg)) org-markers-to-move))))
7634 (defun org-reinstall-markers-in-region (beg)
7635 "Move all remembered markers to their position relative to BEG."
7636 (mapc (lambda (x)
7637 (move-marker (car x) (+ beg (cdr x))))
7638 org-markers-to-move)
7639 (setq org-markers-to-move nil))
7641 (defun org-narrow-to-subtree ()
7642 "Narrow buffer to the current subtree."
7643 (interactive)
7644 (save-excursion
7645 (save-match-data
7646 (org-with-limited-levels
7647 (narrow-to-region
7648 (progn (org-back-to-heading t) (point))
7649 (progn (org-end-of-subtree t t)
7650 (if (and (org-on-heading-p) (not (eobp))) (backward-char 1))
7651 (point)))))))
7653 (defun org-narrow-to-block ()
7654 "Narrow buffer to the current block."
7655 (interactive)
7656 (let ((bstart "^[ \t]*#\\+begin")
7657 (bend "[ \t]*#\\+end")
7658 (case-fold-search t) ;; allow #+BEGIN
7659 b_start b_end)
7660 (if (org-in-regexps-block-p bstart bend)
7661 (progn
7662 (save-excursion (re-search-backward bstart nil t)
7663 (setq b_start (match-beginning 0)))
7664 (save-excursion (re-search-forward bend nil t)
7665 (setq b_end (match-end 0)))
7666 (narrow-to-region b_start b_end))
7667 (error "Not in a block"))))
7669 (eval-when-compile
7670 (defvar org-property-drawer-re))
7672 (defvar org-property-start-re) ;; defined below
7673 (defun org-clone-subtree-with-time-shift (n &optional shift)
7674 "Clone the task (subtree) at point N times.
7675 The clones will be inserted as siblings.
7677 In interactive use, the user will be prompted for the number of
7678 clones to be produced, and for a time SHIFT, which may be a
7679 repeater as used in time stamps, for example `+3d'.
7681 When a valid repeater is given and the entry contains any time
7682 stamps, the clones will become a sequence in time, with time
7683 stamps in the subtree shifted for each clone produced. If SHIFT
7684 is nil or the empty string, time stamps will be left alone. The
7685 ID property of the original subtree is removed.
7687 If the original subtree did contain time stamps with a repeater,
7688 the following will happen:
7689 - the repeater will be removed in each clone
7690 - an additional clone will be produced, with the current, unshifted
7691 date(s) in the entry.
7692 - the original entry will be placed *after* all the clones, with
7693 repeater intact.
7694 - the start days in the repeater in the original entry will be shifted
7695 to past the last clone.
7696 I this way you can spell out a number of instances of a repeating task,
7697 and still retain the repeater to cover future instances of the task."
7698 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7699 (let (beg end template task idprop
7700 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7701 (if (not (and (integerp n) (> n 0)))
7702 (error "Invalid number of replications %s" n))
7703 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7704 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7705 shift)))
7706 (error "Invalid shift specification %s" shift))
7707 (when doshift
7708 (setq shift-n (string-to-number (match-string 1 shift))
7709 shift-what (cdr (assoc (match-string 2 shift)
7710 '(("d" . day) ("w" . week)
7711 ("m" . month) ("y" . year))))))
7712 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7713 (setq nmin 1 nmax n)
7714 (org-back-to-heading t)
7715 (setq beg (point))
7716 (setq idprop (org-entry-get nil "ID"))
7717 (org-end-of-subtree t t)
7718 (or (bolp) (insert "\n"))
7719 (setq end (point))
7720 (setq template (buffer-substring beg end))
7721 ;; Remove clocks and empty drawers
7722 (with-temp-buffer
7723 (insert template)
7724 (goto-char (point-min))
7725 (while (re-search-forward
7726 "^[ \t]*CLOCK:.*$" (save-excursion (org-end-of-subtree t t)) t)
7727 (replace-match "")
7728 (kill-whole-line))
7729 (goto-char (point-min))
7730 (while (re-search-forward
7731 (concat "^[ \t]*:" (regexp-opt org-drawers) ":[ \t]*$") nil t)
7732 (mapc (lambda(d) (org-remove-empty-drawer-at d (point))) org-drawers))
7733 (setq template (buffer-substring (point-min) (point-max))))
7734 (when (and doshift
7735 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7736 (delete-region beg end)
7737 (setq end beg)
7738 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7739 (goto-char end)
7740 (loop for n from nmin to nmax do
7741 ;; prepare clone
7742 (with-temp-buffer
7743 (insert template)
7744 (org-mode)
7745 (goto-char (point-min))
7746 (and idprop (if org-clone-delete-id
7747 (org-entry-delete nil "ID")
7748 (org-id-get-create t)))
7749 (while (re-search-forward org-property-start-re nil t)
7750 (org-remove-empty-drawer-at "PROPERTIES" (point)))
7751 (goto-char (point-min))
7752 (when doshift
7753 (while (re-search-forward org-ts-regexp-both nil t)
7754 (org-timestamp-change (* n shift-n) shift-what))
7755 (unless (= n n-no-remove)
7756 (goto-char (point-min))
7757 (while (re-search-forward org-ts-regexp nil t)
7758 (save-excursion
7759 (goto-char (match-beginning 0))
7760 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7761 (delete-region (match-beginning 1) (match-end 1)))))))
7762 (setq task (buffer-string)))
7763 (insert task))
7764 (goto-char beg)))
7766 ;;; Outline Sorting
7768 (defun org-sort (with-case)
7769 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
7770 Optional argument WITH-CASE means sort case-sensitively.
7771 With a double prefix argument, also remove duplicate entries."
7772 (interactive "P")
7773 (cond
7774 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
7775 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
7777 (org-call-with-arg 'org-sort-entries with-case))))
7779 (defun org-sort-remove-invisible (s)
7780 (remove-text-properties 0 (length s) org-rm-props s)
7781 (while (string-match org-bracket-link-regexp s)
7782 (setq s (replace-match (if (match-end 2)
7783 (match-string 3 s)
7784 (match-string 1 s)) t t s)))
7787 (defvar org-priority-regexp) ; defined later in the file
7789 (defvar org-after-sorting-entries-or-items-hook nil
7790 "Hook that is run after a bunch of entries or items have been sorted.
7791 When children are sorted, the cursor is in the parent line when this
7792 hook gets called. When a region or a plain list is sorted, the cursor
7793 will be in the first entry of the sorted region/list.")
7795 (defun org-sort-entries
7796 (&optional with-case sorting-type getkey-func compare-func property)
7797 "Sort entries on a certain level of an outline tree.
7798 If there is an active region, the entries in the region are sorted.
7799 Else, if the cursor is before the first entry, sort the top-level items.
7800 Else, the children of the entry at point are sorted.
7802 Sorting can be alphabetically, numerically, by date/time as given by
7803 a time stamp, by a property or by priority.
7805 The command prompts for the sorting type unless it has been given to the
7806 function through the SORTING-TYPE argument, which needs to be a character,
7807 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7808 precise meaning of each character:
7810 n Numerically, by converting the beginning of the entry/item to a number.
7811 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7812 t By date/time, either the first active time stamp in the entry, or, if
7813 none exist, by the first inactive one.
7814 s By the scheduled date/time.
7815 d By deadline date/time.
7816 c By creation time, which is assumed to be the first inactive time stamp
7817 at the beginning of a line.
7818 p By priority according to the cookie.
7819 r By the value of a property.
7821 Capital letters will reverse the sort order.
7823 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7824 called with point at the beginning of the record. It must return either
7825 a string or a number that should serve as the sorting key for that record.
7827 Comparing entries ignores case by default. However, with an optional argument
7828 WITH-CASE, the sorting considers case as well."
7829 (interactive "P")
7830 (let ((case-func (if with-case 'identity 'downcase))
7831 start beg end stars re re2
7832 txt what tmp)
7833 ;; Find beginning and end of region to sort
7834 (cond
7835 ((org-region-active-p)
7836 ;; we will sort the region
7837 (setq end (region-end)
7838 what "region")
7839 (goto-char (region-beginning))
7840 (if (not (org-on-heading-p)) (outline-next-heading))
7841 (setq start (point)))
7842 ((or (org-on-heading-p)
7843 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7844 ;; we will sort the children of the current headline
7845 (org-back-to-heading)
7846 (setq start (point)
7847 end (progn (org-end-of-subtree t t)
7848 (or (bolp) (insert "\n"))
7849 (org-back-over-empty-lines)
7850 (point))
7851 what "children")
7852 (goto-char start)
7853 (show-subtree)
7854 (outline-next-heading))
7856 ;; we will sort the top-level entries in this file
7857 (goto-char (point-min))
7858 (or (org-on-heading-p) (outline-next-heading))
7859 (setq start (point))
7860 (goto-char (point-max))
7861 (beginning-of-line 1)
7862 (when (looking-at ".*?\\S-")
7863 ;; File ends in a non-white line
7864 (end-of-line 1)
7865 (insert "\n"))
7866 (setq end (point-max))
7867 (setq what "top-level")
7868 (goto-char start)
7869 (show-all)))
7871 (setq beg (point))
7872 (if (>= beg end) (error "Nothing to sort"))
7874 (looking-at "\\(\\*+\\)")
7875 (setq stars (match-string 1)
7876 re (concat "^" (regexp-quote stars) " +")
7877 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
7878 txt (buffer-substring beg end))
7879 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7880 (if (and (not (equal stars "*")) (string-match re2 txt))
7881 (error "Region to sort contains a level above the first entry"))
7883 (unless sorting-type
7884 (message
7885 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7886 [t]ime [s]cheduled [d]eadline [c]reated
7887 A/N/T/S/D/C/P/O/F means reversed:"
7888 what)
7889 (setq sorting-type (read-char-exclusive))
7891 (and (= (downcase sorting-type) ?f)
7892 (setq getkey-func
7893 (org-icompleting-read "Sort using function: "
7894 obarray 'fboundp t nil nil))
7895 (setq getkey-func (intern getkey-func)))
7897 (and (= (downcase sorting-type) ?r)
7898 (setq property
7899 (org-icompleting-read "Property: "
7900 (mapcar 'list (org-buffer-property-keys t))
7901 nil t))))
7903 (message "Sorting entries...")
7905 (save-restriction
7906 (narrow-to-region start end)
7907 (let ((dcst (downcase sorting-type))
7908 (case-fold-search nil)
7909 (now (current-time)))
7910 (sort-subr
7911 (/= dcst sorting-type)
7912 ;; This function moves to the beginning character of the "record" to
7913 ;; be sorted.
7914 (lambda nil
7915 (if (re-search-forward re nil t)
7916 (goto-char (match-beginning 0))
7917 (goto-char (point-max))))
7918 ;; This function moves to the last character of the "record" being
7919 ;; sorted.
7920 (lambda nil
7921 (save-match-data
7922 (condition-case nil
7923 (outline-forward-same-level 1)
7924 (error
7925 (goto-char (point-max))))))
7926 ;; This function returns the value that gets sorted against.
7927 (lambda nil
7928 (cond
7929 ((= dcst ?n)
7930 (if (looking-at org-complex-heading-regexp)
7931 (string-to-number (match-string 4))
7932 nil))
7933 ((= dcst ?a)
7934 (if (looking-at org-complex-heading-regexp)
7935 (funcall case-func (match-string 4))
7936 nil))
7937 ((= dcst ?t)
7938 (let ((end (save-excursion (outline-next-heading) (point))))
7939 (if (or (re-search-forward org-ts-regexp end t)
7940 (re-search-forward org-ts-regexp-both end t))
7941 (org-time-string-to-seconds (match-string 0))
7942 (org-float-time now))))
7943 ((= dcst ?c)
7944 (let ((end (save-excursion (outline-next-heading) (point))))
7945 (if (re-search-forward
7946 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7947 end t)
7948 (org-time-string-to-seconds (match-string 0))
7949 (org-float-time now))))
7950 ((= dcst ?s)
7951 (let ((end (save-excursion (outline-next-heading) (point))))
7952 (if (re-search-forward org-scheduled-time-regexp end t)
7953 (org-time-string-to-seconds (match-string 1))
7954 (org-float-time now))))
7955 ((= dcst ?d)
7956 (let ((end (save-excursion (outline-next-heading) (point))))
7957 (if (re-search-forward org-deadline-time-regexp end t)
7958 (org-time-string-to-seconds (match-string 1))
7959 (org-float-time now))))
7960 ((= dcst ?p)
7961 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7962 (string-to-char (match-string 2))
7963 org-default-priority))
7964 ((= dcst ?r)
7965 (or (org-entry-get nil property) ""))
7966 ((= dcst ?o)
7967 (if (looking-at org-complex-heading-regexp)
7968 (- 9999 (length (member (match-string 2)
7969 org-todo-keywords-1)))))
7970 ((= dcst ?f)
7971 (if getkey-func
7972 (progn
7973 (setq tmp (funcall getkey-func))
7974 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7975 tmp)
7976 (error "Invalid key function `%s'" getkey-func)))
7977 (t (error "Invalid sorting type `%c'" sorting-type))))
7979 (cond
7980 ((= dcst ?a) 'string<)
7981 ((= dcst ?f) compare-func)
7982 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7983 (t nil)))))
7984 (run-hooks 'org-after-sorting-entries-or-items-hook)
7985 (message "Sorting entries...done")))
7987 (defun org-do-sort (table what &optional with-case sorting-type)
7988 "Sort TABLE of WHAT according to SORTING-TYPE.
7989 The user will be prompted for the SORTING-TYPE if the call to this
7990 function does not specify it. WHAT is only for the prompt, to indicate
7991 what is being sorted. The sorting key will be extracted from
7992 the car of the elements of the table.
7993 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7994 (unless sorting-type
7995 (message
7996 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7997 what)
7998 (setq sorting-type (read-char-exclusive)))
7999 (let ((dcst (downcase sorting-type))
8000 extractfun comparefun)
8001 ;; Define the appropriate functions
8002 (cond
8003 ((= dcst ?n)
8004 (setq extractfun 'string-to-number
8005 comparefun (if (= dcst sorting-type) '< '>)))
8006 ((= dcst ?a)
8007 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8008 (lambda(x) (downcase (org-sort-remove-invisible x))))
8009 comparefun (if (= dcst sorting-type)
8010 'string<
8011 (lambda (a b) (and (not (string< a b))
8012 (not (string= a b)))))))
8013 ((= dcst ?t)
8014 (setq extractfun
8015 (lambda (x)
8016 (if (or (string-match org-ts-regexp x)
8017 (string-match org-ts-regexp-both x))
8018 (org-float-time
8019 (org-time-string-to-time (match-string 0 x)))
8021 comparefun (if (= dcst sorting-type) '< '>)))
8022 (t (error "Invalid sorting type `%c'" sorting-type)))
8024 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8025 table)
8026 (lambda (a b) (funcall comparefun (car a) (car b))))))
8029 ;;; The orgstruct minor mode
8031 ;; Define a minor mode which can be used in other modes in order to
8032 ;; integrate the org-mode structure editing commands.
8034 ;; This is really a hack, because the org-mode structure commands use
8035 ;; keys which normally belong to the major mode. Here is how it
8036 ;; works: The minor mode defines all the keys necessary to operate the
8037 ;; structure commands, but wraps the commands into a function which
8038 ;; tests if the cursor is currently at a headline or a plain list
8039 ;; item. If that is the case, the structure command is used,
8040 ;; temporarily setting many Org-mode variables like regular
8041 ;; expressions for filling etc. However, when any of those keys is
8042 ;; used at a different location, function uses `key-binding' to look
8043 ;; up if the key has an associated command in another currently active
8044 ;; keymap (minor modes, major mode, global), and executes that
8045 ;; command. There might be problems if any of the keys is otherwise
8046 ;; used as a prefix key.
8048 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8049 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8050 ;; addresses this by checking explicitly for both bindings.
8052 (defvar orgstruct-mode-map (make-sparse-keymap)
8053 "Keymap for the minor `orgstruct-mode'.")
8055 (defvar org-local-vars nil
8056 "List of local variables, for use by `orgstruct-mode'.")
8058 ;;;###autoload
8059 (define-minor-mode orgstruct-mode
8060 "Toggle the minor mode `orgstruct-mode'.
8061 This mode is for using Org-mode structure commands in other
8062 modes. The following keys behave as if Org-mode were active, if
8063 the cursor is on a headline, or on a plain list item (both as
8064 defined by Org-mode).
8066 M-up Move entry/item up
8067 M-down Move entry/item down
8068 M-left Promote
8069 M-right Demote
8070 M-S-up Move entry/item up
8071 M-S-down Move entry/item down
8072 M-S-left Promote subtree
8073 M-S-right Demote subtree
8074 M-q Fill paragraph and items like in Org-mode
8075 C-c ^ Sort entries
8076 C-c - Cycle list bullet
8077 TAB Cycle item visibility
8078 M-RET Insert new heading/item
8079 S-M-RET Insert new TODO heading / Checkbox item
8080 C-c C-c Set tags / toggle checkbox"
8081 nil " OrgStruct" nil
8082 (org-load-modules-maybe)
8083 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8085 ;;;###autoload
8086 (defun turn-on-orgstruct ()
8087 "Unconditionally turn on `orgstruct-mode'."
8088 (orgstruct-mode 1))
8090 (defun orgstruct++-mode (&optional arg)
8091 "Toggle `orgstruct-mode', the enhanced version of it.
8092 In addition to setting orgstruct-mode, this also exports all indentation
8093 and autofilling variables from org-mode into the buffer. It will also
8094 recognize item context in multiline items.
8095 Note that turning off orgstruct-mode will *not* remove the
8096 indentation/paragraph settings. This can only be done by refreshing the
8097 major mode, for example with \\[normal-mode]."
8098 (interactive "P")
8099 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8100 (if (< arg 1)
8101 (orgstruct-mode -1)
8102 (orgstruct-mode 1)
8103 (let (var val)
8104 (mapc
8105 (lambda (x)
8106 (when (string-match
8107 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8108 (symbol-name (car x)))
8109 (setq var (car x) val (nth 1 x))
8110 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8111 org-local-vars)
8112 (org-set-local 'orgstruct-is-++ t))))
8114 (defvar orgstruct-is-++ nil
8115 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8116 (make-variable-buffer-local 'orgstruct-is-++)
8118 ;;;###autoload
8119 (defun turn-on-orgstruct++ ()
8120 "Unconditionally turn on `orgstruct++-mode'."
8121 (orgstruct++-mode 1))
8123 (defun orgstruct-error ()
8124 "Error when there is no default binding for a structure key."
8125 (interactive)
8126 (error "This key has no function outside structure elements"))
8128 (defun orgstruct-setup ()
8129 "Setup orgstruct keymaps."
8130 (let ((nfunc 0)
8131 (bindings
8132 (list
8133 '([(meta up)] org-metaup)
8134 '([(meta down)] org-metadown)
8135 '([(meta left)] org-metaleft)
8136 '([(meta right)] org-metaright)
8137 '([(meta shift up)] org-shiftmetaup)
8138 '([(meta shift down)] org-shiftmetadown)
8139 '([(meta shift left)] org-shiftmetaleft)
8140 '([(meta shift right)] org-shiftmetaright)
8141 '([?\e (up)] org-metaup)
8142 '([?\e (down)] org-metadown)
8143 '([?\e (left)] org-metaleft)
8144 '([?\e (right)] org-metaright)
8145 '([?\e (shift up)] org-shiftmetaup)
8146 '([?\e (shift down)] org-shiftmetadown)
8147 '([?\e (shift left)] org-shiftmetaleft)
8148 '([?\e (shift right)] org-shiftmetaright)
8149 '([(shift up)] org-shiftup)
8150 '([(shift down)] org-shiftdown)
8151 '([(shift left)] org-shiftleft)
8152 '([(shift right)] org-shiftright)
8153 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8154 '("\M-q" fill-paragraph)
8155 '("\C-c^" org-sort)
8156 '("\C-c-" org-cycle-list-bullet)))
8157 elt key fun cmd)
8158 (while (setq elt (pop bindings))
8159 (setq nfunc (1+ nfunc))
8160 (setq key (org-key (car elt))
8161 fun (nth 1 elt)
8162 cmd (orgstruct-make-binding fun nfunc key))
8163 (org-defkey orgstruct-mode-map key cmd))
8165 ;; Special treatment needed for TAB and RET
8166 (org-defkey orgstruct-mode-map [(tab)]
8167 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8168 (org-defkey orgstruct-mode-map "\C-i"
8169 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8171 (org-defkey orgstruct-mode-map "\M-\C-m"
8172 (orgstruct-make-binding 'org-insert-heading 105
8173 "\M-\C-m" [(meta return)]))
8174 (org-defkey orgstruct-mode-map [(meta return)]
8175 (orgstruct-make-binding 'org-insert-heading 106
8176 [(meta return)] "\M-\C-m"))
8178 (org-defkey orgstruct-mode-map [(shift meta return)]
8179 (orgstruct-make-binding 'org-insert-todo-heading 107
8180 [(meta return)] "\M-\C-m"))
8182 (org-defkey orgstruct-mode-map "\e\C-m"
8183 (orgstruct-make-binding 'org-insert-heading 108
8184 "\e\C-m" [?\e (return)]))
8185 (org-defkey orgstruct-mode-map [?\e (return)]
8186 (orgstruct-make-binding 'org-insert-heading 109
8187 [?\e (return)] "\e\C-m"))
8188 (org-defkey orgstruct-mode-map [?\e (shift return)]
8189 (orgstruct-make-binding 'org-insert-todo-heading 110
8190 [?\e (return)] "\e\C-m"))
8192 (unless org-local-vars
8193 (setq org-local-vars (org-get-local-variables)))
8197 (defun orgstruct-make-binding (fun n &rest keys)
8198 "Create a function for binding in the structure minor mode.
8199 FUN is the command to call inside a table. N is used to create a unique
8200 command name. KEYS are keys that should be checked in for a command
8201 to execute outside of tables."
8202 (eval
8203 (list 'defun
8204 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8205 '(arg)
8206 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8207 "Outside of structure, run the binding of `"
8208 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8209 "'.")
8210 '(interactive "p")
8211 (list 'if
8212 `(org-context-p 'headline 'item
8213 (and orgstruct-is-++
8214 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8215 'item-body))
8216 (list 'org-run-like-in-org-mode (list 'quote fun))
8217 (list 'let '(orgstruct-mode)
8218 (list 'call-interactively
8219 (append '(or)
8220 (mapcar (lambda (k)
8221 (list 'key-binding k))
8222 keys)
8223 '('orgstruct-error))))))))
8225 (defun org-context-p (&rest contexts)
8226 "Check if local context is any of CONTEXTS.
8227 Possible values in the list of contexts are `table', `headline', and `item'."
8228 (let ((pos (point)))
8229 (goto-char (point-at-bol))
8230 (prog1 (or (and (memq 'table contexts)
8231 (looking-at "[ \t]*|"))
8232 (and (memq 'headline contexts)
8233 ;;????????? (looking-at "\\*+"))
8234 (looking-at outline-regexp))
8235 (and (memq 'item contexts)
8236 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8237 (and (memq 'item-body contexts)
8238 (org-in-item-p)))
8239 (goto-char pos))))
8241 (defun org-get-local-variables ()
8242 "Return a list of all local variables in an org-mode buffer."
8243 (let (varlist)
8244 (with-current-buffer (get-buffer-create "*Org tmp*")
8245 (erase-buffer)
8246 (org-mode)
8247 (setq varlist (buffer-local-variables)))
8248 (kill-buffer "*Org tmp*")
8249 (delq nil
8250 (mapcar
8251 (lambda (x)
8252 (setq x
8253 (if (symbolp x)
8254 (list x)
8255 (list (car x) (list 'quote (cdr x)))))
8256 (if (string-match
8257 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8258 (symbol-name (car x)))
8259 x nil))
8260 varlist))))
8262 (defun org-clone-local-variables (from-buffer &optional regexp)
8263 "Clone local variables from FROM-BUFFER.
8264 Optional argument REGEXP selects variables to clone."
8265 (mapc
8266 (lambda (pair)
8267 (and (symbolp (car pair))
8268 (or (null regexp)
8269 (string-match regexp (symbol-name (car pair))))
8270 (set (make-local-variable (car pair))
8271 (cdr pair))))
8272 (buffer-local-variables from-buffer)))
8274 ;;;###autoload
8275 (defun org-run-like-in-org-mode (cmd)
8276 "Run a command, pretending that the current buffer is in Org-mode.
8277 This will temporarily bind local variables that are typically bound in
8278 Org-mode to the values they have in Org-mode, and then interactively
8279 call CMD."
8280 (org-load-modules-maybe)
8281 (unless org-local-vars
8282 (setq org-local-vars (org-get-local-variables)))
8283 (eval (list 'let org-local-vars
8284 (list 'call-interactively (list 'quote cmd)))))
8286 ;;;; Archiving
8288 (defun org-get-category (&optional pos force-refresh)
8289 "Get the category applying to position POS."
8290 (if force-refresh (org-refresh-category-properties))
8291 (let ((pos (or pos (point))))
8292 (or (get-text-property pos 'org-category)
8293 (progn (org-refresh-category-properties)
8294 (get-text-property pos 'org-category)))))
8296 (defun org-refresh-category-properties ()
8297 "Refresh category text properties in the buffer."
8298 (let ((def-cat (cond
8299 ((null org-category)
8300 (if buffer-file-name
8301 (file-name-sans-extension
8302 (file-name-nondirectory buffer-file-name))
8303 "???"))
8304 ((symbolp org-category) (symbol-name org-category))
8305 (t org-category)))
8306 beg end cat pos optionp)
8307 (org-unmodified
8308 (save-excursion
8309 (save-restriction
8310 (widen)
8311 (goto-char (point-min))
8312 (put-text-property (point) (point-max) 'org-category def-cat)
8313 (while (re-search-forward
8314 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8315 (setq pos (match-end 0)
8316 optionp (equal (char-after (match-beginning 0)) ?#)
8317 cat (org-trim (match-string 2)))
8318 (if optionp
8319 (setq beg (point-at-bol) end (point-max))
8320 (org-back-to-heading t)
8321 (setq beg (point) end (org-end-of-subtree t t)))
8322 (put-text-property beg end 'org-category cat)
8323 (goto-char pos)))))))
8326 ;;;; Link Stuff
8328 ;;; Link abbreviations
8330 (defun org-link-expand-abbrev (link)
8331 "Apply replacements as defined in `org-link-abbrev-alist."
8332 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8333 (let* ((key (match-string 1 link))
8334 (as (or (assoc key org-link-abbrev-alist-local)
8335 (assoc key org-link-abbrev-alist)))
8336 (tag (and (match-end 2) (match-string 3 link)))
8337 rpl)
8338 (if (not as)
8339 link
8340 (setq rpl (cdr as))
8341 (cond
8342 ((symbolp rpl) (funcall rpl tag))
8343 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8344 ((string-match "%h" rpl)
8345 (replace-match (url-hexify-string (or tag "")) t t rpl))
8346 (t (concat rpl tag)))))
8347 link))
8349 ;;; Storing and inserting links
8351 (defvar org-insert-link-history nil
8352 "Minibuffer history for links inserted with `org-insert-link'.")
8354 (defvar org-stored-links nil
8355 "Contains the links stored with `org-store-link'.")
8357 (defvar org-store-link-plist nil
8358 "Plist with info about the most recently link created with `org-store-link'.")
8360 (defvar org-link-protocols nil
8361 "Link protocols added to Org-mode using `org-add-link-type'.")
8363 (defvar org-store-link-functions nil
8364 "List of functions that are called to create and store a link.
8365 Each function will be called in turn until one returns a non-nil
8366 value. Each function should check if it is responsible for creating
8367 this link (for example by looking at the major mode).
8368 If not, it must exit and return nil.
8369 If yes, it should return a non-nil value after a calling
8370 `org-store-link-props' with a list of properties and values.
8371 Special properties are:
8373 :type The link prefix, like \"http\". This must be given.
8374 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8375 This is obligatory as well.
8376 :description Optional default description for the second pair
8377 of brackets in an Org-mode link. The user can still change
8378 this when inserting this link into an Org-mode buffer.
8380 In addition to these, any additional properties can be specified
8381 and then used in remember templates.")
8383 (defun org-add-link-type (type &optional follow export)
8384 "Add TYPE to the list of `org-link-types'.
8385 Re-compute all regular expressions depending on `org-link-types'
8387 FOLLOW and EXPORT are two functions.
8389 FOLLOW should take the link path as the single argument and do whatever
8390 is necessary to follow the link, for example find a file or display
8391 a mail message.
8393 EXPORT should format the link path for export to one of the export formats.
8394 It should be a function accepting three arguments:
8396 path the path of the link, the text after the prefix (like \"http:\")
8397 desc the description of the link, if any, or a description added by
8398 org-export-normalize-links if there is none
8399 format the export format, a symbol like `html' or `latex' or `ascii'..
8401 The function may use the FORMAT information to return different values
8402 depending on the format. The return value will be put literally into
8403 the exported file. If the return value is nil, this means Org should
8404 do what it normally does with links which do not have EXPORT defined.
8406 Org-mode has a built-in default for exporting links. If you are happy with
8407 this default, there is no need to define an export function for the link
8408 type. For a simple example of an export function, see `org-bbdb.el'."
8409 (add-to-list 'org-link-types type t)
8410 (org-make-link-regexps)
8411 (if (assoc type org-link-protocols)
8412 (setcdr (assoc type org-link-protocols) (list follow export))
8413 (push (list type follow export) org-link-protocols)))
8415 (defvar org-agenda-buffer-name)
8417 ;;;###autoload
8418 (defun org-store-link (arg)
8419 "\\<org-mode-map>Store an org-link to the current location.
8420 This link is added to `org-stored-links' and can later be inserted
8421 into an org-buffer with \\[org-insert-link].
8423 For some link types, a prefix arg is interpreted:
8424 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8425 For file links, arg negates `org-context-in-file-links'."
8426 (interactive "P")
8427 (org-load-modules-maybe)
8428 (setq org-store-link-plist nil) ; reset
8429 (org-with-limited-levels
8430 (let (link cpltxt desc description search txt custom-id agenda-link)
8431 (cond
8433 ((run-hook-with-args-until-success 'org-store-link-functions)
8434 (setq link (plist-get org-store-link-plist :link)
8435 desc (or (plist-get org-store-link-plist :description) link)))
8437 ((equal (buffer-name) "*Org Edit Src Example*")
8438 (let (label gc)
8439 (while (or (not label)
8440 (save-excursion
8441 (save-restriction
8442 (widen)
8443 (goto-char (point-min))
8444 (re-search-forward
8445 (regexp-quote (format org-coderef-label-format label))
8446 nil t))))
8447 (when label (message "Label exists already") (sit-for 2))
8448 (setq label (read-string "Code line label: " label)))
8449 (end-of-line 1)
8450 (setq link (format org-coderef-label-format label))
8451 (setq gc (- 79 (length link)))
8452 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8453 (insert link)
8454 (setq link (concat "(" label ")") desc nil)))
8456 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8457 ;; We are in the agenda, link to referenced location
8458 (let ((m (or (get-text-property (point) 'org-hd-marker)
8459 (get-text-property (point) 'org-marker))))
8460 (when m
8461 (org-with-point-at m
8462 (setq agenda-link
8463 (if (org-called-interactively-p 'any)
8464 (call-interactively 'org-store-link)
8465 (org-store-link nil)))))))
8467 ((eq major-mode 'calendar-mode)
8468 (let ((cd (calendar-cursor-to-date)))
8469 (setq link
8470 (format-time-string
8471 (car org-time-stamp-formats)
8472 (apply 'encode-time
8473 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8474 nil nil nil))))
8475 (org-store-link-props :type "calendar" :date cd)))
8477 ((eq major-mode 'w3-mode)
8478 (setq cpltxt (if (and (buffer-name)
8479 (not (string-match "Untitled" (buffer-name))))
8480 (buffer-name)
8481 (url-view-url t))
8482 link (org-make-link (url-view-url t)))
8483 (org-store-link-props :type "w3" :url (url-view-url t)))
8485 ((eq major-mode 'w3m-mode)
8486 (setq cpltxt (or w3m-current-title w3m-current-url)
8487 link (org-make-link w3m-current-url))
8488 (org-store-link-props :type "w3m" :url (url-view-url t)))
8490 ((setq search (run-hook-with-args-until-success
8491 'org-create-file-search-functions))
8492 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8493 "::" search))
8494 (setq cpltxt (or description link)))
8496 ((eq major-mode 'image-mode)
8497 (setq cpltxt (concat "file:"
8498 (abbreviate-file-name buffer-file-name))
8499 link (org-make-link cpltxt))
8500 (org-store-link-props :type "image" :file buffer-file-name))
8502 ((eq major-mode 'dired-mode)
8503 ;; link to the file in the current line
8504 (let ((file (dired-get-filename nil t)))
8505 (setq file (if file
8506 (abbreviate-file-name
8507 (expand-file-name (dired-get-filename nil t)))
8508 ;; otherwise, no file so use current directory.
8509 default-directory))
8510 (setq cpltxt (concat "file:" file)
8511 link (org-make-link cpltxt))))
8513 ((and (buffer-file-name (buffer-base-buffer)) (org-mode-p))
8514 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8515 (cond
8516 ((org-in-regexp "<<\\(.*?\\)>>")
8517 (setq cpltxt
8518 (concat "file:"
8519 (abbreviate-file-name
8520 (buffer-file-name (buffer-base-buffer)))
8521 "::" (match-string 1))
8522 link (org-make-link cpltxt)))
8523 ((and (featurep 'org-id)
8524 (or (eq org-link-to-org-use-id t)
8525 (and (eq org-link-to-org-use-id 'create-if-interactive)
8526 (org-called-interactively-p 'any))
8527 (and (eq org-link-to-org-use-id
8528 'create-if-interactive-and-no-custom-id)
8529 (org-called-interactively-p 'any)
8530 (not custom-id))
8531 (and org-link-to-org-use-id
8532 (org-entry-get nil "ID"))))
8533 ;; We can make a link using the ID.
8534 (setq link (condition-case nil
8535 (prog1 (org-id-store-link)
8536 (setq desc (plist-get org-store-link-plist
8537 :description)))
8538 (error
8539 ;; probably before first headline, link to file only
8540 (concat "file:"
8541 (abbreviate-file-name
8542 (buffer-file-name (buffer-base-buffer))))))))
8544 ;; Just link to current headline
8545 (setq cpltxt (concat "file:"
8546 (abbreviate-file-name
8547 (buffer-file-name (buffer-base-buffer)))))
8548 ;; Add a context search string
8549 (when (org-xor org-context-in-file-links arg)
8550 (setq txt (cond
8551 ((org-on-heading-p) nil)
8552 ((org-region-active-p)
8553 (buffer-substring (region-beginning) (region-end)))
8554 (t nil)))
8555 (when (or (null txt) (string-match "\\S-" txt))
8556 (setq cpltxt
8557 (concat cpltxt "::"
8558 (condition-case nil
8559 (org-make-org-heading-search-string txt)
8560 (error "")))
8561 desc (or (nth 4 (ignore-errors
8562 (org-heading-components))) "NONE"))))
8563 (if (string-match "::\\'" cpltxt)
8564 (setq cpltxt (substring cpltxt 0 -2)))
8565 (setq link (org-make-link cpltxt)))))
8567 ((buffer-file-name (buffer-base-buffer))
8568 ;; Just link to this file here.
8569 (setq cpltxt (concat "file:"
8570 (abbreviate-file-name
8571 (buffer-file-name (buffer-base-buffer)))))
8572 ;; Add a context string
8573 (when (org-xor org-context-in-file-links arg)
8574 (setq txt (if (org-region-active-p)
8575 (buffer-substring (region-beginning) (region-end))
8576 (buffer-substring (point-at-bol) (point-at-eol))))
8577 ;; Only use search option if there is some text.
8578 (when (string-match "\\S-" txt)
8579 (setq cpltxt
8580 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8581 desc "NONE")))
8582 (setq link (org-make-link cpltxt)))
8584 ((org-called-interactively-p 'interactive)
8585 (error "Cannot link to a buffer which is not visiting a file"))
8587 (t (setq link nil)))
8589 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8590 (setq link (or link cpltxt)
8591 desc (or desc cpltxt))
8592 (if (equal desc "NONE") (setq desc nil))
8594 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8595 (progn
8596 (setq org-stored-links
8597 (cons (list link desc) org-stored-links))
8598 (message "Stored: %s" (or desc link))
8599 (when custom-id
8600 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8601 "::#" custom-id))
8602 (setq org-stored-links
8603 (cons (list link desc) org-stored-links))))
8604 (or agenda-link (and link (org-make-link-string link desc)))))))
8606 (defun org-store-link-props (&rest plist)
8607 "Store link properties, extract names and addresses."
8608 (let (x adr)
8609 (when (setq x (plist-get plist :from))
8610 (setq adr (mail-extract-address-components x))
8611 (setq plist (plist-put plist :fromname (car adr)))
8612 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8613 (when (setq x (plist-get plist :to))
8614 (setq adr (mail-extract-address-components x))
8615 (setq plist (plist-put plist :toname (car adr)))
8616 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8617 (let ((from (plist-get plist :from))
8618 (to (plist-get plist :to)))
8619 (when (and from to org-from-is-user-regexp)
8620 (setq plist
8621 (plist-put plist :fromto
8622 (if (string-match org-from-is-user-regexp from)
8623 (concat "to %t")
8624 (concat "from %f"))))))
8625 (setq org-store-link-plist plist))
8627 (defun org-add-link-props (&rest plist)
8628 "Add these properties to the link property list."
8629 (let (key value)
8630 (while plist
8631 (setq key (pop plist) value (pop plist))
8632 (setq org-store-link-plist
8633 (plist-put org-store-link-plist key value)))))
8635 (defun org-email-link-description (&optional fmt)
8636 "Return the description part of an email link.
8637 This takes information from `org-store-link-plist' and formats it
8638 according to FMT (default from `org-email-link-description-format')."
8639 (setq fmt (or fmt org-email-link-description-format))
8640 (let* ((p org-store-link-plist)
8641 (to (plist-get p :toaddress))
8642 (from (plist-get p :fromaddress))
8643 (table
8644 (list
8645 (cons "%c" (plist-get p :fromto))
8646 (cons "%F" (plist-get p :from))
8647 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8648 (cons "%T" (plist-get p :to))
8649 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8650 (cons "%s" (plist-get p :subject))
8651 (cons "%d" (plist-get p :date))
8652 (cons "%m" (plist-get p :message-id)))))
8653 (when (string-match "%c" fmt)
8654 ;; Check if the user wrote this message
8655 (if (and org-from-is-user-regexp from to
8656 (save-match-data (string-match org-from-is-user-regexp from)))
8657 (setq fmt (replace-match "to %t" t t fmt))
8658 (setq fmt (replace-match "from %f" t t fmt))))
8659 (org-replace-escapes fmt table)))
8661 (defun org-make-org-heading-search-string (&optional string heading)
8662 "Make search string for STRING or current headline."
8663 (interactive)
8664 (let ((s (or string (org-get-heading)))
8665 (lines org-context-in-file-links))
8666 (unless (and string (not heading))
8667 ;; We are using a headline, clean up garbage in there.
8668 (if (string-match org-todo-regexp s)
8669 (setq s (replace-match "" t t s)))
8670 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8671 (setq s (replace-match "" t t s)))
8672 (setq s (org-trim s))
8673 (if (string-match (concat "^\\(" org-quote-string "\\|"
8674 org-comment-string "\\)") s)
8675 (setq s (replace-match "" t t s)))
8676 (while (string-match org-ts-regexp s)
8677 (setq s (replace-match "" t t s))))
8678 (or string (setq s (concat "*" s))) ; Add * for headlines
8679 (when (and string (integerp lines) (> lines 0))
8680 (let ((slines (org-split-string s "\n")))
8681 (when (< lines (length slines))
8682 (setq s (mapconcat
8683 'identity
8684 (reverse (nthcdr (- (length slines) lines)
8685 (reverse slines))) "\n")))))
8686 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8688 (defun org-make-link (&rest strings)
8689 "Concatenate STRINGS."
8690 (apply 'concat strings))
8692 (defun org-make-link-string (link &optional description)
8693 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8694 (unless (string-match "\\S-" link)
8695 (error "Empty link"))
8696 (when (and description
8697 (stringp description)
8698 (not (string-match "\\S-" description)))
8699 (setq description nil))
8700 (when (stringp description)
8701 ;; Remove brackets from the description, they are fatal.
8702 (while (string-match "\\[" description)
8703 (setq description (replace-match "{" t t description)))
8704 (while (string-match "\\]" description)
8705 (setq description (replace-match "}" t t description))))
8706 (when (equal link description)
8707 ;; No description needed, it is identical
8708 (setq description nil))
8709 (when (and (not description)
8710 (not (string-match (org-image-file-name-regexp) link))
8711 (not (equal link (org-link-escape link))))
8712 (setq description (org-extract-attributes link)))
8713 (setq link
8714 (cond ((string-match (org-image-file-name-regexp) link) link)
8715 ((string-match org-link-types-re link)
8716 (concat (match-string 1 link)
8717 (org-link-escape (substring link (match-end 1)))))
8718 (t (org-link-escape link))))
8719 (concat "[[" link "]"
8720 (if description (concat "[" description "]") "")
8721 "]"))
8723 (defconst org-link-escape-chars
8724 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8725 "List of characters that should be escaped in link.
8726 This is the list that is used for internal purposes.")
8728 (defvar org-url-encoding-use-url-hexify nil)
8730 (defconst org-link-escape-chars-browser
8731 '(?\ )
8732 "List of escapes for characters that are problematic in links.
8733 This is the list that is used before handing over to the browser.")
8735 (defun org-link-escape (text &optional table merge)
8736 "Return percent escaped representation of TEXT.
8737 TEXT is a string with the text to escape.
8738 Optional argument TABLE is a list with characters that should be
8739 escaped. When nil, `org-link-escape-chars' is used.
8740 If optional argument MERGE is set, merge TABLE into
8741 `org-link-escape-chars'."
8742 (if (and org-url-encoding-use-url-hexify (not table))
8743 (url-hexify-string text)
8744 (cond
8745 ((and table merge)
8746 (mapc (lambda (defchr)
8747 (unless (member defchr table)
8748 (setq table (cons defchr table)))) org-link-escape-chars))
8749 ((null table)
8750 (setq table org-link-escape-chars)))
8751 (mapconcat
8752 (lambda (char)
8753 (if (or (member char table)
8754 (< char 32) (= char 37) (> char 126))
8755 (mapconcat (lambda (sequence-element)
8756 (format "%%%.2X" sequence-element))
8757 (or (encode-coding-char char 'utf-8)
8758 (error "Unable to percent escape character: %s"
8759 (char-to-string char))) "")
8760 (char-to-string char))) text "")))
8762 (defun org-link-unescape (str)
8763 "Unhex hexified unicode strings as returned from the JavaScript function
8764 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
8765 (unless (and (null str) (string= "" str))
8766 (let ((pos 0) (case-fold-search t) unhexed)
8767 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
8768 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
8769 (setq str (replace-match unhexed t t str))
8770 (setq pos (+ pos (length unhexed))))))
8771 str)
8773 (defun org-link-unescape-compound (hex)
8774 "Unhexify unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
8775 Note: this function also decodes single byte encodings like
8776 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
8777 (save-match-data
8778 (let* ((bytes (cdr (split-string hex "%")))
8779 (ret "")
8780 (eat 0)
8781 (sum 0))
8782 (while bytes
8783 (let* ((val (string-to-number (pop bytes) 16))
8784 (shift-xor
8785 (if (= 0 eat)
8786 (cond
8787 ((>= val 252) (cons 6 252))
8788 ((>= val 248) (cons 5 248))
8789 ((>= val 240) (cons 4 240))
8790 ((>= val 224) (cons 3 224))
8791 ((>= val 192) (cons 2 192))
8792 (t (cons 0 0)))
8793 (cons 6 128))))
8794 (if (>= val 192) (setq eat (car shift-xor)))
8795 (setq val (logxor val (cdr shift-xor)))
8796 (setq sum (+ (lsh sum (car shift-xor)) val))
8797 (if (> eat 0) (setq eat (- eat 1)))
8798 (cond
8799 ((= 0 eat) ;multi byte
8800 (setq ret (concat ret (org-char-to-string sum)))
8801 (setq sum 0))
8802 ((not bytes) ; single byte(s)
8803 (setq ret (org-link-unescape-single-byte-sequence hex))))
8804 )) ;; end (while bytes
8805 ret )))
8807 (defun org-link-unescape-single-byte-sequence (hex)
8808 "Unhexify hex-encoded single byte character sequences."
8809 (mapconcat (lambda (byte)
8810 (char-to-string (string-to-number byte 16)))
8811 (cdr (split-string hex "%")) ""))
8813 (defun org-xor (a b)
8814 "Exclusive or."
8815 (if a (not b) b))
8817 (defun org-fixup-message-id-for-http (s)
8818 "Replace special characters in a message id, so it can be used in an http query."
8819 (when (string-match "%" s)
8820 (setq s (mapconcat (lambda (c)
8821 (if (eq c ?%)
8822 "%25"
8823 (char-to-string c)))
8824 s "")))
8825 (while (string-match "<" s)
8826 (setq s (replace-match "%3C" t t s)))
8827 (while (string-match ">" s)
8828 (setq s (replace-match "%3E" t t s)))
8829 (while (string-match "@" s)
8830 (setq s (replace-match "%40" t t s)))
8833 ;;;###autoload
8834 (defun org-insert-link-global ()
8835 "Insert a link like Org-mode does.
8836 This command can be called in any mode to insert a link in Org-mode syntax."
8837 (interactive)
8838 (org-load-modules-maybe)
8839 (org-run-like-in-org-mode 'org-insert-link))
8841 (defun org-insert-link (&optional complete-file link-location)
8842 "Insert a link. At the prompt, enter the link.
8844 Completion can be used to insert any of the link protocol prefixes like
8845 http or ftp in use.
8847 The history can be used to select a link previously stored with
8848 `org-store-link'. When the empty string is entered (i.e. if you just
8849 press RET at the prompt), the link defaults to the most recently
8850 stored link. As SPC triggers completion in the minibuffer, you need to
8851 use M-SPC or C-q SPC to force the insertion of a space character.
8853 You will also be prompted for a description, and if one is given, it will
8854 be displayed in the buffer instead of the link.
8856 If there is already a link at point, this command will allow you to edit link
8857 and description parts.
8859 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
8860 be selected using completion. The path to the file will be relative to the
8861 current directory if the file is in the current directory or a subdirectory.
8862 Otherwise, the link will be the absolute path as completed in the minibuffer
8863 \(i.e. normally ~/path/to/file). You can configure this behavior using the
8864 option `org-link-file-path-type'.
8866 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
8867 the current directory or below.
8869 With three \\[universal-argument] prefixes, negate the meaning of
8870 `org-keep-stored-link-after-insertion'.
8872 If `org-make-link-description-function' is non-nil, this function will be
8873 called with the link target, and the result will be the default
8874 link description.
8876 If the LINK-LOCATION parameter is non-nil, this value will be
8877 used as the link location instead of reading one interactively."
8878 (interactive "P")
8879 (let* ((wcf (current-window-configuration))
8880 (region (if (org-region-active-p)
8881 (buffer-substring (region-beginning) (region-end))))
8882 (remove (and region (list (region-beginning) (region-end))))
8883 (desc region)
8884 tmphist ; byte-compile incorrectly complains about this
8885 (link link-location)
8886 entry file all-prefixes)
8887 (cond
8888 (link-location) ; specified by arg, just use it.
8889 ((org-in-regexp org-bracket-link-regexp 1)
8890 ;; We do have a link at point, and we are going to edit it.
8891 (setq remove (list (match-beginning 0) (match-end 0)))
8892 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8893 (setq link (read-string "Link: "
8894 (org-link-unescape
8895 (org-match-string-no-properties 1)))))
8896 ((or (org-in-regexp org-angle-link-re)
8897 (org-in-regexp org-plain-link-re))
8898 ;; Convert to bracket link
8899 (setq remove (list (match-beginning 0) (match-end 0))
8900 link (read-string "Link: "
8901 (org-remove-angle-brackets (match-string 0)))))
8902 ((member complete-file '((4) (16)))
8903 ;; Completing read for file names.
8904 (setq link (org-file-complete-link complete-file)))
8906 ;; Read link, with completion for stored links.
8907 (with-output-to-temp-buffer "*Org Links*"
8908 (princ "Insert a link.
8909 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8910 (when org-stored-links
8911 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8912 (princ (mapconcat
8913 (lambda (x)
8914 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8915 (reverse org-stored-links) "\n"))))
8916 (let ((cw (selected-window)))
8917 (select-window (get-buffer-window "*Org Links*" 'visible))
8918 (with-current-buffer "*Org Links*" (setq truncate-lines) t)
8919 (unless (pos-visible-in-window-p (point-max))
8920 (org-fit-window-to-buffer))
8921 (and (window-live-p cw) (select-window cw)))
8922 ;; Fake a link history, containing the stored links.
8923 (setq tmphist (append (mapcar 'car org-stored-links)
8924 org-insert-link-history))
8925 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8926 (mapcar 'car org-link-abbrev-alist)
8927 org-link-types))
8928 (unwind-protect
8929 (progn
8930 (setq link
8931 (let ((org-completion-use-ido nil)
8932 (org-completion-use-iswitchb nil))
8933 (org-completing-read
8934 "Link: "
8935 (append
8936 (mapcar (lambda (x) (list (concat x ":")))
8937 all-prefixes)
8938 (mapcar 'car org-stored-links))
8939 nil nil nil
8940 'tmphist
8941 (car (car org-stored-links)))))
8942 (if (not (string-match "\\S-" link))
8943 (error "No link selected"))
8944 (if (or (member link all-prefixes)
8945 (and (equal ":" (substring link -1))
8946 (member (substring link 0 -1) all-prefixes)
8947 (setq link (substring link 0 -1))))
8948 (setq link (org-link-try-special-completion link))))
8949 (set-window-configuration wcf)
8950 (kill-buffer "*Org Links*"))
8951 (setq entry (assoc link org-stored-links))
8952 (or entry (push link org-insert-link-history))
8953 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8954 (not org-keep-stored-link-after-insertion))
8955 (setq org-stored-links (delq (assoc link org-stored-links)
8956 org-stored-links)))
8957 (setq desc (or desc (nth 1 entry)))))
8959 (if (string-match org-plain-link-re link)
8960 ;; URL-like link, normalize the use of angular brackets.
8961 (setq link (org-make-link (org-remove-angle-brackets link))))
8963 ;; Check if we are linking to the current file with a search option
8964 ;; If yes, simplify the link by using only the search option.
8965 (when (and buffer-file-name
8966 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8967 (let* ((path (match-string 1 link))
8968 (case-fold-search nil)
8969 (search (match-string 2 link)))
8970 (save-match-data
8971 (if (equal (file-truename buffer-file-name) (file-truename path))
8972 ;; We are linking to this same file, with a search option
8973 (setq link search)))))
8975 ;; Check if we can/should use a relative path. If yes, simplify the link
8976 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8977 (let* ((type (match-string 1 link))
8978 (path (match-string 2 link))
8979 (origpath path)
8980 (case-fold-search nil))
8981 (cond
8982 ((or (eq org-link-file-path-type 'absolute)
8983 (equal complete-file '(16)))
8984 (setq path (abbreviate-file-name (expand-file-name path))))
8985 ((eq org-link-file-path-type 'noabbrev)
8986 (setq path (expand-file-name path)))
8987 ((eq org-link-file-path-type 'relative)
8988 (setq path (file-relative-name path)))
8990 (save-match-data
8991 (if (string-match (concat "^" (regexp-quote
8992 (expand-file-name
8993 (file-name-as-directory
8994 default-directory))))
8995 (expand-file-name path))
8996 ;; We are linking a file with relative path name.
8997 (setq path (substring (expand-file-name path)
8998 (match-end 0)))
8999 (setq path (abbreviate-file-name (expand-file-name path)))))))
9000 (setq link (concat type path))
9001 (if (equal desc origpath)
9002 (setq desc path))))
9004 (if org-make-link-description-function
9005 (setq desc (funcall org-make-link-description-function link desc)))
9007 (setq desc (read-string "Description: " desc))
9008 (unless (string-match "\\S-" desc) (setq desc nil))
9009 (if remove (apply 'delete-region remove))
9010 (insert (org-make-link-string link desc))))
9012 (defun org-link-try-special-completion (type)
9013 "If there is completion support for link type TYPE, offer it."
9014 (let ((fun (intern (concat "org-" type "-complete-link"))))
9015 (if (functionp fun)
9016 (funcall fun)
9017 (read-string "Link (no completion support): " (concat type ":")))))
9019 (defun org-file-complete-link (&optional arg)
9020 "Create a file link using completion."
9021 (let (file link)
9022 (setq file (read-file-name "File: "))
9023 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9024 (pwd1 (file-name-as-directory (abbreviate-file-name
9025 (expand-file-name ".")))))
9026 (cond
9027 ((equal arg '(16))
9028 (setq link (org-make-link
9029 "file:"
9030 (abbreviate-file-name (expand-file-name file)))))
9031 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9032 (setq link (org-make-link "file:" (match-string 1 file))))
9033 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9034 (expand-file-name file))
9035 (setq link (org-make-link
9036 "file:" (match-string 1 (expand-file-name file)))))
9037 (t (setq link (org-make-link "file:" file)))))
9038 link))
9040 (defun org-completing-read (&rest args)
9041 "Completing-read with SPACE being a normal character."
9042 (let ((minibuffer-local-completion-map
9043 (copy-keymap minibuffer-local-completion-map)))
9044 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9045 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9046 (apply 'org-icompleting-read args)))
9048 (defun org-completing-read-no-i (&rest args)
9049 (let (org-completion-use-ido org-completion-use-iswitchb)
9050 (apply 'org-completing-read args)))
9052 (defun org-iswitchb-completing-read (prompt choices &rest args)
9053 "Use iswitch as a completing-read replacement to choose from choices.
9054 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9055 from."
9056 (let* ((iswitchb-use-virtual-buffers nil)
9057 (iswitchb-make-buflist-hook
9058 (lambda ()
9059 (setq iswitchb-temp-buflist choices))))
9060 (iswitchb-read-buffer prompt)))
9062 (defun org-icompleting-read (&rest args)
9063 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9064 (org-without-partial-completion
9065 (if (and org-completion-use-ido
9066 (fboundp 'ido-completing-read)
9067 (boundp 'ido-mode) ido-mode
9068 (listp (second args)))
9069 (let ((ido-enter-matching-directory nil))
9070 (apply 'ido-completing-read (concat (car args))
9071 (if (consp (car (nth 1 args)))
9072 (mapcar 'car (nth 1 args))
9073 (nth 1 args))
9074 (cddr args)))
9075 (if (and org-completion-use-iswitchb
9076 (boundp 'iswitchb-mode) iswitchb-mode
9077 (listp (second args)))
9078 (apply 'org-iswitchb-completing-read (concat (car args))
9079 (if (consp (car (nth 1 args)))
9080 (mapcar 'car (nth 1 args))
9081 (nth 1 args))
9082 (cddr args))
9083 (apply 'completing-read args)))))
9085 (defun org-extract-attributes (s)
9086 "Extract the attributes cookie from a string and set as text property."
9087 (let (a attr (start 0) key value)
9088 (save-match-data
9089 (when (string-match "{{\\([^}]+\\)}}$" s)
9090 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9091 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9092 (setq key (match-string 1 a) value (match-string 2 a)
9093 start (match-end 0)
9094 attr (plist-put attr (intern key) value))))
9095 (org-add-props s nil 'org-attr attr))
9098 (defun org-extract-attributes-from-string (tag)
9099 (let (key value attr)
9100 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9101 (setq key (match-string 1 tag) value (match-string 2 tag)
9102 tag (replace-match "" t t tag)
9103 attr (plist-put attr (intern key) value)))
9104 (cons tag attr)))
9106 (defun org-attributes-to-string (plist)
9107 "Format a property list into an HTML attribute list."
9108 (let ((s "") key value)
9109 (while plist
9110 (setq key (pop plist) value (pop plist))
9111 (and value
9112 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9115 ;;; Opening/following a link
9117 (defvar org-link-search-failed nil)
9119 (defvar org-open-link-functions nil
9120 "Hook for functions finding a plain text link.
9121 These functions must take a single argument, the link content.
9122 They will be called for links that look like [[link text][description]]
9123 when LINK TEXT does not have a protocol like \"http:\" and does not look
9124 like a filename (e.g. \"./blue.png\").
9126 These functions will be called *before* Org attempts to resolve the
9127 link by doing text searches in the current buffer - so if you want a
9128 link \"[[target]]\" to still find \"<<target>>\", your function should
9129 handle this as a special case.
9131 When the function does handle the link, it must return a non-nil value.
9132 If it decides that it is not responsible for this link, it must return
9133 nil to indicate that that Org-mode can continue with other options
9134 like exact and fuzzy text search.")
9136 (defun org-next-link ()
9137 "Move forward to the next link.
9138 If the link is in hidden text, expose it."
9139 (interactive)
9140 (when (and org-link-search-failed (eq this-command last-command))
9141 (goto-char (point-min))
9142 (message "Link search wrapped back to beginning of buffer"))
9143 (setq org-link-search-failed nil)
9144 (let* ((pos (point))
9145 (ct (org-context))
9146 (a (assoc :link ct)))
9147 (if a (goto-char (nth 2 a)))
9148 (if (re-search-forward org-any-link-re nil t)
9149 (progn
9150 (goto-char (match-beginning 0))
9151 (if (outline-invisible-p) (org-show-context)))
9152 (goto-char pos)
9153 (setq org-link-search-failed t)
9154 (error "No further link found"))))
9156 (defun org-previous-link ()
9157 "Move backward to the previous link.
9158 If the link is in hidden text, expose it."
9159 (interactive)
9160 (when (and org-link-search-failed (eq this-command last-command))
9161 (goto-char (point-max))
9162 (message "Link search wrapped back to end of buffer"))
9163 (setq org-link-search-failed nil)
9164 (let* ((pos (point))
9165 (ct (org-context))
9166 (a (assoc :link ct)))
9167 (if a (goto-char (nth 1 a)))
9168 (if (re-search-backward org-any-link-re nil t)
9169 (progn
9170 (goto-char (match-beginning 0))
9171 (if (outline-invisible-p) (org-show-context)))
9172 (goto-char pos)
9173 (setq org-link-search-failed t)
9174 (error "No further link found"))))
9176 (defun org-translate-link (s)
9177 "Translate a link string if a translation function has been defined."
9178 (if (and org-link-translation-function
9179 (fboundp org-link-translation-function)
9180 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9181 (progn
9182 (setq s (funcall org-link-translation-function
9183 (match-string 1) (match-string 2)))
9184 (concat (car s) ":" (cdr s)))
9187 (defun org-translate-link-from-planner (type path)
9188 "Translate a link from Emacs Planner syntax so that Org can follow it.
9189 This is still an experimental function, your mileage may vary."
9190 (cond
9191 ((member type '("http" "https" "news" "ftp"))
9192 ;; standard Internet links are the same.
9193 nil)
9194 ((and (equal type "irc") (string-match "^//" path))
9195 ;; Planner has two / at the beginning of an irc link, we have 1.
9196 ;; We should have zero, actually....
9197 (setq path (substring path 1)))
9198 ((and (equal type "lisp") (string-match "^/" path))
9199 ;; Planner has a slash, we do not.
9200 (setq type "elisp" path (substring path 1)))
9201 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9202 ;; A typical message link. Planner has the id after the final slash,
9203 ;; we separate it with a hash mark
9204 (setq path (concat (match-string 1 path) "#"
9205 (org-remove-angle-brackets (match-string 2 path)))))
9207 (cons type path))
9209 (defun org-find-file-at-mouse (ev)
9210 "Open file link or URL at mouse."
9211 (interactive "e")
9212 (mouse-set-point ev)
9213 (org-open-at-point 'in-emacs))
9215 (defun org-open-at-mouse (ev)
9216 "Open file link or URL at mouse."
9217 (interactive "e")
9218 (mouse-set-point ev)
9219 (if (eq major-mode 'org-agenda-mode)
9220 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9221 (org-open-at-point))
9223 (defvar org-window-config-before-follow-link nil
9224 "The window configuration before following a link.
9225 This is saved in case the need arises to restore it.")
9227 (defvar org-open-link-marker (make-marker)
9228 "Marker pointing to the location where `org-open-at-point; was called.")
9230 ;;;###autoload
9231 (defun org-open-at-point-global ()
9232 "Follow a link like Org-mode does.
9233 This command can be called in any mode to follow a link that has
9234 Org-mode syntax."
9235 (interactive)
9236 (org-run-like-in-org-mode 'org-open-at-point))
9238 ;;;###autoload
9239 (defun org-open-link-from-string (s &optional arg reference-buffer)
9240 "Open a link in the string S, as if it was in Org-mode."
9241 (interactive "sLink: \nP")
9242 (let ((reference-buffer (or reference-buffer (current-buffer))))
9243 (with-temp-buffer
9244 (let ((org-inhibit-startup t))
9245 (org-mode)
9246 (insert s)
9247 (goto-char (point-min))
9248 (when reference-buffer
9249 (setq org-link-abbrev-alist-local
9250 (with-current-buffer reference-buffer
9251 org-link-abbrev-alist-local)))
9252 (org-open-at-point arg reference-buffer)))))
9254 (defvar org-open-at-point-functions nil
9255 "Hook that is run when following a link at point.
9257 Functions in this hook must return t if they identify and follow
9258 a link at point. If they don't find anything interesting at point,
9259 they must return nil.")
9261 (defun org-open-at-point (&optional arg reference-buffer)
9262 "Open link at or after point.
9263 If there is no link at point, this function will search forward up to
9264 the end of the current line.
9265 Normally, files will be opened by an appropriate application. If the
9266 optional prefix argument ARG is non-nil, Emacs will visit the file.
9267 With a double prefix argument, try to open outside of Emacs, in the
9268 application the system uses for this file type."
9269 (interactive "P")
9270 ;; if in a code block, then open the block's results
9271 (unless (call-interactively #'org-babel-open-src-block-result)
9272 (org-load-modules-maybe)
9273 (move-marker org-open-link-marker (point))
9274 (setq org-window-config-before-follow-link (current-window-configuration))
9275 (org-remove-occur-highlights nil nil t)
9276 (cond
9277 ((and (org-on-heading-p)
9278 (not (org-in-regexp
9279 (concat org-plain-link-re "\\|"
9280 org-bracket-link-regexp "\\|"
9281 org-angle-link-re "\\|"
9282 "[ \t]:[^ \t\n]+:[ \t]*$")))
9283 (not (get-text-property (point) 'org-linked-text)))
9284 (or (org-offer-links-in-entry arg)
9285 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9286 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9287 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9288 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9289 (not (org-in-regexp org-bracket-link-regexp)))
9290 (org-footnote-action))
9292 (let (type path link line search (pos (point)))
9293 (catch 'match
9294 (save-excursion
9295 (skip-chars-forward "^]\n\r")
9296 (when (org-in-regexp org-bracket-link-regexp 1)
9297 (setq link (org-extract-attributes
9298 (org-link-unescape (org-match-string-no-properties 1))))
9299 (while (string-match " *\n *" link)
9300 (setq link (replace-match " " t t link)))
9301 (setq link (org-link-expand-abbrev link))
9302 (cond
9303 ((or (file-name-absolute-p link)
9304 (string-match "^\\.\\.?/" link))
9305 (setq type "file" path link))
9306 ((string-match org-link-re-with-space3 link)
9307 (setq type (match-string 1 link) path (match-string 2 link)))
9308 (t (setq type "thisfile" path link)))
9309 (throw 'match t)))
9311 (when (get-text-property (point) 'org-linked-text)
9312 (setq type "thisfile"
9313 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9314 (1+ (point)) (point))
9315 path (buffer-substring
9316 (or (previous-single-property-change pos 'org-linked-text)
9317 (point-min))
9318 (or (next-single-property-change pos 'org-linked-text)
9319 (point-max))))
9320 (throw 'match t))
9322 (save-excursion
9323 (when (or (org-in-regexp org-angle-link-re)
9324 (org-in-regexp org-plain-link-re))
9325 (setq type (match-string 1) path (match-string 2))
9326 (throw 'match t)))
9327 (save-excursion
9328 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9329 (setq type "tags"
9330 path (match-string 1))
9331 (while (string-match ":" path)
9332 (setq path (replace-match "+" t t path)))
9333 (throw 'match t)))
9334 (when (org-in-regexp "<\\([^><\n]+\\)>")
9335 (setq type "tree-match"
9336 path (match-string 1))
9337 (throw 'match t)))
9338 (unless path
9339 (error "No link found"))
9341 ;; switch back to reference buffer
9342 ;; needed when if called in a temporary buffer through
9343 ;; org-open-link-from-string
9344 (with-current-buffer (or reference-buffer (current-buffer))
9346 ;; Remove any trailing spaces in path
9347 (if (string-match " +\\'" path)
9348 (setq path (replace-match "" t t path)))
9349 (if (and org-link-translation-function
9350 (fboundp org-link-translation-function))
9351 ;; Check if we need to translate the link
9352 (let ((tmp (funcall org-link-translation-function type path)))
9353 (setq type (car tmp) path (cdr tmp))))
9355 (cond
9357 ((assoc type org-link-protocols)
9358 (funcall (nth 1 (assoc type org-link-protocols)) path))
9360 ((equal type "mailto")
9361 (let ((cmd (car org-link-mailto-program))
9362 (args (cdr org-link-mailto-program)) args1
9363 (address path) (subject "") a)
9364 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9365 (setq address (match-string 1 path)
9366 subject (org-link-escape (match-string 2 path))))
9367 (while args
9368 (cond
9369 ((not (stringp (car args))) (push (pop args) args1))
9370 (t (setq a (pop args))
9371 (if (string-match "%a" a)
9372 (setq a (replace-match address t t a)))
9373 (if (string-match "%s" a)
9374 (setq a (replace-match subject t t a)))
9375 (push a args1))))
9376 (apply cmd (nreverse args1))))
9378 ((member type '("http" "https" "ftp" "news"))
9379 (browse-url (concat type ":" (org-link-escape
9380 path org-link-escape-chars-browser))))
9382 ((string= type "doi")
9383 (browse-url (concat "http://dx.doi.org/"
9384 (org-link-escape
9385 path org-link-escape-chars-browser))))
9387 ((member type '("message"))
9388 (browse-url (concat type ":" path)))
9390 ((string= type "tags")
9391 (org-tags-view arg path))
9393 ((string= type "tree-match")
9394 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9396 ((string= type "file")
9397 (if (string-match "::\\([0-9]+\\)\\'" path)
9398 (setq line (string-to-number (match-string 1 path))
9399 path (substring path 0 (match-beginning 0)))
9400 (if (string-match "::\\(.+\\)\\'" path)
9401 (setq search (match-string 1 path)
9402 path (substring path 0 (match-beginning 0)))))
9403 (if (string-match "[*?{]" (file-name-nondirectory path))
9404 (dired path)
9405 (org-open-file path arg line search)))
9407 ((string= type "shell")
9408 (let ((cmd path))
9409 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9410 (string-match org-confirm-shell-link-not-regexp cmd))
9411 (not org-confirm-shell-link-function)
9412 (funcall org-confirm-shell-link-function
9413 (format "Execute \"%s\" in shell? "
9414 (org-add-props cmd nil
9415 'face 'org-warning))))
9416 (progn
9417 (message "Executing %s" cmd)
9418 (shell-command cmd))
9419 (error "Abort"))))
9421 ((string= type "elisp")
9422 (let ((cmd path))
9423 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9424 (string-match org-confirm-elisp-link-not-regexp cmd))
9425 (not org-confirm-elisp-link-function)
9426 (funcall org-confirm-elisp-link-function
9427 (format "Execute \"%s\" as elisp? "
9428 (org-add-props cmd nil
9429 'face 'org-warning))))
9430 (message "%s => %s" cmd
9431 (if (equal (string-to-char cmd) ?\()
9432 (eval (read cmd))
9433 (call-interactively (read cmd))))
9434 (error "Abort"))))
9436 ((and (string= type "thisfile")
9437 (run-hook-with-args-until-success
9438 'org-open-link-functions path)))
9440 ((string= type "thisfile")
9441 (if arg
9442 (switch-to-buffer-other-window
9443 (org-get-buffer-for-internal-link (current-buffer)))
9444 (org-mark-ring-push))
9445 (let ((cmd `(org-link-search
9446 ,path
9447 ,(cond ((equal arg '(4)) ''occur)
9448 ((equal arg '(16)) ''org-occur)
9449 (t nil))
9450 ,pos)))
9451 (condition-case nil (eval cmd)
9452 (error (progn (widen) (eval cmd))))))
9455 (browse-url-at-point)))))))
9456 (move-marker org-open-link-marker nil)
9457 (run-hook-with-args 'org-follow-link-hook)))
9459 (defun org-offer-links-in-entry (&optional nth zero)
9460 "Offer links in the current entry and follow the selected link.
9461 If there is only one link, follow it immediately as well.
9462 If NTH is an integer, immediately pick the NTH link found.
9463 If ZERO is a string, check also this string for a link, and if
9464 there is one, offer it as link number zero."
9465 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9466 "\\(" org-angle-link-re "\\)\\|"
9467 "\\(" org-plain-link-re "\\)"))
9468 (cnt ?0)
9469 (in-emacs (if (integerp nth) nil nth))
9470 have-zero end links link c)
9471 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9472 (push (match-string 0 zero) links)
9473 (setq cnt (1- cnt) have-zero t))
9474 (save-excursion
9475 (org-back-to-heading t)
9476 (setq end (save-excursion (outline-next-heading) (point)))
9477 (while (re-search-forward re end t)
9478 (push (match-string 0) links))
9479 (setq links (org-uniquify (reverse links))))
9481 (cond
9482 ((null links)
9483 (message "No links"))
9484 ((equal (length links) 1)
9485 (setq link (list (car links))))
9486 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9487 (setq link (nth (if have-zero nth (1- nth)) links)))
9488 (t ; we have to select a link
9489 (save-excursion
9490 (save-window-excursion
9491 (delete-other-windows)
9492 (with-output-to-temp-buffer "*Select Link*"
9493 (mapc (lambda (l)
9494 (if (not (string-match org-bracket-link-regexp l))
9495 (princ (format "[%c] %s\n" (incf cnt)
9496 (org-remove-angle-brackets l)))
9497 (if (match-end 3)
9498 (princ (format "[%c] %s (%s)\n" (incf cnt)
9499 (match-string 3 l) (match-string 1 l)))
9500 (princ (format "[%c] %s\n" (incf cnt)
9501 (match-string 1 l))))))
9502 links))
9503 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9504 (message "Select link to open, RET to open all:")
9505 (setq c (read-char-exclusive))
9506 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9507 (when (equal c ?q) (error "Abort"))
9508 (if (equal c ?\C-m)
9509 (setq link links)
9510 (setq nth (- c ?0))
9511 (if have-zero (setq nth (1+ nth)))
9512 (unless (and (integerp nth) (>= (length links) nth))
9513 (error "Invalid link selection"))
9514 (setq link (list (nth (1- nth) links))))))
9515 (if link
9516 (let ((buf (current-buffer)))
9517 (dolist (l link)
9518 (org-open-link-from-string l in-emacs buf))
9520 nil)))
9522 ;; Add special file links that specify the way of opening
9524 (org-add-link-type "file+sys" 'org-open-file-with-system)
9525 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9526 (defun org-open-file-with-system (path)
9527 "Open file at PATH using the system way of opening it."
9528 (org-open-file path 'system))
9529 (defun org-open-file-with-emacs (path)
9530 "Open file at PATH in Emacs."
9531 (org-open-file path 'emacs))
9532 (defun org-remove-file-link-modifiers ()
9533 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9534 (goto-char (point-min))
9535 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9536 (org-if-unprotected
9537 (replace-match "file:" t t))))
9538 (eval-after-load "org-exp"
9539 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9540 'org-remove-file-link-modifiers))
9542 ;;;; Time estimates
9544 (defun org-get-effort (&optional pom)
9545 "Get the effort estimate for the current entry."
9546 (org-entry-get pom org-effort-property))
9548 ;;; File search
9550 (defvar org-create-file-search-functions nil
9551 "List of functions to construct the right search string for a file link.
9552 These functions are called in turn with point at the location to
9553 which the link should point.
9555 A function in the hook should first test if it would like to
9556 handle this file type, for example by checking the `major-mode'
9557 or the file extension. If it decides not to handle this file, it
9558 should just return nil to give other functions a chance. If it
9559 does handle the file, it must return the search string to be used
9560 when following the link. The search string will be part of the
9561 file link, given after a double colon, and `org-open-at-point'
9562 will automatically search for it. If special measures must be
9563 taken to make the search successful, another function should be
9564 added to the companion hook `org-execute-file-search-functions',
9565 which see.
9567 A function in this hook may also use `setq' to set the variable
9568 `description' to provide a suggestion for the descriptive text to
9569 be used for this link when it gets inserted into an Org-mode
9570 buffer with \\[org-insert-link].")
9572 (defvar org-execute-file-search-functions nil
9573 "List of functions to execute a file search triggered by a link.
9575 Functions added to this hook must accept a single argument, the
9576 search string that was part of the file link, the part after the
9577 double colon. The function must first check if it would like to
9578 handle this search, for example by checking the `major-mode' or
9579 the file extension. If it decides not to handle this search, it
9580 should just return nil to give other functions a chance. If it
9581 does handle the search, it must return a non-nil value to keep
9582 other functions from trying.
9584 Each function can access the current prefix argument through the
9585 variable `current-prefix-argument'. Note that a single prefix is
9586 used to force opening a link in Emacs, so it may be good to only
9587 use a numeric or double prefix to guide the search function.
9589 In case this is needed, a function in this hook can also restore
9590 the window configuration before `org-open-at-point' was called using:
9592 (set-window-configuration org-window-config-before-follow-link)")
9594 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9595 (defun org-link-search (s &optional type avoid-pos)
9596 "Search for a link search option.
9597 If S is surrounded by forward slashes, it is interpreted as a
9598 regular expression. In org-mode files, this will create an `org-occur'
9599 sparse tree. In ordinary files, `occur' will be used to list matches.
9600 If the current buffer is in `dired-mode', grep will be used to search
9601 in all files. If AVOID-POS is given, ignore matches near that position."
9602 (let ((case-fold-search t)
9603 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9604 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9605 (append '(("") (" ") ("\t") ("\n"))
9606 org-emphasis-alist)
9607 "\\|") "\\)"))
9608 (pos (point))
9609 (pre nil) (post nil)
9610 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9611 (cond
9612 ;; First check if there are any special search functions
9613 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9614 ;; Now try the builtin stuff
9615 ((and (equal (string-to-char s0) ?#)
9616 (> (length s0) 1)
9617 (save-excursion
9618 (goto-char (point-min))
9619 (and
9620 (re-search-forward
9621 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9622 (setq type 'dedicated
9623 pos (match-beginning 0))))
9624 ;; There is an exact target for this
9625 (goto-char pos)
9626 (org-back-to-heading t)))
9627 ((save-excursion
9628 (goto-char (point-min))
9629 (and
9630 (re-search-forward
9631 (concat "<<" (regexp-quote s0) ">>") nil t)
9632 (setq type 'dedicated
9633 pos (match-beginning 0))))
9634 ;; There is an exact target for this
9635 (goto-char pos))
9636 ((and (string-match "^(\\(.*\\))$" s0)
9637 (save-excursion
9638 (goto-char (point-min))
9639 (and
9640 (re-search-forward
9641 (concat "[^[]" (regexp-quote
9642 (format org-coderef-label-format
9643 (match-string 1 s0))))
9644 nil t)
9645 (setq type 'dedicated
9646 pos (1+ (match-beginning 0))))))
9647 ;; There is a coderef target for this
9648 (goto-char pos))
9649 ((string-match "^/\\(.*\\)/$" s)
9650 ;; A regular expression
9651 (cond
9652 ((org-mode-p)
9653 (org-occur (match-string 1 s)))
9654 ;;((eq major-mode 'dired-mode)
9655 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9656 (t (org-do-occur (match-string 1 s)))))
9657 ((and (org-mode-p) org-link-search-must-match-exact-headline)
9658 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9659 (goto-char (point-min))
9660 (cond
9661 ((let (case-fold-search)
9662 (re-search-forward (format org-complex-heading-regexp-format
9663 (regexp-quote s))
9664 nil t))
9665 ;; OK, found a match
9666 (setq type 'dedicated)
9667 (goto-char (match-beginning 0)))
9668 ((and (not org-link-search-inhibit-query)
9669 (eq org-link-search-must-match-exact-headline 'query-to-create)
9670 (y-or-n-p "No match - create this as a new heading? "))
9671 (goto-char (point-max))
9672 (or (bolp) (newline))
9673 (insert "* " s "\n")
9674 (beginning-of-line 0))
9676 (goto-char pos)
9677 (error "No match"))))
9679 ;; A normal search string
9680 (when (equal (string-to-char s) ?*)
9681 ;; Anchor on headlines, post may include tags.
9682 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9683 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9684 s (substring s 1)))
9685 (remove-text-properties
9686 0 (length s)
9687 '(face nil mouse-face nil keymap nil fontified nil) s)
9688 ;; Make a series of regular expressions to find a match
9689 (setq words (org-split-string s "[ \n\r\t]+")
9691 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9692 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9693 "\\)" markers)
9694 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9695 re2a (concat "[ \t\r\n]" re2a_)
9696 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9697 re4 (concat "[^a-zA-Z_]" re4_)
9699 re1 (concat pre re2 post)
9700 re3 (concat pre (if pre re4_ re4) post)
9701 re5 (concat pre ".*" re4)
9702 re2 (concat pre re2)
9703 re2a (concat pre (if pre re2a_ re2a))
9704 re4 (concat pre (if pre re4_ re4))
9705 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9706 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9707 re5 "\\)"
9709 (cond
9710 ((eq type 'org-occur) (org-occur reall))
9711 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9712 (t (goto-char (point-min))
9713 (setq type 'fuzzy)
9714 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9715 (org-search-not-self 1 re1 nil t)
9716 (org-search-not-self 1 re2 nil t)
9717 (org-search-not-self 1 re2a nil t)
9718 (org-search-not-self 1 re3 nil t)
9719 (org-search-not-self 1 re4 nil t)
9720 (org-search-not-self 1 re5 nil t)
9722 (goto-char (match-beginning 1))
9723 (goto-char pos)
9724 (error "No match"))))))
9725 (and (org-mode-p) (org-show-context 'link-search))
9726 type))
9728 (defun org-search-not-self (group &rest args)
9729 "Execute `re-search-forward', but only accept matches that do not
9730 enclose the position of `org-open-link-marker'."
9731 (let ((m org-open-link-marker))
9732 (catch 'exit
9733 (while (apply 're-search-forward args)
9734 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9735 (goto-char (match-end group))
9736 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9737 (> (match-beginning 0) (marker-position m))
9738 (< (match-end 0) (marker-position m)))
9739 (save-match-data
9740 (or (not (org-in-regexp
9741 org-bracket-link-analytic-regexp 1))
9742 (not (match-end 4)) ; no description
9743 (and (<= (match-beginning 4) (point))
9744 (>= (match-end 4) (point))))))
9745 (throw 'exit (point))))))))
9747 (defun org-get-buffer-for-internal-link (buffer)
9748 "Return a buffer to be used for displaying the link target of internal links."
9749 (cond
9750 ((not org-display-internal-link-with-indirect-buffer)
9751 buffer)
9752 ((string-match "(Clone)$" (buffer-name buffer))
9753 (message "Buffer is already a clone, not making another one")
9754 ;; we also do not modify visibility in this case
9755 buffer)
9756 (t ; make a new indirect buffer for displaying the link
9757 (let* ((bn (buffer-name buffer))
9758 (ibn (concat bn "(Clone)"))
9759 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9760 (with-current-buffer ib (org-overview))
9761 ib))))
9763 (defun org-do-occur (regexp &optional cleanup)
9764 "Call the Emacs command `occur'.
9765 If CLEANUP is non-nil, remove the printout of the regular expression
9766 in the *Occur* buffer. This is useful if the regex is long and not useful
9767 to read."
9768 (occur regexp)
9769 (when cleanup
9770 (let ((cwin (selected-window)) win beg end)
9771 (when (setq win (get-buffer-window "*Occur*"))
9772 (select-window win))
9773 (goto-char (point-min))
9774 (when (re-search-forward "match[a-z]+" nil t)
9775 (setq beg (match-end 0))
9776 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9777 (setq end (1- (match-beginning 0)))))
9778 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9779 (goto-char (point-min))
9780 (select-window cwin))))
9782 ;;; The mark ring for links jumps
9784 (defvar org-mark-ring nil
9785 "Mark ring for positions before jumps in Org-mode.")
9786 (defvar org-mark-ring-last-goto nil
9787 "Last position in the mark ring used to go back.")
9788 ;; Fill and close the ring
9789 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9790 (loop for i from 1 to org-mark-ring-length do
9791 (push (make-marker) org-mark-ring))
9792 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9793 org-mark-ring)
9795 (defun org-mark-ring-push (&optional pos buffer)
9796 "Put the current position or POS into the mark ring and rotate it."
9797 (interactive)
9798 (setq pos (or pos (point)))
9799 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9800 (move-marker (car org-mark-ring)
9801 (or pos (point))
9802 (or buffer (current-buffer)))
9803 (message "%s"
9804 (substitute-command-keys
9805 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9807 (defun org-mark-ring-goto (&optional n)
9808 "Jump to the previous position in the mark ring.
9809 With prefix arg N, jump back that many stored positions. When
9810 called several times in succession, walk through the entire ring.
9811 Org-mode commands jumping to a different position in the current file,
9812 or to another Org-mode file, automatically push the old position
9813 onto the ring."
9814 (interactive "p")
9815 (let (p m)
9816 (if (eq last-command this-command)
9817 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9818 (setq p org-mark-ring))
9819 (setq org-mark-ring-last-goto p)
9820 (setq m (car p))
9821 (switch-to-buffer (marker-buffer m))
9822 (goto-char m)
9823 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9825 (defun org-remove-angle-brackets (s)
9826 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9827 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9829 (defun org-add-angle-brackets (s)
9830 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9831 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9833 (defun org-remove-double-quotes (s)
9834 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9835 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
9838 ;;; Following specific links
9840 (defun org-follow-timestamp-link ()
9841 (cond
9842 ((org-at-date-range-p t)
9843 (let ((org-agenda-start-on-weekday)
9844 (t1 (match-string 1))
9845 (t2 (match-string 2)))
9846 (setq t1 (time-to-days (org-time-string-to-time t1))
9847 t2 (time-to-days (org-time-string-to-time t2)))
9848 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9849 ((org-at-timestamp-p t)
9850 (org-agenda-list nil (time-to-days (org-time-string-to-time
9851 (substring (match-string 1) 0 10)))
9853 (t (error "This should not happen"))))
9856 ;;; Following file links
9857 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
9858 (declare-function mailcap-extension-to-mime "mailcap" (extn))
9859 (declare-function mailcap-mime-info
9860 "mailcap" (string &optional request no-decode))
9861 (defvar org-wait nil)
9862 (defun org-open-file (path &optional in-emacs line search)
9863 "Open the file at PATH.
9864 First, this expands any special file name abbreviations. Then the
9865 configuration variable `org-file-apps' is checked if it contains an
9866 entry for this file type, and if yes, the corresponding command is launched.
9868 If no application is found, Emacs simply visits the file.
9870 With optional prefix argument IN-EMACS, Emacs will visit the file.
9871 With a double \\[universal-argument] \\[universal-argument] \
9872 prefix arg, Org tries to avoid opening in Emacs
9873 and to use an external application to visit the file.
9875 Optional LINE specifies a line to go to, optional SEARCH a string
9876 to search for. If LINE or SEARCH is given, the file will be
9877 opened in Emacs, unless an entry from org-file-apps that makes
9878 use of groups in a regexp matches.
9879 If the file does not exist, an error is thrown."
9880 (let* ((file (if (equal path "")
9881 buffer-file-name
9882 (substitute-in-file-name (expand-file-name path))))
9883 (file-apps (append org-file-apps (org-default-apps)))
9884 (apps (org-remove-if
9885 'org-file-apps-entry-match-against-dlink-p file-apps))
9886 (apps-dlink (org-remove-if-not
9887 'org-file-apps-entry-match-against-dlink-p file-apps))
9888 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9889 (dirp (if remp nil (file-directory-p file)))
9890 (file (if (and dirp org-open-directory-means-index-dot-org)
9891 (concat (file-name-as-directory file) "index.org")
9892 file))
9893 (a-m-a-p (assq 'auto-mode apps))
9894 (dfile (downcase file))
9895 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
9896 (link (cond ((and (eq line nil)
9897 (eq search nil))
9898 file)
9899 (line
9900 (concat file "::" (number-to-string line)))
9901 (search
9902 (concat file "::" search))))
9903 (dlink (downcase link))
9904 (old-buffer (current-buffer))
9905 (old-pos (point))
9906 (old-mode major-mode)
9907 ext cmd link-match-data)
9908 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9909 (setq ext (match-string 1 dfile))
9910 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9911 (setq ext (match-string 1 dfile))))
9912 (cond
9913 ((member in-emacs '((16) system))
9914 (setq cmd (cdr (assoc 'system apps))))
9915 (in-emacs (setq cmd 'emacs))
9917 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9918 (and dirp (cdr (assoc 'directory apps)))
9919 ; first, try matching against apps-dlink
9920 ; if we get a match here, store the match data for later
9921 (let ((match (assoc-default dlink apps-dlink
9922 'string-match)))
9923 (if match
9924 (progn (setq link-match-data (match-data))
9925 match)
9926 (progn (setq in-emacs (or in-emacs line search))
9927 nil))) ; if we have no match in apps-dlink,
9928 ; always open the file in emacs if line or search
9929 ; is given (for backwards compatibility)
9930 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
9931 'string-match)
9932 (cdr (assoc ext apps))
9933 (cdr (assoc t apps))))))
9934 (when (eq cmd 'system)
9935 (setq cmd (cdr (assoc 'system apps))))
9936 (when (eq cmd 'default)
9937 (setq cmd (cdr (assoc t apps))))
9938 (when (eq cmd 'mailcap)
9939 (require 'mailcap)
9940 (mailcap-parse-mailcaps)
9941 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9942 (command (mailcap-mime-info mime-type)))
9943 (if (stringp command)
9944 (setq cmd command)
9945 (setq cmd 'emacs))))
9946 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
9947 (not (file-exists-p file))
9948 (not org-open-non-existing-files))
9949 (error "No such file: %s" file))
9950 (cond
9951 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9952 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9953 (while (string-match "['\"]%s['\"]" cmd)
9954 (setq cmd (replace-match "%s" t t cmd)))
9955 (while (string-match "%s" cmd)
9956 (setq cmd (replace-match
9957 (save-match-data
9958 (shell-quote-argument
9959 (convert-standard-filename file)))
9960 t t cmd)))
9962 ;; Replace "%1", "%2" etc. in command with group matches from regex
9963 (save-match-data
9964 (let ((match-index 1)
9965 (number-of-groups (- (/ (length link-match-data) 2) 1)))
9966 (set-match-data link-match-data)
9967 (while (<= match-index number-of-groups)
9968 (let ((regex (concat "%" (number-to-string match-index)))
9969 (replace-with (match-string match-index dlink)))
9970 (while (string-match regex cmd)
9971 (setq cmd (replace-match replace-with t t cmd))))
9972 (setq match-index (+ match-index 1)))))
9974 (save-window-excursion
9975 (start-process-shell-command cmd nil cmd)
9976 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9978 ((or (stringp cmd)
9979 (eq cmd 'emacs))
9980 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9981 (widen)
9982 (if line (org-goto-line line)
9983 (if search (org-link-search search))))
9984 ((consp cmd)
9985 (let ((file (convert-standard-filename file)))
9986 (save-match-data
9987 (set-match-data link-match-data)
9988 (eval cmd))))
9989 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9990 (and (org-mode-p) (eq old-mode 'org-mode)
9991 (or (not (equal old-buffer (current-buffer)))
9992 (not (equal old-pos (point))))
9993 (org-mark-ring-push old-pos old-buffer))))
9995 (defun org-file-apps-entry-match-against-dlink-p (entry)
9996 "This function returns non-nil if `entry' uses a regular
9997 expression which should be matched against the whole link by
9998 org-open-file.
10000 It assumes that is the case when the entry uses a regular
10001 expression which has at least one grouping construct and the
10002 action is either a lisp form or a command string containing
10003 '%1', i.e. using at least one subexpression match as a
10004 parameter."
10005 (let ((selector (car entry))
10006 (action (cdr entry)))
10007 (if (stringp selector)
10008 (and (> (regexp-opt-depth selector) 0)
10009 (or (and (stringp action)
10010 (string-match "%[0-9]" action))
10011 (consp action)))
10012 nil)))
10014 (defun org-default-apps ()
10015 "Return the default applications for this operating system."
10016 (cond
10017 ((eq system-type 'darwin)
10018 org-file-apps-defaults-macosx)
10019 ((eq system-type 'windows-nt)
10020 org-file-apps-defaults-windowsnt)
10021 (t org-file-apps-defaults-gnu)))
10023 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10024 "Convert extensions to regular expressions in the cars of LIST.
10025 Also, weed out any non-string entries, because the return value is used
10026 only for regexp matching.
10027 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10028 point to the symbol `emacs', indicating that the file should
10029 be opened in Emacs."
10030 (append
10031 (delq nil
10032 (mapcar (lambda (x)
10033 (if (not (stringp (car x)))
10035 (if (string-match "\\W" (car x))
10037 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10038 list))
10039 (if add-auto-mode
10040 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10042 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10043 (defun org-file-remote-p (file)
10044 "Test whether FILE specifies a location on a remote system.
10045 Return non-nil if the location is indeed remote.
10047 For example, the filename \"/user@host:/foo\" specifies a location
10048 on the system \"/user@host:\"."
10049 (cond ((fboundp 'file-remote-p)
10050 (file-remote-p file))
10051 ((fboundp 'tramp-handle-file-remote-p)
10052 (tramp-handle-file-remote-p file))
10053 ((and (boundp 'ange-ftp-name-format)
10054 (string-match (car ange-ftp-name-format) file))
10056 (t nil)))
10059 ;;;; Refiling
10061 (defun org-get-org-file ()
10062 "Read a filename, with default directory `org-directory'."
10063 (let ((default (or org-default-notes-file remember-data-file)))
10064 (read-file-name (format "File name [%s]: " default)
10065 (file-name-as-directory org-directory)
10066 default)))
10068 (defun org-notes-order-reversed-p ()
10069 "Check if the current file should receive notes in reversed order."
10070 (cond
10071 ((not org-reverse-note-order) nil)
10072 ((eq t org-reverse-note-order) t)
10073 ((not (listp org-reverse-note-order)) nil)
10074 (t (catch 'exit
10075 (let ((all org-reverse-note-order)
10076 entry)
10077 (while (setq entry (pop all))
10078 (if (string-match (car entry) buffer-file-name)
10079 (throw 'exit (cdr entry))))
10080 nil)))))
10082 (defvar org-refile-target-table nil
10083 "The list of refile targets, created by `org-refile'.")
10085 (defvar org-agenda-new-buffers nil
10086 "Buffers created to visit agenda files.")
10088 (defvar org-refile-cache nil
10089 "Cache for refile targets.")
10091 (defvar org-refile-markers nil
10092 "All the markers used for caching refile locations.")
10094 (defun org-refile-marker (pos)
10095 "Get a new refile marker, but only if caching is in use."
10096 (if (not org-refile-use-cache)
10098 (let ((m (make-marker)))
10099 (move-marker m pos)
10100 (push m org-refile-markers)
10101 m)))
10103 (defun org-refile-cache-clear ()
10104 "Clear the refile cache and disable all the markers."
10105 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10106 (setq org-refile-markers nil)
10107 (setq org-refile-cache nil)
10108 (message "Refile cache has been cleared"))
10110 (defun org-refile-cache-check-set (set)
10111 "Check if all the markers in the cache still have live buffers."
10112 (let (marker)
10113 (catch 'exit
10114 (while (and set (setq marker (nth 3 (pop set))))
10115 ;; if org-refile-use-outline-path is 'file, marker may be nil
10116 (when (and marker (null (marker-buffer marker)))
10117 (message "not found") (sit-for 3)
10118 (throw 'exit nil)))
10119 t)))
10121 (defun org-refile-cache-put (set &rest identifiers)
10122 "Push the refile targets SET into the cache, under IDENTIFIERS."
10123 (let* ((key (sha1 (prin1-to-string identifiers)))
10124 (entry (assoc key org-refile-cache)))
10125 (if entry
10126 (setcdr entry set)
10127 (push (cons key set) org-refile-cache))))
10129 (defun org-refile-cache-get (&rest identifiers)
10130 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10131 (cond
10132 ((not org-refile-cache) nil)
10133 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10135 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10136 org-refile-cache))))
10137 (and set (org-refile-cache-check-set set) set)))))
10139 (defun org-refile-get-targets (&optional default-buffer)
10140 "Produce a table with refile targets."
10141 (let ((case-fold-search nil)
10142 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10143 (entries (or org-refile-targets '((nil . (:level . 1)))))
10144 targets tgs txt re files f desc descre fast-path-p level pos0)
10145 (message "Getting targets...")
10146 (with-current-buffer (or default-buffer (current-buffer))
10147 (while (setq entry (pop entries))
10148 (setq files (car entry) desc (cdr entry))
10149 (setq fast-path-p nil)
10150 (cond
10151 ((null files) (setq files (list (current-buffer))))
10152 ((eq files 'org-agenda-files)
10153 (setq files (org-agenda-files 'unrestricted)))
10154 ((and (symbolp files) (fboundp files))
10155 (setq files (funcall files)))
10156 ((and (symbolp files) (boundp files))
10157 (setq files (symbol-value files))))
10158 (if (stringp files) (setq files (list files)))
10159 (cond
10160 ((eq (car desc) :tag)
10161 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10162 ((eq (car desc) :todo)
10163 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10164 ((eq (car desc) :regexp)
10165 (setq descre (cdr desc)))
10166 ((eq (car desc) :level)
10167 (setq descre (concat "^\\*\\{" (number-to-string
10168 (if org-odd-levels-only
10169 (1- (* 2 (cdr desc)))
10170 (cdr desc)))
10171 "\\}[ \t]")))
10172 ((eq (car desc) :maxlevel)
10173 (setq fast-path-p t)
10174 (setq descre (concat "^\\*\\{1," (number-to-string
10175 (if org-odd-levels-only
10176 (1- (* 2 (cdr desc)))
10177 (cdr desc)))
10178 "\\}[ \t]")))
10179 (t (error "Bad refiling target description %s" desc)))
10180 (while (setq f (pop files))
10181 (with-current-buffer
10182 (if (bufferp f) f (org-get-agenda-file-buffer f))
10184 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10185 (progn
10186 (if (bufferp f) (setq f (buffer-file-name
10187 (buffer-base-buffer f))))
10188 (setq f (and f (expand-file-name f)))
10189 (if (eq org-refile-use-outline-path 'file)
10190 (push (list (file-name-nondirectory f) f nil nil) tgs))
10191 (save-excursion
10192 (save-restriction
10193 (widen)
10194 (goto-char (point-min))
10195 (while (re-search-forward descre nil t)
10196 (goto-char (setq pos0 (point-at-bol)))
10197 (catch 'next
10198 (when org-refile-target-verify-function
10199 (save-match-data
10200 (or (funcall org-refile-target-verify-function)
10201 (throw 'next t))))
10202 (when (looking-at org-complex-heading-regexp)
10203 (setq level (org-reduced-level
10204 (- (match-end 1) (match-beginning 1)))
10205 txt (org-link-display-format (match-string 4))
10206 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10207 re (format org-complex-heading-regexp-format
10208 (regexp-quote (match-string 4))))
10209 (when org-refile-use-outline-path
10210 (setq txt (mapconcat
10211 'org-protect-slash
10212 (append
10213 (if (eq org-refile-use-outline-path
10214 'file)
10215 (list (file-name-nondirectory
10216 (buffer-file-name
10217 (buffer-base-buffer))))
10218 (if (eq org-refile-use-outline-path
10219 'full-file-path)
10220 (list (buffer-file-name
10221 (buffer-base-buffer)))))
10222 (org-get-outline-path fast-path-p
10223 level txt)
10224 (list txt))
10225 "/")))
10226 (push (list txt f re (org-refile-marker (point)))
10227 tgs)))
10228 (when (= (point) pos0)
10229 ;; verification function has not moved point
10230 (goto-char (point-at-eol))))))))
10231 (when org-refile-use-cache
10232 (org-refile-cache-put tgs (buffer-file-name) descre))
10233 (setq targets (append tgs targets))
10234 ))))
10235 (message "Getting targets...done")
10236 (nreverse targets)))
10238 (defun org-protect-slash (s)
10239 (while (string-match "/" s)
10240 (setq s (replace-match "\\" t t s)))
10243 (defvar org-olpa (make-vector 20 nil))
10245 (defun org-get-outline-path (&optional fastp level heading)
10246 "Return the outline path to the current entry, as a list.
10248 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10249 routine which makes outline path derivations for an entire file,
10250 avoiding backtracing. Refile target collection makes use of that."
10251 (if fastp
10252 (progn
10253 (if (> level 19)
10254 (error "Outline path failure, more than 19 levels"))
10255 (loop for i from level upto 19 do
10256 (aset org-olpa i nil))
10257 (prog1
10258 (delq nil (append org-olpa nil))
10259 (aset org-olpa level heading)))
10260 (let (rtn case-fold-search)
10261 (save-excursion
10262 (save-restriction
10263 (widen)
10264 (while (org-up-heading-safe)
10265 (when (looking-at org-complex-heading-regexp)
10266 (push (org-match-string-no-properties 4) rtn)))
10267 rtn)))))
10269 (defun org-format-outline-path (path &optional width prefix)
10270 "Format the outline path PATH for display.
10271 Width is the maximum number of characters that is available.
10272 Prefix is a prefix to be included in the returned string,
10273 such as the file name."
10274 (setq width (or width 79))
10275 (if prefix (setq width (- width (length prefix))))
10276 (if (not path)
10277 (or prefix "")
10278 (let* ((nsteps (length path))
10279 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10280 (maxwidth (if (<= total-width width)
10281 10000 ;; everything fits
10282 ;; we need to shorten the level headings
10283 (/ (- width nsteps) nsteps)))
10284 (org-odd-levels-only nil)
10285 (n 0)
10286 (total (1+ (length prefix))))
10287 (setq maxwidth (max maxwidth 10))
10288 (concat prefix
10289 (mapconcat
10290 (lambda (h)
10291 (setq n (1+ n))
10292 (if (and (= n nsteps) (< maxwidth 10000))
10293 (setq maxwidth (- total-width total)))
10294 (if (< (length h) maxwidth)
10295 (progn (setq total (+ total (length h) 1)) h)
10296 (setq h (substring h 0 (- maxwidth 2))
10297 total (+ total maxwidth 1))
10298 (if (string-match "[ \t]+\\'" h)
10299 (setq h (substring h 0 (match-beginning 0))))
10300 (setq h (concat h "..")))
10301 (org-add-props h nil 'face
10302 (nth (% (1- n) org-n-level-faces)
10303 org-level-faces))
10305 path "/")))))
10307 (defun org-display-outline-path (&optional file current)
10308 "Display the current outline path in the echo area."
10309 (interactive "P")
10310 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10311 (case-fold-search nil)
10312 (path (and (org-mode-p) (org-get-outline-path))))
10313 (if current (setq path (append path
10314 (save-excursion
10315 (org-back-to-heading t)
10316 (if (looking-at org-complex-heading-regexp)
10317 (list (match-string 4)))))))
10318 (message "%s"
10319 (org-format-outline-path
10320 path
10321 (1- (frame-width))
10322 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10324 (defvar org-refile-history nil
10325 "History for refiling operations.")
10327 (defvar org-after-refile-insert-hook nil
10328 "Hook run after `org-refile' has inserted its stuff at the new location.
10329 Note that this is still *before* the stuff will be removed from
10330 the *old* location.")
10332 (defvar org-capture-last-stored-marker)
10333 (defun org-refile (&optional goto default-buffer rfloc)
10334 "Move the entry at point to another heading.
10335 The list of target headings is compiled using the information in
10336 `org-refile-targets', which see. This list is created before each use
10337 and will therefore always be up-to-date.
10339 At the target location, the entry is filed as a subitem of the target heading.
10340 Depending on `org-reverse-note-order', the new subitem will either be the
10341 first or the last subitem.
10343 If there is an active region, all entries in that region will be moved.
10344 However, the region must fulfill the requirement that the first heading
10345 is the first one sets the top-level of the moved text - at most siblings
10346 below it are allowed.
10348 With prefix arg GOTO, the command will only visit the target location,
10349 not actually move anything.
10350 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10351 go to the location where the last refiling
10352 operation has put the subtree.
10353 With a prefix argument of `2', refile to the running clock.
10355 RFLOC can be a refile location obtained in a different way.
10357 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10359 If you are using target caching (see `org-refile-use-cache'),
10360 You have to clear the target cache in order to find new targets.
10361 This can be done with a 0 prefix: `C-0 C-c C-w'"
10362 (interactive "P")
10363 (if (member goto '(0 (64)))
10364 (org-refile-cache-clear)
10365 (let* ((cbuf (current-buffer))
10366 (regionp (org-region-active-p))
10367 (region-start (and regionp (region-beginning)))
10368 (region-end (and regionp (region-end)))
10369 (region-length (and regionp (- region-end region-start)))
10370 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10371 pos it nbuf file re level reversed)
10372 (setq last-command nil)
10373 (when regionp
10374 (goto-char region-start)
10375 (or (bolp) (goto-char (point-at-bol)))
10376 (setq region-start (point))
10377 (unless (org-kill-is-subtree-p
10378 (buffer-substring region-start region-end))
10379 (error "The region is not a (sequence of) subtree(s)")))
10380 (if (equal goto '(16))
10381 (org-refile-goto-last-stored)
10382 (when (or
10383 (and (equal goto 2)
10384 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10385 (prog1
10386 (setq it (list (or org-clock-heading "running clock")
10387 (buffer-file-name
10388 (marker-buffer org-clock-hd-marker))
10390 (marker-position org-clock-hd-marker)))
10391 (setq goto nil)))
10392 (setq it (or rfloc
10393 (save-excursion
10394 (org-refile-get-location
10395 (if goto "Goto" "Refile to") default-buffer
10396 org-refile-allow-creating-parent-nodes)))))
10397 (setq file (nth 1 it)
10398 re (nth 2 it)
10399 pos (nth 3 it))
10400 (if (and (not goto)
10402 (equal (buffer-file-name) file)
10403 (if regionp
10404 (and (>= pos region-start)
10405 (<= pos region-end))
10406 (and (>= pos (point))
10407 (< pos (save-excursion
10408 (org-end-of-subtree t t))))))
10409 (error "Cannot refile to position inside the tree or region"))
10411 (setq nbuf (or (find-buffer-visiting file)
10412 (find-file-noselect file)))
10413 (if goto
10414 (progn
10415 (switch-to-buffer nbuf)
10416 (goto-char pos)
10417 (org-show-context 'org-goto))
10418 (if regionp
10419 (progn
10420 (org-kill-new (buffer-substring region-start region-end))
10421 (org-save-markers-in-region region-start region-end))
10422 (org-copy-subtree 1 nil t))
10423 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10424 (find-file-noselect file)))
10425 (setq reversed (org-notes-order-reversed-p))
10426 (save-excursion
10427 (save-restriction
10428 (widen)
10429 (if pos
10430 (progn
10431 (goto-char pos)
10432 (looking-at outline-regexp)
10433 (setq level (org-get-valid-level (funcall outline-level) 1))
10434 (goto-char
10435 (if reversed
10436 (or (outline-next-heading) (point-max))
10437 (or (save-excursion (org-get-next-sibling))
10438 (org-end-of-subtree t t)
10439 (point-max)))))
10440 (setq level 1)
10441 (if (not reversed)
10442 (goto-char (point-max))
10443 (goto-char (point-min))
10444 (or (outline-next-heading) (goto-char (point-max)))))
10445 (if (not (bolp)) (newline))
10446 (org-paste-subtree level)
10447 (when org-log-refile
10448 (org-add-log-setup 'refile nil nil 'findpos
10449 org-log-refile)
10450 (unless (eq org-log-refile 'note)
10451 (save-excursion (org-add-log-note))))
10452 (and org-auto-align-tags (org-set-tags nil t))
10453 (bookmark-set "org-refile-last-stored")
10454 ;; If we are refiling for capture, make sure that the
10455 ;; last-capture pointers point here
10456 (when (org-bound-and-true-p org-refile-for-capture)
10457 (bookmark-set "org-capture-last-stored-marker")
10458 (move-marker org-capture-last-stored-marker (point)))
10459 (if (fboundp 'deactivate-mark) (deactivate-mark))
10460 (run-hooks 'org-after-refile-insert-hook))))
10461 (if regionp
10462 (delete-region (point) (+ (point) region-length))
10463 (org-cut-subtree))
10464 (when (featurep 'org-inlinetask)
10465 (org-inlinetask-remove-END-maybe))
10466 (setq org-markers-to-move nil)
10467 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10469 (defun org-refile-goto-last-stored ()
10470 "Go to the location where the last refile was stored."
10471 (interactive)
10472 (bookmark-jump "org-refile-last-stored")
10473 (message "This is the location of the last refile"))
10475 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
10476 "Prompt the user for a refile location, using PROMPT.
10477 PROMPT should not be suffixed with a colon and a space, because
10478 this function appends the default value from
10479 `org-refile-history' automatically, if that is not empty."
10480 (let ((org-refile-targets org-refile-targets)
10481 (org-refile-use-outline-path org-refile-use-outline-path))
10482 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
10483 (unless org-refile-target-table
10484 (error "No refile targets"))
10485 (let* ((prompt (concat prompt
10486 (and (car org-refile-history)
10487 (concat " (default " (car org-refile-history) ")"))
10488 ": "))
10489 (cbuf (current-buffer))
10490 (partial-completion-mode nil)
10491 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10492 (cfunc (if (and org-refile-use-outline-path
10493 org-outline-path-complete-in-steps)
10494 'org-olpath-completing-read
10495 'org-icompleting-read))
10496 (extra (if org-refile-use-outline-path "/" ""))
10497 (filename (and cfn (expand-file-name cfn)))
10498 (tbl (mapcar
10499 (lambda (x)
10500 (if (and (not (member org-refile-use-outline-path
10501 '(file full-file-path)))
10502 (not (equal filename (nth 1 x))))
10503 (cons (concat (car x) extra " ("
10504 (file-name-nondirectory (nth 1 x)) ")")
10505 (cdr x))
10506 (cons (concat (car x) extra) (cdr x))))
10507 org-refile-target-table))
10508 (completion-ignore-case t)
10509 pa answ parent-target child parent old-hist)
10510 (setq old-hist org-refile-history)
10511 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10512 nil 'org-refile-history (car org-refile-history)))
10513 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10514 (org-refile-check-position pa)
10515 (if pa
10516 (progn
10517 (when (or (not org-refile-history)
10518 (not (eq old-hist org-refile-history))
10519 (not (equal (car pa) (car org-refile-history))))
10520 (setq org-refile-history
10521 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10522 org-refile-history
10523 (cdr org-refile-history))))
10524 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10525 (pop org-refile-history)))
10527 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10528 (progn
10529 (setq parent (match-string 1 answ)
10530 child (match-string 2 answ))
10531 (setq parent-target (or (assoc parent tbl)
10532 (assoc (concat parent "/") tbl)))
10533 (when (and parent-target
10534 (or (eq new-nodes t)
10535 (and (eq new-nodes 'confirm)
10536 (y-or-n-p (format "Create new node \"%s\"? "
10537 child)))))
10538 (org-refile-new-child parent-target child)))
10539 (error "Invalid target location")))))
10541 (defun org-refile-check-position (refile-pointer)
10542 "Check if the refile pointer matches the readline to which it points."
10543 (let* ((file (nth 1 refile-pointer))
10544 (re (nth 2 refile-pointer))
10545 (pos (nth 3 refile-pointer))
10546 buffer)
10547 (when (org-string-nw-p re)
10548 (setq buffer (if (markerp pos)
10549 (marker-buffer pos)
10550 (or (find-buffer-visiting file)
10551 (find-file-noselect file))))
10552 (with-current-buffer buffer
10553 (save-excursion
10554 (save-restriction
10555 (widen)
10556 (goto-char pos)
10557 (beginning-of-line 1)
10558 (unless (org-looking-at-p re)
10559 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10561 (defun org-refile-new-child (parent-target child)
10562 "Use refile target PARENT-TARGET to add new CHILD below it."
10563 (unless parent-target
10564 (error "Cannot find parent for new node"))
10565 (let ((file (nth 1 parent-target))
10566 (pos (nth 3 parent-target))
10567 level)
10568 (with-current-buffer (or (find-buffer-visiting file)
10569 (find-file-noselect file))
10570 (save-excursion
10571 (save-restriction
10572 (widen)
10573 (if pos
10574 (goto-char pos)
10575 (goto-char (point-max))
10576 (if (not (bolp)) (newline)))
10577 (when (looking-at outline-regexp)
10578 (setq level (funcall outline-level))
10579 (org-end-of-subtree t t))
10580 (org-back-over-empty-lines)
10581 (insert "\n" (make-string
10582 (if pos (org-get-valid-level level 1) 1) ?*)
10583 " " child "\n")
10584 (beginning-of-line 0)
10585 (list (concat (car parent-target) "/" child) file "" (point)))))))
10587 (defun org-olpath-completing-read (prompt collection &rest args)
10588 "Read an outline path like a file name."
10589 (let ((thetable collection)
10590 (org-completion-use-ido nil) ; does not work with ido.
10591 (org-completion-use-iswitchb nil)) ; or iswitchb
10592 (apply
10593 'org-icompleting-read prompt
10594 (lambda (string predicate &optional flag)
10595 (let (rtn r f (l (length string)))
10596 (cond
10597 ((eq flag nil)
10598 ;; try completion
10599 (try-completion string thetable))
10600 ((eq flag t)
10601 ;; all-completions
10602 (setq rtn (all-completions string thetable predicate))
10603 (mapcar
10604 (lambda (x)
10605 (setq r (substring x l))
10606 (if (string-match " ([^)]*)$" x)
10607 (setq f (match-string 0 x))
10608 (setq f ""))
10609 (if (string-match "/" r)
10610 (concat string (substring r 0 (match-end 0)) f)
10612 rtn))
10613 ((eq flag 'lambda)
10614 ;; exact match?
10615 (assoc string thetable)))
10617 args)))
10619 ;;;; Dynamic blocks
10621 (defun org-find-dblock (name)
10622 "Find the first dynamic block with name NAME in the buffer.
10623 If not found, stay at current position and return nil."
10624 (let (pos)
10625 (save-excursion
10626 (goto-char (point-min))
10627 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10628 nil t)
10629 (match-beginning 0))))
10630 (if pos (goto-char pos))
10631 pos))
10633 (defconst org-dblock-start-re
10634 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10635 "Matches the start line of a dynamic block, with parameters.")
10637 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10638 "Matches the end of a dynamic block.")
10640 (defun org-create-dblock (plist)
10641 "Create a dynamic block section, with parameters taken from PLIST.
10642 PLIST must contain a :name entry which is used as name of the block."
10643 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10644 (end-of-line 1)
10645 (newline))
10646 (let ((col (current-column))
10647 (name (plist-get plist :name)))
10648 (insert "#+BEGIN: " name)
10649 (while plist
10650 (if (eq (car plist) :name)
10651 (setq plist (cddr plist))
10652 (insert " " (prin1-to-string (pop plist)))))
10653 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10654 (beginning-of-line -2)))
10656 (defun org-prepare-dblock ()
10657 "Prepare dynamic block for refresh.
10658 This empties the block, puts the cursor at the insert position and returns
10659 the property list including an extra property :name with the block name."
10660 (unless (looking-at org-dblock-start-re)
10661 (error "Not at a dynamic block"))
10662 (let* ((begdel (1+ (match-end 0)))
10663 (name (org-no-properties (match-string 1)))
10664 (params (append (list :name name)
10665 (read (concat "(" (match-string 3) ")")))))
10666 (save-excursion
10667 (beginning-of-line 1)
10668 (skip-chars-forward " \t")
10669 (setq params (plist-put params :indentation-column (current-column))))
10670 (unless (re-search-forward org-dblock-end-re nil t)
10671 (error "Dynamic block not terminated"))
10672 (setq params
10673 (append params
10674 (list :content (buffer-substring
10675 begdel (match-beginning 0)))))
10676 (delete-region begdel (match-beginning 0))
10677 (goto-char begdel)
10678 (open-line 1)
10679 params))
10681 (defun org-map-dblocks (&optional command)
10682 "Apply COMMAND to all dynamic blocks in the current buffer.
10683 If COMMAND is not given, use `org-update-dblock'."
10684 (let ((cmd (or command 'org-update-dblock)))
10685 (save-excursion
10686 (goto-char (point-min))
10687 (while (re-search-forward org-dblock-start-re nil t)
10688 (goto-char (match-beginning 0))
10689 (save-excursion
10690 (condition-case nil
10691 (funcall cmd)
10692 (error (message "Error during update of dynamic block"))))
10693 (unless (re-search-forward org-dblock-end-re nil t)
10694 (error "Dynamic block not terminated"))))))
10696 (defun org-dblock-update (&optional arg)
10697 "User command for updating dynamic blocks.
10698 Update the dynamic block at point. With prefix ARG, update all dynamic
10699 blocks in the buffer."
10700 (interactive "P")
10701 (if arg
10702 (org-update-all-dblocks)
10703 (or (looking-at org-dblock-start-re)
10704 (org-beginning-of-dblock))
10705 (org-update-dblock)))
10707 (defun org-update-dblock ()
10708 "Update the dynamic block at point.
10709 This means to empty the block, parse for parameters and then call
10710 the correct writing function."
10711 (interactive)
10712 (save-window-excursion
10713 (let* ((pos (point))
10714 (line (org-current-line))
10715 (params (org-prepare-dblock))
10716 (name (plist-get params :name))
10717 (indent (plist-get params :indentation-column))
10718 (cmd (intern (concat "org-dblock-write:" name))))
10719 (message "Updating dynamic block `%s' at line %d..." name line)
10720 (funcall cmd params)
10721 (message "Updating dynamic block `%s' at line %d...done" name line)
10722 (goto-char pos)
10723 (when (and indent (> indent 0))
10724 (setq indent (make-string indent ?\ ))
10725 (save-excursion
10726 (org-beginning-of-dblock)
10727 (forward-line 1)
10728 (while (not (looking-at org-dblock-end-re))
10729 (insert indent)
10730 (beginning-of-line 2))
10731 (when (looking-at org-dblock-end-re)
10732 (and (looking-at "[ \t]+")
10733 (replace-match ""))
10734 (insert indent)))))))
10736 (defun org-beginning-of-dblock ()
10737 "Find the beginning of the dynamic block at point.
10738 Error if there is no such block at point."
10739 (let ((pos (point))
10740 beg)
10741 (end-of-line 1)
10742 (if (and (re-search-backward org-dblock-start-re nil t)
10743 (setq beg (match-beginning 0))
10744 (re-search-forward org-dblock-end-re nil t)
10745 (> (match-end 0) pos))
10746 (goto-char beg)
10747 (goto-char pos)
10748 (error "Not in a dynamic block"))))
10750 (defun org-update-all-dblocks ()
10751 "Update all dynamic blocks in the buffer.
10752 This function can be used in a hook."
10753 (interactive)
10754 (when (org-mode-p)
10755 (org-map-dblocks 'org-update-dblock)))
10758 ;;;; Completion
10760 (defconst org-additional-option-like-keywords
10761 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
10762 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
10763 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
10764 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
10765 "BEGIN:" "END:"
10766 "ORGTBL" "TBLFM:" "TBLNAME:"
10767 "BEGIN_EXAMPLE" "END_EXAMPLE"
10768 "BEGIN_QUOTE" "END_QUOTE"
10769 "BEGIN_VERSE" "END_VERSE"
10770 "BEGIN_CENTER" "END_CENTER"
10771 "BEGIN_SRC" "END_SRC"
10772 "BEGIN_RESULT" "END_RESULT"
10773 "SOURCE:" "SRCNAME:" "FUNCTION:"
10774 "RESULTS:" "DATA:"
10775 "HEADER:" "HEADERS:"
10776 "BABEL:"
10777 "CATEGORY:" "COLUMNS:" "PROPERTY:"
10778 "CAPTION:" "LABEL:"
10779 "SETUPFILE:"
10780 "INCLUDE:"
10781 "BIND:"
10782 "MACRO:"))
10784 (defcustom org-structure-template-alist
10786 ("s" "#+begin_src ?\n\n#+end_src"
10787 "<src lang=\"?\">\n\n</src>")
10788 ("e" "#+begin_example\n?\n#+end_example"
10789 "<example>\n?\n</example>")
10790 ("q" "#+begin_quote\n?\n#+end_quote"
10791 "<quote>\n?\n</quote>")
10792 ("v" "#+begin_verse\n?\n#+end_verse"
10793 "<verse>\n?\n/verse>")
10794 ("c" "#+begin_center\n?\n#+end_center"
10795 "<center>\n?\n/center>")
10796 ("l" "#+begin_latex\n?\n#+end_latex"
10797 "<literal style=\"latex\">\n?\n</literal>")
10798 ("L" "#+latex: "
10799 "<literal style=\"latex\">?</literal>")
10800 ("h" "#+begin_html\n?\n#+end_html"
10801 "<literal style=\"html\">\n?\n</literal>")
10802 ("H" "#+html: "
10803 "<literal style=\"html\">?</literal>")
10804 ("a" "#+begin_ascii\n?\n#+end_ascii")
10805 ("A" "#+ascii: ")
10806 ("i" "#+index: ?"
10807 "#+index: ?")
10808 ("I" "#+include %file ?"
10809 "<include file=%file markup=\"?\">")
10811 "Structure completion elements.
10812 This is a list of abbreviation keys and values. The value gets inserted
10813 if you type `<' followed by the key and then press the completion key,
10814 usually `M-TAB'. %file will be replaced by a file name after prompting
10815 for the file using completion. The cursor will be placed at the position
10816 of the `?` in the template.
10817 There are two templates for each key, the first uses the original Org syntax,
10818 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
10819 the default when the /org-mtags.el/ module has been loaded. See also the
10820 variable `org-mtags-prefer-muse-templates'.
10821 This is an experimental feature, it is undecided if it is going to stay in."
10822 :group 'org-completion
10823 :type '(repeat
10824 (string :tag "Key")
10825 (string :tag "Template")
10826 (string :tag "Muse Template")))
10828 (defun org-try-structure-completion ()
10829 "Try to complete a structure template before point.
10830 This looks for strings like \"<e\" on an otherwise empty line and
10831 expands them."
10832 (let ((l (buffer-substring (point-at-bol) (point)))
10834 (when (and (looking-at "[ \t]*$")
10835 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
10836 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
10837 (org-complete-expand-structure-template (+ -1 (point-at-bol)
10838 (match-beginning 1)) a)
10839 t)))
10841 (defun org-complete-expand-structure-template (start cell)
10842 "Expand a structure template."
10843 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
10844 (rpl (nth (if musep 2 1) cell))
10845 (ind ""))
10846 (delete-region start (point))
10847 (when (string-match "\\`#\\+" rpl)
10848 (cond
10849 ((bolp))
10850 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
10851 (setq ind (buffer-substring (point-at-bol) (point))))
10852 (t (newline))))
10853 (setq start (point))
10854 (if (string-match "%file" rpl)
10855 (setq rpl (replace-match
10856 (concat
10857 "\""
10858 (save-match-data
10859 (abbreviate-file-name (read-file-name "Include file: ")))
10860 "\"")
10861 t t rpl)))
10862 (setq rpl (mapconcat 'identity (split-string rpl "\n")
10863 (concat "\n" ind)))
10864 (insert rpl)
10865 (if (re-search-backward "\\?" start t) (delete-char 1))))
10867 ;;;; TODO, DEADLINE, Comments
10869 (defun org-toggle-comment ()
10870 "Change the COMMENT state of an entry."
10871 (interactive)
10872 (save-excursion
10873 (org-back-to-heading)
10874 (let (case-fold-search)
10875 (if (looking-at (concat outline-regexp
10876 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10877 (replace-match "" t t nil 1)
10878 (if (looking-at outline-regexp)
10879 (progn
10880 (goto-char (match-end 0))
10881 (insert org-comment-string " ")))))))
10883 (defvar org-last-todo-state-is-todo nil
10884 "This is non-nil when the last TODO state change led to a TODO state.
10885 If the last change removed the TODO tag or switched to DONE, then
10886 this is nil.")
10888 (defvar org-setting-tags nil) ; dynamically skipped
10890 (defvar org-todo-setup-filter-hook nil
10891 "Hook for functions that pre-filter todo specs.
10892 Each function takes a todo spec and returns either nil or the spec
10893 transformed into canonical form." )
10895 (defvar org-todo-get-default-hook nil
10896 "Hook for functions that get a default item for todo.
10897 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
10898 nil or a string to be used for the todo mark." )
10900 (defvar org-agenda-headline-snapshot-before-repeat)
10902 (defun org-todo (&optional arg)
10903 "Change the TODO state of an item.
10904 The state of an item is given by a keyword at the start of the heading,
10905 like
10906 *** TODO Write paper
10907 *** DONE Call mom
10909 The different keywords are specified in the variable `org-todo-keywords'.
10910 By default the available states are \"TODO\" and \"DONE\".
10911 So for this example: when the item starts with TODO, it is changed to DONE.
10912 When it starts with DONE, the DONE is removed. And when neither TODO nor
10913 DONE are present, add TODO at the beginning of the heading.
10915 With \\[universal-argument] prefix arg, use completion to determine the new \
10916 state.
10917 With numeric prefix arg, switch to that state.
10918 With a double \\[universal-argument] prefix, switch to the next set of TODO \
10919 keywords (nextset).
10920 With a triple \\[universal-argument] prefix, circumvent any state blocking.
10922 For calling through lisp, arg is also interpreted in the following way:
10923 'none -> empty state
10924 \"\"(empty string) -> switch to empty state
10925 'done -> switch to DONE
10926 'nextset -> switch to the next set of keywords
10927 'previousset -> switch to the previous set of keywords
10928 \"WAITING\" -> switch to the specified keyword, but only if it
10929 really is a member of `org-todo-keywords'."
10930 (interactive "P")
10931 (if (equal arg '(16)) (setq arg 'nextset))
10932 (let ((org-blocker-hook org-blocker-hook)
10933 (case-fold-search nil))
10934 (when (equal arg '(64))
10935 (setq arg nil org-blocker-hook nil))
10936 (when (and org-blocker-hook
10937 (or org-inhibit-blocking
10938 (org-entry-get nil "NOBLOCKING")))
10939 (setq org-blocker-hook nil))
10940 (save-excursion
10941 (catch 'exit
10942 (org-back-to-heading t)
10943 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
10944 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
10945 (looking-at " *"))
10946 (let* ((match-data (match-data))
10947 (startpos (point-at-bol))
10948 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
10949 (org-log-done org-log-done)
10950 (org-log-repeat org-log-repeat)
10951 (org-todo-log-states org-todo-log-states)
10952 (this (match-string 1))
10953 (hl-pos (match-beginning 0))
10954 (head (org-get-todo-sequence-head this))
10955 (ass (assoc head org-todo-kwd-alist))
10956 (interpret (nth 1 ass))
10957 (done-word (nth 3 ass))
10958 (final-done-word (nth 4 ass))
10959 (last-state (or this ""))
10960 (completion-ignore-case t)
10961 (member (member this org-todo-keywords-1))
10962 (tail (cdr member))
10963 (state (cond
10964 ((and org-todo-key-trigger
10965 (or (and (equal arg '(4))
10966 (eq org-use-fast-todo-selection 'prefix))
10967 (and (not arg) org-use-fast-todo-selection
10968 (not (eq org-use-fast-todo-selection
10969 'prefix)))))
10970 ;; Use fast selection
10971 (org-fast-todo-selection))
10972 ((and (equal arg '(4))
10973 (or (not org-use-fast-todo-selection)
10974 (not org-todo-key-trigger)))
10975 ;; Read a state with completion
10976 (org-icompleting-read
10977 "State: " (mapcar (lambda(x) (list x))
10978 org-todo-keywords-1)
10979 nil t))
10980 ((eq arg 'right)
10981 (if this
10982 (if tail (car tail) nil)
10983 (car org-todo-keywords-1)))
10984 ((eq arg 'left)
10985 (if (equal member org-todo-keywords-1)
10987 (if this
10988 (nth (- (length org-todo-keywords-1)
10989 (length tail) 2)
10990 org-todo-keywords-1)
10991 (org-last org-todo-keywords-1))))
10992 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10993 (setq arg nil))) ; hack to fall back to cycling
10994 (arg
10995 ;; user or caller requests a specific state
10996 (cond
10997 ((equal arg "") nil)
10998 ((eq arg 'none) nil)
10999 ((eq arg 'done) (or done-word (car org-done-keywords)))
11000 ((eq arg 'nextset)
11001 (or (car (cdr (member head org-todo-heads)))
11002 (car org-todo-heads)))
11003 ((eq arg 'previousset)
11004 (let ((org-todo-heads (reverse org-todo-heads)))
11005 (or (car (cdr (member head org-todo-heads)))
11006 (car org-todo-heads))))
11007 ((car (member arg org-todo-keywords-1)))
11008 ((stringp arg)
11009 (error "State `%s' not valid in this file" arg))
11010 ((nth (1- (prefix-numeric-value arg))
11011 org-todo-keywords-1))))
11012 ((null member) (or head (car org-todo-keywords-1)))
11013 ((equal this final-done-word) nil) ;; -> make empty
11014 ((null tail) nil) ;; -> first entry
11015 ((memq interpret '(type priority))
11016 (if (eq this-command last-command)
11017 (car tail)
11018 (if (> (length tail) 0)
11019 (or done-word (car org-done-keywords))
11020 nil)))
11022 (car tail))))
11023 (state (or
11024 (run-hook-with-args-until-success
11025 'org-todo-get-default-hook state last-state)
11026 state))
11027 (next (if state (concat " " state " ") " "))
11028 (change-plist (list :type 'todo-state-change :from this :to state
11029 :position startpos))
11030 dolog now-done-p)
11031 (when org-blocker-hook
11032 (setq org-last-todo-state-is-todo
11033 (not (member this org-done-keywords)))
11034 (unless (save-excursion
11035 (save-match-data
11036 (org-with-wide-buffer
11037 (run-hook-with-args-until-failure
11038 'org-blocker-hook change-plist))))
11039 (if (org-called-interactively-p 'interactive)
11040 (error "TODO state change from %s to %s blocked" this state)
11041 ;; fail silently
11042 (message "TODO state change from %s to %s blocked" this state)
11043 (throw 'exit nil))))
11044 (store-match-data match-data)
11045 (replace-match next t t)
11046 (unless (pos-visible-in-window-p hl-pos)
11047 (message "TODO state changed to %s" (org-trim next)))
11048 (unless head
11049 (setq head (org-get-todo-sequence-head state)
11050 ass (assoc head org-todo-kwd-alist)
11051 interpret (nth 1 ass)
11052 done-word (nth 3 ass)
11053 final-done-word (nth 4 ass)))
11054 (when (memq arg '(nextset previousset))
11055 (message "Keyword-Set %d/%d: %s"
11056 (- (length org-todo-sets) -1
11057 (length (memq (assoc state org-todo-sets) org-todo-sets)))
11058 (length org-todo-sets)
11059 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11060 (setq org-last-todo-state-is-todo
11061 (not (member state org-done-keywords)))
11062 (setq now-done-p (and (member state org-done-keywords)
11063 (not (member this org-done-keywords))))
11064 (and logging (org-local-logging logging))
11065 (when (and (or org-todo-log-states org-log-done)
11066 (not (eq org-inhibit-logging t))
11067 (not (memq arg '(nextset previousset))))
11068 ;; we need to look at recording a time and note
11069 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
11070 (nth 2 (assoc this org-todo-log-states))))
11071 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11072 (setq dolog 'time))
11073 (when (and state
11074 (member state org-not-done-keywords)
11075 (not (member this org-not-done-keywords)))
11076 ;; This is now a todo state and was not one before
11077 ;; If there was a CLOSED time stamp, get rid of it.
11078 (org-add-planning-info nil nil 'closed))
11079 (when (and now-done-p org-log-done)
11080 ;; It is now done, and it was not done before
11081 (org-add-planning-info 'closed (org-current-time))
11082 (if (and (not dolog) (eq 'note org-log-done))
11083 (org-add-log-setup 'done state this 'findpos 'note)))
11084 (when (and state dolog)
11085 ;; This is a non-nil state, and we need to log it
11086 (org-add-log-setup 'state state this 'findpos dolog)))
11087 ;; Fixup tag positioning
11088 (org-todo-trigger-tag-changes state)
11089 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11090 (when org-provide-todo-statistics
11091 (org-update-parent-todo-statistics))
11092 (run-hooks 'org-after-todo-state-change-hook)
11093 (if (and arg (not (member state org-done-keywords)))
11094 (setq head (org-get-todo-sequence-head state)))
11095 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11096 ;; Do we need to trigger a repeat?
11097 (when now-done-p
11098 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11099 ;; This is for the agenda, take a snapshot of the headline.
11100 (save-match-data
11101 (setq org-agenda-headline-snapshot-before-repeat
11102 (org-get-heading))))
11103 (org-auto-repeat-maybe state))
11104 ;; Fixup cursor location if close to the keyword
11105 (if (and (outline-on-heading-p)
11106 (not (bolp))
11107 (save-excursion (beginning-of-line 1)
11108 (looking-at org-todo-line-regexp))
11109 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11110 (progn
11111 (goto-char (or (match-end 2) (match-end 1)))
11112 (and (looking-at " ") (just-one-space))))
11113 (when org-trigger-hook
11114 (save-excursion
11115 (run-hook-with-args 'org-trigger-hook change-plist))))))))
11117 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11118 "Block turning an entry into a TODO, using the hierarchy.
11119 This checks whether the current task should be blocked from state
11120 changes. Such blocking occurs when:
11122 1. The task has children which are not all in a completed state.
11124 2. A task has a parent with the property :ORDERED:, and there
11125 are siblings prior to the current task with incomplete
11126 status.
11128 3. The parent of the task is blocked because it has siblings that should
11129 be done first, or is child of a block grandparent TODO entry."
11131 (if (not org-enforce-todo-dependencies)
11132 t ; if locally turned off don't block
11133 (catch 'dont-block
11134 ;; If this is not a todo state change, or if this entry is already DONE,
11135 ;; do not block
11136 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11137 (member (plist-get change-plist :from)
11138 (cons 'done org-done-keywords))
11139 (member (plist-get change-plist :to)
11140 (cons 'todo org-not-done-keywords))
11141 (not (plist-get change-plist :to)))
11142 (throw 'dont-block t))
11143 ;; If this task has children, and any are undone, it's blocked
11144 (save-excursion
11145 (org-back-to-heading t)
11146 (let ((this-level (funcall outline-level)))
11147 (outline-next-heading)
11148 (let ((child-level (funcall outline-level)))
11149 (while (and (not (eobp))
11150 (> child-level this-level))
11151 ;; this todo has children, check whether they are all
11152 ;; completed
11153 (if (and (not (org-entry-is-done-p))
11154 (org-entry-is-todo-p))
11155 (throw 'dont-block nil))
11156 (outline-next-heading)
11157 (setq child-level (funcall outline-level))))))
11158 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11159 ;; any previous siblings are undone, it's blocked
11160 (save-excursion
11161 (org-back-to-heading t)
11162 (let* ((pos (point))
11163 (parent-pos (and (org-up-heading-safe) (point))))
11164 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11165 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11166 (forward-line 1)
11167 (re-search-forward org-not-done-heading-regexp pos t))
11168 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11169 ;; Search further up the hierarchy, to see if an anchestor is blocked
11170 (while t
11171 (goto-char parent-pos)
11172 (if (not (looking-at org-not-done-heading-regexp))
11173 (throw 'dont-block t)) ; do not block, parent is not a TODO
11174 (setq pos (point))
11175 (setq parent-pos (and (org-up-heading-safe) (point)))
11176 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11177 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11178 (forward-line 1)
11179 (re-search-forward org-not-done-heading-regexp pos t))
11180 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11182 (defcustom org-track-ordered-property-with-tag nil
11183 "Should the ORDERED property also be shown as a tag?
11184 The ORDERED property decides if an entry should require subtasks to be
11185 completed in sequence. Since a property is not very visible, setting
11186 this option means that toggling the ORDERED property with the command
11187 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11188 not relevant for the behavior, but it makes things more visible.
11190 Note that toggling the tag with tags commands will not change the property
11191 and therefore not influence behavior!
11193 This can be t, meaning the tag ORDERED should be used, It can also be a
11194 string to select a different tag for this task."
11195 :group 'org-todo
11196 :type '(choice
11197 (const :tag "No tracking" nil)
11198 (const :tag "Track with ORDERED tag" t)
11199 (string :tag "Use other tag")))
11201 (defun org-toggle-ordered-property ()
11202 "Toggle the ORDERED property of the current entry.
11203 For better visibility, you can track the value of this property with a tag.
11204 See variable `org-track-ordered-property-with-tag'."
11205 (interactive)
11206 (let* ((t1 org-track-ordered-property-with-tag)
11207 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11208 (save-excursion
11209 (org-back-to-heading)
11210 (if (org-entry-get nil "ORDERED")
11211 (progn
11212 (org-delete-property "ORDERED")
11213 (and tag (org-toggle-tag tag 'off))
11214 (message "Subtasks can be completed in arbitrary order"))
11215 (org-entry-put nil "ORDERED" "t")
11216 (and tag (org-toggle-tag tag 'on))
11217 (message "Subtasks must be completed in sequence")))))
11219 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11220 (defun org-block-todo-from-checkboxes (change-plist)
11221 "Block turning an entry into a TODO, using checkboxes.
11222 This checks whether the current task should be blocked from state
11223 changes because there are unchecked boxes in this entry."
11224 (if (not org-enforce-todo-checkbox-dependencies)
11225 t ; if locally turned off don't block
11226 (catch 'dont-block
11227 ;; If this is not a todo state change, or if this entry is already DONE,
11228 ;; do not block
11229 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11230 (member (plist-get change-plist :from)
11231 (cons 'done org-done-keywords))
11232 (member (plist-get change-plist :to)
11233 (cons 'todo org-not-done-keywords))
11234 (not (plist-get change-plist :to)))
11235 (throw 'dont-block t))
11236 ;; If this task has checkboxes that are not checked, it's blocked
11237 (save-excursion
11238 (org-back-to-heading t)
11239 (let ((beg (point)) end)
11240 (outline-next-heading)
11241 (setq end (point))
11242 (goto-char beg)
11243 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
11244 end t)
11245 (progn
11246 (if (boundp 'org-blocked-by-checkboxes)
11247 (setq org-blocked-by-checkboxes t))
11248 (throw 'dont-block nil)))))
11249 t))) ; do not block
11251 (defun org-entry-blocked-p ()
11252 "Is the current entry blocked?"
11253 (if (org-entry-get nil "NOBLOCKING")
11254 nil ;; Never block this entry
11255 (not
11256 (run-hook-with-args-until-failure
11257 'org-blocker-hook
11258 (list :type 'todo-state-change
11259 :position (point)
11260 :from 'todo
11261 :to 'done)))))
11263 (defun org-update-statistics-cookies (all)
11264 "Update the statistics cookie, either from TODO or from checkboxes.
11265 This should be called with the cursor in a line with a statistics cookie."
11266 (interactive "P")
11267 (if all
11268 (progn
11269 (org-update-checkbox-count 'all)
11270 (org-map-entries 'org-update-parent-todo-statistics))
11271 (if (not (org-on-heading-p))
11272 (org-update-checkbox-count)
11273 (let ((pos (move-marker (make-marker) (point)))
11274 end l1 l2)
11275 (ignore-errors (org-back-to-heading t))
11276 (if (not (org-on-heading-p))
11277 (org-update-checkbox-count)
11278 (setq l1 (org-outline-level))
11279 (setq end (save-excursion
11280 (outline-next-heading)
11281 (if (org-on-heading-p) (setq l2 (org-outline-level)))
11282 (point)))
11283 (if (and (save-excursion
11284 (re-search-forward
11285 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11286 (not (save-excursion (re-search-forward
11287 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11288 (org-update-checkbox-count)
11289 (if (and l2 (> l2 l1))
11290 (progn
11291 (goto-char end)
11292 (org-update-parent-todo-statistics))
11293 (goto-char pos)
11294 (beginning-of-line 1)
11295 (while (re-search-forward
11296 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11297 (point-at-eol) t)
11298 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11299 (goto-char pos)
11300 (move-marker pos nil)))))
11302 (defvar org-entry-property-inherited-from) ;; defined below
11303 (defun org-update-parent-todo-statistics ()
11304 "Update any statistics cookie in the parent of the current headline.
11305 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11306 the entire subtree and this will travel up the hierarchy and update
11307 statistics everywhere."
11308 (interactive)
11309 (let* ((lim 0) prop
11310 (recursive (or (not org-hierarchical-todo-statistics)
11311 (string-match
11312 "\\<recursive\\>"
11313 (or (setq prop (org-entry-get
11314 nil "COOKIE_DATA" 'inherit)) ""))))
11315 (lim (or (and prop (marker-position
11316 org-entry-property-inherited-from))
11317 lim))
11318 (first t)
11319 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11320 level ltoggle l1 new ndel
11321 (cnt-all 0) (cnt-done 0) is-percent kwd
11322 checkbox-beg ov ovs ove cookie-present)
11323 (catch 'exit
11324 (save-excursion
11325 (beginning-of-line 1)
11326 (if (org-at-heading-p)
11327 (setq ltoggle (funcall outline-level))
11328 (error "This should not happen"))
11329 (while (and (setq level (org-up-heading-safe))
11330 (or recursive first)
11331 (>= (point) lim))
11332 (setq first nil cookie-present nil)
11333 (unless (and level
11334 (not (string-match
11335 "\\<checkbox\\>"
11336 (downcase
11337 (or (org-entry-get
11338 nil "COOKIE_DATA")
11339 "")))))
11340 (throw 'exit nil))
11341 (while (re-search-forward box-re (point-at-eol) t)
11342 (setq cnt-all 0 cnt-done 0 cookie-present t)
11343 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11344 (save-match-data
11345 (unless (outline-next-heading) (throw 'exit nil))
11346 (while (and (looking-at org-complex-heading-regexp)
11347 (> (setq l1 (length (match-string 1))) level))
11348 (setq kwd (and (or recursive (= l1 ltoggle))
11349 (match-string 2)))
11350 (if (or (eq org-provide-todo-statistics 'all-headlines)
11351 (and (listp org-provide-todo-statistics)
11352 (or (member kwd org-provide-todo-statistics)
11353 (member kwd org-done-keywords))))
11354 (setq cnt-all (1+ cnt-all))
11355 (if (eq org-provide-todo-statistics t)
11356 (and kwd (setq cnt-all (1+ cnt-all)))))
11357 (and (member kwd org-done-keywords)
11358 (setq cnt-done (1+ cnt-done)))
11359 (outline-next-heading)))
11360 (setq new
11361 (if is-percent
11362 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11363 (format "[%d/%d]" cnt-done cnt-all))
11364 ndel (- (match-end 0) checkbox-beg))
11365 ;; handle overlays when updating cookie from column view
11366 (when (setq ov (car (overlays-at checkbox-beg)))
11367 (setq ovs (overlay-start ov) ove (overlay-end ov))
11368 (delete-overlay ov))
11369 (goto-char checkbox-beg)
11370 (insert new)
11371 (delete-region (point) (+ (point) ndel))
11372 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11373 (when ov (move-overlay ov ovs ove)))
11374 (when cookie-present
11375 (run-hook-with-args 'org-after-todo-statistics-hook
11376 cnt-done (- cnt-all cnt-done))))))
11377 (run-hooks 'org-todo-statistics-hook)))
11379 (defvar org-after-todo-statistics-hook nil
11380 "Hook that is called after a TODO statistics cookie has been updated.
11381 Each function is called with two arguments: the number of not-done entries
11382 and the number of done entries.
11384 For example, the following function, when added to this hook, will switch
11385 an entry to DONE when all children are done, and back to TODO when new
11386 entries are set to a TODO status. Note that this hook is only called
11387 when there is a statistics cookie in the headline!
11389 (defun org-summary-todo (n-done n-not-done)
11390 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11391 (let (org-log-done org-log-states) ; turn off logging
11392 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11395 (defvar org-todo-statistics-hook nil
11396 "Hook that is run whenever Org thinks TODO statistics should be updated.
11397 This hook runs even if there is no statistics cookie present, in which case
11398 `org-after-todo-statistics-hook' would not run.")
11400 (defun org-todo-trigger-tag-changes (state)
11401 "Apply the changes defined in `org-todo-state-tags-triggers'."
11402 (let ((l org-todo-state-tags-triggers)
11403 changes)
11404 (when (or (not state) (equal state ""))
11405 (setq changes (append changes (cdr (assoc "" l)))))
11406 (when (and (stringp state) (> (length state) 0))
11407 (setq changes (append changes (cdr (assoc state l)))))
11408 (when (member state org-not-done-keywords)
11409 (setq changes (append changes (cdr (assoc 'todo l)))))
11410 (when (member state org-done-keywords)
11411 (setq changes (append changes (cdr (assoc 'done l)))))
11412 (dolist (c changes)
11413 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11415 (defun org-local-logging (value)
11416 "Get logging settings from a property VALUE."
11417 (let* (words w a)
11418 ;; directly set the variables, they are already local.
11419 (setq org-log-done nil
11420 org-log-repeat nil
11421 org-todo-log-states nil)
11422 (setq words (org-split-string value))
11423 (while (setq w (pop words))
11424 (cond
11425 ((setq a (assoc w org-startup-options))
11426 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11427 (set (nth 1 a) (nth 2 a))))
11428 ((setq a (org-extract-log-state-settings w))
11429 (and (member (car a) org-todo-keywords-1)
11430 (push a org-todo-log-states)))))))
11432 (defun org-get-todo-sequence-head (kwd)
11433 "Return the head of the TODO sequence to which KWD belongs.
11434 If KWD is not set, check if there is a text property remembering the
11435 right sequence."
11436 (let (p)
11437 (cond
11438 ((not kwd)
11439 (or (get-text-property (point-at-bol) 'org-todo-head)
11440 (progn
11441 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11442 nil (point-at-eol)))
11443 (get-text-property p 'org-todo-head))))
11444 ((not (member kwd org-todo-keywords-1))
11445 (car org-todo-keywords-1))
11446 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11448 (defun org-fast-todo-selection ()
11449 "Fast TODO keyword selection with single keys.
11450 Returns the new TODO keyword, or nil if no state change should occur."
11451 (let* ((fulltable org-todo-key-alist)
11452 (done-keywords org-done-keywords) ;; needed for the faces.
11453 (maxlen (apply 'max (mapcar
11454 (lambda (x)
11455 (if (stringp (car x)) (string-width (car x)) 0))
11456 fulltable)))
11457 (expert nil)
11458 (fwidth (+ maxlen 3 1 3))
11459 (ncol (/ (- (window-width) 4) fwidth))
11460 tg cnt e c tbl
11461 groups ingroup)
11462 (save-excursion
11463 (save-window-excursion
11464 (if expert
11465 (set-buffer (get-buffer-create " *Org todo*"))
11466 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11467 (erase-buffer)
11468 (org-set-local 'org-done-keywords done-keywords)
11469 (setq tbl fulltable cnt 0)
11470 (while (setq e (pop tbl))
11471 (cond
11472 ((equal e '(:startgroup))
11473 (push '() groups) (setq ingroup t)
11474 (when (not (= cnt 0))
11475 (setq cnt 0)
11476 (insert "\n"))
11477 (insert "{ "))
11478 ((equal e '(:endgroup))
11479 (setq ingroup nil cnt 0)
11480 (insert "}\n"))
11481 ((equal e '(:newline))
11482 (when (not (= cnt 0))
11483 (setq cnt 0)
11484 (insert "\n")
11485 (setq e (car tbl))
11486 (while (equal (car tbl) '(:newline))
11487 (insert "\n")
11488 (setq tbl (cdr tbl)))))
11490 (setq tg (car e) c (cdr e))
11491 (if ingroup (push tg (car groups)))
11492 (setq tg (org-add-props tg nil 'face
11493 (org-get-todo-face tg)))
11494 (if (and (= cnt 0) (not ingroup)) (insert " "))
11495 (insert "[" c "] " tg (make-string
11496 (- fwidth 4 (length tg)) ?\ ))
11497 (when (= (setq cnt (1+ cnt)) ncol)
11498 (insert "\n")
11499 (if ingroup (insert " "))
11500 (setq cnt 0)))))
11501 (insert "\n")
11502 (goto-char (point-min))
11503 (if (not expert) (org-fit-window-to-buffer))
11504 (message "[a-z..]:Set [SPC]:clear")
11505 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11506 (cond
11507 ((or (= c ?\C-g)
11508 (and (= c ?q) (not (rassoc c fulltable))))
11509 (setq quit-flag t))
11510 ((= c ?\ ) nil)
11511 ((setq e (rassoc c fulltable) tg (car e))
11513 (t (setq quit-flag t)))))))
11515 (defun org-entry-is-todo-p ()
11516 (member (org-get-todo-state) org-not-done-keywords))
11518 (defun org-entry-is-done-p ()
11519 (member (org-get-todo-state) org-done-keywords))
11521 (defun org-get-todo-state ()
11522 (save-excursion
11523 (org-back-to-heading t)
11524 (and (looking-at org-todo-line-regexp)
11525 (match-end 2)
11526 (match-string 2))))
11528 (defun org-at-date-range-p (&optional inactive-ok)
11529 "Is the cursor inside a date range?"
11530 (interactive)
11531 (save-excursion
11532 (catch 'exit
11533 (let ((pos (point)))
11534 (skip-chars-backward "^[<\r\n")
11535 (skip-chars-backward "<[")
11536 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11537 (>= (match-end 0) pos)
11538 (throw 'exit t))
11539 (skip-chars-backward "^<[\r\n")
11540 (skip-chars-backward "<[")
11541 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11542 (>= (match-end 0) pos)
11543 (throw 'exit t)))
11544 nil)))
11546 (defun org-get-repeat (&optional tagline)
11547 "Check if there is a deadline/schedule with repeater in this entry."
11548 (save-match-data
11549 (save-excursion
11550 (org-back-to-heading t)
11551 (and (re-search-forward (if tagline
11552 (concat tagline "\\s-*" org-repeat-re)
11553 org-repeat-re)
11554 (org-entry-end-position) t)
11555 (match-string-no-properties 1)))))
11557 (defvar org-last-changed-timestamp)
11558 (defvar org-last-inserted-timestamp)
11559 (defvar org-log-post-message)
11560 (defvar org-log-note-purpose)
11561 (defvar org-log-note-how)
11562 (defvar org-log-note-extra)
11563 (defun org-auto-repeat-maybe (done-word)
11564 "Check if the current headline contains a repeated deadline/schedule.
11565 If yes, set TODO state back to what it was and change the base date
11566 of repeating deadline/scheduled time stamps to new date.
11567 This function is run automatically after each state change to a DONE state."
11568 ;; last-state is dynamically scoped into this function
11569 (let* ((repeat (org-get-repeat))
11570 (aa (assoc last-state org-todo-kwd-alist))
11571 (interpret (nth 1 aa))
11572 (head (nth 2 aa))
11573 (whata '(("d" . day) ("m" . month) ("y" . year)))
11574 (msg "Entry repeats: ")
11575 (org-log-done nil)
11576 (org-todo-log-states nil)
11577 re type n what ts time to-state)
11578 (when repeat
11579 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11580 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11581 org-todo-repeat-to-state))
11582 (unless (and to-state (member to-state org-todo-keywords-1))
11583 (setq to-state (if (eq interpret 'type) last-state head)))
11584 (org-todo to-state)
11585 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11586 (org-entry-put nil "LAST_REPEAT" (format-time-string
11587 (org-time-stamp-format t t))))
11588 (when org-log-repeat
11589 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11590 (memq 'org-add-log-note post-command-hook))
11591 ;; OK, we are already setup for some record
11592 (if (eq org-log-repeat 'note)
11593 ;; make sure we take a note, not only a time stamp
11594 (setq org-log-note-how 'note))
11595 ;; Set up for taking a record
11596 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11597 last-state
11598 'findpos org-log-repeat)))
11599 (org-back-to-heading t)
11600 (org-add-planning-info nil nil 'closed)
11601 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11602 org-deadline-time-regexp "\\)\\|\\("
11603 org-ts-regexp "\\)"))
11604 (while (re-search-forward
11605 re (save-excursion (outline-next-heading) (point)) t)
11606 (setq type (if (match-end 1) org-scheduled-string
11607 (if (match-end 3) org-deadline-string "Plain:"))
11608 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11609 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11610 (setq n (string-to-number (match-string 2 ts))
11611 what (match-string 3 ts))
11612 (if (equal what "w") (setq n (* n 7) what "d"))
11613 ;; Preparation, see if we need to modify the start date for the change
11614 (when (match-end 1)
11615 (setq time (save-match-data (org-time-string-to-time ts)))
11616 (cond
11617 ((equal (match-string 1 ts) ".")
11618 ;; Shift starting date to today
11619 (org-timestamp-change
11620 (- (time-to-days (current-time)) (time-to-days time))
11621 'day))
11622 ((equal (match-string 1 ts) "+")
11623 (let ((nshiftmax 10) (nshift 0))
11624 (while (or (= nshift 0)
11625 (<= (time-to-days time)
11626 (time-to-days (current-time))))
11627 (when (= (incf nshift) nshiftmax)
11628 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11629 (error "Abort")))
11630 (org-timestamp-change n (cdr (assoc what whata)))
11631 (org-at-timestamp-p t)
11632 (setq ts (match-string 1))
11633 (setq time (save-match-data (org-time-string-to-time ts)))))
11634 (org-timestamp-change (- n) (cdr (assoc what whata)))
11635 ;; rematch, so that we have everything in place for the real shift
11636 (org-at-timestamp-p t)
11637 (setq ts (match-string 1))
11638 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11639 (org-timestamp-change n (cdr (assoc what whata)))
11640 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11641 (setq org-log-post-message msg)
11642 (message "%s" msg))))
11644 (defun org-show-todo-tree (arg)
11645 "Make a compact tree which shows all headlines marked with TODO.
11646 The tree will show the lines where the regexp matches, and all higher
11647 headlines above the match.
11648 With a \\[universal-argument] prefix, prompt for a regexp to match.
11649 With a numeric prefix N, construct a sparse tree for the Nth element
11650 of `org-todo-keywords-1'."
11651 (interactive "P")
11652 (let ((case-fold-search nil)
11653 (kwd-re
11654 (cond ((null arg) org-not-done-regexp)
11655 ((equal arg '(4))
11656 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11657 (mapcar 'list org-todo-keywords-1))))
11658 (concat "\\("
11659 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11660 "\\)\\>")))
11661 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11662 (regexp-quote (nth (1- (prefix-numeric-value arg))
11663 org-todo-keywords-1)))
11664 (t (error "Invalid prefix argument: %s" arg)))))
11665 (message "%d TODO entries found"
11666 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
11668 (defun org-deadline (&optional remove time)
11669 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11670 With argument REMOVE, remove any deadline from the item.
11671 When TIME is set, it should be an internal time specification, and the
11672 scheduling will use the corresponding date."
11673 (interactive "P")
11674 (let* ((old-date (org-entry-get nil "DEADLINE"))
11675 (repeater (and old-date
11676 (string-match
11677 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11678 old-date)
11679 (match-string 1 old-date))))
11680 (if remove
11681 (progn
11682 (when (and old-date org-log-redeadline)
11683 (org-add-log-setup 'deldeadline nil old-date 'findpos
11684 org-log-redeadline))
11685 (org-remove-timestamp-with-keyword org-deadline-string)
11686 (message "Item no longer has a deadline."))
11687 (org-add-planning-info 'deadline time 'closed)
11688 (when (and old-date org-log-redeadline
11689 (not (equal old-date
11690 (substring org-last-inserted-timestamp 1 -1))))
11691 (org-add-log-setup 'redeadline nil old-date 'findpos
11692 org-log-redeadline))
11693 (when repeater
11694 (save-excursion
11695 (org-back-to-heading t)
11696 (when (re-search-forward (concat org-deadline-string " "
11697 org-last-inserted-timestamp)
11698 (save-excursion
11699 (outline-next-heading) (point)) t)
11700 (goto-char (1- (match-end 0)))
11701 (insert " " repeater)
11702 (setq org-last-inserted-timestamp
11703 (concat (substring org-last-inserted-timestamp 0 -1)
11704 " " repeater
11705 (substring org-last-inserted-timestamp -1))))))
11706 (message "Deadline on %s" org-last-inserted-timestamp))))
11708 (defun org-schedule (&optional remove time)
11709 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11710 With argument REMOVE, remove any scheduling date from the item.
11711 When TIME is set, it should be an internal time specification, and the
11712 scheduling will use the corresponding date."
11713 (interactive "P")
11714 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11715 (repeater (and old-date
11716 (string-match
11717 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11718 old-date)
11719 (match-string 1 old-date))))
11720 (if remove
11721 (progn
11722 (when (and old-date org-log-reschedule)
11723 (org-add-log-setup 'delschedule nil old-date 'findpos
11724 org-log-reschedule))
11725 (org-remove-timestamp-with-keyword org-scheduled-string)
11726 (message "Item is no longer scheduled."))
11727 (org-add-planning-info 'scheduled time 'closed)
11728 (when (and old-date org-log-reschedule
11729 (not (equal old-date
11730 (substring org-last-inserted-timestamp 1 -1))))
11731 (org-add-log-setup 'reschedule nil old-date 'findpos
11732 org-log-reschedule))
11733 (when repeater
11734 (save-excursion
11735 (org-back-to-heading t)
11736 (when (re-search-forward (concat org-scheduled-string " "
11737 org-last-inserted-timestamp)
11738 (save-excursion
11739 (outline-next-heading) (point)) t)
11740 (goto-char (1- (match-end 0)))
11741 (insert " " repeater)
11742 (setq org-last-inserted-timestamp
11743 (concat (substring org-last-inserted-timestamp 0 -1)
11744 " " repeater
11745 (substring org-last-inserted-timestamp -1))))))
11746 (message "Scheduled to %s" org-last-inserted-timestamp))))
11748 (defun org-get-scheduled-time (pom &optional inherit)
11749 "Get the scheduled time as a time tuple, of a format suitable
11750 for calling org-schedule with, or if there is no scheduling,
11751 returns nil."
11752 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
11753 (when time
11754 (apply 'encode-time (org-parse-time-string time)))))
11756 (defun org-get-deadline-time (pom &optional inherit)
11757 "Get the deadline as a time tuple, of a format suitable for
11758 calling org-deadline with, or if there is no scheduling, returns
11759 nil."
11760 (let ((time (org-entry-get pom "DEADLINE" inherit)))
11761 (when time
11762 (apply 'encode-time (org-parse-time-string time)))))
11764 (defun org-remove-timestamp-with-keyword (keyword)
11765 "Remove all time stamps with KEYWORD in the current entry."
11766 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
11767 beg)
11768 (save-excursion
11769 (org-back-to-heading t)
11770 (setq beg (point))
11771 (outline-next-heading)
11772 (while (re-search-backward re beg t)
11773 (replace-match "")
11774 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
11775 (equal (char-before) ?\ ))
11776 (backward-delete-char 1)
11777 (if (string-match "^[ \t]*$" (buffer-substring
11778 (point-at-bol) (point-at-eol)))
11779 (delete-region (point-at-bol)
11780 (min (point-max) (1+ (point-at-eol))))))))))
11782 (defun org-add-planning-info (what &optional time &rest remove)
11783 "Insert new timestamp with keyword in the line directly after the headline.
11784 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11785 If non is given, the user is prompted for a date.
11786 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11787 be removed."
11788 (interactive)
11789 (let (org-time-was-given org-end-time-was-given ts
11790 end default-time default-input)
11792 (catch 'exit
11793 (when (and (not time) (memq what '(scheduled deadline)))
11794 ;; Try to get a default date/time from existing timestamp
11795 (save-excursion
11796 (org-back-to-heading t)
11797 (setq end (save-excursion (outline-next-heading) (point)))
11798 (when (re-search-forward (if (eq what 'scheduled)
11799 org-scheduled-time-regexp
11800 org-deadline-time-regexp)
11801 end t)
11802 (setq ts (match-string 1)
11803 default-time
11804 (apply 'encode-time (org-parse-time-string ts))
11805 default-input (and ts (org-get-compact-tod ts))))))
11806 (when what
11807 ;; If necessary, get the time from the user
11808 (setq time (or time (org-read-date nil 'to-time nil nil
11809 default-time default-input))))
11811 (when (and org-insert-labeled-timestamps-at-point
11812 (member what '(scheduled deadline)))
11813 (insert
11814 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11815 (org-insert-time-stamp time org-time-was-given
11816 nil nil nil (list org-end-time-was-given))
11817 (setq what nil))
11818 (save-excursion
11819 (save-restriction
11820 (let (col list elt ts buffer-invisibility-spec)
11821 (org-back-to-heading t)
11822 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11823 (goto-char (match-end 1))
11824 (setq col (current-column))
11825 (goto-char (match-end 0))
11826 (if (eobp) (insert "\n") (forward-char 1))
11827 (when (and (not what)
11828 (not (looking-at
11829 (concat "[ \t]*"
11830 org-keyword-time-not-clock-regexp))))
11831 ;; Nothing to add, nothing to remove...... :-)
11832 (throw 'exit nil))
11833 (if (and (not (looking-at outline-regexp))
11834 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11835 "[^\r\n]*"))
11836 (not (equal (match-string 1) org-clock-string)))
11837 (narrow-to-region (match-beginning 0) (match-end 0))
11838 (insert-before-markers "\n")
11839 (backward-char 1)
11840 (narrow-to-region (point) (point))
11841 (and org-adapt-indentation (org-indent-to-column col)))
11842 ;; Check if we have to remove something.
11843 (setq list (cons what remove))
11844 (while list
11845 (setq elt (pop list))
11846 (when (or (and (eq elt 'scheduled)
11847 (re-search-forward org-scheduled-time-regexp nil t))
11848 (and (eq elt 'deadline)
11849 (re-search-forward org-deadline-time-regexp nil t))
11850 (and (eq elt 'closed)
11851 (re-search-forward org-closed-time-regexp nil t)))
11852 (replace-match "")
11853 (if (looking-at "--+<[^>]+>") (replace-match ""))))
11854 (and (looking-at "^[ \t]+") (replace-match ""))
11855 (and org-adapt-indentation (bolp) (org-indent-to-column col))
11856 (when what
11857 (insert
11858 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
11859 (cond ((eq what 'scheduled) org-scheduled-string)
11860 ((eq what 'deadline) org-deadline-string)
11861 ((eq what 'closed) org-closed-string))
11862 " ")
11863 (setq ts (org-insert-time-stamp
11864 time
11865 (or org-time-was-given
11866 (and (eq what 'closed) org-log-done-with-time))
11867 (eq what 'closed)
11868 nil nil (list org-end-time-was-given)))
11869 (insert
11870 (if (not (or (bolp) (eq (char-before) ?\ )
11871 (memq (char-after) '(32 10))
11872 (eobp))) " " ""))
11873 (end-of-line 1))
11874 (goto-char (point-min))
11875 (widen)
11876 (if (and (looking-at "[ \t]*\n")
11877 (equal (char-before) ?\n))
11878 (delete-region (1- (point)) (point-at-eol)))
11879 ts))))))
11881 (defvar org-log-note-marker (make-marker))
11882 (defvar org-log-note-purpose nil)
11883 (defvar org-log-note-state nil)
11884 (defvar org-log-note-previous-state nil)
11885 (defvar org-log-note-how nil)
11886 (defvar org-log-note-extra nil)
11887 (defvar org-log-note-window-configuration nil)
11888 (defvar org-log-note-return-to (make-marker))
11889 (defvar org-log-post-message nil
11890 "Message to be displayed after a log note has been stored.
11891 The auto-repeater uses this.")
11893 (defun org-add-note ()
11894 "Add a note to the current entry.
11895 This is done in the same way as adding a state change note."
11896 (interactive)
11897 (org-add-log-setup 'note nil nil 'findpos nil))
11899 (defvar org-property-end-re)
11900 (defun org-add-log-setup (&optional purpose state prev-state
11901 findpos how extra)
11902 "Set up the post command hook to take a note.
11903 If this is about to TODO state change, the new state is expected in STATE.
11904 When FINDPOS is non-nil, find the correct position for the note in
11905 the current entry. If not, assume that it can be inserted at point.
11906 HOW is an indicator what kind of note should be created.
11907 EXTRA is additional text that will be inserted into the notes buffer."
11908 (let* ((org-log-into-drawer (org-log-into-drawer))
11909 (drawer (cond ((stringp org-log-into-drawer)
11910 org-log-into-drawer)
11911 (org-log-into-drawer "LOGBOOK")
11912 (t nil))))
11913 (save-restriction
11914 (save-excursion
11915 (when findpos
11916 (org-back-to-heading t)
11917 (narrow-to-region (point) (save-excursion
11918 (outline-next-heading) (point)))
11919 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11920 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11921 "[^\r\n]*\\)?"))
11922 (goto-char (match-end 0))
11923 (cond
11924 (drawer
11925 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
11926 nil t)
11927 (progn
11928 (goto-char (match-end 0))
11929 (or org-log-states-order-reversed
11930 (and (re-search-forward org-property-end-re nil t)
11931 (goto-char (1- (match-beginning 0))))))
11932 (insert "\n:" drawer ":\n:END:")
11933 (beginning-of-line 0)
11934 (org-indent-line-function)
11935 (beginning-of-line 2)
11936 (org-indent-line-function)
11937 (end-of-line 0)))
11938 ((and org-log-state-notes-insert-after-drawers
11939 (save-excursion
11940 (forward-line) (looking-at org-drawer-regexp)))
11941 (forward-line)
11942 (while (looking-at org-drawer-regexp)
11943 (goto-char (match-end 0))
11944 (re-search-forward org-property-end-re (point-max) t)
11945 (forward-line))
11946 (forward-line -1)))
11947 (unless org-log-states-order-reversed
11948 (and (= (char-after) ?\n) (forward-char 1))
11949 (org-skip-over-state-notes)
11950 (skip-chars-backward " \t\n\r")))
11951 (move-marker org-log-note-marker (point))
11952 (setq org-log-note-purpose purpose
11953 org-log-note-state state
11954 org-log-note-previous-state prev-state
11955 org-log-note-how how
11956 org-log-note-extra extra)
11957 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
11959 (defun org-skip-over-state-notes ()
11960 "Skip past the list of State notes in an entry."
11961 (if (looking-at "\n[ \t]*- State") (forward-char 1))
11962 (when (ignore-errors (goto-char (org-in-item-p)))
11963 (let* ((struct (org-list-struct))
11964 (prevs (org-list-prevs-alist struct)))
11965 (while (looking-at "[ \t]*- State")
11966 (goto-char (or (org-list-get-next-item (point) struct prevs)
11967 (org-list-get-item-end (point) struct)))))))
11969 (defun org-add-log-note (&optional purpose)
11970 "Pop up a window for taking a note, and add this note later at point."
11971 (remove-hook 'post-command-hook 'org-add-log-note)
11972 (setq org-log-note-window-configuration (current-window-configuration))
11973 (delete-other-windows)
11974 (move-marker org-log-note-return-to (point))
11975 (switch-to-buffer (marker-buffer org-log-note-marker))
11976 (goto-char org-log-note-marker)
11977 (org-switch-to-buffer-other-window "*Org Note*")
11978 (erase-buffer)
11979 (if (memq org-log-note-how '(time state))
11980 (let (current-prefix-arg) (org-store-log-note))
11981 (let ((org-inhibit-startup t)) (org-mode))
11982 (insert (format "# Insert note for %s.
11983 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
11984 (cond
11985 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11986 ((eq org-log-note-purpose 'done) "closed todo item")
11987 ((eq org-log-note-purpose 'state)
11988 (format "state change from \"%s\" to \"%s\""
11989 (or org-log-note-previous-state "")
11990 (or org-log-note-state "")))
11991 ((eq org-log-note-purpose 'reschedule)
11992 "rescheduling")
11993 ((eq org-log-note-purpose 'delschedule)
11994 "no longer scheduled")
11995 ((eq org-log-note-purpose 'redeadline)
11996 "changing deadline")
11997 ((eq org-log-note-purpose 'deldeadline)
11998 "removing deadline")
11999 ((eq org-log-note-purpose 'refile)
12000 "refiling")
12001 ((eq org-log-note-purpose 'note)
12002 "this entry")
12003 (t (error "This should not happen")))))
12004 (if org-log-note-extra (insert org-log-note-extra))
12005 (org-set-local 'org-finish-function 'org-store-log-note)))
12007 (defvar org-note-abort nil) ; dynamically scoped
12008 (defun org-store-log-note ()
12009 "Finish taking a log note, and insert it to where it belongs."
12010 (let ((txt (buffer-string))
12011 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12012 lines ind bul)
12013 (kill-buffer (current-buffer))
12014 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12015 (setq txt (replace-match "" t t txt)))
12016 (if (string-match "\\s-+\\'" txt)
12017 (setq txt (replace-match "" t t txt)))
12018 (setq lines (org-split-string txt "\n"))
12019 (when (and note (string-match "\\S-" note))
12020 (setq note
12021 (org-replace-escapes
12022 note
12023 (list (cons "%u" (user-login-name))
12024 (cons "%U" user-full-name)
12025 (cons "%t" (format-time-string
12026 (org-time-stamp-format 'long 'inactive)
12027 (current-time)))
12028 (cons "%T" (format-time-string
12029 (org-time-stamp-format 'long nil)
12030 (current-time)))
12031 (cons "%s" (if org-log-note-state
12032 (concat "\"" org-log-note-state "\"")
12033 ""))
12034 (cons "%S" (if org-log-note-previous-state
12035 (concat "\"" org-log-note-previous-state "\"")
12036 "\"\"")))))
12037 (if lines (setq note (concat note " \\\\")))
12038 (push note lines))
12039 (when (or current-prefix-arg org-note-abort)
12040 (when org-log-into-drawer
12041 (org-remove-empty-drawer-at
12042 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12043 org-log-note-marker))
12044 (setq lines nil))
12045 (when lines
12046 (with-current-buffer (marker-buffer org-log-note-marker)
12047 (save-excursion
12048 (goto-char org-log-note-marker)
12049 (move-marker org-log-note-marker nil)
12050 (end-of-line 1)
12051 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12052 (setq ind (save-excursion
12053 (if (ignore-errors (goto-char (org-in-item-p)))
12054 (let ((struct (org-list-struct)))
12055 (org-list-get-ind
12056 (org-list-get-top-point struct) struct))
12057 (skip-chars-backward " \r\t\n")
12058 (cond
12059 ((and (org-at-heading-p)
12060 org-adapt-indentation)
12061 (1+ (org-current-level)))
12062 ((org-at-heading-p) 0)
12063 (t (org-get-indentation))))))
12064 (setq bul (org-list-bullet-string "-"))
12065 (org-indent-line-to ind)
12066 (insert bul (pop lines))
12067 (let ((ind-body (+ (length bul) ind)))
12068 (while lines
12069 (insert "\n")
12070 (org-indent-line-to ind-body)
12071 (insert (pop lines))))
12072 (message "Note stored")
12073 (org-back-to-heading t)
12074 (org-cycle-hide-drawers 'children)))))
12075 (set-window-configuration org-log-note-window-configuration)
12076 (with-current-buffer (marker-buffer org-log-note-return-to)
12077 (goto-char org-log-note-return-to))
12078 (move-marker org-log-note-return-to nil)
12079 (and org-log-post-message (message "%s" org-log-post-message)))
12081 (defun org-remove-empty-drawer-at (drawer pos)
12082 "Remove an empty drawer DRAWER at position POS.
12083 POS may also be a marker."
12084 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12085 (save-excursion
12086 (save-restriction
12087 (widen)
12088 (goto-char pos)
12089 (if (org-in-regexp
12090 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12091 (replace-match ""))))))
12093 (defun org-sparse-tree (&optional arg)
12094 "Create a sparse tree, prompt for the details.
12095 This command can create sparse trees. You first need to select the type
12096 of match used to create the tree:
12098 t Show all TODO entries.
12099 T Show entries with a specific TODO keyword.
12100 m Show entries selected by a tags/property match.
12101 p Enter a property name and its value (both with completion on existing
12102 names/values) and show entries with that property.
12103 r Show entries matching a regular expression (`/' can be used as well)
12104 d Show deadlines due within `org-deadline-warning-days'.
12105 b Show deadlines and scheduled items before a date.
12106 a Show deadlines and scheduled items after a date."
12107 (interactive "P")
12108 (let (ans kwd value)
12109 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date")
12110 (setq ans (read-char-exclusive))
12111 (cond
12112 ((equal ans ?d)
12113 (call-interactively 'org-check-deadlines))
12114 ((equal ans ?b)
12115 (call-interactively 'org-check-before-date))
12116 ((equal ans ?a)
12117 (call-interactively 'org-check-after-date))
12118 ((equal ans ?t)
12119 (org-show-todo-tree nil))
12120 ((equal ans ?T)
12121 (org-show-todo-tree '(4)))
12122 ((member ans '(?T ?m))
12123 (call-interactively 'org-match-sparse-tree))
12124 ((member ans '(?p ?P))
12125 (setq kwd (org-icompleting-read "Property: "
12126 (mapcar 'list (org-buffer-property-keys))))
12127 (setq value (org-icompleting-read "Value: "
12128 (mapcar 'list (org-property-values kwd))))
12129 (unless (string-match "\\`{.*}\\'" value)
12130 (setq value (concat "\"" value "\"")))
12131 (org-match-sparse-tree arg (concat kwd "=" value)))
12132 ((member ans '(?r ?R ?/))
12133 (call-interactively 'org-occur))
12134 (t (error "No such sparse tree command \"%c\"" ans)))))
12136 (defvar org-occur-highlights nil
12137 "List of overlays used for occur matches.")
12138 (make-variable-buffer-local 'org-occur-highlights)
12139 (defvar org-occur-parameters nil
12140 "Parameters of the active org-occur calls.
12141 This is a list, each call to org-occur pushes as cons cell,
12142 containing the regular expression and the callback, onto the list.
12143 The list can contain several entries if `org-occur' has been called
12144 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12145 will only contain one set of parameters. When the highlights are
12146 removed (for example with `C-c C-c', or with the next edit (depending
12147 on `org-remove-highlights-with-change'), this variable is emptied
12148 as well.")
12149 (make-variable-buffer-local 'org-occur-parameters)
12151 (defun org-occur (regexp &optional keep-previous callback)
12152 "Make a compact tree which shows all matches of REGEXP.
12153 The tree will show the lines where the regexp matches, and all higher
12154 headlines above the match. It will also show the heading after the match,
12155 to make sure editing the matching entry is easy.
12156 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12157 call to `org-occur' will be kept, to allow stacking of calls to this
12158 command.
12159 If CALLBACK is non-nil, it is a function which is called to confirm
12160 that the match should indeed be shown."
12161 (interactive "sRegexp: \nP")
12162 (when (equal regexp "")
12163 (error "Regexp cannot be empty"))
12164 (unless keep-previous
12165 (org-remove-occur-highlights nil nil t))
12166 (push (cons regexp callback) org-occur-parameters)
12167 (let ((cnt 0))
12168 (save-excursion
12169 (goto-char (point-min))
12170 (if (or (not keep-previous) ; do not want to keep
12171 (not org-occur-highlights)) ; no previous matches
12172 ;; hide everything
12173 (org-overview))
12174 (while (re-search-forward regexp nil t)
12175 (when (or (not callback)
12176 (save-match-data (funcall callback)))
12177 (setq cnt (1+ cnt))
12178 (when org-highlight-sparse-tree-matches
12179 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12180 (org-show-context 'occur-tree))))
12181 (when org-remove-highlights-with-change
12182 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12183 nil 'local))
12184 (unless org-sparse-tree-open-archived-trees
12185 (org-hide-archived-subtrees (point-min) (point-max)))
12186 (run-hooks 'org-occur-hook)
12187 (if (org-called-interactively-p 'interactive)
12188 (message "%d match(es) for regexp %s" cnt regexp))
12189 cnt))
12191 (defun org-occur-next-match (&optional n reset)
12192 "Function for `next-error-function' to find sparse tree matches.
12193 N is the number of matches to move, when negative move backwards.
12194 RESET is entirely ignored - this function always goes back to the
12195 starting point when no match is found."
12196 (let* ((limit (if (< n 0) (point-min) (point-max)))
12197 (search-func (if (< n 0)
12198 'previous-single-char-property-change
12199 'next-single-char-property-change))
12200 (n (abs n))
12201 (pos (point))
12203 (catch 'exit
12204 (while (setq p1 (funcall search-func (point) 'org-type))
12205 (when (equal p1 limit)
12206 (goto-char pos)
12207 (error "No more matches"))
12208 (when (equal (get-char-property p1 'org-type) 'org-occur)
12209 (setq n (1- n))
12210 (when (= n 0)
12211 (goto-char p1)
12212 (throw 'exit (point))))
12213 (goto-char p1))
12214 (goto-char p1)
12215 (error "No more matches"))))
12217 (defun org-show-context (&optional key)
12218 "Make sure point and context are visible.
12219 How much context is shown depends upon the variables
12220 `org-show-hierarchy-above', `org-show-following-heading'. and
12221 `org-show-siblings'."
12222 (let ((heading-p (org-on-heading-p t))
12223 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12224 (following-p (org-get-alist-option org-show-following-heading key))
12225 (entry-p (org-get-alist-option org-show-entry-below key))
12226 (siblings-p (org-get-alist-option org-show-siblings key)))
12227 (catch 'exit
12228 ;; Show heading or entry text
12229 (if (and heading-p (not entry-p))
12230 (org-flag-heading nil) ; only show the heading
12231 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12232 (org-show-hidden-entry))) ; show entire entry
12233 (when following-p
12234 ;; Show next sibling, or heading below text
12235 (save-excursion
12236 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12237 (org-flag-heading nil))))
12238 (when siblings-p (org-show-siblings))
12239 (when hierarchy-p
12240 ;; show all higher headings, possibly with siblings
12241 (save-excursion
12242 (while (and (condition-case nil
12243 (progn (org-up-heading-all 1) t)
12244 (error nil))
12245 (not (bobp)))
12246 (org-flag-heading nil)
12247 (when siblings-p (org-show-siblings))))))))
12249 (defvar org-reveal-start-hook nil
12250 "Hook run before revealing a location.")
12252 (defun org-reveal (&optional siblings)
12253 "Show current entry, hierarchy above it, and the following headline.
12254 This can be used to show a consistent set of context around locations
12255 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12256 not t for the search context.
12258 With optional argument SIBLINGS, on each level of the hierarchy all
12259 siblings are shown. This repairs the tree structure to what it would
12260 look like when opened with hierarchical calls to `org-cycle'.
12261 With double optional argument \\[universal-argument] \\[universal-argument], \
12262 go to the parent and show the
12263 entire tree."
12264 (interactive "P")
12265 (run-hooks 'org-reveal-start-hook)
12266 (let ((org-show-hierarchy-above t)
12267 (org-show-following-heading t)
12268 (org-show-siblings (if siblings t org-show-siblings)))
12269 (org-show-context nil))
12270 (when (equal siblings '(16))
12271 (save-excursion
12272 (when (org-up-heading-safe)
12273 (org-show-subtree)
12274 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12276 (defun org-highlight-new-match (beg end)
12277 "Highlight from BEG to END and mark the highlight is an occur headline."
12278 (let ((ov (make-overlay beg end)))
12279 (overlay-put ov 'face 'secondary-selection)
12280 (overlay-put ov 'org-type 'org-occur)
12281 (push ov org-occur-highlights)))
12283 (defun org-remove-occur-highlights (&optional beg end noremove)
12284 "Remove the occur highlights from the buffer.
12285 BEG and END are ignored. If NOREMOVE is nil, remove this function
12286 from the `before-change-functions' in the current buffer."
12287 (interactive)
12288 (unless org-inhibit-highlight-removal
12289 (mapc 'delete-overlay org-occur-highlights)
12290 (setq org-occur-highlights nil)
12291 (setq org-occur-parameters nil)
12292 (unless noremove
12293 (remove-hook 'before-change-functions
12294 'org-remove-occur-highlights 'local))))
12296 ;;;; Priorities
12298 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12299 "Regular expression matching the priority indicator.")
12301 (defvar org-remove-priority-next-time nil)
12303 (defun org-priority-up ()
12304 "Increase the priority of the current item."
12305 (interactive)
12306 (org-priority 'up))
12308 (defun org-priority-down ()
12309 "Decrease the priority of the current item."
12310 (interactive)
12311 (org-priority 'down))
12313 (defun org-priority (&optional action)
12314 "Change the priority of an item by ARG.
12315 ACTION can be `set', `up', `down', or a character."
12316 (interactive)
12317 (unless org-enable-priority-commands
12318 (error "Priority commands are disabled"))
12319 (setq action (or action 'set))
12320 (let (current new news have remove)
12321 (save-excursion
12322 (org-back-to-heading t)
12323 (if (looking-at org-priority-regexp)
12324 (setq current (string-to-char (match-string 2))
12325 have t))
12326 (cond
12327 ((eq action 'remove)
12328 (setq remove t new ?\ ))
12329 ((or (eq action 'set)
12330 (if (featurep 'xemacs) (characterp action) (integerp action)))
12331 (if (not (eq action 'set))
12332 (setq new action)
12333 (message "Priority %c-%c, SPC to remove: "
12334 org-highest-priority org-lowest-priority)
12335 (save-match-data
12336 (setq new (read-char-exclusive))))
12337 (if (and (= (upcase org-highest-priority) org-highest-priority)
12338 (= (upcase org-lowest-priority) org-lowest-priority))
12339 (setq new (upcase new)))
12340 (cond ((equal new ?\ ) (setq remove t))
12341 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12342 (error "Priority must be between `%c' and `%c'"
12343 org-highest-priority org-lowest-priority))))
12344 ((eq action 'up)
12345 (setq new (if have
12346 (1- current) ; normal cycling
12347 ;; last priority was empty
12348 (if (eq last-command this-command)
12349 org-lowest-priority ; wrap around empty to lowest
12350 ;; default
12351 (if org-priority-start-cycle-with-default
12352 org-default-priority
12353 (1- org-default-priority))))))
12354 ((eq action 'down)
12355 (setq new (if have
12356 (1+ current) ; normal cycling
12357 ;; last priority was empty
12358 (if (eq last-command this-command)
12359 org-highest-priority ; wrap around empty to highest
12360 ;; default
12361 (if org-priority-start-cycle-with-default
12362 org-default-priority
12363 (1+ org-default-priority))))))
12364 (t (error "Invalid action")))
12365 (if (or (< (upcase new) org-highest-priority)
12366 (> (upcase new) org-lowest-priority))
12367 (if (and (memq action '(up down))
12368 (not have) (not (eq last-command this-command)))
12369 ;; `new' is from default priority
12370 (error
12371 "The default can not be set, see `org-default-priority' why")
12372 ;; normal cycling: `new' is beyond highest/lowest priority
12373 ;; and is wrapped around to the empty priority
12374 (setq remove t)))
12375 (setq news (format "%c" new))
12376 (if have
12377 (if remove
12378 (replace-match "" t t nil 1)
12379 (replace-match news t t nil 2))
12380 (if remove
12381 (error "No priority cookie found in line")
12382 (let ((case-fold-search nil))
12383 (looking-at org-todo-line-regexp))
12384 (if (match-end 2)
12385 (progn
12386 (goto-char (match-end 2))
12387 (insert " [#" news "]"))
12388 (goto-char (match-beginning 3))
12389 (insert "[#" news "] "))))
12390 (org-preserve-lc (org-set-tags nil 'align)))
12391 (if remove
12392 (message "Priority removed")
12393 (message "Priority of current item set to %s" news))))
12395 (defun org-get-priority (s)
12396 "Find priority cookie and return priority."
12397 (if (functionp org-get-priority-function)
12398 (funcall org-get-priority-function)
12399 (save-match-data
12400 (if (not (string-match org-priority-regexp s))
12401 (* 1000 (- org-lowest-priority org-default-priority))
12402 (* 1000 (- org-lowest-priority
12403 (string-to-char (match-string 2 s))))))))
12405 ;;;; Tags
12407 (defvar org-agenda-archives-mode)
12408 (defvar org-map-continue-from nil
12409 "Position from where mapping should continue.
12410 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
12412 (defvar org-scanner-tags nil
12413 "The current tag list while the tags scanner is running.")
12414 (defvar org-trust-scanner-tags nil
12415 "Should `org-get-tags-at' use the tags for the scanner.
12416 This is for internal dynamical scoping only.
12417 When this is non-nil, the function `org-get-tags-at' will return the value
12418 of `org-scanner-tags' instead of building the list by itself. This
12419 can lead to large speed-ups when the tags scanner is used in a file with
12420 many entries, and when the list of tags is retrieved, for example to
12421 obtain a list of properties. Building the tags list for each entry in such
12422 a file becomes an N^2 operation - but with this variable set, it scales
12423 as N.")
12425 (defun org-scan-tags (action matcher &optional todo-only)
12426 "Scan headline tags with inheritance and produce output ACTION.
12428 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12429 or `agenda' to produce an entry list for an agenda view. It can also be
12430 a Lisp form or a function that should be called at each matched headline, in
12431 this case the return value is a list of all return values from these calls.
12433 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12434 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12435 only lines with a TODO keyword are included in the output."
12436 (require 'org-agenda)
12437 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
12438 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12439 (org-re
12440 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12441 (props (list 'face 'default
12442 'done-face 'org-agenda-done
12443 'undone-face 'default
12444 'mouse-face 'highlight
12445 'org-not-done-regexp org-not-done-regexp
12446 'org-todo-regexp org-todo-regexp
12447 'help-echo
12448 (format "mouse-2 or RET jump to org file %s"
12449 (abbreviate-file-name
12450 (or (buffer-file-name (buffer-base-buffer))
12451 (buffer-name (buffer-base-buffer)))))))
12452 (case-fold-search nil)
12453 (org-map-continue-from nil)
12454 lspos tags tags-list
12455 (tags-alist (list (cons 0 org-file-tags)))
12456 (llast 0) rtn rtn1 level category i txt
12457 todo marker entry priority)
12458 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12459 (setq action (list 'lambda nil action)))
12460 (save-excursion
12461 (goto-char (point-min))
12462 (when (eq action 'sparse-tree)
12463 (org-overview)
12464 (org-remove-occur-highlights))
12465 (while (re-search-forward re nil t)
12466 (catch :skip
12467 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12468 tags (if (match-end 4) (org-match-string-no-properties 4)))
12469 (goto-char (setq lspos (match-beginning 0)))
12470 (setq level (org-reduced-level (funcall outline-level))
12471 category (org-get-category))
12472 (setq i llast llast level)
12473 ;; remove tag lists from same and sublevels
12474 (while (>= i level)
12475 (when (setq entry (assoc i tags-alist))
12476 (setq tags-alist (delete entry tags-alist)))
12477 (setq i (1- i)))
12478 ;; add the next tags
12479 (when tags
12480 (setq tags (org-split-string tags ":")
12481 tags-alist
12482 (cons (cons level tags) tags-alist)))
12483 ;; compile tags for current headline
12484 (setq tags-list
12485 (if org-use-tag-inheritance
12486 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12487 tags)
12488 org-scanner-tags tags-list)
12489 (when org-use-tag-inheritance
12490 (setcdr (car tags-alist)
12491 (mapcar (lambda (x)
12492 (setq x (copy-sequence x))
12493 (org-add-prop-inherited x))
12494 (cdar tags-alist))))
12495 (when (and tags org-use-tag-inheritance
12496 (or (not (eq t org-use-tag-inheritance))
12497 org-tags-exclude-from-inheritance))
12498 ;; selective inheritance, remove uninherited ones
12499 (setcdr (car tags-alist)
12500 (org-remove-uninherited-tags (cdar tags-alist))))
12501 (when (and
12503 ;; eval matcher only when the todo condition is OK
12504 (and (or (not todo-only) (member todo org-not-done-keywords))
12505 (let ((case-fold-search t)) (eval matcher)))
12507 ;; Call the skipper, but return t if it does not skip,
12508 ;; so that the `and' form continues evaluating
12509 (progn
12510 (unless (eq action 'sparse-tree) (org-agenda-skip))
12513 ;; Check if timestamps are deselecting this entry
12514 (or (not todo-only)
12515 (and (member todo org-not-done-keywords)
12516 (or (not org-agenda-tags-todo-honor-ignore-options)
12517 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12519 ;; Extra check for the archive tag
12520 ;; FIXME: Does the skipper already do this????
12522 (not (member org-archive-tag tags-list))
12523 ;; we have an archive tag, should we use this anyway?
12524 (or (not org-agenda-skip-archived-trees)
12525 (and (eq action 'agenda) org-agenda-archives-mode))))
12527 ;; select this headline
12529 (cond
12530 ((eq action 'sparse-tree)
12531 (and org-highlight-sparse-tree-matches
12532 (org-get-heading) (match-end 0)
12533 (org-highlight-new-match
12534 (match-beginning 0) (match-beginning 1)))
12535 (org-show-context 'tags-tree))
12536 ((eq action 'agenda)
12537 (setq txt (org-format-agenda-item
12539 (concat
12540 (if (eq org-tags-match-list-sublevels 'indented)
12541 (make-string (1- level) ?.) "")
12542 (org-get-heading))
12543 category
12544 tags-list
12546 priority (org-get-priority txt))
12547 (goto-char lspos)
12548 (setq marker (org-agenda-new-marker))
12549 (org-add-props txt props
12550 'org-marker marker 'org-hd-marker marker 'org-category category
12551 'todo-state todo
12552 'priority priority 'type "tagsmatch")
12553 (push txt rtn))
12554 ((functionp action)
12555 (setq org-map-continue-from nil)
12556 (save-excursion
12557 (setq rtn1 (funcall action))
12558 (push rtn1 rtn)))
12559 (t (error "Invalid action")))
12561 ;; if we are to skip sublevels, jump to end of subtree
12562 (unless org-tags-match-list-sublevels
12563 (org-end-of-subtree t)
12564 (backward-char 1))))
12565 ;; Get the correct position from where to continue
12566 (if org-map-continue-from
12567 (goto-char org-map-continue-from)
12568 (and (= (point) lspos) (end-of-line 1)))))
12569 (when (and (eq action 'sparse-tree)
12570 (not org-sparse-tree-open-archived-trees))
12571 (org-hide-archived-subtrees (point-min) (point-max)))
12572 (nreverse rtn)))
12574 (defun org-remove-uninherited-tags (tags)
12575 "Remove all tags that are not inherited from the list TAGS."
12576 (cond
12577 ((eq org-use-tag-inheritance t)
12578 (if org-tags-exclude-from-inheritance
12579 (org-delete-all org-tags-exclude-from-inheritance tags)
12580 tags))
12581 ((not org-use-tag-inheritance) nil)
12582 ((stringp org-use-tag-inheritance)
12583 (delq nil (mapcar
12584 (lambda (x)
12585 (if (and (string-match org-use-tag-inheritance x)
12586 (not (member x org-tags-exclude-from-inheritance)))
12587 x nil))
12588 tags)))
12589 ((listp org-use-tag-inheritance)
12590 (delq nil (mapcar
12591 (lambda (x)
12592 (if (member x org-use-tag-inheritance) x nil))
12593 tags)))))
12595 (defvar todo-only) ;; dynamically scoped
12597 (defun org-match-sparse-tree (&optional todo-only match)
12598 "Create a sparse tree according to tags string MATCH.
12599 MATCH can contain positive and negative selection of tags, like
12600 \"+WORK+URGENT-WITHBOSS\".
12601 If optional argument TODO-ONLY is non-nil, only select lines that are
12602 also TODO lines."
12603 (interactive "P")
12604 (org-prepare-agenda-buffers (list (current-buffer)))
12605 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12607 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12609 (defvar org-cached-props nil)
12610 (defun org-cached-entry-get (pom property)
12611 (if (or (eq t org-use-property-inheritance)
12612 (and (stringp org-use-property-inheritance)
12613 (string-match org-use-property-inheritance property))
12614 (and (listp org-use-property-inheritance)
12615 (member property org-use-property-inheritance)))
12616 ;; Caching is not possible, check it directly
12617 (org-entry-get pom property 'inherit)
12618 ;; Get all properties, so that we can do complicated checks easily
12619 (cdr (assoc property (or org-cached-props
12620 (setq org-cached-props
12621 (org-entry-properties pom)))))))
12623 (defun org-global-tags-completion-table (&optional files)
12624 "Return the list of all tags in all agenda buffer/files.
12625 Optional FILES argument is a list of files to which can be used
12626 instead of the agenda files."
12627 (save-excursion
12628 (org-uniquify
12629 (delq nil
12630 (apply 'append
12631 (mapcar
12632 (lambda (file)
12633 (set-buffer (find-file-noselect file))
12634 (append (org-get-buffer-tags)
12635 (mapcar (lambda (x) (if (stringp (car-safe x))
12636 (list (car-safe x)) nil))
12637 org-tag-alist)))
12638 (if (and files (car files))
12639 files
12640 (org-agenda-files))))))))
12642 (defun org-make-tags-matcher (match)
12643 "Create the TAGS/TODO matcher form for the selection string MATCH."
12644 ;; todo-only is scoped dynamically into this function, and the function
12645 ;; may change it if the matcher asks for it.
12646 (unless match
12647 ;; Get a new match request, with completion
12648 (let ((org-last-tags-completion-table
12649 (org-global-tags-completion-table)))
12650 (setq match (org-completing-read-no-i
12651 "Match: " 'org-tags-completion-function nil nil nil
12652 'org-tags-history))))
12654 ;; Parse the string and create a lisp form
12655 (let ((match0 match)
12656 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
12657 minus tag mm
12658 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12659 orterms term orlist re-p str-p level-p level-op time-p
12660 prop-p pn pv po gv rest)
12661 (if (string-match "/+" match)
12662 ;; match contains also a todo-matching request
12663 (progn
12664 (setq tagsmatch (substring match 0 (match-beginning 0))
12665 todomatch (substring match (match-end 0)))
12666 (if (string-match "^!" todomatch)
12667 (setq todo-only t todomatch (substring todomatch 1)))
12668 (if (string-match "^\\s-*$" todomatch)
12669 (setq todomatch nil)))
12670 ;; only matching tags
12671 (setq tagsmatch match todomatch nil))
12673 ;; Make the tags matcher
12674 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12675 (setq tagsmatcher t)
12676 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12677 (while (setq term (pop orterms))
12678 (while (and (equal (substring term -1) "\\") orterms)
12679 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12680 (while (string-match re term)
12681 (setq rest (substring term (match-end 0))
12682 minus (and (match-end 1)
12683 (equal (match-string 1 term) "-"))
12684 tag (save-match-data (replace-regexp-in-string
12685 "\\\\-" "-"
12686 (match-string 2 term)))
12687 re-p (equal (string-to-char tag) ?{)
12688 level-p (match-end 4)
12689 prop-p (match-end 5)
12690 mm (cond
12691 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12692 (level-p
12693 (setq level-op (org-op-to-function (match-string 3 term)))
12694 `(,level-op level ,(string-to-number
12695 (match-string 4 term))))
12696 (prop-p
12697 (setq pn (match-string 5 term)
12698 po (match-string 6 term)
12699 pv (match-string 7 term)
12700 re-p (equal (string-to-char pv) ?{)
12701 str-p (equal (string-to-char pv) ?\")
12702 time-p (save-match-data
12703 (string-match "^\"[[<].*[]>]\"$" pv))
12704 pv (if (or re-p str-p) (substring pv 1 -1) pv))
12705 (if time-p (setq pv (org-matcher-time pv)))
12706 (setq po (org-op-to-function po (if time-p 'time str-p)))
12707 (cond
12708 ((equal pn "CATEGORY")
12709 (setq gv '(get-text-property (point) 'org-category)))
12710 ((equal pn "TODO")
12711 (setq gv 'todo))
12713 (setq gv `(org-cached-entry-get nil ,pn))))
12714 (if re-p
12715 (if (eq po 'org<>)
12716 `(not (string-match ,pv (or ,gv "")))
12717 `(string-match ,pv (or ,gv "")))
12718 (if str-p
12719 `(,po (or ,gv "") ,pv)
12720 `(,po (string-to-number (or ,gv ""))
12721 ,(string-to-number pv) ))))
12722 (t `(member ,tag tags-list)))
12723 mm (if minus (list 'not mm) mm)
12724 term rest)
12725 (push mm tagsmatcher))
12726 (push (if (> (length tagsmatcher) 1)
12727 (cons 'and tagsmatcher)
12728 (car tagsmatcher))
12729 orlist)
12730 (setq tagsmatcher nil))
12731 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
12732 (setq tagsmatcher
12733 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
12734 ;; Make the todo matcher
12735 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
12736 (setq todomatcher t)
12737 (setq orterms (org-split-string todomatch "|") orlist nil)
12738 (while (setq term (pop orterms))
12739 (while (string-match re term)
12740 (setq minus (and (match-end 1)
12741 (equal (match-string 1 term) "-"))
12742 kwd (match-string 2 term)
12743 re-p (equal (string-to-char kwd) ?{)
12744 term (substring term (match-end 0))
12745 mm (if re-p
12746 `(string-match ,(substring kwd 1 -1) todo)
12747 (list 'equal 'todo kwd))
12748 mm (if minus (list 'not mm) mm))
12749 (push mm todomatcher))
12750 (push (if (> (length todomatcher) 1)
12751 (cons 'and todomatcher)
12752 (car todomatcher))
12753 orlist)
12754 (setq todomatcher nil))
12755 (setq todomatcher (if (> (length orlist) 1)
12756 (cons 'or orlist) (car orlist))))
12758 ;; Return the string and lisp forms of the matcher
12759 (setq matcher (if todomatcher
12760 (list 'and tagsmatcher todomatcher)
12761 tagsmatcher))
12762 (cons match0 matcher)))
12764 (defun org-op-to-function (op &optional stringp)
12765 "Turn an operator into the appropriate function."
12766 (setq op
12767 (cond
12768 ((equal op "<" ) '(< string< org-time<))
12769 ((equal op ">" ) '(> org-string> org-time>))
12770 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
12771 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
12772 ((member op '("=" "==")) '(= string= org-time=))
12773 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
12774 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
12776 (defun org<> (a b) (not (= a b)))
12777 (defun org-string<= (a b) (or (string= a b) (string< a b)))
12778 (defun org-string>= (a b) (not (string< a b)))
12779 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
12780 (defun org-string<> (a b) (not (string= a b)))
12781 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
12782 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
12783 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
12784 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
12785 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
12786 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
12787 (defun org-2ft (s)
12788 "Convert S to a floating point time.
12789 If S is already a number, just return it. If it is a string, parse
12790 it as a time string and apply `float-time' to it. If S is nil, just return 0."
12791 (cond
12792 ((numberp s) s)
12793 ((stringp s)
12794 (condition-case nil
12795 (float-time (apply 'encode-time (org-parse-time-string s)))
12796 (error 0.)))
12797 (t 0.)))
12799 (defun org-time-today ()
12800 "Time in seconds today at 0:00.
12801 Returns the float number of seconds since the beginning of the
12802 epoch to the beginning of today (00:00)."
12803 (float-time (apply 'encode-time
12804 (append '(0 0 0) (nthcdr 3 (decode-time))))))
12806 (defun org-matcher-time (s)
12807 "Interpret a time comparison value."
12808 (save-match-data
12809 (cond
12810 ((string= s "<now>") (float-time))
12811 ((string= s "<today>") (org-time-today))
12812 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
12813 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
12814 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
12815 (+ (org-time-today)
12816 (* (string-to-number (match-string 1 s))
12817 (cdr (assoc (match-string 2 s)
12818 '(("d" . 86400.0) ("w" . 604800.0)
12819 ("m" . 2678400.0) ("y" . 31557600.0)))))))
12820 (t (org-2ft s)))))
12822 (defun org-match-any-p (re list)
12823 "Does re match any element of list?"
12824 (setq list (mapcar (lambda (x) (string-match re x)) list))
12825 (delq nil list))
12827 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
12828 (defvar org-tags-overlay (make-overlay 1 1))
12829 (org-detach-overlay org-tags-overlay)
12831 (defun org-get-local-tags-at (&optional pos)
12832 "Get a list of tags defined in the current headline."
12833 (org-get-tags-at pos 'local))
12835 (defun org-get-local-tags ()
12836 "Get a list of tags defined in the current headline."
12837 (org-get-tags-at nil 'local))
12839 (defun org-get-tags-at (&optional pos local)
12840 "Get a list of all headline tags applicable at POS.
12841 POS defaults to point. If tags are inherited, the list contains
12842 the targets in the same sequence as the headlines appear, i.e.
12843 the tags of the current headline come last.
12844 When LOCAL is non-nil, only return tags from the current headline,
12845 ignore inherited ones."
12846 (interactive)
12847 (if (and org-trust-scanner-tags
12848 (or (not pos) (equal pos (point)))
12849 (not local))
12850 org-scanner-tags
12851 (let (tags ltags lastpos parent)
12852 (save-excursion
12853 (save-restriction
12854 (widen)
12855 (goto-char (or pos (point)))
12856 (save-match-data
12857 (catch 'done
12858 (condition-case nil
12859 (progn
12860 (org-back-to-heading t)
12861 (while (not (equal lastpos (point)))
12862 (setq lastpos (point))
12863 (when (looking-at
12864 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
12865 (setq ltags (org-split-string
12866 (org-match-string-no-properties 1) ":"))
12867 (when parent
12868 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
12869 (setq tags (append
12870 (if parent
12871 (org-remove-uninherited-tags ltags)
12872 ltags)
12873 tags)))
12874 (or org-use-tag-inheritance (throw 'done t))
12875 (if local (throw 'done t))
12876 (or (org-up-heading-safe) (error nil))
12877 (setq parent t)))
12878 (error nil)))))
12879 (if local
12880 tags
12881 (append (org-remove-uninherited-tags org-file-tags) tags))))))
12883 (defun org-add-prop-inherited (s)
12884 (add-text-properties 0 (length s) '(inherited t) s)
12887 (defun org-toggle-tag (tag &optional onoff)
12888 "Toggle the tag TAG for the current line.
12889 If ONOFF is `on' or `off', don't toggle but set to this state."
12890 (let (res current)
12891 (save-excursion
12892 (org-back-to-heading t)
12893 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
12894 (point-at-eol) t)
12895 (progn
12896 (setq current (match-string 1))
12897 (replace-match ""))
12898 (setq current ""))
12899 (setq current (nreverse (org-split-string current ":")))
12900 (cond
12901 ((eq onoff 'on)
12902 (setq res t)
12903 (or (member tag current) (push tag current)))
12904 ((eq onoff 'off)
12905 (or (not (member tag current)) (setq current (delete tag current))))
12906 (t (if (member tag current)
12907 (setq current (delete tag current))
12908 (setq res t)
12909 (push tag current))))
12910 (end-of-line 1)
12911 (if current
12912 (progn
12913 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
12914 (org-set-tags nil t))
12915 (delete-horizontal-space))
12916 (run-hooks 'org-after-tags-change-hook))
12917 res))
12919 (defun org-align-tags-here (to-col)
12920 ;; Assumes that this is a headline
12921 (let ((pos (point)) (col (current-column)) ncol tags-l p)
12922 (beginning-of-line 1)
12923 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
12924 (< pos (match-beginning 2)))
12925 (progn
12926 (setq tags-l (- (match-end 2) (match-beginning 2)))
12927 (goto-char (match-beginning 1))
12928 (insert " ")
12929 (delete-region (point) (1+ (match-beginning 2)))
12930 (setq ncol (max (1+ (current-column))
12931 (1+ col)
12932 (if (> to-col 0)
12933 to-col
12934 (- (abs to-col) tags-l))))
12935 (setq p (point))
12936 (insert (make-string (- ncol (current-column)) ?\ ))
12937 (setq ncol (current-column))
12938 (when indent-tabs-mode (tabify p (point-at-eol)))
12939 (org-move-to-column (min ncol col) t))
12940 (goto-char pos))))
12942 (defun org-set-tags-command (&optional arg just-align)
12943 "Call the set-tags command for the current entry."
12944 (interactive "P")
12945 (if (org-on-heading-p)
12946 (org-set-tags arg just-align)
12947 (save-excursion
12948 (org-back-to-heading t)
12949 (org-set-tags arg just-align))))
12951 (defun org-set-tags-to (data)
12952 "Set the tags of the current entry to DATA, replacing the current tags.
12953 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
12954 If DATA is nil or the empty string, any tags will be removed."
12955 (interactive "sTags: ")
12956 (setq data
12957 (cond
12958 ((eq data nil) "")
12959 ((equal data "") "")
12960 ((stringp data)
12961 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
12962 ":"))
12963 ((listp data)
12964 (concat ":" (mapconcat 'identity data ":") ":"))
12965 (t nil)))
12966 (when data
12967 (save-excursion
12968 (org-back-to-heading t)
12969 (when (looking-at org-complex-heading-regexp)
12970 (if (match-end 5)
12971 (progn
12972 (goto-char (match-beginning 5))
12973 (insert data)
12974 (delete-region (point) (point-at-eol))
12975 (org-set-tags nil 'align))
12976 (goto-char (point-at-eol))
12977 (insert " " data)
12978 (org-set-tags nil 'align)))
12979 (beginning-of-line 1)
12980 (if (looking-at ".*?\\([ \t]+\\)$")
12981 (delete-region (match-beginning 1) (match-end 1))))))
12983 (defun org-align-all-tags ()
12984 "Align the tags i all headings."
12985 (interactive)
12986 (save-excursion
12987 (or (ignore-errors (org-back-to-heading t))
12988 (outline-next-heading))
12989 (if (org-on-heading-p)
12990 (org-set-tags t)
12991 (message "No headings"))))
12993 (defvar org-indent-indentation-per-level)
12994 (defun org-set-tags (&optional arg just-align)
12995 "Set the tags for the current headline.
12996 With prefix ARG, realign all tags in headings in the current buffer."
12997 (interactive "P")
12998 (let* ((re (concat "^" outline-regexp))
12999 (current (org-get-tags-string))
13000 (col (current-column))
13001 (org-setting-tags t)
13002 table current-tags inherited-tags ; computed below when needed
13003 tags p0 c0 c1 rpl di tc level)
13004 (if arg
13005 (save-excursion
13006 (goto-char (point-min))
13007 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13008 (while (re-search-forward re nil t)
13009 (org-set-tags nil t)
13010 (end-of-line 1)))
13011 (message "All tags realigned to column %d" org-tags-column))
13012 (if just-align
13013 (setq tags current)
13014 ;; Get a new set of tags from the user
13015 (save-excursion
13016 (setq table (append org-tag-persistent-alist
13017 (or org-tag-alist (org-get-buffer-tags))
13018 (and
13019 org-complete-tags-always-offer-all-agenda-tags
13020 (org-global-tags-completion-table
13021 (org-agenda-files))))
13022 org-last-tags-completion-table table
13023 current-tags (org-split-string current ":")
13024 inherited-tags (nreverse
13025 (nthcdr (length current-tags)
13026 (nreverse (org-get-tags-at))))
13027 tags
13028 (if (or (eq t org-use-fast-tag-selection)
13029 (and org-use-fast-tag-selection
13030 (delq nil (mapcar 'cdr table))))
13031 (org-fast-tag-selection
13032 current-tags inherited-tags table
13033 (if org-fast-tag-selection-include-todo
13034 org-todo-key-alist))
13035 (let ((org-add-colon-after-tag-completion t))
13036 (org-trim
13037 (org-icompleting-read "Tags: "
13038 'org-tags-completion-function
13039 nil nil current 'org-tags-history))))))
13040 (while (string-match "[-+&]+" tags)
13041 ;; No boolean logic, just a list
13042 (setq tags (replace-match ":" t t tags))))
13044 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13046 (if org-tags-sort-function
13047 (setq tags (mapconcat 'identity
13048 (sort (org-split-string
13049 tags (org-re "[^[:alnum:]_@#%]+"))
13050 org-tags-sort-function) ":")))
13052 (if (string-match "\\`[\t ]*\\'" tags)
13053 (setq tags "")
13054 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13055 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13057 ;; Insert new tags at the correct column
13058 (beginning-of-line 1)
13059 (setq level (or (and (looking-at org-outline-regexp)
13060 (- (match-end 0) (point) 1))
13062 (cond
13063 ((and (equal current "") (equal tags "")))
13064 ((re-search-forward
13065 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13066 (point-at-eol) t)
13067 (if (equal tags "")
13068 (setq rpl "")
13069 (goto-char (match-beginning 0))
13070 (setq c0 (current-column)
13071 ;; compute offset for the case of org-indent-mode active
13072 di (if org-indent-mode
13073 (* (1- org-indent-indentation-per-level) (1- level))
13075 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13076 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13077 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13078 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13079 (replace-match rpl t t)
13080 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13081 tags)
13082 (t (error "Tags alignment failed")))
13083 (org-move-to-column col)
13084 (unless just-align
13085 (run-hooks 'org-after-tags-change-hook)))))
13087 (defun org-change-tag-in-region (beg end tag off)
13088 "Add or remove TAG for each entry in the region.
13089 This works in the agenda, and also in an org-mode buffer."
13090 (interactive
13091 (list (region-beginning) (region-end)
13092 (let ((org-last-tags-completion-table
13093 (if (org-mode-p)
13094 (org-get-buffer-tags)
13095 (org-global-tags-completion-table))))
13096 (org-icompleting-read
13097 "Tag: " 'org-tags-completion-function nil nil nil
13098 'org-tags-history))
13099 (progn
13100 (message "[s]et or [r]emove? ")
13101 (equal (read-char-exclusive) ?r))))
13102 (if (fboundp 'deactivate-mark) (deactivate-mark))
13103 (let ((agendap (equal major-mode 'org-agenda-mode))
13104 l1 l2 m buf pos newhead (cnt 0))
13105 (goto-char end)
13106 (setq l2 (1- (org-current-line)))
13107 (goto-char beg)
13108 (setq l1 (org-current-line))
13109 (loop for l from l1 to l2 do
13110 (org-goto-line l)
13111 (setq m (get-text-property (point) 'org-hd-marker))
13112 (when (or (and (org-mode-p) (org-on-heading-p))
13113 (and agendap m))
13114 (setq buf (if agendap (marker-buffer m) (current-buffer))
13115 pos (if agendap m (point)))
13116 (with-current-buffer buf
13117 (save-excursion
13118 (save-restriction
13119 (goto-char pos)
13120 (setq cnt (1+ cnt))
13121 (org-toggle-tag tag (if off 'off 'on))
13122 (setq newhead (org-get-heading)))))
13123 (and agendap (org-agenda-change-all-lines newhead m))))
13124 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13126 (defun org-tags-completion-function (string predicate &optional flag)
13127 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13128 (confirm (lambda (x) (stringp (car x)))))
13129 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13130 (setq s1 (match-string 1 string)
13131 s2 (match-string 2 string))
13132 (setq s1 "" s2 string))
13133 (cond
13134 ((eq flag nil)
13135 ;; try completion
13136 (setq rtn (try-completion s2 ctable confirm))
13137 (if (stringp rtn)
13138 (setq rtn
13139 (concat s1 s2 (substring rtn (length s2))
13140 (if (and org-add-colon-after-tag-completion
13141 (assoc rtn ctable))
13142 ":" ""))))
13143 rtn)
13144 ((eq flag t)
13145 ;; all-completions
13146 (all-completions s2 ctable confirm)
13148 ((eq flag 'lambda)
13149 ;; exact match?
13150 (assoc s2 ctable)))
13153 (defun org-fast-tag-insert (kwd tags face &optional end)
13154 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13155 (insert (format "%-12s" (concat kwd ":"))
13156 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13157 (or end "")))
13159 (defun org-fast-tag-show-exit (flag)
13160 (save-excursion
13161 (org-goto-line 3)
13162 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13163 (replace-match ""))
13164 (when flag
13165 (end-of-line 1)
13166 (org-move-to-column (- (window-width) 19) t)
13167 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13169 (defun org-set-current-tags-overlay (current prefix)
13170 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13171 (if (featurep 'xemacs)
13172 (org-overlay-display org-tags-overlay (concat prefix s)
13173 'secondary-selection)
13174 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13175 (org-overlay-display org-tags-overlay (concat prefix s)))))
13177 (defvar org-last-tag-selection-key nil)
13178 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13179 "Fast tag selection with single keys.
13180 CURRENT is the current list of tags in the headline, INHERITED is the
13181 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13182 possibly with grouping information. TODO-TABLE is a similar table with
13183 TODO keywords, should these have keys assigned to them.
13184 If the keys are nil, a-z are automatically assigned.
13185 Returns the new tags string, or nil to not change the current settings."
13186 (let* ((fulltable (append table todo-table))
13187 (maxlen (apply 'max (mapcar
13188 (lambda (x)
13189 (if (stringp (car x)) (string-width (car x)) 0))
13190 fulltable)))
13191 (buf (current-buffer))
13192 (expert (eq org-fast-tag-selection-single-key 'expert))
13193 (buffer-tags nil)
13194 (fwidth (+ maxlen 3 1 3))
13195 (ncol (/ (- (window-width) 4) fwidth))
13196 (i-face 'org-done)
13197 (c-face 'org-todo)
13198 tg cnt e c char c1 c2 ntable tbl rtn
13199 ov-start ov-end ov-prefix
13200 (exit-after-next org-fast-tag-selection-single-key)
13201 (done-keywords org-done-keywords)
13202 groups ingroup)
13203 (save-excursion
13204 (beginning-of-line 1)
13205 (if (looking-at
13206 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13207 (setq ov-start (match-beginning 1)
13208 ov-end (match-end 1)
13209 ov-prefix "")
13210 (setq ov-start (1- (point-at-eol))
13211 ov-end (1+ ov-start))
13212 (skip-chars-forward "^\n\r")
13213 (setq ov-prefix
13214 (concat
13215 (buffer-substring (1- (point)) (point))
13216 (if (> (current-column) org-tags-column)
13218 (make-string (- org-tags-column (current-column)) ?\ ))))))
13219 (move-overlay org-tags-overlay ov-start ov-end)
13220 (save-window-excursion
13221 (if expert
13222 (set-buffer (get-buffer-create " *Org tags*"))
13223 (delete-other-windows)
13224 (split-window-vertically)
13225 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13226 (erase-buffer)
13227 (org-set-local 'org-done-keywords done-keywords)
13228 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13229 (org-fast-tag-insert "Current" current c-face "\n\n")
13230 (org-fast-tag-show-exit exit-after-next)
13231 (org-set-current-tags-overlay current ov-prefix)
13232 (setq tbl fulltable char ?a cnt 0)
13233 (while (setq e (pop tbl))
13234 (cond
13235 ((equal (car e) :startgroup)
13236 (push '() groups) (setq ingroup t)
13237 (when (not (= cnt 0))
13238 (setq cnt 0)
13239 (insert "\n"))
13240 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13241 ((equal (car e) :endgroup)
13242 (setq ingroup nil cnt 0)
13243 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13244 ((equal e '(:newline))
13245 (when (not (= cnt 0))
13246 (setq cnt 0)
13247 (insert "\n")
13248 (setq e (car tbl))
13249 (while (equal (car tbl) '(:newline))
13250 (insert "\n")
13251 (setq tbl (cdr tbl)))))
13253 (setq tg (copy-sequence (car e)) c2 nil)
13254 (if (cdr e)
13255 (setq c (cdr e))
13256 ;; automatically assign a character.
13257 (setq c1 (string-to-char
13258 (downcase (substring
13259 tg (if (= (string-to-char tg) ?@) 1 0)))))
13260 (if (or (rassoc c1 ntable) (rassoc c1 table))
13261 (while (or (rassoc char ntable) (rassoc char table))
13262 (setq char (1+ char)))
13263 (setq c2 c1))
13264 (setq c (or c2 char)))
13265 (if ingroup (push tg (car groups)))
13266 (setq tg (org-add-props tg nil 'face
13267 (cond
13268 ((not (assoc tg table))
13269 (org-get-todo-face tg))
13270 ((member tg current) c-face)
13271 ((member tg inherited) i-face)
13272 (t nil))))
13273 (if (and (= cnt 0) (not ingroup)) (insert " "))
13274 (insert "[" c "] " tg (make-string
13275 (- fwidth 4 (length tg)) ?\ ))
13276 (push (cons tg c) ntable)
13277 (when (= (setq cnt (1+ cnt)) ncol)
13278 (insert "\n")
13279 (if ingroup (insert " "))
13280 (setq cnt 0)))))
13281 (setq ntable (nreverse ntable))
13282 (insert "\n")
13283 (goto-char (point-min))
13284 (if (not expert) (org-fit-window-to-buffer))
13285 (setq rtn
13286 (catch 'exit
13287 (while t
13288 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13289 (if (not groups) "no " "")
13290 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13291 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13292 (setq org-last-tag-selection-key c)
13293 (cond
13294 ((= c ?\r) (throw 'exit t))
13295 ((= c ?!)
13296 (setq groups (not groups))
13297 (goto-char (point-min))
13298 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13299 ((= c ?\C-c)
13300 (if (not expert)
13301 (org-fast-tag-show-exit
13302 (setq exit-after-next (not exit-after-next)))
13303 (setq expert nil)
13304 (delete-other-windows)
13305 (set-window-buffer (split-window-vertically) " *Org tags*")
13306 (org-switch-to-buffer-other-window " *Org tags*")
13307 (org-fit-window-to-buffer)))
13308 ((or (= c ?\C-g)
13309 (and (= c ?q) (not (rassoc c ntable))))
13310 (org-detach-overlay org-tags-overlay)
13311 (setq quit-flag t))
13312 ((= c ?\ )
13313 (setq current nil)
13314 (if exit-after-next (setq exit-after-next 'now)))
13315 ((= c ?\t)
13316 (condition-case nil
13317 (setq tg (org-icompleting-read
13318 "Tag: "
13319 (or buffer-tags
13320 (with-current-buffer buf
13321 (org-get-buffer-tags)))))
13322 (quit (setq tg "")))
13323 (when (string-match "\\S-" tg)
13324 (add-to-list 'buffer-tags (list tg))
13325 (if (member tg current)
13326 (setq current (delete tg current))
13327 (push tg current)))
13328 (if exit-after-next (setq exit-after-next 'now)))
13329 ((setq e (rassoc c todo-table) tg (car e))
13330 (with-current-buffer buf
13331 (save-excursion (org-todo tg)))
13332 (if exit-after-next (setq exit-after-next 'now)))
13333 ((setq e (rassoc c ntable) tg (car e))
13334 (if (member tg current)
13335 (setq current (delete tg current))
13336 (loop for g in groups do
13337 (if (member tg g)
13338 (mapc (lambda (x)
13339 (setq current (delete x current)))
13340 g)))
13341 (push tg current))
13342 (if exit-after-next (setq exit-after-next 'now))))
13344 ;; Create a sorted list
13345 (setq current
13346 (sort current
13347 (lambda (a b)
13348 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13349 (if (eq exit-after-next 'now) (throw 'exit t))
13350 (goto-char (point-min))
13351 (beginning-of-line 2)
13352 (delete-region (point) (point-at-eol))
13353 (org-fast-tag-insert "Current" current c-face)
13354 (org-set-current-tags-overlay current ov-prefix)
13355 (while (re-search-forward
13356 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13357 (setq tg (match-string 1))
13358 (add-text-properties
13359 (match-beginning 1) (match-end 1)
13360 (list 'face
13361 (cond
13362 ((member tg current) c-face)
13363 ((member tg inherited) i-face)
13364 (t (get-text-property (match-beginning 1) 'face))))))
13365 (goto-char (point-min)))))
13366 (org-detach-overlay org-tags-overlay)
13367 (if rtn
13368 (mapconcat 'identity current ":")
13369 nil))))
13371 (defun org-get-tags-string ()
13372 "Get the TAGS string in the current headline."
13373 (unless (org-on-heading-p t)
13374 (error "Not on a heading"))
13375 (save-excursion
13376 (beginning-of-line 1)
13377 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13378 (org-match-string-no-properties 1)
13379 "")))
13381 (defun org-get-tags ()
13382 "Get the list of tags specified in the current headline."
13383 (org-split-string (org-get-tags-string) ":"))
13385 (defun org-get-buffer-tags ()
13386 "Get a table of all tags used in the buffer, for completion."
13387 (let (tags)
13388 (save-excursion
13389 (goto-char (point-min))
13390 (while (re-search-forward
13391 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13392 (when (equal (char-after (point-at-bol 0)) ?*)
13393 (mapc (lambda (x) (add-to-list 'tags x))
13394 (org-split-string (org-match-string-no-properties 1) ":")))))
13395 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13396 (mapcar 'list tags)))
13398 ;;;; The mapping API
13400 ;;;###autoload
13401 (defun org-map-entries (func &optional match scope &rest skip)
13402 "Call FUNC at each headline selected by MATCH in SCOPE.
13404 FUNC is a function or a lisp form. The function will be called without
13405 arguments, with the cursor positioned at the beginning of the headline.
13406 The return values of all calls to the function will be collected and
13407 returned as a list.
13409 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13410 does not need to preserve point. After evaluation, the cursor will be
13411 moved to the end of the line (presumably of the headline of the
13412 processed entry) and search continues from there. Under some
13413 circumstances, this may not produce the wanted results. For example,
13414 if you have removed (e.g. archived) the current (sub)tree it could
13415 mean that the next entry will be skipped entirely. In such cases, you
13416 can specify the position from where search should continue by making
13417 FUNC set the variable `org-map-continue-from' to the desired buffer
13418 position.
13420 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13421 Only headlines that are matched by this query will be considered during
13422 the iteration. When MATCH is nil or t, all headlines will be
13423 visited by the iteration.
13425 SCOPE determines the scope of this command. It can be any of:
13427 nil The current buffer, respecting the restriction if any
13428 tree The subtree started with the entry at point
13429 file The current buffer, without restriction
13430 file-with-archives
13431 The current buffer, and any archives associated with it
13432 agenda All agenda files
13433 agenda-with-archives
13434 All agenda files with any archive files associated with them
13435 \(file1 file2 ...)
13436 If this is a list, all files in the list will be scanned
13438 The remaining args are treated as settings for the skipping facilities of
13439 the scanner. The following items can be given here:
13441 archive skip trees with the archive tag.
13442 comment skip trees with the COMMENT keyword
13443 function or Emacs Lisp form:
13444 will be used as value for `org-agenda-skip-function', so whenever
13445 the function returns t, FUNC will not be called for that
13446 entry and search will continue from the point where the
13447 function leaves it.
13449 If your function needs to retrieve the tags including inherited tags
13450 at the *current* entry, you can use the value of the variable
13451 `org-scanner-tags' which will be much faster than getting the value
13452 with `org-get-tags-at'. If your function gets properties with
13453 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13454 to t around the call to `org-entry-properties' to get the same speedup.
13455 Note that if your function moves around to retrieve tags and properties at
13456 a *different* entry, you cannot use these techniques."
13457 (let* ((org-agenda-archives-mode nil) ; just to make sure
13458 (org-agenda-skip-archived-trees (memq 'archive skip))
13459 (org-agenda-skip-comment-trees (memq 'comment skip))
13460 (org-agenda-skip-function
13461 (car (org-delete-all '(comment archive) skip)))
13462 (org-tags-match-list-sublevels t)
13463 matcher file res
13464 org-todo-keywords-for-agenda
13465 org-done-keywords-for-agenda
13466 org-todo-keyword-alist-for-agenda
13467 org-drawers-for-agenda
13468 org-tag-alist-for-agenda)
13470 (cond
13471 ((eq match t) (setq matcher t))
13472 ((eq match nil) (setq matcher t))
13473 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13475 (save-excursion
13476 (save-restriction
13477 (when (eq scope 'tree)
13478 (org-back-to-heading t)
13479 (org-narrow-to-subtree)
13480 (setq scope nil))
13482 (if (not scope)
13483 (progn
13484 (org-prepare-agenda-buffers
13485 (list (buffer-file-name (current-buffer))))
13486 (setq res (org-scan-tags func matcher)))
13487 ;; Get the right scope
13488 (cond
13489 ((and scope (listp scope) (symbolp (car scope)))
13490 (setq scope (eval scope)))
13491 ((eq scope 'agenda)
13492 (setq scope (org-agenda-files t)))
13493 ((eq scope 'agenda-with-archives)
13494 (setq scope (org-agenda-files t))
13495 (setq scope (org-add-archive-files scope)))
13496 ((eq scope 'file)
13497 (setq scope (list (buffer-file-name))))
13498 ((eq scope 'file-with-archives)
13499 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13500 (org-prepare-agenda-buffers scope)
13501 (while (setq file (pop scope))
13502 (with-current-buffer (org-find-base-buffer-visiting file)
13503 (save-excursion
13504 (save-restriction
13505 (widen)
13506 (goto-char (point-min))
13507 (setq res (append res (org-scan-tags func matcher))))))))))
13508 res))
13510 ;;;; Properties
13512 ;;; Setting and retrieving properties
13514 (defconst org-special-properties
13515 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13516 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13517 "The special properties valid in Org-mode.
13519 These are properties that are not defined in the property drawer,
13520 but in some other way.")
13522 (defconst org-default-properties
13523 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13524 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13525 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13526 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13527 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13528 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13529 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13530 "Some properties that are used by Org-mode for various purposes.
13531 Being in this list makes sure that they are offered for completion.")
13533 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13534 "Regular expression matching the first line of a property drawer.")
13536 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13537 "Regular expression matching the last line of a property drawer.")
13539 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13540 "Regular expression matching the first line of a property drawer.")
13542 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13543 "Regular expression matching the first line of a property drawer.")
13545 (defconst org-property-drawer-re
13546 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13547 org-property-end-re "\\)\n?")
13548 "Matches an entire property drawer.")
13550 (defconst org-clock-drawer-re
13551 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13552 org-property-end-re "\\)\n?")
13553 "Matches an entire clock drawer.")
13555 (defsubst org-re-property (property)
13556 "Return a regexp matching PROPERTY.
13557 Match group 1 will be set to the value "
13558 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
13560 (defun org-property-action ()
13561 "Do an action on properties."
13562 (interactive)
13563 (let (c)
13564 (org-at-property-p)
13565 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13566 (setq c (read-char-exclusive))
13567 (cond
13568 ((equal c ?s)
13569 (call-interactively 'org-set-property))
13570 ((equal c ?d)
13571 (call-interactively 'org-delete-property))
13572 ((equal c ?D)
13573 (call-interactively 'org-delete-property-globally))
13574 ((equal c ?c)
13575 (call-interactively 'org-compute-property-at-point))
13576 (t (error "No such property action %c" c)))))
13578 (defun org-set-effort (&optional value)
13579 "Set the effort property of the current entry.
13580 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13581 allowed value."
13582 (interactive "P")
13583 (if (equal value 0) (setq value 10))
13584 (let* ((completion-ignore-case t)
13585 (prop org-effort-property)
13586 (cur (org-entry-get nil prop))
13587 (allowed (org-property-get-allowed-values nil prop 'table))
13588 (existing (mapcar 'list (org-property-values prop)))
13590 (val (cond
13591 ((stringp value) value)
13592 ((and allowed (integerp value))
13593 (or (car (nth (1- value) allowed))
13594 (car (org-last allowed))))
13595 (allowed
13596 (message "Select 1-9,0, [RET%s]: %s"
13597 (if cur (concat "=" cur) "")
13598 (mapconcat 'car allowed " "))
13599 (setq rpl (read-char-exclusive))
13600 (if (equal rpl ?\r)
13602 (setq rpl (- rpl ?0))
13603 (if (equal rpl 0) (setq rpl 10))
13604 (if (and (> rpl 0) (<= rpl (length allowed)))
13605 (car (nth (1- rpl) allowed))
13606 (org-completing-read "Effort: " allowed nil))))
13608 (let (org-completion-use-ido org-completion-use-iswitchb)
13609 (org-completing-read
13610 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13611 (concat "[" cur "]") "")
13612 ": ")
13613 existing nil nil "" nil cur))))))
13614 (unless (equal (org-entry-get nil prop) val)
13615 (org-entry-put nil prop val))
13616 (message "%s is now %s" prop val)))
13618 (defun org-at-property-p ()
13619 "Is cursor inside a property drawer?"
13620 (save-excursion
13621 (beginning-of-line 1)
13622 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13623 (save-match-data ;; Used by calling procedures
13624 (let ((p (point))
13625 (range (unless (org-before-first-heading-p)
13626 (org-get-property-block))))
13627 (and range (<= (car range) p) (< p (cdr range))))))))
13629 (defun org-get-property-block (&optional beg end force)
13630 "Return the (beg . end) range of the body of the property drawer.
13631 BEG and END can be beginning and end of subtree, if not given
13632 they will be found.
13633 If the drawer does not exist and FORCE is non-nil, create the drawer."
13634 (catch 'exit
13635 (save-excursion
13636 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13637 (end (or end (progn (outline-next-heading) (point)))))
13638 (goto-char beg)
13639 (if (re-search-forward org-property-start-re end t)
13640 (setq beg (1+ (match-end 0)))
13641 (if force
13642 (save-excursion
13643 (org-insert-property-drawer)
13644 (setq end (progn (outline-next-heading) (point))))
13645 (throw 'exit nil))
13646 (goto-char beg)
13647 (if (re-search-forward org-property-start-re end t)
13648 (setq beg (1+ (match-end 0)))))
13649 (if (re-search-forward org-property-end-re end t)
13650 (setq end (match-beginning 0))
13651 (or force (throw 'exit nil))
13652 (goto-char beg)
13653 (setq end beg)
13654 (org-indent-line-function)
13655 (insert ":END:\n"))
13656 (cons beg end)))))
13658 (defun org-entry-properties (&optional pom which specific)
13659 "Get all properties of the entry at point-or-marker POM.
13660 This includes the TODO keyword, the tags, time strings for deadline,
13661 scheduled, and clocking, and any additional properties defined in the
13662 entry. The return value is an alist, keys may occur multiple times
13663 if the property key was used several times.
13664 POM may also be nil, in which case the current entry is used.
13665 If WHICH is nil or `all', get all properties. If WHICH is
13666 `special' or `standard', only get that subclass. If WHICH
13667 is a string only get exactly this property. SPECIFIC can be a string, the
13668 specific property we are interested in. Specifying it can speed
13669 things up because then unnecessary parsing is avoided."
13670 (setq which (or which 'all))
13671 (org-with-point-at pom
13672 (let ((clockstr (substring org-clock-string 0 -1))
13673 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13674 (case-fold-search nil)
13675 beg end range props sum-props key key1 value string clocksum)
13676 (save-excursion
13677 (when (condition-case nil
13678 (and (org-mode-p) (org-back-to-heading t))
13679 (error nil))
13680 (setq beg (point))
13681 (setq sum-props (get-text-property (point) 'org-summaries))
13682 (setq clocksum (get-text-property (point) :org-clock-minutes))
13683 (outline-next-heading)
13684 (setq end (point))
13685 (when (memq which '(all special))
13686 ;; Get the special properties, like TODO and tags
13687 (goto-char beg)
13688 (when (and (or (not specific) (string= specific "TODO"))
13689 (looking-at org-todo-line-regexp) (match-end 2))
13690 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13691 (when (and (or (not specific) (string= specific "PRIORITY"))
13692 (looking-at org-priority-regexp))
13693 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13694 (when (or (not specific) (string= specific "FILE"))
13695 (push (cons "FILE" buffer-file-name) props))
13696 (when (and (or (not specific) (string= specific "TAGS"))
13697 (setq value (org-get-tags-string))
13698 (string-match "\\S-" value))
13699 (push (cons "TAGS" value) props))
13700 (when (and (or (not specific) (string= specific "ALLTAGS"))
13701 (setq value (org-get-tags-at)))
13702 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
13703 ":"))
13704 props))
13705 (when (or (not specific) (string= specific "BLOCKED"))
13706 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
13707 (when (or (not specific)
13708 (member specific
13709 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
13710 "TIMESTAMP" "TIMESTAMP_IA")))
13711 (catch 'match
13712 (while (re-search-forward org-maybe-keyword-time-regexp end t)
13713 (setq key (if (match-end 1)
13714 (substring (org-match-string-no-properties 1)
13715 0 -1))
13716 string (if (equal key clockstr)
13717 (org-no-properties
13718 (org-trim
13719 (buffer-substring
13720 (match-beginning 3) (goto-char
13721 (point-at-eol)))))
13722 (substring (org-match-string-no-properties 3)
13723 1 -1)))
13724 ;; Get the correct property name from the key. This is
13725 ;; necessary if the user has configured time keywords.
13726 (setq key1 (concat key ":"))
13727 (cond
13728 ((not key)
13729 (setq key
13730 (if (= (char-after (match-beginning 3)) ?\[)
13731 "TIMESTAMP_IA" "TIMESTAMP")))
13732 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
13733 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
13734 ((equal key1 org-closed-string) (setq key "CLOSED"))
13735 ((equal key1 org-clock-string) (setq key "CLOCK")))
13736 (if (and specific (equal key specific) (not (equal key "CLOCK")))
13737 (progn
13738 (push (cons key string) props)
13739 ;; no need to search further if match is found
13740 (throw 'match t))
13741 (when (or (equal key "CLOCK") (not (assoc key props)))
13742 (push (cons key string) props))))))
13745 (when (memq which '(all standard))
13746 ;; Get the standard properties, like :PROP: ...
13747 (setq range (org-get-property-block beg end))
13748 (when range
13749 (goto-char (car range))
13750 (while (re-search-forward
13751 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
13752 (cdr range) t)
13753 (setq key (org-match-string-no-properties 1)
13754 value (org-trim (or (org-match-string-no-properties 2) "")))
13755 (unless (member key excluded)
13756 (push (cons key (or value "")) props)))))
13757 (if clocksum
13758 (push (cons "CLOCKSUM"
13759 (org-columns-number-to-string (/ (float clocksum) 60.)
13760 'add_times))
13761 props))
13762 (unless (assoc "CATEGORY" props)
13763 (push (cons "CATEGORY" (org-get-category)) props))
13764 (append sum-props (nreverse props)))))))
13766 (defun org-entry-get (pom property &optional inherit literal-nil)
13767 "Get value of PROPERTY for entry at point-or-marker POM.
13768 If INHERIT is non-nil and the entry does not have the property,
13769 then also check higher levels of the hierarchy.
13770 If INHERIT is the symbol `selective', use inheritance only if the setting
13771 in `org-use-property-inheritance' selects PROPERTY for inheritance.
13772 If the property is present but empty, the return value is the empty string.
13773 If the property is not present at all, nil is returned.
13775 If LITERAL-NIL is set, return the string value \"nil\" as a string,
13776 do not interpret it as the list atom nil. This is used for inheritance
13777 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
13778 (org-with-point-at pom
13779 (if (and inherit (if (eq inherit 'selective)
13780 (org-property-inherit-p property)
13782 (org-entry-get-with-inheritance property literal-nil)
13783 (if (member property org-special-properties)
13784 ;; We need a special property. Use `org-entry-properties' to
13785 ;; retrieve it, but specify the wanted property
13786 (cdr (assoc property (org-entry-properties nil 'special property)))
13787 (let ((range (unless (org-before-first-heading-p)
13788 (org-get-property-block))))
13789 (if (and range
13790 (goto-char (car range))
13791 (re-search-forward
13792 (org-re-property property)
13793 (cdr range) t))
13794 ;; Found the property, return it.
13795 (if (match-end 1)
13796 (if literal-nil
13797 (org-match-string-no-properties 1)
13798 (org-not-nil (org-match-string-no-properties 1)))
13799 "")))))))
13801 (defun org-property-or-variable-value (var &optional inherit)
13802 "Check if there is a property fixing the value of VAR.
13803 If yes, return this value. If not, return the current value of the variable."
13804 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13805 (if (and prop (stringp prop) (string-match "\\S-" prop))
13806 (read prop)
13807 (symbol-value var))))
13809 (defun org-entry-delete (pom property)
13810 "Delete the property PROPERTY from entry at point-or-marker POM."
13811 (org-with-point-at pom
13812 (if (member property org-special-properties)
13813 nil ; cannot delete these properties.
13814 (let ((range (org-get-property-block)))
13815 (if (and range
13816 (goto-char (car range))
13817 (re-search-forward
13818 (org-re-property property)
13819 (cdr range) t))
13820 (progn
13821 (delete-region (match-beginning 0) (1+ (point-at-eol)))
13823 nil)))))
13825 ;; Multi-values properties are properties that contain multiple values
13826 ;; These values are assumed to be single words, separated by whitespace.
13827 (defun org-entry-add-to-multivalued-property (pom property value)
13828 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
13829 (let* ((old (org-entry-get pom property))
13830 (values (and old (org-split-string old "[ \t]"))))
13831 (setq value (org-entry-protect-space value))
13832 (unless (member value values)
13833 (setq values (cons value values))
13834 (org-entry-put pom property
13835 (mapconcat 'identity values " ")))))
13837 (defun org-entry-remove-from-multivalued-property (pom property value)
13838 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
13839 (let* ((old (org-entry-get pom property))
13840 (values (and old (org-split-string old "[ \t]"))))
13841 (setq value (org-entry-protect-space value))
13842 (when (member value values)
13843 (setq values (delete value values))
13844 (org-entry-put pom property
13845 (mapconcat 'identity values " ")))))
13847 (defun org-entry-member-in-multivalued-property (pom property value)
13848 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
13849 (let* ((old (org-entry-get pom property))
13850 (values (and old (org-split-string old "[ \t]"))))
13851 (setq value (org-entry-protect-space value))
13852 (member value values)))
13854 (defun org-entry-get-multivalued-property (pom property)
13855 "Return a list of values in a multivalued property."
13856 (let* ((value (org-entry-get pom property))
13857 (values (and value (org-split-string value "[ \t]"))))
13858 (mapcar 'org-entry-restore-space values)))
13860 (defun org-entry-put-multivalued-property (pom property &rest values)
13861 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
13862 VALUES should be a list of strings. Spaces will be protected."
13863 (org-entry-put pom property
13864 (mapconcat 'org-entry-protect-space values " "))
13865 (let* ((value (org-entry-get pom property))
13866 (values (and value (org-split-string value "[ \t]"))))
13867 (mapcar 'org-entry-restore-space values)))
13869 (defun org-entry-protect-space (s)
13870 "Protect spaces and newline in string S."
13871 (while (string-match " " s)
13872 (setq s (replace-match "%20" t t s)))
13873 (while (string-match "\n" s)
13874 (setq s (replace-match "%0A" t t s)))
13877 (defun org-entry-restore-space (s)
13878 "Restore spaces and newline in string S."
13879 (while (string-match "%20" s)
13880 (setq s (replace-match " " t t s)))
13881 (while (string-match "%0A" s)
13882 (setq s (replace-match "\n" t t s)))
13885 (defvar org-entry-property-inherited-from (make-marker)
13886 "Marker pointing to the entry from where a property was inherited.
13887 Each call to `org-entry-get-with-inheritance' will set this marker to the
13888 location of the entry where the inheritance search matched. If there was
13889 no match, the marker will point nowhere.
13890 Note that also `org-entry-get' calls this function, if the INHERIT flag
13891 is set.")
13893 (defun org-entry-get-with-inheritance (property &optional literal-nil)
13894 "Get entry property, and search higher levels if not present.
13895 The search will stop at the first ancestor which has the property defined.
13896 If the value found is \"nil\", return nil to show that the property
13897 should be considered as undefined (this is the meaning of nil here).
13898 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
13899 (move-marker org-entry-property-inherited-from nil)
13900 (let (tmp)
13901 (unless (org-before-first-heading-p)
13902 (save-excursion
13903 (save-restriction
13904 (widen)
13905 (catch 'ex
13906 (while t
13907 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
13908 (org-back-to-heading t)
13909 (move-marker org-entry-property-inherited-from (point))
13910 (throw 'ex tmp))
13911 (or (org-up-heading-safe) (throw 'ex nil)))))))
13912 (setq tmp (or tmp
13913 (cdr (assoc property org-file-properties))
13914 (cdr (assoc property org-global-properties))
13915 (cdr (assoc property org-global-properties-fixed))))
13916 (if literal-nil tmp (org-not-nil tmp))))
13918 (defvar org-property-changed-functions nil
13919 "Hook called when the value of a property has changed.
13920 Each hook function should accept two arguments, the name of the property
13921 and the new value.")
13923 (defun org-entry-put (pom property value)
13924 "Set PROPERTY to VALUE for entry at point-or-marker POM."
13925 (org-with-point-at pom
13926 (org-back-to-heading t)
13927 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
13928 range)
13929 (cond
13930 ((equal property "TODO")
13931 (when (and (stringp value) (string-match "\\S-" value)
13932 (not (member value org-todo-keywords-1)))
13933 (error "\"%s\" is not a valid TODO state" value))
13934 (if (or (not value)
13935 (not (string-match "\\S-" value)))
13936 (setq value 'none))
13937 (org-todo value)
13938 (org-set-tags nil 'align))
13939 ((equal property "PRIORITY")
13940 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
13941 (string-to-char value) ?\ ))
13942 (org-set-tags nil 'align))
13943 ((equal property "SCHEDULED")
13944 (if (re-search-forward org-scheduled-time-regexp end t)
13945 (cond
13946 ((eq value 'earlier) (org-timestamp-change -1 'day))
13947 ((eq value 'later) (org-timestamp-change 1 'day))
13948 (t (call-interactively 'org-schedule)))
13949 (call-interactively 'org-schedule)))
13950 ((equal property "DEADLINE")
13951 (if (re-search-forward org-deadline-time-regexp end t)
13952 (cond
13953 ((eq value 'earlier) (org-timestamp-change -1 'day))
13954 ((eq value 'later) (org-timestamp-change 1 'day))
13955 (t (call-interactively 'org-deadline)))
13956 (call-interactively 'org-deadline)))
13957 ((member property org-special-properties)
13958 (error "The %s property can not yet be set with `org-entry-put'"
13959 property))
13960 (t ; a non-special property
13961 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
13962 (setq range (org-get-property-block beg end 'force))
13963 (goto-char (car range))
13964 (if (re-search-forward
13965 (org-re-property property) (cdr range) t)
13966 (progn
13967 (delete-region (match-beginning 0) (match-end 0))
13968 (goto-char (match-beginning 0)))
13969 (goto-char (cdr range))
13970 (insert "\n")
13971 (backward-char 1)
13972 (org-indent-line-function))
13973 (insert ":" property ":")
13974 (and value (insert " " value))
13975 (org-indent-line-function)))))
13976 (run-hook-with-args 'org-property-changed-functions property value)))
13978 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
13979 "Get all property keys in the current buffer.
13980 With INCLUDE-SPECIALS, also list the special properties that reflect things
13981 like tags and TODO state.
13982 With INCLUDE-DEFAULTS, also include properties that has special meaning
13983 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
13984 and others.
13985 With INCLUDE-COLUMNS, also include property names given in COLUMN
13986 formats in the current buffer."
13987 (let (rtn range cfmt s p)
13988 (save-excursion
13989 (save-restriction
13990 (widen)
13991 (goto-char (point-min))
13992 (while (re-search-forward org-property-start-re nil t)
13993 (setq range (org-get-property-block))
13994 (goto-char (car range))
13995 (while (re-search-forward
13996 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
13997 (cdr range) t)
13998 (add-to-list 'rtn (org-match-string-no-properties 1)))
13999 (outline-next-heading))))
14001 (when include-specials
14002 (setq rtn (append org-special-properties rtn)))
14004 (when include-defaults
14005 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14006 (add-to-list 'rtn org-effort-property))
14008 (when include-columns
14009 (save-excursion
14010 (save-restriction
14011 (widen)
14012 (goto-char (point-min))
14013 (while (re-search-forward
14014 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14015 nil t)
14016 (setq cfmt (match-string 2) s 0)
14017 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14018 cfmt s)
14019 (setq s (match-end 0)
14020 p (match-string 1 cfmt))
14021 (unless (or (equal p "ITEM")
14022 (member p org-special-properties))
14023 (add-to-list 'rtn (match-string 1 cfmt))))))))
14025 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14027 (defun org-property-values (key)
14028 "Return a list of all values of property KEY in the current buffer."
14029 (save-excursion
14030 (save-restriction
14031 (widen)
14032 (goto-char (point-min))
14033 (let ((re (org-re-property key))
14034 values)
14035 (while (re-search-forward re nil t)
14036 (add-to-list 'values (org-trim (match-string 1))))
14037 (delete "" values)))))
14039 (defun org-insert-property-drawer ()
14040 "Insert a property drawer into the current entry."
14041 (interactive)
14042 (org-back-to-heading t)
14043 (looking-at outline-regexp)
14044 (let ((indent (if org-adapt-indentation
14045 (- (match-end 0)(match-beginning 0))
14047 (beg (point))
14048 (re (concat "^[ \t]*" org-keyword-time-regexp))
14049 end hiddenp)
14050 (outline-next-heading)
14051 (setq end (point))
14052 (goto-char beg)
14053 (while (re-search-forward re end t))
14054 (setq hiddenp (outline-invisible-p))
14055 (end-of-line 1)
14056 (and (equal (char-after) ?\n) (forward-char 1))
14057 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14058 (if (member (match-string 1) '("CLOCK:" ":END:"))
14059 ;; just skip this line
14060 (beginning-of-line 2)
14061 ;; Drawer start, find the end
14062 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14063 (beginning-of-line 1)))
14064 (org-skip-over-state-notes)
14065 (skip-chars-backward " \t\n\r")
14066 (if (eq (char-before) ?*) (forward-char 1))
14067 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14068 (beginning-of-line 0)
14069 (org-indent-to-column indent)
14070 (beginning-of-line 2)
14071 (org-indent-to-column indent)
14072 (beginning-of-line 0)
14073 (if hiddenp
14074 (save-excursion
14075 (org-back-to-heading t)
14076 (hide-entry))
14077 (org-flag-drawer t))))
14079 (defvar org-property-set-functions-alist nil
14080 "Property set function alist.
14081 Each entry should have the following format:
14083 (PROPERTY . READ-FUNCTION)
14085 The read function will be called with the same argument as
14086 `org-completing-read'.")
14088 (defun org-set-property-function (property)
14089 "Get the function that should be used to set PROPERTY.
14090 This is computed according to `org-property-set-functions-alist'."
14091 (or (cdr (assoc property org-property-set-functions-alist))
14092 'org-completing-read))
14094 (defun org-read-property-value (property)
14095 "Read PROPERTY value from user."
14096 (let* ((completion-ignore-case t)
14097 (allowed (org-property-get-allowed-values nil property 'table))
14098 (cur (org-entry-get nil property))
14099 (prompt (concat property " value"
14100 (if (and cur (string-match "\\S-" cur))
14101 (concat " [" cur "]") "") ": "))
14102 (set-function (org-set-property-function property))
14103 (val (if allowed
14104 (funcall set-function prompt allowed nil
14105 (not (get-text-property 0 'org-unrestricted
14106 (caar allowed))))
14107 (let (org-completion-use-ido org-completion-use-iswitchb)
14108 (funcall set-function prompt
14109 (mapcar 'list (org-property-values property))
14110 nil nil "" nil cur)))))
14111 (if (equal val "")
14113 val)))
14115 (defun org-read-property-name ()
14116 "Read a property name."
14117 (let* ((completion-ignore-case t)
14118 (keys (org-buffer-property-keys nil t t))
14119 (default-prop (save-excursion
14120 (save-match-data
14121 (beginning-of-line)
14122 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14123 (null (string= (match-string 1) "END"))
14124 (match-string 1)))))
14125 (property (org-icompleting-read
14126 (concat "Property"
14127 (if default-prop (concat " [" default-prop "]") "")
14128 ": ")
14129 (mapcar 'list keys)
14130 nil nil nil nil
14131 default-prop
14133 (if (member property keys)
14134 property
14135 (or (cdr (assoc (downcase property)
14136 (mapcar (lambda (x) (cons (downcase x) x))
14137 keys)))
14138 property))))
14140 (defun org-set-property (property value)
14141 "In the current entry, set PROPERTY to VALUE.
14142 When called interactively, this will prompt for a property name, offering
14143 completion on existing and default properties. And then it will prompt
14144 for a value, offering completion either on allowed values (via an inherited
14145 xxx_ALL property) or on existing values in other instances of this property
14146 in the current file."
14147 (interactive (list nil nil))
14148 (let* ((property (or property (org-read-property-name)))
14149 (value (or value (org-read-property-value property))))
14150 (unless (equal (org-entry-get nil property) value)
14151 (org-entry-put nil property value))))
14153 (defun org-delete-property (property)
14154 "In the current entry, delete PROPERTY."
14155 (interactive
14156 (let* ((completion-ignore-case t)
14157 (prop (org-icompleting-read "Property: "
14158 (org-entry-properties nil 'standard))))
14159 (list prop)))
14160 (message "Property %s %s" property
14161 (if (org-entry-delete nil property)
14162 "deleted"
14163 "was not present in the entry")))
14165 (defun org-delete-property-globally (property)
14166 "Remove PROPERTY globally, from all entries."
14167 (interactive
14168 (let* ((completion-ignore-case t)
14169 (prop (org-icompleting-read
14170 "Globally remove property: "
14171 (mapcar 'list (org-buffer-property-keys)))))
14172 (list prop)))
14173 (save-excursion
14174 (save-restriction
14175 (widen)
14176 (goto-char (point-min))
14177 (let ((cnt 0))
14178 (while (re-search-forward
14179 (org-re-property property)
14180 nil t)
14181 (setq cnt (1+ cnt))
14182 (replace-match ""))
14183 (message "Property \"%s\" removed from %d entries" property cnt)))))
14185 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14187 (defun org-compute-property-at-point ()
14188 "Compute the property at point.
14189 This looks for an enclosing column format, extracts the operator and
14190 then applies it to the property in the column format's scope."
14191 (interactive)
14192 (unless (org-at-property-p)
14193 (error "Not at a property"))
14194 (let ((prop (org-match-string-no-properties 2)))
14195 (org-columns-get-format-and-top-level)
14196 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14197 (error "No operator defined for property %s" prop))
14198 (org-columns-compute prop)))
14200 (defvar org-property-allowed-value-functions nil
14201 "Hook for functions supplying allowed values for a specific property.
14202 The functions must take a single argument, the name of the property, and
14203 return a flat list of allowed values. If \":ETC\" is one of
14204 the values, this means that these values are intended as defaults for
14205 completion, but that other values should be allowed too.
14206 The functions must return nil if they are not responsible for this
14207 property.")
14209 (defun org-property-get-allowed-values (pom property &optional table)
14210 "Get allowed values for the property PROPERTY.
14211 When TABLE is non-nil, return an alist that can directly be used for
14212 completion."
14213 (let (vals)
14214 (cond
14215 ((equal property "TODO")
14216 (setq vals (org-with-point-at pom
14217 (append org-todo-keywords-1 '("")))))
14218 ((equal property "PRIORITY")
14219 (let ((n org-lowest-priority))
14220 (while (>= n org-highest-priority)
14221 (push (char-to-string n) vals)
14222 (setq n (1- n)))))
14223 ((member property org-special-properties))
14224 ((setq vals (run-hook-with-args-until-success
14225 'org-property-allowed-value-functions property)))
14227 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14228 (when (and vals (string-match "\\S-" vals))
14229 (setq vals (car (read-from-string (concat "(" vals ")"))))
14230 (setq vals (mapcar (lambda (x)
14231 (cond ((stringp x) x)
14232 ((numberp x) (number-to-string x))
14233 ((symbolp x) (symbol-name x))
14234 (t "???")))
14235 vals)))))
14236 (when (member ":ETC" vals)
14237 (setq vals (remove ":ETC" vals))
14238 (org-add-props (car vals) '(org-unrestricted t)))
14239 (if table (mapcar 'list vals) vals)))
14241 (defun org-property-previous-allowed-value (&optional previous)
14242 "Switch to the next allowed value for this property."
14243 (interactive)
14244 (org-property-next-allowed-value t))
14246 (defun org-property-next-allowed-value (&optional previous)
14247 "Switch to the next allowed value for this property."
14248 (interactive)
14249 (unless (org-at-property-p)
14250 (error "Not at a property"))
14251 (let* ((key (match-string 2))
14252 (value (match-string 3))
14253 (allowed (or (org-property-get-allowed-values (point) key)
14254 (and (member value '("[ ]" "[-]" "[X]"))
14255 '("[ ]" "[X]"))))
14256 nval)
14257 (unless allowed
14258 (error "Allowed values for this property have not been defined"))
14259 (if previous (setq allowed (reverse allowed)))
14260 (if (member value allowed)
14261 (setq nval (car (cdr (member value allowed)))))
14262 (setq nval (or nval (car allowed)))
14263 (if (equal nval value)
14264 (error "Only one allowed value for this property"))
14265 (org-at-property-p)
14266 (replace-match (concat " :" key ": " nval) t t)
14267 (org-indent-line-function)
14268 (beginning-of-line 1)
14269 (skip-chars-forward " \t")
14270 (run-hook-with-args 'org-property-changed-functions key nval)))
14272 (defun org-find-olp (path &optional this-buffer)
14273 "Return a marker pointing to the entry at outline path OLP.
14274 If anything goes wrong, throw an error.
14275 You can wrap this call to catch the error like this:
14277 (condition-case msg
14278 (org-mobile-locate-entry (match-string 4))
14279 (error (nth 1 msg)))
14281 The return value will then be either a string with the error message,
14282 or a marker if everything is OK.
14284 If THIS-BUFFER is set, the outline path does not contain a file,
14285 only headings."
14286 (let* ((file (if this-buffer buffer-file-name (pop path)))
14287 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14288 (level 1)
14289 (lmin 1)
14290 (lmax 1)
14291 limit re end found pos heading cnt flevel)
14292 (unless buffer (error "File not found :%s" file))
14293 (with-current-buffer buffer
14294 (save-excursion
14295 (save-restriction
14296 (widen)
14297 (setq limit (point-max))
14298 (goto-char (point-min))
14299 (while (setq heading (pop path))
14300 (setq re (format org-complex-heading-regexp-format
14301 (regexp-quote heading)))
14302 (setq cnt 0 pos (point))
14303 (while (re-search-forward re end t)
14304 (setq level (- (match-end 1) (match-beginning 1)))
14305 (if (and (>= level lmin) (<= level lmax))
14306 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14307 (when (= cnt 0) (error "Heading not found on level %d: %s"
14308 lmax heading))
14309 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14310 lmax heading))
14311 (goto-char found)
14312 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14313 (setq end (save-excursion (org-end-of-subtree t t))))
14314 (when (org-on-heading-p)
14315 (move-marker (make-marker) (point))))))))
14317 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14318 "Find node HEADING in BUFFER.
14319 Return a marker to the heading if it was found, or nil if not.
14320 If POS-ONLY is set, return just the position instead of a marker.
14322 The heading text must match exact, but it may have a TODO keyword,
14323 a priority cookie and tags in the standard locations."
14324 (with-current-buffer (or buffer (current-buffer))
14325 (save-excursion
14326 (save-restriction
14327 (widen)
14328 (goto-char (point-min))
14329 (let (case-fold-search)
14330 (if (re-search-forward
14331 (format org-complex-heading-regexp-format
14332 (regexp-quote heading)) nil t)
14333 (if pos-only
14334 (match-beginning 0)
14335 (move-marker (make-marker) (match-beginning 0)))))))))
14337 (defun org-find-exact-heading-in-directory (heading &optional dir)
14338 "Find Org node headline HEADING in all .org files in directory DIR.
14339 When the target headline is found, return a marker to this location."
14340 (let ((files (directory-files (or dir default-directory)
14341 nil "\\`[^.#].*\\.org\\'"))
14342 file visiting m buffer)
14343 (catch 'found
14344 (while (setq file (pop files))
14345 (message "trying %s" file)
14346 (setq visiting (org-find-base-buffer-visiting file))
14347 (setq buffer (or visiting (find-file-noselect file)))
14348 (setq m (org-find-exact-headline-in-buffer
14349 heading buffer))
14350 (when (and (not m) (not visiting)) (kill-buffer buffer))
14351 (and m (throw 'found m))))))
14353 (defun org-find-entry-with-id (ident)
14354 "Locate the entry that contains the ID property with exact value IDENT.
14355 IDENT can be a string, a symbol or a number, this function will search for
14356 the string representation of it.
14357 Return the position where this entry starts, or nil if there is no such entry."
14358 (interactive "sID: ")
14359 (let ((id (cond
14360 ((stringp ident) ident)
14361 ((symbol-name ident) (symbol-name ident))
14362 ((numberp ident) (number-to-string ident))
14363 (t (error "IDENT %s must be a string, symbol or number" ident))))
14364 (case-fold-search nil))
14365 (save-excursion
14366 (save-restriction
14367 (widen)
14368 (goto-char (point-min))
14369 (when (re-search-forward
14370 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14371 nil t)
14372 (org-back-to-heading t)
14373 (point))))))
14375 ;;;; Timestamps
14377 (defvar org-last-changed-timestamp nil)
14378 (defvar org-last-inserted-timestamp nil
14379 "The last time stamp inserted with `org-insert-time-stamp'.")
14380 (defvar org-time-was-given) ; dynamically scoped parameter
14381 (defvar org-end-time-was-given) ; dynamically scoped parameter
14382 (defvar org-ts-what) ; dynamically scoped parameter
14384 (defun org-time-stamp (arg &optional inactive)
14385 "Prompt for a date/time and insert a time stamp.
14386 If the user specifies a time like HH:MM, or if this command is called
14387 with a prefix argument, the time stamp will contain date and time.
14388 Otherwise, only the date will be included. All parts of a date not
14389 specified by the user will be filled in from the current date/time.
14390 So if you press just return without typing anything, the time stamp
14391 will represent the current date/time. If there is already a timestamp
14392 at the cursor, it will be modified."
14393 (interactive "P")
14394 (let* ((ts nil)
14395 (default-time
14396 ;; Default time is either today, or, when entering a range,
14397 ;; the range start.
14398 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14399 (save-excursion
14400 (re-search-backward
14401 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14402 (- (point) 20) t)))
14403 (apply 'encode-time (org-parse-time-string (match-string 1)))
14404 (current-time)))
14405 (default-input (and ts (org-get-compact-tod ts)))
14406 (repeater (save-excursion
14407 (save-match-data
14408 (beginning-of-line)
14409 (when (re-search-forward
14410 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14411 (save-excursion (progn (end-of-line) (point))) t)
14412 (match-string 0)))))
14413 org-time-was-given org-end-time-was-given time)
14414 (cond
14415 ((and (org-at-timestamp-p t)
14416 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14417 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14418 (insert "--")
14419 (setq time (let ((this-command this-command))
14420 (org-read-date arg 'totime nil nil
14421 default-time default-input)))
14422 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14423 ((org-at-timestamp-p t)
14424 (setq time (let ((this-command this-command))
14425 (org-read-date arg 'totime nil nil default-time default-input)))
14426 (when (org-at-timestamp-p t) ; just to get the match data
14427 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14428 (replace-match "")
14429 (setq org-last-changed-timestamp
14430 (org-insert-time-stamp
14431 time (or org-time-was-given arg)
14432 inactive nil nil (list org-end-time-was-given)))
14433 (when repeater (goto-char (1- (point))) (insert " " repeater)
14434 (setq org-last-changed-timestamp
14435 (concat (substring org-last-inserted-timestamp 0 -1)
14436 " " repeater ">"))))
14437 (message "Timestamp updated"))
14439 (setq time (let ((this-command this-command))
14440 (org-read-date arg 'totime nil nil default-time default-input)))
14441 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14442 nil nil (list org-end-time-was-given))))))
14444 ;; FIXME: can we use this for something else, like computing time differences?
14445 (defun org-get-compact-tod (s)
14446 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14447 (let* ((t1 (match-string 1 s))
14448 (h1 (string-to-number (match-string 2 s)))
14449 (m1 (string-to-number (match-string 3 s)))
14450 (t2 (and (match-end 4) (match-string 5 s)))
14451 (h2 (and t2 (string-to-number (match-string 6 s))))
14452 (m2 (and t2 (string-to-number (match-string 7 s))))
14453 dh dm)
14454 (if (not t2)
14456 (setq dh (- h2 h1) dm (- m2 m1))
14457 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14458 (concat t1 "+" (number-to-string dh)
14459 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14461 (defun org-time-stamp-inactive (&optional arg)
14462 "Insert an inactive time stamp.
14463 An inactive time stamp is enclosed in square brackets instead of angle
14464 brackets. It is inactive in the sense that it does not trigger agenda entries,
14465 does not link to the calendar and cannot be changed with the S-cursor keys.
14466 So these are more for recording a certain time/date."
14467 (interactive "P")
14468 (org-time-stamp arg 'inactive))
14470 (defvar org-date-ovl (make-overlay 1 1))
14471 (overlay-put org-date-ovl 'face 'org-warning)
14472 (org-detach-overlay org-date-ovl)
14474 (defvar org-ans1) ; dynamically scoped parameter
14475 (defvar org-ans2) ; dynamically scoped parameter
14477 (defvar org-plain-time-of-day-regexp) ; defined below
14479 (defvar org-overriding-default-time nil) ; dynamically scoped
14480 (defvar org-read-date-overlay nil)
14481 (defvar org-dcst nil) ; dynamically scoped
14482 (defvar org-read-date-history nil)
14483 (defvar org-read-date-final-answer nil)
14484 (defvar org-read-date-analyze-futurep nil)
14485 (defvar org-read-date-analyze-forced-year nil)
14487 (defun org-read-date (&optional with-time to-time from-string prompt
14488 default-time default-input)
14489 "Read a date, possibly a time, and make things smooth for the user.
14490 The prompt will suggest to enter an ISO date, but you can also enter anything
14491 which will at least partially be understood by `parse-time-string'.
14492 Unrecognized parts of the date will default to the current day, month, year,
14493 hour and minute. If this command is called to replace a timestamp at point,
14494 of to enter the second timestamp of a range, the default time is taken
14495 from the existing stamp. Furthermore, the command prefers the future,
14496 so if you are giving a date where the year is not given, and the day-month
14497 combination is already past in the current year, it will assume you
14498 mean next year. For details, see the manual. A few examples:
14500 3-2-5 --> 2003-02-05
14501 feb 15 --> currentyear-02-15
14502 2/15 --> currentyear-02-15
14503 sep 12 9 --> 2009-09-12
14504 12:45 --> today 12:45
14505 22 sept 0:34 --> currentyear-09-22 0:34
14506 12 --> currentyear-currentmonth-12
14507 Fri --> nearest Friday (today or later)
14508 etc.
14510 Furthermore you can specify a relative date by giving, as the *first* thing
14511 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14512 change in days weeks, months, years.
14513 With a single plus or minus, the date is relative to today. With a double
14514 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14515 +4d --> four days from today
14516 +4 --> same as above
14517 +2w --> two weeks from today
14518 ++5 --> five days from default date
14520 The function understands only English month and weekday abbreviations,
14521 but this can be configured with the variables `parse-time-months' and
14522 `parse-time-weekdays'.
14524 While prompting, a calendar is popped up - you can also select the
14525 date with the mouse (button 1). The calendar shows a period of three
14526 months. To scroll it to other months, use the keys `>' and `<'.
14527 If you don't like the calendar, turn it off with
14528 \(setq org-read-date-popup-calendar nil)
14530 With optional argument TO-TIME, the date will immediately be converted
14531 to an internal time.
14532 With an optional argument WITH-TIME, the prompt will suggest to also
14533 insert a time. Note that when WITH-TIME is not set, you can still
14534 enter a time, and this function will inform the calling routine about
14535 this change. The calling routine may then choose to change the format
14536 used to insert the time stamp into the buffer to include the time.
14537 With optional argument FROM-STRING, read from this string instead from
14538 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14539 the time/date that is used for everything that is not specified by the
14540 user."
14541 (require 'parse-time)
14542 (let* ((org-time-stamp-rounding-minutes
14543 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14544 (org-dcst org-display-custom-times)
14545 (ct (org-current-time))
14546 (def (or org-overriding-default-time default-time ct))
14547 (defdecode (decode-time def))
14548 (dummy (progn
14549 (when (< (nth 2 defdecode) org-extend-today-until)
14550 (setcar (nthcdr 2 defdecode) -1)
14551 (setcar (nthcdr 1 defdecode) 59)
14552 (setq def (apply 'encode-time defdecode)
14553 defdecode (decode-time def)))))
14554 (calendar-frame-setup nil)
14555 (calendar-setup nil)
14556 (calendar-move-hook nil)
14557 (calendar-view-diary-initially-flag nil)
14558 (calendar-view-holidays-initially-flag nil)
14559 (timestr (format-time-string
14560 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14561 (prompt (concat (if prompt (concat prompt " ") "")
14562 (format "Date+time [%s]: " timestr)))
14563 ans (org-ans0 "") org-ans1 org-ans2 final)
14565 (cond
14566 (from-string (setq ans from-string))
14567 (org-read-date-popup-calendar
14568 (save-excursion
14569 (save-window-excursion
14570 (calendar)
14571 (unwind-protect
14572 (progn
14573 (calendar-forward-day (- (time-to-days def)
14574 (calendar-absolute-from-gregorian
14575 (calendar-current-date))))
14576 (org-eval-in-calendar nil t)
14577 (let* ((old-map (current-local-map))
14578 (map (copy-keymap calendar-mode-map))
14579 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14580 (org-defkey map (kbd "RET") 'org-calendar-select)
14581 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14582 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14583 (org-defkey minibuffer-local-map [(meta shift left)]
14584 (lambda () (interactive)
14585 (org-eval-in-calendar '(calendar-backward-month 1))))
14586 (org-defkey minibuffer-local-map [(meta shift right)]
14587 (lambda () (interactive)
14588 (org-eval-in-calendar '(calendar-forward-month 1))))
14589 (org-defkey minibuffer-local-map [(meta shift up)]
14590 (lambda () (interactive)
14591 (org-eval-in-calendar '(calendar-backward-year 1))))
14592 (org-defkey minibuffer-local-map [(meta shift down)]
14593 (lambda () (interactive)
14594 (org-eval-in-calendar '(calendar-forward-year 1))))
14595 (org-defkey minibuffer-local-map [?\e (shift left)]
14596 (lambda () (interactive)
14597 (org-eval-in-calendar '(calendar-backward-month 1))))
14598 (org-defkey minibuffer-local-map [?\e (shift right)]
14599 (lambda () (interactive)
14600 (org-eval-in-calendar '(calendar-forward-month 1))))
14601 (org-defkey minibuffer-local-map [?\e (shift up)]
14602 (lambda () (interactive)
14603 (org-eval-in-calendar '(calendar-backward-year 1))))
14604 (org-defkey minibuffer-local-map [?\e (shift down)]
14605 (lambda () (interactive)
14606 (org-eval-in-calendar '(calendar-forward-year 1))))
14607 (org-defkey minibuffer-local-map [(shift up)]
14608 (lambda () (interactive)
14609 (org-eval-in-calendar '(calendar-backward-week 1))))
14610 (org-defkey minibuffer-local-map [(shift down)]
14611 (lambda () (interactive)
14612 (org-eval-in-calendar '(calendar-forward-week 1))))
14613 (org-defkey minibuffer-local-map [(shift left)]
14614 (lambda () (interactive)
14615 (org-eval-in-calendar '(calendar-backward-day 1))))
14616 (org-defkey minibuffer-local-map [(shift right)]
14617 (lambda () (interactive)
14618 (org-eval-in-calendar '(calendar-forward-day 1))))
14619 (org-defkey minibuffer-local-map ">"
14620 (lambda () (interactive)
14621 (org-eval-in-calendar '(scroll-calendar-left 1))))
14622 (org-defkey minibuffer-local-map "<"
14623 (lambda () (interactive)
14624 (org-eval-in-calendar '(scroll-calendar-right 1))))
14625 (org-defkey minibuffer-local-map "\C-v"
14626 (lambda () (interactive)
14627 (org-eval-in-calendar
14628 '(calendar-scroll-left-three-months 1))))
14629 (org-defkey minibuffer-local-map "\M-v"
14630 (lambda () (interactive)
14631 (org-eval-in-calendar
14632 '(calendar-scroll-right-three-months 1))))
14633 (run-hooks 'org-read-date-minibuffer-setup-hook)
14634 (unwind-protect
14635 (progn
14636 (use-local-map map)
14637 (add-hook 'post-command-hook 'org-read-date-display)
14638 (setq org-ans0 (read-string prompt default-input
14639 'org-read-date-history nil))
14640 ;; org-ans0: from prompt
14641 ;; org-ans1: from mouse click
14642 ;; org-ans2: from calendar motion
14643 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14644 (remove-hook 'post-command-hook 'org-read-date-display)
14645 (use-local-map old-map)
14646 (when org-read-date-overlay
14647 (delete-overlay org-read-date-overlay)
14648 (setq org-read-date-overlay nil)))))
14649 (bury-buffer "*Calendar*")))))
14651 (t ; Naked prompt only
14652 (unwind-protect
14653 (setq ans (read-string prompt default-input
14654 'org-read-date-history timestr))
14655 (when org-read-date-overlay
14656 (delete-overlay org-read-date-overlay)
14657 (setq org-read-date-overlay nil)))))
14659 (setq final (org-read-date-analyze ans def defdecode))
14661 (when org-read-date-analyze-forced-year
14662 (message "Year was forced into %s"
14663 (if org-read-date-force-compatible-dates
14664 "compatible range (1970-2037)"
14665 "range representable on this machine"))
14666 (ding))
14668 ;; One round trip to get rid of 34th of August and stuff like that....
14669 (setq final (decode-time (apply 'encode-time final)))
14671 (setq org-read-date-final-answer ans)
14673 (if to-time
14674 (apply 'encode-time final)
14675 (if (and (boundp 'org-time-was-given) org-time-was-given)
14676 (format "%04d-%02d-%02d %02d:%02d"
14677 (nth 5 final) (nth 4 final) (nth 3 final)
14678 (nth 2 final) (nth 1 final))
14679 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
14681 (defvar def)
14682 (defvar defdecode)
14683 (defvar with-time)
14684 (defun org-read-date-display ()
14685 "Display the current date prompt interpretation in the minibuffer."
14686 (when org-read-date-display-live
14687 (when org-read-date-overlay
14688 (delete-overlay org-read-date-overlay))
14689 (let ((p (point)))
14690 (end-of-line 1)
14691 (while (not (equal (buffer-substring
14692 (max (point-min) (- (point) 4)) (point))
14693 " "))
14694 (insert " "))
14695 (goto-char p))
14696 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
14697 " " (or org-ans1 org-ans2)))
14698 (org-end-time-was-given nil)
14699 (f (org-read-date-analyze ans def defdecode))
14700 (fmts (if org-dcst
14701 org-time-stamp-custom-formats
14702 org-time-stamp-formats))
14703 (fmt (if (or with-time
14704 (and (boundp 'org-time-was-given) org-time-was-given))
14705 (cdr fmts)
14706 (car fmts)))
14707 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
14708 (when (and org-end-time-was-given
14709 (string-match org-plain-time-of-day-regexp txt))
14710 (setq txt (concat (substring txt 0 (match-end 0)) "-"
14711 org-end-time-was-given
14712 (substring txt (match-end 0)))))
14713 (when org-read-date-analyze-futurep
14714 (setq txt (concat txt " (=>F)")))
14715 (setq org-read-date-overlay
14716 (make-overlay (1- (point-at-eol)) (point-at-eol)))
14717 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
14719 (defun org-read-date-analyze (ans def defdecode)
14720 "Analyze the combined answer of the date prompt."
14721 ;; FIXME: cleanup and comment
14722 (let ((nowdecode (decode-time (current-time)))
14723 delta deltan deltaw deltadef year month day
14724 hour minute second wday pm h2 m2 tl wday1
14725 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
14726 (setq org-read-date-analyze-futurep nil
14727 org-read-date-analyze-forced-year nil)
14728 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
14729 (setq ans "+0"))
14731 (when (setq delta (org-read-date-get-relative ans (current-time) def))
14732 (setq ans (replace-match "" t t ans)
14733 deltan (car delta)
14734 deltaw (nth 1 delta)
14735 deltadef (nth 2 delta)))
14737 ;; Check if there is an iso week date in there
14738 ;; If yes, store the info and postpone interpreting it until the rest
14739 ;; of the parsing is done
14740 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
14741 (setq iso-year (if (match-end 1)
14742 (org-small-year-to-year
14743 (string-to-number (match-string 1 ans))))
14744 iso-weekday (if (match-end 3)
14745 (string-to-number (match-string 3 ans)))
14746 iso-week (string-to-number (match-string 2 ans)))
14747 (setq ans (replace-match "" t t ans)))
14749 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
14750 (when (string-match
14751 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
14752 (setq year (if (match-end 2)
14753 (string-to-number (match-string 2 ans))
14754 (progn (setq kill-year t)
14755 (string-to-number (format-time-string "%Y"))))
14756 month (string-to-number (match-string 3 ans))
14757 day (string-to-number (match-string 4 ans)))
14758 (if (< year 100) (setq year (+ 2000 year)))
14759 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14760 t nil ans)))
14762 ;; Help matching dottet european dates
14763 (when (string-match
14764 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
14765 (setq year (if (match-end 3)
14766 (string-to-number (match-string 3 ans))
14767 (progn (setq kill-year t)
14768 (string-to-number (format-time-string "%Y"))))
14769 day (string-to-number (match-string 1 ans))
14770 month (string-to-number (match-string 2 ans))
14771 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14772 t nil ans)))
14774 ;; Help matching american dates, like 5/30 or 5/30/7
14775 (when (string-match
14776 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
14777 (setq year (if (match-end 4)
14778 (string-to-number (match-string 4 ans))
14779 (progn (setq kill-year t)
14780 (string-to-number (format-time-string "%Y"))))
14781 month (string-to-number (match-string 1 ans))
14782 day (string-to-number (match-string 2 ans)))
14783 (if (< year 100) (setq year (+ 2000 year)))
14784 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14785 t nil ans)))
14786 ;; Help matching am/pm times, because `parse-time-string' does not do that.
14787 ;; If there is a time with am/pm, and *no* time without it, we convert
14788 ;; so that matching will be successful.
14789 (loop for i from 1 to 2 do ; twice, for end time as well
14790 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
14791 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
14792 (setq hour (string-to-number (match-string 1 ans))
14793 minute (if (match-end 3)
14794 (string-to-number (match-string 3 ans))
14796 pm (equal ?p
14797 (string-to-char (downcase (match-string 4 ans)))))
14798 (if (and (= hour 12) (not pm))
14799 (setq hour 0)
14800 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
14801 (setq ans (replace-match (format "%02d:%02d" hour minute)
14802 t t ans))))
14804 ;; Check if a time range is given as a duration
14805 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
14806 (setq hour (string-to-number (match-string 1 ans))
14807 h2 (+ hour (string-to-number (match-string 3 ans)))
14808 minute (string-to-number (match-string 2 ans))
14809 m2 (+ minute (if (match-end 5) (string-to-number
14810 (match-string 5 ans))0)))
14811 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
14812 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
14813 t t ans)))
14815 ;; Check if there is a time range
14816 (when (boundp 'org-end-time-was-given)
14817 (setq org-time-was-given nil)
14818 (when (and (string-match org-plain-time-of-day-regexp ans)
14819 (match-end 8))
14820 (setq org-end-time-was-given (match-string 8 ans))
14821 (setq ans (concat (substring ans 0 (match-beginning 7))
14822 (substring ans (match-end 7))))))
14824 (setq tl (parse-time-string ans)
14825 day (or (nth 3 tl) (nth 3 defdecode))
14826 month (or (nth 4 tl)
14827 (if (and org-read-date-prefer-future
14828 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
14829 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
14830 (nth 4 defdecode)))
14831 year (or (and (not kill-year) (nth 5 tl))
14832 (if (and org-read-date-prefer-future
14833 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
14834 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
14835 (nth 5 defdecode)))
14836 hour (or (nth 2 tl) (nth 2 defdecode))
14837 minute (or (nth 1 tl) (nth 1 defdecode))
14838 second (or (nth 0 tl) 0)
14839 wday (nth 6 tl))
14841 (when (and (eq org-read-date-prefer-future 'time)
14842 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
14843 (equal day (nth 3 nowdecode))
14844 (equal month (nth 4 nowdecode))
14845 (equal year (nth 5 nowdecode))
14846 (nth 2 tl)
14847 (or (< (nth 2 tl) (nth 2 nowdecode))
14848 (and (= (nth 2 tl) (nth 2 nowdecode))
14849 (nth 1 tl)
14850 (< (nth 1 tl) (nth 1 nowdecode)))))
14851 (setq day (1+ day)
14852 futurep t))
14854 ;; Special date definitions below
14855 (cond
14856 (iso-week
14857 ;; There was an iso week
14858 (require 'cal-iso)
14859 (setq futurep nil)
14860 (setq year (or iso-year year)
14861 day (or iso-weekday wday 1)
14862 wday nil ; to make sure that the trigger below does not match
14863 iso-date (calendar-gregorian-from-absolute
14864 (calendar-absolute-from-iso
14865 (list iso-week day year))))
14866 ; FIXME: Should we also push ISO weeks into the future?
14867 ; (when (and org-read-date-prefer-future
14868 ; (not iso-year)
14869 ; (< (calendar-absolute-from-gregorian iso-date)
14870 ; (time-to-days (current-time))))
14871 ; (setq year (1+ year)
14872 ; iso-date (calendar-gregorian-from-absolute
14873 ; (calendar-absolute-from-iso
14874 ; (list iso-week day year)))))
14875 (setq month (car iso-date)
14876 year (nth 2 iso-date)
14877 day (nth 1 iso-date)))
14878 (deltan
14879 (setq futurep nil)
14880 (unless deltadef
14881 (let ((now (decode-time (current-time))))
14882 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
14883 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
14884 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
14885 ((equal deltaw "m") (setq month (+ month deltan)))
14886 ((equal deltaw "y") (setq year (+ year deltan)))))
14887 ((and wday (not (nth 3 tl)))
14888 (setq futurep nil)
14889 ;; Weekday was given, but no day, so pick that day in the week
14890 ;; on or after the derived date.
14891 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
14892 (unless (equal wday wday1)
14893 (setq day (+ day (% (- wday wday1 -7) 7))))))
14894 (if (and (boundp 'org-time-was-given)
14895 (nth 2 tl))
14896 (setq org-time-was-given t))
14897 (if (< year 100) (setq year (+ 2000 year)))
14898 ;; Check of the date is representable
14899 (if org-read-date-force-compatible-dates
14900 (progn
14901 (if (< year 1970)
14902 (setq year 1970 org-read-date-analyze-forced-year t))
14903 (if (> year 2037)
14904 (setq year 2037 org-read-date-analyze-forced-year t)))
14905 (condition-case nil
14906 (ignore (encode-time second minute hour day month year))
14907 (error
14908 (setq year (nth 5 defdecode))
14909 (setq org-read-date-analyze-forced-year t))))
14910 (setq org-read-date-analyze-futurep futurep)
14911 (list second minute hour day month year)))
14913 (defvar parse-time-weekdays)
14915 (defun org-read-date-get-relative (s today default)
14916 "Check string S for special relative date string.
14917 TODAY and DEFAULT are internal times, for today and for a default.
14918 Return shift list (N what def-flag)
14919 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
14920 N is the number of WHATs to shift.
14921 DEF-FLAG is t when a double ++ or -- indicates shift relative to
14922 the DEFAULT date rather than TODAY."
14923 (when (and
14924 (string-match
14925 (concat
14926 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
14927 "\\([0-9]+\\)?"
14928 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
14929 "\\([ \t]\\|$\\)") s)
14930 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
14931 (let* ((dir (if (> (match-end 1) (match-beginning 1))
14932 (string-to-char (substring (match-string 1 s) -1))
14933 ?+))
14934 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
14935 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
14936 (what (if (match-end 3) (match-string 3 s) "d"))
14937 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
14938 (date (if rel default today))
14939 (wday (nth 6 (decode-time date)))
14940 delta)
14941 (if wday1
14942 (progn
14943 (setq delta (mod (+ 7 (- wday1 wday)) 7))
14944 (if (= dir ?-) (setq delta (- delta 7)))
14945 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
14946 (list delta "d" rel))
14947 (list (* n (if (= dir ?-) -1 1)) what rel)))))
14949 (defun org-order-calendar-date-args (arg1 arg2 arg3)
14950 "Turn a user-specified date into the internal representation.
14951 The internal representation needed by the calendar is (month day year).
14952 This is a wrapper to handle the brain-dead convention in calendar that
14953 user function argument order change dependent on argument order."
14954 (if (boundp 'calendar-date-style)
14955 (cond
14956 ((eq calendar-date-style 'american)
14957 (list arg1 arg2 arg3))
14958 ((eq calendar-date-style 'european)
14959 (list arg2 arg1 arg3))
14960 ((eq calendar-date-style 'iso)
14961 (list arg2 arg3 arg1)))
14962 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
14963 (if (org-bound-and-true-p european-calendar-style)
14964 (list arg2 arg1 arg3)
14965 (list arg1 arg2 arg3)))))
14967 (defun org-eval-in-calendar (form &optional keepdate)
14968 "Eval FORM in the calendar window and return to current window.
14969 Also, store the cursor date in variable org-ans2."
14970 (let ((sf (selected-frame))
14971 (sw (selected-window)))
14972 (select-window (get-buffer-window "*Calendar*" t))
14973 (eval form)
14974 (when (and (not keepdate) (calendar-cursor-to-date))
14975 (let* ((date (calendar-cursor-to-date))
14976 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14977 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
14978 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
14979 (select-window sw)
14980 (org-select-frame-set-input-focus sf)))
14982 (defun org-calendar-select ()
14983 "Return to `org-read-date' with the date currently selected.
14984 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14985 (interactive)
14986 (when (calendar-cursor-to-date)
14987 (let* ((date (calendar-cursor-to-date))
14988 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14989 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14990 (if (active-minibuffer-window) (exit-minibuffer))))
14992 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
14993 "Insert a date stamp for the date given by the internal TIME.
14994 WITH-HM means use the stamp format that includes the time of the day.
14995 INACTIVE means use square brackets instead of angular ones, so that the
14996 stamp will not contribute to the agenda.
14997 PRE and POST are optional strings to be inserted before and after the
14998 stamp.
14999 The command returns the inserted time stamp."
15000 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15001 stamp)
15002 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15003 (insert-before-markers (or pre ""))
15004 (when (listp extra)
15005 (setq extra (car extra))
15006 (if (and (stringp extra)
15007 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15008 (setq extra (format "-%02d:%02d"
15009 (string-to-number (match-string 1 extra))
15010 (string-to-number (match-string 2 extra))))
15011 (setq extra nil)))
15012 (when extra
15013 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15014 (insert-before-markers (setq stamp (format-time-string fmt time)))
15015 (insert-before-markers (or post ""))
15016 (setq org-last-inserted-timestamp stamp)))
15018 (defun org-toggle-time-stamp-overlays ()
15019 "Toggle the use of custom time stamp formats."
15020 (interactive)
15021 (setq org-display-custom-times (not org-display-custom-times))
15022 (unless org-display-custom-times
15023 (let ((p (point-min)) (bmp (buffer-modified-p)))
15024 (while (setq p (next-single-property-change p 'display))
15025 (if (and (get-text-property p 'display)
15026 (eq (get-text-property p 'face) 'org-date))
15027 (remove-text-properties
15028 p (setq p (next-single-property-change p 'display))
15029 '(display t))))
15030 (set-buffer-modified-p bmp)))
15031 (if (featurep 'xemacs)
15032 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15033 (org-restart-font-lock)
15034 (setq org-table-may-need-update t)
15035 (if org-display-custom-times
15036 (message "Time stamps are overlayed with custom format")
15037 (message "Time stamp overlays removed")))
15039 (defun org-display-custom-time (beg end)
15040 "Overlay modified time stamp format over timestamp between BEG and END."
15041 (let* ((ts (buffer-substring beg end))
15042 t1 w1 with-hm tf time str w2 (off 0))
15043 (save-match-data
15044 (setq t1 (org-parse-time-string ts t))
15045 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15046 (setq off (- (match-end 0) (match-beginning 0)))))
15047 (setq end (- end off))
15048 (setq w1 (- end beg)
15049 with-hm (and (nth 1 t1) (nth 2 t1))
15050 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15051 time (org-fix-decoded-time t1)
15052 str (org-add-props
15053 (format-time-string
15054 (substring tf 1 -1) (apply 'encode-time time))
15055 nil 'mouse-face 'highlight)
15056 w2 (length str))
15057 (if (not (= w2 w1))
15058 (add-text-properties (1+ beg) (+ 2 beg)
15059 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15060 (if (featurep 'xemacs)
15061 (progn
15062 (put-text-property beg end 'invisible t)
15063 (put-text-property beg end 'end-glyph (make-glyph str)))
15064 (put-text-property beg end 'display str))))
15066 (defun org-translate-time (string)
15067 "Translate all timestamps in STRING to custom format.
15068 But do this only if the variable `org-display-custom-times' is set."
15069 (when org-display-custom-times
15070 (save-match-data
15071 (let* ((start 0)
15072 (re org-ts-regexp-both)
15073 t1 with-hm inactive tf time str beg end)
15074 (while (setq start (string-match re string start))
15075 (setq beg (match-beginning 0)
15076 end (match-end 0)
15077 t1 (save-match-data
15078 (org-parse-time-string (substring string beg end) t))
15079 with-hm (and (nth 1 t1) (nth 2 t1))
15080 inactive (equal (substring string beg (1+ beg)) "[")
15081 tf (funcall (if with-hm 'cdr 'car)
15082 org-time-stamp-custom-formats)
15083 time (org-fix-decoded-time t1)
15084 str (format-time-string
15085 (concat
15086 (if inactive "[" "<") (substring tf 1 -1)
15087 (if inactive "]" ">"))
15088 (apply 'encode-time time))
15089 string (replace-match str t t string)
15090 start (+ start (length str)))))))
15091 string)
15093 (defun org-fix-decoded-time (time)
15094 "Set 0 instead of nil for the first 6 elements of time.
15095 Don't touch the rest."
15096 (let ((n 0))
15097 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15099 (defun org-days-to-time (timestamp-string)
15100 "Difference between TIMESTAMP-STRING and now in days."
15101 (- (time-to-days (org-time-string-to-time timestamp-string))
15102 (time-to-days (current-time))))
15104 (defun org-deadline-close (timestamp-string &optional ndays)
15105 "Is the time in TIMESTAMP-STRING close to the current date?"
15106 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15107 (and (< (org-days-to-time timestamp-string) ndays)
15108 (not (org-entry-is-done-p))))
15110 (defun org-get-wdays (ts)
15111 "Get the deadline lead time appropriate for timestring TS."
15112 (cond
15113 ((<= org-deadline-warning-days 0)
15114 ;; 0 or negative, enforce this value no matter what
15115 (- org-deadline-warning-days))
15116 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15117 ;; lead time is specified.
15118 (floor (* (string-to-number (match-string 1 ts))
15119 (cdr (assoc (match-string 2 ts)
15120 '(("d" . 1) ("w" . 7)
15121 ("m" . 30.4) ("y" . 365.25)))))))
15122 ;; go for the default.
15123 (t org-deadline-warning-days)))
15125 (defun org-calendar-select-mouse (ev)
15126 "Return to `org-read-date' with the date currently selected.
15127 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15128 (interactive "e")
15129 (mouse-set-point ev)
15130 (when (calendar-cursor-to-date)
15131 (let* ((date (calendar-cursor-to-date))
15132 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15133 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15134 (if (active-minibuffer-window) (exit-minibuffer))))
15136 (defun org-check-deadlines (ndays)
15137 "Check if there are any deadlines due or past due.
15138 A deadline is considered due if it happens within `org-deadline-warning-days'
15139 days from today's date. If the deadline appears in an entry marked DONE,
15140 it is not shown. The prefix arg NDAYS can be used to test that many
15141 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15142 (interactive "P")
15143 (let* ((org-warn-days
15144 (cond
15145 ((equal ndays '(4)) 100000)
15146 (ndays (prefix-numeric-value ndays))
15147 (t (abs org-deadline-warning-days))))
15148 (case-fold-search nil)
15149 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15150 (callback
15151 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15153 (message "%d deadlines past-due or due within %d days"
15154 (org-occur regexp nil callback)
15155 org-warn-days)))
15157 (defun org-check-before-date (date)
15158 "Check if there are deadlines or scheduled entries before DATE."
15159 (interactive (list (org-read-date)))
15160 (let ((case-fold-search nil)
15161 (regexp (concat "\\<\\(" org-deadline-string
15162 "\\|" org-scheduled-string
15163 "\\) *<\\([^>]+\\)>"))
15164 (callback
15165 (lambda () (time-less-p
15166 (org-time-string-to-time (match-string 2))
15167 (org-time-string-to-time date)))))
15168 (message "%d entries before %s"
15169 (org-occur regexp nil callback) date)))
15171 (defun org-check-after-date (date)
15172 "Check if there are deadlines or scheduled entries after DATE."
15173 (interactive (list (org-read-date)))
15174 (let ((case-fold-search nil)
15175 (regexp (concat "\\<\\(" org-deadline-string
15176 "\\|" org-scheduled-string
15177 "\\) *<\\([^>]+\\)>"))
15178 (callback
15179 (lambda () (not
15180 (time-less-p
15181 (org-time-string-to-time (match-string 2))
15182 (org-time-string-to-time date))))))
15183 (message "%d entries after %s"
15184 (org-occur regexp nil callback) date)))
15186 (defun org-evaluate-time-range (&optional to-buffer)
15187 "Evaluate a time range by computing the difference between start and end.
15188 Normally the result is just printed in the echo area, but with prefix arg
15189 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15190 If the time range is actually in a table, the result is inserted into the
15191 next column.
15192 For time difference computation, a year is assumed to be exactly 365
15193 days in order to avoid rounding problems."
15194 (interactive "P")
15196 (org-clock-update-time-maybe)
15197 (save-excursion
15198 (unless (org-at-date-range-p t)
15199 (goto-char (point-at-bol))
15200 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15201 (if (not (org-at-date-range-p t))
15202 (error "Not at a time-stamp range, and none found in current line")))
15203 (let* ((ts1 (match-string 1))
15204 (ts2 (match-string 2))
15205 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15206 (match-end (match-end 0))
15207 (time1 (org-time-string-to-time ts1))
15208 (time2 (org-time-string-to-time ts2))
15209 (t1 (org-float-time time1))
15210 (t2 (org-float-time time2))
15211 (diff (abs (- t2 t1)))
15212 (negative (< (- t2 t1) 0))
15213 ;; (ys (floor (* 365 24 60 60)))
15214 (ds (* 24 60 60))
15215 (hs (* 60 60))
15216 (fy "%dy %dd %02d:%02d")
15217 (fy1 "%dy %dd")
15218 (fd "%dd %02d:%02d")
15219 (fd1 "%dd")
15220 (fh "%02d:%02d")
15221 y d h m align)
15222 (if havetime
15223 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15225 d (floor (/ diff ds)) diff (mod diff ds)
15226 h (floor (/ diff hs)) diff (mod diff hs)
15227 m (floor (/ diff 60)))
15228 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15230 d (floor (+ (/ diff ds) 0.5))
15231 h 0 m 0))
15232 (if (not to-buffer)
15233 (message "%s" (org-make-tdiff-string y d h m))
15234 (if (org-at-table-p)
15235 (progn
15236 (goto-char match-end)
15237 (setq align t)
15238 (and (looking-at " *|") (goto-char (match-end 0))))
15239 (goto-char match-end))
15240 (if (looking-at
15241 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15242 (replace-match ""))
15243 (if negative (insert " -"))
15244 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15245 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15246 (insert " " (format fh h m))))
15247 (if align (org-table-align))
15248 (message "Time difference inserted")))))
15250 (defun org-make-tdiff-string (y d h m)
15251 (let ((fmt "")
15252 (l nil))
15253 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15254 l (push y l)))
15255 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15256 l (push d l)))
15257 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15258 l (push h l)))
15259 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15260 l (push m l)))
15261 (apply 'format fmt (nreverse l))))
15263 (defun org-time-string-to-time (s)
15264 (apply 'encode-time (org-parse-time-string s)))
15265 (defun org-time-string-to-seconds (s)
15266 (org-float-time (org-time-string-to-time s)))
15268 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
15269 "Convert a time stamp to an absolute day number.
15270 If there is a specifier for a cyclic time stamp, get the closest date to
15271 DAYNR.
15272 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15273 The variable date is bound by the calendar when this is called."
15274 (cond
15275 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15276 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15277 daynr
15278 (+ daynr 1000)))
15279 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15280 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15281 (time-to-days (current-time))) (match-string 0 s)
15282 prefer show-all))
15283 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
15285 (defun org-days-to-iso-week (days)
15286 "Return the iso week number."
15287 (require 'cal-iso)
15288 (car (calendar-iso-from-absolute days)))
15290 (defun org-small-year-to-year (year)
15291 "Convert 2-digit years into 4-digit years.
15292 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15293 The year 2000 cannot be abbreviated. Any year larger than 99
15294 is returned unchanged."
15295 (if (< year 38)
15296 (setq year (+ 2000 year))
15297 (if (< year 100)
15298 (setq year (+ 1900 year))))
15299 year)
15301 (defun org-time-from-absolute (d)
15302 "Return the time corresponding to date D.
15303 D may be an absolute day number, or a calendar-type list (month day year)."
15304 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15305 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15307 (defun org-calendar-holiday ()
15308 "List of holidays, for Diary display in Org-mode."
15309 (require 'holidays)
15310 (let ((hl (funcall
15311 (if (fboundp 'calendar-check-holidays)
15312 'calendar-check-holidays 'check-calendar-holidays) date)))
15313 (if hl (mapconcat 'identity hl "; "))))
15315 (defun org-diary-sexp-entry (sexp entry date)
15316 "Process a SEXP diary ENTRY for DATE."
15317 (require 'diary-lib)
15318 (let ((result (if calendar-debug-sexp
15319 (let ((stack-trace-on-error t))
15320 (eval (car (read-from-string sexp))))
15321 (condition-case nil
15322 (eval (car (read-from-string sexp)))
15323 (error
15324 (beep)
15325 (message "Bad sexp at line %d in %s: %s"
15326 (org-current-line)
15327 (buffer-file-name) sexp)
15328 (sleep-for 2))))))
15329 (cond ((stringp result) (split-string result "; "))
15330 ((and (consp result)
15331 (not (consp (cdr result)))
15332 (stringp (cdr result))) (cdr result))
15333 ((and (consp result)
15334 (stringp (car result))) result)
15335 (result entry)
15336 (t nil))))
15338 (defun org-diary-to-ical-string (frombuf)
15339 "Get iCalendar entries from diary entries in buffer FROMBUF.
15340 This uses the icalendar.el library."
15341 (let* ((tmpdir (if (featurep 'xemacs)
15342 (temp-directory)
15343 temporary-file-directory))
15344 (tmpfile (make-temp-name
15345 (expand-file-name "orgics" tmpdir)))
15346 buf rtn b e)
15347 (with-current-buffer frombuf
15348 (icalendar-export-region (point-min) (point-max) tmpfile)
15349 (setq buf (find-buffer-visiting tmpfile))
15350 (set-buffer buf)
15351 (goto-char (point-min))
15352 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15353 (setq b (match-beginning 0)))
15354 (goto-char (point-max))
15355 (if (re-search-backward "^END:VEVENT" nil t)
15356 (setq e (match-end 0)))
15357 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15358 (kill-buffer buf)
15359 (delete-file tmpfile)
15360 rtn))
15362 (defun org-closest-date (start current change prefer show-all)
15363 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15364 When PREFER is `past', return a date that is either CURRENT or past.
15365 When PREFER is `future', return a date that is either CURRENT or future.
15366 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15367 ;; Make the proper lists from the dates
15368 (catch 'exit
15369 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15370 dn dw sday cday n1 n2 n0
15371 d m y y1 y2 date1 date2 nmonths nm ny m2)
15373 (setq start (org-date-to-gregorian start)
15374 current (org-date-to-gregorian
15375 (if show-all
15376 current
15377 (time-to-days (current-time))))
15378 sday (calendar-absolute-from-gregorian start)
15379 cday (calendar-absolute-from-gregorian current))
15381 (if (<= cday sday) (throw 'exit sday))
15383 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15384 (setq dn (string-to-number (match-string 1 change))
15385 dw (cdr (assoc (match-string 2 change) a1)))
15386 (error "Invalid change specifier: %s" change))
15387 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15388 (cond
15389 ((eq dw 'day)
15390 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15391 n2 (+ n1 dn)))
15392 ((eq dw 'year)
15393 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15394 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15395 (setq date1 (list m d y1)
15396 n1 (calendar-absolute-from-gregorian date1)
15397 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15398 n2 (calendar-absolute-from-gregorian date2)))
15399 ((eq dw 'month)
15400 ;; approx number of month between the two dates
15401 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15402 ;; How often does dn fit in there?
15403 (setq d (nth 1 start) m (car start) y (nth 2 start)
15404 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15405 m (+ m nm)
15406 ny (floor (/ m 12))
15407 y (+ y ny)
15408 m (- m (* ny 12)))
15409 (while (> m 12) (setq m (- m 12) y (1+ y)))
15410 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15411 (setq m2 (+ m dn) y2 y)
15412 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15413 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15414 (while (<= n2 cday)
15415 (setq n1 n2 m m2 y y2)
15416 (setq m2 (+ m dn) y2 y)
15417 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15418 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15419 ;; Make sure n1 is the earlier date
15420 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15421 (if show-all
15422 (cond
15423 ((eq prefer 'past) (if (= cday n2) n2 n1))
15424 ((eq prefer 'future) (if (= cday n1) n1 n2))
15425 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15426 (cond
15427 ((eq prefer 'past) (if (= cday n2) n2 n1))
15428 ((eq prefer 'future) (if (= cday n1) n1 n2))
15429 (t (if (= cday n1) n1 n2)))))))
15431 (defun org-date-to-gregorian (date)
15432 "Turn any specification of DATE into a Gregorian date for the calendar."
15433 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15434 ((and (listp date) (= (length date) 3)) date)
15435 ((stringp date)
15436 (setq date (org-parse-time-string date))
15437 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15438 ((listp date)
15439 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15441 (defun org-parse-time-string (s &optional nodefault)
15442 "Parse the standard Org-mode time string.
15443 This should be a lot faster than the normal `parse-time-string'.
15444 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15445 hour and minute fields will be nil if not given."
15446 (if (string-match org-ts-regexp0 s)
15447 (list 0
15448 (if (or (match-beginning 8) (not nodefault))
15449 (string-to-number (or (match-string 8 s) "0")))
15450 (if (or (match-beginning 7) (not nodefault))
15451 (string-to-number (or (match-string 7 s) "0")))
15452 (string-to-number (match-string 4 s))
15453 (string-to-number (match-string 3 s))
15454 (string-to-number (match-string 2 s))
15455 nil nil nil)
15456 (error "Not a standard Org-mode time string: %s" s)))
15458 (defun org-timestamp-up (&optional arg)
15459 "Increase the date item at the cursor by one.
15460 If the cursor is on the year, change the year. If it is on the month,
15461 the day or the time, change that.
15462 With prefix ARG, change by that many units."
15463 (interactive "p")
15464 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15466 (defun org-timestamp-down (&optional arg)
15467 "Decrease the date item at the cursor by one.
15468 If the cursor is on the year, change the year. If it is on the month,
15469 the day or the time, change that.
15470 With prefix ARG, change by that many units."
15471 (interactive "p")
15472 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15474 (defun org-timestamp-up-day (&optional arg)
15475 "Increase the date in the time stamp by one day.
15476 With prefix ARG, change that many days."
15477 (interactive "p")
15478 (if (and (not (org-at-timestamp-p t))
15479 (org-on-heading-p))
15480 (org-todo 'up)
15481 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15483 (defun org-timestamp-down-day (&optional arg)
15484 "Decrease the date in the time stamp by one day.
15485 With prefix ARG, change that many days."
15486 (interactive "p")
15487 (if (and (not (org-at-timestamp-p t))
15488 (org-on-heading-p))
15489 (org-todo 'down)
15490 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15492 (defun org-at-timestamp-p (&optional inactive-ok)
15493 "Determine if the cursor is in or at a timestamp."
15494 (interactive)
15495 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15496 (pos (point))
15497 (ans (or (looking-at tsr)
15498 (save-excursion
15499 (skip-chars-backward "^[<\n\r\t")
15500 (if (> (point) (point-min)) (backward-char 1))
15501 (and (looking-at tsr)
15502 (> (- (match-end 0) pos) -1))))))
15503 (and ans
15504 (boundp 'org-ts-what)
15505 (setq org-ts-what
15506 (cond
15507 ((= pos (match-beginning 0)) 'bracket)
15508 ((= pos (1- (match-end 0))) 'bracket)
15509 ((org-pos-in-match-range pos 2) 'year)
15510 ((org-pos-in-match-range pos 3) 'month)
15511 ((org-pos-in-match-range pos 7) 'hour)
15512 ((org-pos-in-match-range pos 8) 'minute)
15513 ((or (org-pos-in-match-range pos 4)
15514 (org-pos-in-match-range pos 5)) 'day)
15515 ((and (> pos (or (match-end 8) (match-end 5)))
15516 (< pos (match-end 0)))
15517 (- pos (or (match-end 8) (match-end 5))))
15518 (t 'day))))
15519 ans))
15521 (defun org-toggle-timestamp-type ()
15522 "Toggle the type (<active> or [inactive]) of a time stamp."
15523 (interactive)
15524 (when (org-at-timestamp-p t)
15525 (let ((beg (match-beginning 0)) (end (match-end 0))
15526 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
15527 (save-excursion
15528 (goto-char beg)
15529 (while (re-search-forward "[][<>]" end t)
15530 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
15531 t t)))
15532 (message "Timestamp is now %sactive"
15533 (if (equal (char-after beg) ?<) "" "in")))))
15535 (defun org-timestamp-change (n &optional what updown)
15536 "Change the date in the time stamp at point.
15537 The date will be changed by N times WHAT. WHAT can be `day', `month',
15538 `year', `minute', `second'. If WHAT is not given, the cursor position
15539 in the timestamp determines what will be changed."
15540 (let ((pos (point))
15541 with-hm inactive
15542 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
15543 org-ts-what
15544 extra rem
15545 ts time time0)
15546 (if (not (org-at-timestamp-p t))
15547 (error "Not at a timestamp"))
15548 (if (and (not what) (eq org-ts-what 'bracket))
15549 (org-toggle-timestamp-type)
15550 (if (and (not what) (not (eq org-ts-what 'day))
15551 org-display-custom-times
15552 (get-text-property (point) 'display)
15553 (not (get-text-property (1- (point)) 'display)))
15554 (setq org-ts-what 'day))
15555 (setq org-ts-what (or what org-ts-what)
15556 inactive (= (char-after (match-beginning 0)) ?\[)
15557 ts (match-string 0))
15558 (replace-match "")
15559 (if (string-match
15560 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
15562 (setq extra (match-string 1 ts)))
15563 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15564 (setq with-hm t))
15565 (setq time0 (org-parse-time-string ts))
15566 (when (and updown
15567 (eq org-ts-what 'minute)
15568 (not current-prefix-arg))
15569 ;; This looks like s-up and s-down. Change by one rounding step.
15570 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
15571 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
15572 (setcar (cdr time0) (+ (nth 1 time0)
15573 (if (> n 0) (- rem) (- dm rem))))))
15574 (setq time
15575 (encode-time (or (car time0) 0)
15576 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
15577 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
15578 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
15579 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
15580 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
15581 (nthcdr 6 time0)))
15582 (when (and (member org-ts-what '(hour minute))
15583 extra
15584 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
15585 (setq extra (org-modify-ts-extra
15586 extra
15587 (if (eq org-ts-what 'hour) 2 5)
15588 n dm)))
15589 (when (integerp org-ts-what)
15590 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
15591 (if (eq what 'calendar)
15592 (let ((cal-date (org-get-date-from-calendar)))
15593 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15594 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15595 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15596 (setcar time0 (or (car time0) 0))
15597 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15598 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15599 (setq time (apply 'encode-time time0))))
15600 (setq org-last-changed-timestamp
15601 (org-insert-time-stamp time with-hm inactive nil nil extra))
15602 (org-clock-update-time-maybe)
15603 (goto-char pos)
15604 ;; Try to recenter the calendar window, if any
15605 (if (and org-calendar-follow-timestamp-change
15606 (get-buffer-window "*Calendar*" t)
15607 (memq org-ts-what '(day month year)))
15608 (org-recenter-calendar (time-to-days time))))))
15610 (defun org-modify-ts-extra (s pos n dm)
15611 "Change the different parts of the lead-time and repeat fields in timestamp."
15612 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15613 ng h m new rem)
15614 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15615 (cond
15616 ((or (org-pos-in-match-range pos 2)
15617 (org-pos-in-match-range pos 3))
15618 (setq m (string-to-number (match-string 3 s))
15619 h (string-to-number (match-string 2 s)))
15620 (if (org-pos-in-match-range pos 2)
15621 (setq h (+ h n))
15622 (setq n (* dm (org-no-warnings (signum n))))
15623 (when (not (= 0 (setq rem (% m dm))))
15624 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
15625 (setq m (+ m n)))
15626 (if (< m 0) (setq m (+ m 60) h (1- h)))
15627 (if (> m 59) (setq m (- m 60) h (1+ h)))
15628 (setq h (min 24 (max 0 h)))
15629 (setq ng 1 new (format "-%02d:%02d" h m)))
15630 ((org-pos-in-match-range pos 6)
15631 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15632 ((org-pos-in-match-range pos 5)
15633 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
15635 ((org-pos-in-match-range pos 9)
15636 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
15637 ((org-pos-in-match-range pos 8)
15638 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
15640 (when ng
15641 (setq s (concat
15642 (substring s 0 (match-beginning ng))
15644 (substring s (match-end ng))))))
15647 (defun org-recenter-calendar (date)
15648 "If the calendar is visible, recenter it to DATE."
15649 (let* ((win (selected-window))
15650 (cwin (get-buffer-window "*Calendar*" t))
15651 (calendar-move-hook nil))
15652 (when cwin
15653 (select-window cwin)
15654 (calendar-goto-date (if (listp date) date
15655 (calendar-gregorian-from-absolute date)))
15656 (select-window win))))
15658 (defun org-goto-calendar (&optional arg)
15659 "Go to the Emacs calendar at the current date.
15660 If there is a time stamp in the current line, go to that date.
15661 A prefix ARG can be used to force the current date."
15662 (interactive "P")
15663 (let ((tsr org-ts-regexp) diff
15664 (calendar-move-hook nil)
15665 (calendar-view-holidays-initially-flag nil)
15666 (calendar-view-diary-initially-flag nil))
15667 (if (or (org-at-timestamp-p)
15668 (save-excursion
15669 (beginning-of-line 1)
15670 (looking-at (concat ".*" tsr))))
15671 (let ((d1 (time-to-days (current-time)))
15672 (d2 (time-to-days
15673 (org-time-string-to-time (match-string 1)))))
15674 (setq diff (- d2 d1))))
15675 (calendar)
15676 (calendar-goto-today)
15677 (if (and diff (not arg)) (calendar-forward-day diff))))
15679 (defun org-get-date-from-calendar ()
15680 "Return a list (month day year) of date at point in calendar."
15681 (with-current-buffer "*Calendar*"
15682 (save-match-data
15683 (calendar-cursor-to-date))))
15685 (defun org-date-from-calendar ()
15686 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
15687 If there is already a time stamp at the cursor position, update it."
15688 (interactive)
15689 (if (org-at-timestamp-p t)
15690 (org-timestamp-change 0 'calendar)
15691 (let ((cal-date (org-get-date-from-calendar)))
15692 (org-insert-time-stamp
15693 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
15695 (defun org-minutes-to-hh:mm-string (m)
15696 "Compute H:MM from a number of minutes."
15697 (let ((h (/ m 60)))
15698 (setq m (- m (* 60 h)))
15699 (format org-time-clocksum-format h m)))
15701 (defun org-hh:mm-string-to-minutes (s)
15702 "Convert a string H:MM to a number of minutes.
15703 If the string is just a number, interpret it as minutes.
15704 In fact, the first hh:mm or number in the string will be taken,
15705 there can be extra stuff in the string.
15706 If no number is found, the return value is 0."
15707 (cond
15708 ((integerp s) s)
15709 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
15710 (+ (* (string-to-number (match-string 1 s)) 60)
15711 (string-to-number (match-string 2 s))))
15712 ((string-match "\\([0-9]+\\)" s)
15713 (string-to-number (match-string 1 s)))
15714 (t 0)))
15716 (defcustom org-effort-durations
15717 `(("h" . 60)
15718 ("d" . ,(* 60 8))
15719 ("w" . ,(* 60 8 5))
15720 ("m" . ,(* 60 8 5 4))
15721 ("y" . ,(* 60 8 5 40)))
15722 "Conversion factor to minutes for an effort modifier.
15724 Each entry has the form (MODIFIER . MINUTES).
15726 In an effort string, a number followed by MODIFIER is multiplied
15727 by the specified number of MINUTES to obtain an effort in
15728 minutes.
15730 For example, if the value of this variable is ((\"hours\" . 60)), then an
15731 effort string \"2hours\" is equivalent to 120 minutes."
15732 :group 'org-agenda
15733 :type '(alist :key-type (string :tag "Modifier")
15734 :value-type (number :tag "Minutes")))
15736 (defun org-duration-string-to-minutes (s)
15737 "Convert a duration string S to minutes.
15739 A bare number is interpreted as minutes, modifiers can be set by
15740 customizing `org-effort-durations' (which see).
15742 Entries containing a colon are interpreted as H:MM by
15743 `org-hh:mm-string-to-minutes'."
15744 (let ((result 0)
15745 (re (concat "\\([0-9]+\\) *\\("
15746 (regexp-opt (mapcar 'car org-effort-durations))
15747 "\\)")))
15748 (while (string-match re s)
15749 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
15750 (string-to-number (match-string 1 s))))
15751 (setq s (replace-match "" nil t s)))
15752 (incf result (org-hh:mm-string-to-minutes s))
15753 result))
15755 ;;;; Files
15757 (defun org-save-all-org-buffers ()
15758 "Save all Org-mode buffers without user confirmation."
15759 (interactive)
15760 (message "Saving all Org-mode buffers...")
15761 (save-some-buffers t 'org-mode-p)
15762 (when (featurep 'org-id) (org-id-locations-save))
15763 (message "Saving all Org-mode buffers... done"))
15765 (defun org-revert-all-org-buffers ()
15766 "Revert all Org-mode buffers.
15767 Prompt for confirmation when there are unsaved changes.
15768 Be sure you know what you are doing before letting this function
15769 overwrite your changes.
15771 This function is useful in a setup where one tracks org files
15772 with a version control system, to revert on one machine after pulling
15773 changes from another. I believe the procedure must be like this:
15775 1. M-x org-save-all-org-buffers
15776 2. Pull changes from the other machine, resolve conflicts
15777 3. M-x org-revert-all-org-buffers"
15778 (interactive)
15779 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
15780 (error "Abort"))
15781 (save-excursion
15782 (save-window-excursion
15783 (mapc
15784 (lambda (b)
15785 (when (and (with-current-buffer b (org-mode-p))
15786 (with-current-buffer b buffer-file-name))
15787 (switch-to-buffer b)
15788 (revert-buffer t 'no-confirm)))
15789 (buffer-list))
15790 (when (and (featurep 'org-id) org-id-track-globally)
15791 (org-id-locations-load)))))
15793 ;;;; Agenda files
15795 ;;;###autoload
15796 (defun org-switchb (&optional arg)
15797 "Switch between Org buffers.
15798 With a prefix argument, restrict available to files.
15799 With two prefix arguments, restrict available buffers to agenda files.
15801 Defaults to `iswitchb' for buffer name completion.
15802 Set `org-completion-use-ido' to make it use ido instead."
15803 (interactive "P")
15804 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
15805 ((equal arg '(16)) (org-buffer-list 'agenda))
15806 (t (org-buffer-list))))
15807 (org-completion-use-iswitchb org-completion-use-iswitchb)
15808 (org-completion-use-ido org-completion-use-ido))
15809 (unless (or org-completion-use-ido org-completion-use-iswitchb)
15810 (setq org-completion-use-iswitchb t))
15811 (switch-to-buffer
15812 (org-icompleting-read "Org buffer: "
15813 (mapcar 'list (mapcar 'buffer-name blist))
15814 nil t))))
15816 ;;; Define some older names previously used for this functionality
15817 ;;;###autoload
15818 (defalias 'org-ido-switchb 'org-switchb)
15819 ;;;###autoload
15820 (defalias 'org-iswitchb 'org-switchb)
15822 (defun org-buffer-list (&optional predicate exclude-tmp)
15823 "Return a list of Org buffers.
15824 PREDICATE can be `export', `files' or `agenda'.
15826 export restrict the list to Export buffers.
15827 files restrict the list to buffers visiting Org files.
15828 agenda restrict the list to buffers visiting agenda files.
15830 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
15831 (let* ((bfn nil)
15832 (agenda-files (and (eq predicate 'agenda)
15833 (mapcar 'file-truename (org-agenda-files t))))
15834 (filter
15835 (cond
15836 ((eq predicate 'files)
15837 (lambda (b) (with-current-buffer b (org-mode-p))))
15838 ((eq predicate 'export)
15839 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
15840 ((eq predicate 'agenda)
15841 (lambda (b)
15842 (with-current-buffer b
15843 (and (org-mode-p)
15844 (setq bfn (buffer-file-name b))
15845 (member (file-truename bfn) agenda-files)))))
15846 (t (lambda (b) (with-current-buffer b
15847 (or (org-mode-p)
15848 (string-match "\*Org .*Export"
15849 (buffer-name b)))))))))
15850 (delq nil
15851 (mapcar
15852 (lambda(b)
15853 (if (and (funcall filter b)
15854 (or (not exclude-tmp)
15855 (not (string-match "tmp" (buffer-name b)))))
15857 nil))
15858 (buffer-list)))))
15860 (defun org-agenda-files (&optional unrestricted archives)
15861 "Get the list of agenda files.
15862 Optional UNRESTRICTED means return the full list even if a restriction
15863 is currently in place.
15864 When ARCHIVES is t, include all archive files that are really being
15865 used by the agenda files. If ARCHIVE is `ifmode', do this only if
15866 `org-agenda-archives-mode' is t."
15867 (let ((files
15868 (cond
15869 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
15870 ((stringp org-agenda-files) (org-read-agenda-file-list))
15871 ((listp org-agenda-files) org-agenda-files)
15872 (t (error "Invalid value of `org-agenda-files'")))))
15873 (setq files (apply 'append
15874 (mapcar (lambda (f)
15875 (if (file-directory-p f)
15876 (directory-files
15877 f t org-agenda-file-regexp)
15878 (list f)))
15879 files)))
15880 (when org-agenda-skip-unavailable-files
15881 (setq files (delq nil
15882 (mapcar (function
15883 (lambda (file)
15884 (and (file-readable-p file) file)))
15885 files))))
15886 (when (or (eq archives t)
15887 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
15888 (setq files (org-add-archive-files files)))
15889 files))
15891 (defun org-agenda-file-p (&optional file)
15892 "Return non-nil, if FILE is an agenda file.
15893 If FILE is omitted, use the file associated with the current
15894 buffer."
15895 (member (or file (buffer-file-name))
15896 (org-agenda-files t)))
15898 (defun org-edit-agenda-file-list ()
15899 "Edit the list of agenda files.
15900 Depending on setup, this either uses customize to edit the variable
15901 `org-agenda-files', or it visits the file that is holding the list. In the
15902 latter case, the buffer is set up in a way that saving it automatically kills
15903 the buffer and restores the previous window configuration."
15904 (interactive)
15905 (if (stringp org-agenda-files)
15906 (let ((cw (current-window-configuration)))
15907 (find-file org-agenda-files)
15908 (org-set-local 'org-window-configuration cw)
15909 (org-add-hook 'after-save-hook
15910 (lambda ()
15911 (set-window-configuration
15912 (prog1 org-window-configuration
15913 (kill-buffer (current-buffer))))
15914 (org-install-agenda-files-menu)
15915 (message "New agenda file list installed"))
15916 nil 'local)
15917 (message "%s" (substitute-command-keys
15918 "Edit list and finish with \\[save-buffer]")))
15919 (customize-variable 'org-agenda-files)))
15921 (defun org-store-new-agenda-file-list (list)
15922 "Set new value for the agenda file list and save it correctly."
15923 (if (stringp org-agenda-files)
15924 (let ((fe (org-read-agenda-file-list t)) b u)
15925 (while (setq b (find-buffer-visiting org-agenda-files))
15926 (kill-buffer b))
15927 (with-temp-file org-agenda-files
15928 (insert
15929 (mapconcat
15930 (lambda (f) ;; Keep un-expanded entries.
15931 (if (setq u (assoc f fe))
15932 (cdr u)
15934 list "\n")
15935 "\n")))
15936 (let ((org-mode-hook nil) (org-inhibit-startup t)
15937 (org-insert-mode-line-in-empty-file nil))
15938 (setq org-agenda-files list)
15939 (customize-save-variable 'org-agenda-files org-agenda-files))))
15941 (defun org-read-agenda-file-list (&optional pair-with-expansion)
15942 "Read the list of agenda files from a file.
15943 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
15944 filenames, used by `org-store-new-agenda-file-list' to write back
15945 un-expanded file names."
15946 (when (file-directory-p org-agenda-files)
15947 (error "`org-agenda-files' cannot be a single directory"))
15948 (when (stringp org-agenda-files)
15949 (with-temp-buffer
15950 (insert-file-contents org-agenda-files)
15951 (mapcar
15952 (lambda (f)
15953 (let ((e (expand-file-name (substitute-in-file-name f)
15954 org-directory)))
15955 (if pair-with-expansion
15956 (cons e f)
15957 e)))
15958 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
15960 ;;;###autoload
15961 (defun org-cycle-agenda-files ()
15962 "Cycle through the files in `org-agenda-files'.
15963 If the current buffer visits an agenda file, find the next one in the list.
15964 If the current buffer does not, find the first agenda file."
15965 (interactive)
15966 (let* ((fs (org-agenda-files t))
15967 (files (append fs (list (car fs))))
15968 (tcf (if buffer-file-name (file-truename buffer-file-name)))
15969 file)
15970 (unless files (error "No agenda files"))
15971 (catch 'exit
15972 (while (setq file (pop files))
15973 (if (equal (file-truename file) tcf)
15974 (when (car files)
15975 (find-file (car files))
15976 (throw 'exit t))))
15977 (find-file (car fs)))
15978 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
15980 (defun org-agenda-file-to-front (&optional to-end)
15981 "Move/add the current file to the top of the agenda file list.
15982 If the file is not present in the list, it is added to the front. If it is
15983 present, it is moved there. With optional argument TO-END, add/move to the
15984 end of the list."
15985 (interactive "P")
15986 (let ((org-agenda-skip-unavailable-files nil)
15987 (file-alist (mapcar (lambda (x)
15988 (cons (file-truename x) x))
15989 (org-agenda-files t)))
15990 (ctf (file-truename buffer-file-name))
15991 x had)
15992 (setq x (assoc ctf file-alist) had x)
15994 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
15995 (if to-end
15996 (setq file-alist (append (delq x file-alist) (list x)))
15997 (setq file-alist (cons x (delq x file-alist))))
15998 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
15999 (org-install-agenda-files-menu)
16000 (message "File %s to %s of agenda file list"
16001 (if had "moved" "added") (if to-end "end" "front"))))
16003 (defun org-remove-file (&optional file)
16004 "Remove current file from the list of files in variable `org-agenda-files'.
16005 These are the files which are being checked for agenda entries.
16006 Optional argument FILE means use this file instead of the current."
16007 (interactive)
16008 (let* ((org-agenda-skip-unavailable-files nil)
16009 (file (or file buffer-file-name))
16010 (true-file (file-truename file))
16011 (afile (abbreviate-file-name file))
16012 (files (delq nil (mapcar
16013 (lambda (x)
16014 (if (equal true-file
16015 (file-truename x))
16016 nil x))
16017 (org-agenda-files t)))))
16018 (if (not (= (length files) (length (org-agenda-files t))))
16019 (progn
16020 (org-store-new-agenda-file-list files)
16021 (org-install-agenda-files-menu)
16022 (message "Removed file: %s" afile))
16023 (message "File was not in list: %s (not removed)" afile))))
16025 (defun org-file-menu-entry (file)
16026 (vector file (list 'find-file file) t))
16028 (defun org-check-agenda-file (file)
16029 "Make sure FILE exists. If not, ask user what to do."
16030 (when (not (file-exists-p file))
16031 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16032 (abbreviate-file-name file))
16033 (let ((r (downcase (read-char-exclusive))))
16034 (cond
16035 ((equal r ?r)
16036 (org-remove-file file)
16037 (throw 'nextfile t))
16038 (t (error "Abort"))))))
16040 (defun org-get-agenda-file-buffer (file)
16041 "Get a buffer visiting FILE. If the buffer needs to be created, add
16042 it to the list of buffers which might be released later."
16043 (let ((buf (org-find-base-buffer-visiting file)))
16044 (if buf
16045 buf ; just return it
16046 ;; Make a new buffer and remember it
16047 (setq buf (find-file-noselect file))
16048 (if buf (push buf org-agenda-new-buffers))
16049 buf)))
16051 (defun org-release-buffers (blist)
16052 "Release all buffers in list, asking the user for confirmation when needed.
16053 When a buffer is unmodified, it is just killed. When modified, it is saved
16054 \(if the user agrees) and then killed."
16055 (let (buf file)
16056 (while (setq buf (pop blist))
16057 (setq file (buffer-file-name buf))
16058 (when (and (buffer-modified-p buf)
16059 file
16060 (y-or-n-p (format "Save file %s? " file)))
16061 (with-current-buffer buf (save-buffer)))
16062 (kill-buffer buf))))
16064 (defun org-prepare-agenda-buffers (files)
16065 "Create buffers for all agenda files, protect archived trees and comments."
16066 (interactive)
16067 (let ((pa '(:org-archived t))
16068 (pc '(:org-comment t))
16069 (pall '(:org-archived t :org-comment t))
16070 (inhibit-read-only t)
16071 (rea (concat ":" org-archive-tag ":"))
16072 bmp file re)
16073 (save-excursion
16074 (save-restriction
16075 (while (setq file (pop files))
16076 (catch 'nextfile
16077 (if (bufferp file)
16078 (set-buffer file)
16079 (org-check-agenda-file file)
16080 (set-buffer (org-get-agenda-file-buffer file)))
16081 (widen)
16082 (setq bmp (buffer-modified-p))
16083 (org-refresh-category-properties)
16084 (setq org-todo-keywords-for-agenda
16085 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16086 (setq org-done-keywords-for-agenda
16087 (append org-done-keywords-for-agenda org-done-keywords))
16088 (setq org-todo-keyword-alist-for-agenda
16089 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16090 (setq org-drawers-for-agenda
16091 (append org-drawers-for-agenda org-drawers))
16092 (setq org-tag-alist-for-agenda
16093 (append org-tag-alist-for-agenda org-tag-alist))
16095 (save-excursion
16096 (remove-text-properties (point-min) (point-max) pall)
16097 (when org-agenda-skip-archived-trees
16098 (goto-char (point-min))
16099 (while (re-search-forward rea nil t)
16100 (if (org-on-heading-p t)
16101 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16102 (goto-char (point-min))
16103 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
16104 (while (re-search-forward re nil t)
16105 (add-text-properties
16106 (match-beginning 0) (org-end-of-subtree t) pc)))
16107 (set-buffer-modified-p bmp)))))
16108 (setq org-todo-keywords-for-agenda
16109 (org-uniquify org-todo-keywords-for-agenda))
16110 (setq org-todo-keyword-alist-for-agenda
16111 (org-uniquify org-todo-keyword-alist-for-agenda)
16112 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16114 ;;;; Embedded LaTeX
16116 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16117 "Keymap for the minor `org-cdlatex-mode'.")
16119 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16120 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16121 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16122 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16123 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16125 (defvar org-cdlatex-texmathp-advice-is-done nil
16126 "Flag remembering if we have applied the advice to texmathp already.")
16128 (define-minor-mode org-cdlatex-mode
16129 "Toggle the minor `org-cdlatex-mode'.
16130 This mode supports entering LaTeX environment and math in LaTeX fragments
16131 in Org-mode.
16132 \\{org-cdlatex-mode-map}"
16133 nil " OCDL" nil
16134 (when org-cdlatex-mode (require 'cdlatex))
16135 (unless org-cdlatex-texmathp-advice-is-done
16136 (setq org-cdlatex-texmathp-advice-is-done t)
16137 (defadvice texmathp (around org-math-always-on activate)
16138 "Always return t in org-mode buffers.
16139 This is because we want to insert math symbols without dollars even outside
16140 the LaTeX math segments. If Orgmode thinks that point is actually inside
16141 an embedded LaTeX fragment, let texmathp do its job.
16142 \\[org-cdlatex-mode-map]"
16143 (interactive)
16144 (let (p)
16145 (cond
16146 ((not (org-mode-p)) ad-do-it)
16147 ((eq this-command 'cdlatex-math-symbol)
16148 (setq ad-return-value t
16149 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16151 (let ((p (org-inside-LaTeX-fragment-p)))
16152 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16153 (setq ad-return-value t
16154 texmathp-why '("Org-mode embedded math" . 0))
16155 (if p ad-do-it)))))))))
16157 (defun turn-on-org-cdlatex ()
16158 "Unconditionally turn on `org-cdlatex-mode'."
16159 (org-cdlatex-mode 1))
16161 (defun org-inside-LaTeX-fragment-p ()
16162 "Test if point is inside a LaTeX fragment.
16163 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16164 sequence appearing also before point.
16165 Even though the matchers for math are configurable, this function assumes
16166 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16167 delimiters are skipped when they have been removed by customization.
16168 The return value is nil, or a cons cell with the delimiter and the
16169 position of this delimiter.
16171 This function does a reasonably good job, but can locally be fooled by
16172 for example currency specifications. For example it will assume being in
16173 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16174 fragments that are properly closed, but during editing, we have to live
16175 with the uncertainty caused by missing closing delimiters. This function
16176 looks only before point, not after."
16177 (catch 'exit
16178 (let ((pos (point))
16179 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16180 (lim (progn
16181 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16182 (point)))
16183 dd-on str (start 0) m re)
16184 (goto-char pos)
16185 (when dodollar
16186 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16187 re (nth 1 (assoc "$" org-latex-regexps)))
16188 (while (string-match re str start)
16189 (cond
16190 ((= (match-end 0) (length str))
16191 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16192 ((= (match-end 0) (- (length str) 5))
16193 (throw 'exit nil))
16194 (t (setq start (match-end 0))))))
16195 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16196 (goto-char pos)
16197 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16198 (and (match-beginning 2) (throw 'exit nil))
16199 ;; count $$
16200 (while (re-search-backward "\\$\\$" lim t)
16201 (setq dd-on (not dd-on)))
16202 (goto-char pos)
16203 (if dd-on (cons "$$" m))))))
16205 (defun org-inside-latex-macro-p ()
16206 "Is point inside a LaTeX macro or its arguments?"
16207 (save-match-data
16208 (org-in-regexp
16209 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16211 (defun org-try-cdlatex-tab ()
16212 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16213 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16214 - inside a LaTeX fragment, or
16215 - after the first word in a line, where an abbreviation expansion could
16216 insert a LaTeX environment."
16217 (when org-cdlatex-mode
16218 (cond
16219 ((save-excursion
16220 (skip-chars-backward "a-zA-Z0-9*")
16221 (skip-chars-backward " \t")
16222 (bolp))
16223 (cdlatex-tab) t)
16224 ((org-inside-LaTeX-fragment-p)
16225 (cdlatex-tab) t)
16226 (t nil))))
16228 (defun org-cdlatex-underscore-caret (&optional arg)
16229 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16230 Revert to the normal definition outside of these fragments."
16231 (interactive "P")
16232 (if (org-inside-LaTeX-fragment-p)
16233 (call-interactively 'cdlatex-sub-superscript)
16234 (let (org-cdlatex-mode)
16235 (call-interactively (key-binding (vector last-input-event))))))
16237 (defun org-cdlatex-math-modify (&optional arg)
16238 "Execute `cdlatex-math-modify' in LaTeX fragments.
16239 Revert to the normal definition outside of these fragments."
16240 (interactive "P")
16241 (if (org-inside-LaTeX-fragment-p)
16242 (call-interactively 'cdlatex-math-modify)
16243 (let (org-cdlatex-mode)
16244 (call-interactively (key-binding (vector last-input-event))))))
16246 (defvar org-latex-fragment-image-overlays nil
16247 "List of overlays carrying the images of latex fragments.")
16248 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16250 (defun org-remove-latex-fragment-image-overlays ()
16251 "Remove all overlays with LaTeX fragment images in current buffer."
16252 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16253 (setq org-latex-fragment-image-overlays nil))
16255 (defun org-preview-latex-fragment (&optional subtree)
16256 "Preview the LaTeX fragment at point, or all locally or globally.
16257 If the cursor is in a LaTeX fragment, create the image and overlay
16258 it over the source code. If there is no fragment at point, display
16259 all fragments in the current text, from one headline to the next. With
16260 prefix SUBTREE, display all fragments in the current subtree. With a
16261 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16262 the cursor is before the first headline,
16263 display all fragments in the buffer.
16264 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16265 (interactive "P")
16266 (org-remove-latex-fragment-image-overlays)
16267 (save-excursion
16268 (save-restriction
16269 (let (beg end at msg)
16270 (cond
16271 ((or (equal subtree '(16))
16272 (not (save-excursion
16273 (re-search-backward (concat "^" outline-regexp) nil t))))
16274 (setq beg (point-min) end (point-max)
16275 msg "Creating images for buffer...%s"))
16276 ((equal subtree '(4))
16277 (org-back-to-heading)
16278 (setq beg (point) end (org-end-of-subtree t)
16279 msg "Creating images for subtree...%s"))
16281 (if (setq at (org-inside-LaTeX-fragment-p))
16282 (goto-char (max (point-min) (- (cdr at) 2)))
16283 (org-back-to-heading))
16284 (setq beg (point) end (progn (outline-next-heading) (point))
16285 msg (if at "Creating image...%s"
16286 "Creating images for entry...%s"))))
16287 (message msg "")
16288 (narrow-to-region beg end)
16289 (goto-char beg)
16290 (org-format-latex
16291 (concat "ltxpng/" (file-name-sans-extension
16292 (file-name-nondirectory
16293 buffer-file-name)))
16294 default-directory 'overlays msg at 'forbuffer 'dvipng)
16295 (message msg "done. Use `C-c C-c' to remove images.")))))
16297 (defvar org-latex-regexps
16298 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16299 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16300 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16301 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16302 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16303 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16304 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16305 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16306 "Regular expressions for matching embedded LaTeX.")
16308 (defvar org-export-have-math nil) ;; dynamic scoping
16309 (defun org-format-latex (prefix &optional dir overlays msg at
16310 forbuffer processing-type)
16311 "Replace LaTeX fragments with links to an image, and produce images.
16312 Some of the options can be changed using the variable
16313 `org-format-latex-options'."
16314 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16315 (let* ((prefixnodir (file-name-nondirectory prefix))
16316 (absprefix (expand-file-name prefix dir))
16317 (todir (file-name-directory absprefix))
16318 (opt org-format-latex-options)
16319 (matchers (plist-get opt :matchers))
16320 (re-list org-latex-regexps)
16321 (org-format-latex-header-extra
16322 (plist-get (org-infile-export-plist) :latex-header-extra))
16323 (cnt 0) txt hash link beg end re e checkdir
16324 executables-checked string
16325 m n block linkfile movefile ov)
16326 ;; Check the different regular expressions
16327 (while (setq e (pop re-list))
16328 (setq m (car e) re (nth 1 e) n (nth 2 e)
16329 block (if (nth 3 e) "\n\n" ""))
16330 (when (member m matchers)
16331 (goto-char (point-min))
16332 (while (re-search-forward re nil t)
16333 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16334 (not (get-text-property (match-beginning n)
16335 'org-protected))
16336 (or (not overlays)
16337 (not (eq (get-char-property (match-beginning n)
16338 'org-overlay-type)
16339 'org-latex-overlay))))
16340 (setq org-export-have-math t)
16341 (cond
16342 ((eq processing-type 'verbatim)
16343 ;; Leave the text verbatim, just protect it
16344 (add-text-properties (match-beginning n) (match-end n)
16345 '(org-protected t)))
16346 ((eq processing-type 'mathjax)
16347 ;; Prepare for MathJax processing
16348 (setq string (match-string n))
16349 (if (member m '("$" "$1"))
16350 (save-excursion
16351 (delete-region (match-beginning n) (match-end n))
16352 (goto-char (match-beginning n))
16353 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16354 "\\)")
16355 '(org-protected t))))
16356 (add-text-properties (match-beginning n) (match-end n)
16357 '(org-protected t))))
16358 ((or (eq processing-type 'dvipng) t)
16359 ;; Process to an image
16360 (setq txt (match-string n)
16361 beg (match-beginning n) end (match-end n)
16362 cnt (1+ cnt))
16363 (let (print-length print-level) ; make sure full list is printed
16364 (setq hash (sha1 (prin1-to-string
16365 (list org-format-latex-header
16366 org-format-latex-header-extra
16367 org-export-latex-default-packages-alist
16368 org-export-latex-packages-alist
16369 org-format-latex-options
16370 forbuffer txt)))
16371 linkfile (format "%s_%s.png" prefix hash)
16372 movefile (format "%s_%s.png" absprefix hash)))
16373 (setq link (concat block "[[file:" linkfile "]]" block))
16374 (if msg (message msg cnt))
16375 (goto-char beg)
16376 (unless checkdir ; make sure the directory exists
16377 (setq checkdir t)
16378 (or (file-directory-p todir) (make-directory todir t)))
16380 (unless executables-checked
16381 (org-check-external-command
16382 "latex" "needed to convert LaTeX fragments to images")
16383 (org-check-external-command
16384 "dvipng" "needed to convert LaTeX fragments to images")
16385 (setq executables-checked t))
16387 (unless (file-exists-p movefile)
16388 (org-create-formula-image
16389 txt movefile opt forbuffer))
16390 (if overlays
16391 (progn
16392 (mapc (lambda (o)
16393 (if (eq (overlay-get o 'org-overlay-type)
16394 'org-latex-overlay)
16395 (delete-overlay o)))
16396 (overlays-in beg end))
16397 (setq ov (make-overlay beg end))
16398 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16399 (if (featurep 'xemacs)
16400 (progn
16401 (overlay-put ov 'invisible t)
16402 (overlay-put
16403 ov 'end-glyph
16404 (make-glyph (vector 'png :file movefile))))
16405 (overlay-put
16406 ov 'display
16407 (list 'image :type 'png :file movefile :ascent 'center)))
16408 (push ov org-latex-fragment-image-overlays)
16409 (goto-char end))
16410 (delete-region beg end)
16411 (insert (org-add-props link
16412 (list 'org-latex-src
16413 (replace-regexp-in-string
16414 "\"" "" txt)))))))))))))
16416 ;; This function borrows from Ganesh Swami's latex2png.el
16417 (defun org-create-formula-image (string tofile options buffer)
16418 "This calls dvipng."
16419 (require 'org-latex)
16420 (let* ((tmpdir (if (featurep 'xemacs)
16421 (temp-directory)
16422 temporary-file-directory))
16423 (texfilebase (make-temp-name
16424 (expand-file-name "orgtex" tmpdir)))
16425 (texfile (concat texfilebase ".tex"))
16426 (dvifile (concat texfilebase ".dvi"))
16427 (pngfile (concat texfilebase ".png"))
16428 (fnh (if (featurep 'xemacs)
16429 (font-height (get-face-font 'default))
16430 (face-attribute 'default :height nil)))
16431 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
16432 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
16433 (fg (or (plist-get options (if buffer :foreground :html-foreground))
16434 "Black"))
16435 (bg (or (plist-get options (if buffer :background :html-background))
16436 "Transparent")))
16437 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
16438 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
16439 (with-temp-file texfile
16440 (insert (org-splice-latex-header
16441 org-format-latex-header
16442 org-export-latex-default-packages-alist
16443 org-export-latex-packages-alist t
16444 org-format-latex-header-extra))
16445 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
16446 (require 'org-latex)
16447 (org-export-latex-fix-inputenc))
16448 (let ((dir default-directory))
16449 (condition-case nil
16450 (progn
16451 (cd tmpdir)
16452 (call-process "latex" nil nil nil texfile))
16453 (error nil))
16454 (cd dir))
16455 (if (not (file-exists-p dvifile))
16456 (progn (message "Failed to create dvi file from %s" texfile) nil)
16457 (condition-case nil
16458 (call-process "dvipng" nil nil nil
16459 "-fg" fg "-bg" bg
16460 "-D" dpi
16461 ;;"-x" scale "-y" scale
16462 "-T" "tight"
16463 "-o" pngfile
16464 dvifile)
16465 (error nil))
16466 (if (not (file-exists-p pngfile))
16467 (if org-format-latex-signal-error
16468 (error "Failed to create png file from %s" texfile)
16469 (message "Failed to create png file from %s" texfile)
16470 nil)
16471 ;; Use the requested file name and clean up
16472 (copy-file pngfile tofile 'replace)
16473 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16474 (delete-file (concat texfilebase e)))
16475 pngfile))))
16477 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
16478 "Fill a LaTeX header template TPL.
16479 In the template, the following place holders will be recognized:
16481 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
16482 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
16483 [PACKAGES] \\usepackage statements for PKG
16484 [NO-PACKAGES] do not include PKG
16485 [EXTRA] the string EXTRA
16486 [NO-EXTRA] do not include EXTRA
16488 For backward compatibility, if both the positive and the negative place
16489 holder is missing, the positive one (without the \"NO-\") will be
16490 assumed to be present at the end of the template.
16491 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
16492 EXTRA is a string.
16493 SNIPPETS-P indicates if this is run to create snippet images for HTML."
16494 (let (rpl (end ""))
16495 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
16496 (setq rpl (if (or (match-end 1) (not def-pkg))
16497 "" (org-latex-packages-to-string def-pkg snippets-p t))
16498 tpl (replace-match rpl t t tpl))
16499 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
16501 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
16502 (setq rpl (if (or (match-end 1) (not pkg))
16503 "" (org-latex-packages-to-string pkg snippets-p t))
16504 tpl (replace-match rpl t t tpl))
16505 (if pkg (setq end
16506 (concat end "\n"
16507 (org-latex-packages-to-string pkg snippets-p)))))
16509 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
16510 (setq rpl (if (or (match-end 1) (not extra))
16511 "" (concat extra "\n"))
16512 tpl (replace-match rpl t t tpl))
16513 (if (and extra (string-match "\\S-" extra))
16514 (setq end (concat end "\n" extra))))
16516 (if (string-match "\\S-" end)
16517 (concat tpl "\n" end)
16518 tpl)))
16520 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
16521 "Turn an alist of packages into a string with the \\usepackage macros."
16522 (setq pkg (mapconcat (lambda(p)
16523 (cond
16524 ((stringp p) p)
16525 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
16526 (format "%% Package %s omitted" (cadr p)))
16527 ((equal "" (car p))
16528 (format "\\usepackage{%s}" (cadr p)))
16530 (format "\\usepackage[%s]{%s}"
16531 (car p) (cadr p)))))
16533 "\n"))
16534 (if newline (concat pkg "\n") pkg))
16536 (defun org-dvipng-color (attr)
16537 "Return an rgb color specification for dvipng."
16538 (apply 'format "rgb %s %s %s"
16539 (mapcar 'org-normalize-color
16540 (color-values (face-attribute 'default attr nil)))))
16542 (defun org-normalize-color (value)
16543 "Return string to be used as color value for an RGB component."
16544 (format "%g" (/ value 65535.0)))
16546 ;; Image display
16549 (defvar org-inline-image-overlays nil)
16550 (make-variable-buffer-local 'org-inline-image-overlays)
16552 (defun org-toggle-inline-images (&optional include-linked)
16553 "Toggle the display of inline images.
16554 INCLUDE-LINKED is passed to `org-display-inline-images'."
16555 (interactive "P")
16556 (if org-inline-image-overlays
16557 (progn
16558 (org-remove-inline-images)
16559 (message "Inline image display turned off"))
16560 (org-display-inline-images include-linked)
16561 (if org-inline-image-overlays
16562 (message "%d images displayed inline"
16563 (length org-inline-image-overlays))
16564 (message "No images to display inline"))))
16566 (defun org-display-inline-images (&optional include-linked refresh beg end)
16567 "Display inline images.
16568 Normally only links without a description part are inlined, because this
16569 is how it will work for export. When INCLUDE-LINKED is set, also links
16570 with a description part will be inlined. This can be nice for a quick
16571 look at those images, but it does not reflect what exported files will look
16572 like.
16573 When REFRESH is set, refresh existing images between BEG and END.
16574 This will create new image displays only if necessary.
16575 BEG and END default to the buffer boundaries."
16576 (interactive "P")
16577 (unless refresh
16578 (org-remove-inline-images)
16579 (if (fboundp 'clear-image-cache) (clear-image-cache)))
16580 (save-excursion
16581 (save-restriction
16582 (widen)
16583 (setq beg (or beg (point-min)) end (or end (point-max)))
16584 (goto-char (point-min))
16585 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
16586 (substring (org-image-file-name-regexp) 0 -2)
16587 "\\)\\]" (if include-linked "" "\\]")))
16588 old file ov img)
16589 (while (re-search-forward re end t)
16590 (setq old (get-char-property-and-overlay (match-beginning 1)
16591 'org-image-overlay))
16592 (setq file (expand-file-name
16593 (concat (or (match-string 3) "") (match-string 4))))
16594 (when (file-exists-p file)
16595 (if (and (car-safe old) refresh)
16596 (image-refresh (overlay-get (cdr old) 'display))
16597 (setq img (save-match-data (create-image file)))
16598 (when img
16599 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
16600 (overlay-put ov 'display img)
16601 (overlay-put ov 'face 'default)
16602 (overlay-put ov 'org-image-overlay t)
16603 (overlay-put ov 'modification-hooks
16604 (list 'org-display-inline-modification-hook))
16605 (push ov org-inline-image-overlays)))))))))
16607 (defun org-display-inline-modification-hook (ov after beg end &optional len)
16608 "Remove inline-display overlay if a corresponding region is modified."
16609 (let ((inhibit-modification-hooks t))
16610 (when (and ov after)
16611 (delete ov org-inline-image-overlays)
16612 (delete-overlay ov))))
16614 (defun org-remove-inline-images ()
16615 "Remove inline display of images."
16616 (interactive)
16617 (mapc 'delete-overlay org-inline-image-overlays)
16618 (setq org-inline-image-overlays nil))
16620 ;;;; Key bindings
16622 ;; Make `C-c C-x' a prefix key
16623 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
16625 ;; TAB key with modifiers
16626 (org-defkey org-mode-map "\C-i" 'org-cycle)
16627 (org-defkey org-mode-map [(tab)] 'org-cycle)
16628 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
16629 (org-defkey org-mode-map [(meta tab)] 'pcomplete)
16630 (org-defkey org-mode-map "\M-\t" 'pcomplete)
16631 (org-defkey org-mode-map "\M-\C-i" 'pcomplete)
16632 ;; The following line is necessary under Suse GNU/Linux
16633 (unless (featurep 'xemacs)
16634 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
16635 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
16636 (define-key org-mode-map [backtab] 'org-shifttab)
16638 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
16639 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
16640 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
16642 ;; Cursor keys with modifiers
16643 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
16644 (org-defkey org-mode-map [(meta right)] 'org-metaright)
16645 (org-defkey org-mode-map [(meta up)] 'org-metaup)
16646 (org-defkey org-mode-map [(meta down)] 'org-metadown)
16648 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
16649 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
16650 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
16651 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
16653 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
16654 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
16655 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
16656 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
16658 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
16659 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
16660 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
16661 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
16663 ;; Babel keys
16664 (define-key org-mode-map org-babel-key-prefix org-babel-map)
16665 (mapc (lambda (pair)
16666 (define-key org-babel-map (car pair) (cdr pair)))
16667 org-babel-key-bindings)
16669 ;;; Extra keys for tty access.
16670 ;; We only set them when really needed because otherwise the
16671 ;; menus don't show the simple keys
16673 (when (or org-use-extra-keys
16674 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
16675 (not window-system))
16676 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
16677 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
16678 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
16679 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
16680 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
16681 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
16682 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
16683 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
16684 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
16685 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
16686 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
16687 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
16688 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
16689 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
16690 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
16691 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
16692 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
16693 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
16694 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
16695 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
16696 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
16697 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
16698 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
16699 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
16700 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
16701 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
16702 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
16703 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
16705 ;; All the other keys
16707 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
16708 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
16709 (if (boundp 'narrow-map)
16710 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
16711 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
16712 (if (boundp 'narrow-map)
16713 (org-defkey narrow-map "b" 'org-narrow-to-block)
16714 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
16715 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
16716 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
16717 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
16718 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
16719 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
16720 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
16721 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
16722 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
16723 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
16724 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
16725 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
16726 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
16727 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
16728 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
16729 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
16730 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
16731 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
16732 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
16733 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
16734 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
16735 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
16736 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
16737 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
16738 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
16739 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
16740 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
16741 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
16742 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
16743 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
16744 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
16745 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
16746 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
16747 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
16748 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
16749 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
16750 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
16751 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
16752 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
16753 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
16754 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
16755 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16756 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
16757 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
16758 (org-defkey org-mode-map "\C-c^" 'org-sort)
16759 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
16760 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
16761 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
16762 (org-defkey org-mode-map "\C-m" 'org-return)
16763 (org-defkey org-mode-map "\C-j" 'org-return-indent)
16764 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
16765 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
16766 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
16767 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
16768 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
16769 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
16770 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
16771 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
16772 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
16773 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
16774 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
16775 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
16776 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
16777 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
16778 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
16779 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
16780 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
16781 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
16782 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
16783 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
16784 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
16786 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
16787 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
16788 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
16789 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
16791 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
16792 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
16793 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
16794 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
16795 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
16796 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
16797 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
16798 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
16799 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
16800 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
16801 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
16802 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
16803 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
16804 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
16805 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
16806 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
16807 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
16808 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
16810 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
16811 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
16812 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
16813 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
16814 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
16816 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
16818 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
16820 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
16821 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
16823 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
16826 (when (featurep 'xemacs)
16827 (org-defkey org-mode-map 'button3 'popup-mode-menu))
16830 (defconst org-speed-commands-default
16832 ("Outline Navigation")
16833 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
16834 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
16835 ("f" . (org-speed-move-safe 'org-forward-same-level))
16836 ("b" . (org-speed-move-safe 'org-backward-same-level))
16837 ("u" . (org-speed-move-safe 'outline-up-heading))
16838 ("j" . org-goto)
16839 ("g" . (org-refile t))
16840 ("Outline Visibility")
16841 ("c" . org-cycle)
16842 ("C" . org-shifttab)
16843 (" " . org-display-outline-path)
16844 ("Outline Structure Editing")
16845 ("U" . org-shiftmetaup)
16846 ("D" . org-shiftmetadown)
16847 ("r" . org-metaright)
16848 ("l" . org-metaleft)
16849 ("R" . org-shiftmetaright)
16850 ("L" . org-shiftmetaleft)
16851 ("i" . (progn (forward-char 1) (call-interactively
16852 'org-insert-heading-respect-content)))
16853 ("^" . org-sort)
16854 ("w" . org-refile)
16855 ("a" . org-archive-subtree-default-with-confirmation)
16856 ("." . org-mark-subtree)
16857 ("Clock Commands")
16858 ("I" . org-clock-in)
16859 ("O" . org-clock-out)
16860 ("Meta Data Editing")
16861 ("t" . org-todo)
16862 ("0" . (org-priority ?\ ))
16863 ("1" . (org-priority ?A))
16864 ("2" . (org-priority ?B))
16865 ("3" . (org-priority ?C))
16866 (";" . org-set-tags-command)
16867 ("e" . org-set-effort)
16868 ("Agenda Views etc")
16869 ("v" . org-agenda)
16870 ("/" . org-sparse-tree)
16871 ("Misc")
16872 ("o" . org-open-at-point)
16873 ("?" . org-speed-command-help)
16874 ("<" . (org-agenda-set-restriction-lock 'subtree))
16875 (">" . (org-agenda-remove-restriction-lock))
16877 "The default speed commands.")
16879 (defun org-print-speed-command (e)
16880 (if (> (length (car e)) 1)
16881 (progn
16882 (princ "\n")
16883 (princ (car e))
16884 (princ "\n")
16885 (princ (make-string (length (car e)) ?-))
16886 (princ "\n"))
16887 (princ (car e))
16888 (princ " ")
16889 (if (symbolp (cdr e))
16890 (princ (symbol-name (cdr e)))
16891 (prin1 (cdr e)))
16892 (princ "\n")))
16894 (defun org-speed-command-help ()
16895 "Show the available speed commands."
16896 (interactive)
16897 (if (not org-use-speed-commands)
16898 (error "Speed commands are not activated, customize `org-use-speed-commands'")
16899 (with-output-to-temp-buffer "*Help*"
16900 (princ "User-defined Speed commands\n===========================\n")
16901 (mapc 'org-print-speed-command org-speed-commands-user)
16902 (princ "\n")
16903 (princ "Built-in Speed commands\n=======================\n")
16904 (mapc 'org-print-speed-command org-speed-commands-default))
16905 (with-current-buffer "*Help*"
16906 (setq truncate-lines t))))
16908 (defun org-speed-move-safe (cmd)
16909 "Execute CMD, but make sure that the cursor always ends up in a headline.
16910 If not, return to the original position and throw an error."
16911 (interactive)
16912 (let ((pos (point)))
16913 (call-interactively cmd)
16914 (unless (and (bolp) (org-on-heading-p))
16915 (goto-char pos)
16916 (error "Boundary reached while executing %s" cmd))))
16918 (defvar org-self-insert-command-undo-counter 0)
16920 (defvar org-table-auto-blank-field) ; defined in org-table.el
16921 (defvar org-speed-command nil)
16923 (defun org-speed-command-default-hook (keys)
16924 "Hook for activating single-letter speed commands.
16925 `org-speed-commands-default' specifies a minimal command set. Use
16926 `org-speed-commands-user' for further customization."
16927 (when (or (and (bolp) (looking-at outline-regexp))
16928 (and (functionp org-use-speed-commands)
16929 (funcall org-use-speed-commands)))
16930 (cdr (assoc keys (append org-speed-commands-user
16931 org-speed-commands-default)))))
16933 (defun org-babel-speed-command-hook (keys)
16934 "Hook for activating single-letter code block commands."
16935 (when (and (bolp) (looking-at org-babel-src-block-regexp))
16936 (cdr (assoc keys org-babel-key-bindings))))
16938 (defcustom org-speed-command-hook
16939 '(org-speed-command-default-hook org-babel-speed-command-hook)
16940 "Hook for activating speed commands at strategic locations.
16941 Hook functions are called in sequence until a valid handler is
16942 found.
16944 Each hook takes a single argument, a user-pressed command key
16945 which is also a `self-insert-command' from the global map.
16947 Within the hook, examine the cursor position and the command key
16948 and return nil or a valid handler as appropriate. Handler could
16949 be one of an interactive command, a function, or a form.
16951 Set `org-use-speed-commands' to non-nil value to enable this
16952 hook. The default setting is `org-speed-command-default-hook'."
16953 :group 'org-structure
16954 :type 'hook)
16956 (defun org-self-insert-command (N)
16957 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
16958 If the cursor is in a table looking at whitespace, the whitespace is
16959 overwritten, and the table is not marked as requiring realignment."
16960 (interactive "p")
16961 (cond
16962 ((and org-use-speed-commands
16963 (setq org-speed-command
16964 (run-hook-with-args-until-success
16965 'org-speed-command-hook (this-command-keys))))
16966 (cond
16967 ((commandp org-speed-command)
16968 (setq this-command org-speed-command)
16969 (call-interactively org-speed-command))
16970 ((functionp org-speed-command)
16971 (funcall org-speed-command))
16972 ((and org-speed-command (listp org-speed-command))
16973 (eval org-speed-command))
16974 (t (let (org-use-speed-commands)
16975 (call-interactively 'org-self-insert-command)))))
16976 ((and
16977 (org-table-p)
16978 (progn
16979 ;; check if we blank the field, and if that triggers align
16980 (and (featurep 'org-table) org-table-auto-blank-field
16981 (member last-command
16982 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
16983 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
16984 ;; got extra space, this field does not determine column width
16985 (let (org-table-may-need-update) (org-table-blank-field))
16986 ;; no extra space, this field may determine column width
16987 (org-table-blank-field)))
16989 (eq N 1)
16990 (looking-at "[^|\n]* |"))
16991 (let (org-table-may-need-update)
16992 (goto-char (1- (match-end 0)))
16993 (delete-char -1)
16994 (goto-char (match-beginning 0))
16995 (self-insert-command N)))
16997 (setq org-table-may-need-update t)
16998 (self-insert-command N)
16999 (org-fix-tags-on-the-fly)
17000 (if org-self-insert-cluster-for-undo
17001 (if (not (eq last-command 'org-self-insert-command))
17002 (setq org-self-insert-command-undo-counter 1)
17003 (if (>= org-self-insert-command-undo-counter 20)
17004 (setq org-self-insert-command-undo-counter 1)
17005 (and (> org-self-insert-command-undo-counter 0)
17006 buffer-undo-list (listp buffer-undo-list)
17007 (not (cadr buffer-undo-list)) ; remove nil entry
17008 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17009 (setq org-self-insert-command-undo-counter
17010 (1+ org-self-insert-command-undo-counter))))))))
17012 (defun org-fix-tags-on-the-fly ()
17013 (when (and (equal (char-after (point-at-bol)) ?*)
17014 (org-on-heading-p))
17015 (org-align-tags-here org-tags-column)))
17017 (defun org-delete-backward-char (N)
17018 "Like `delete-backward-char', insert whitespace at field end in tables.
17019 When deleting backwards, in tables this function will insert whitespace in
17020 front of the next \"|\" separator, to keep the table aligned. The table will
17021 still be marked for re-alignment if the field did fill the entire column,
17022 because, in this case the deletion might narrow the column."
17023 (interactive "p")
17024 (if (and (org-table-p)
17025 (eq N 1)
17026 (string-match "|" (buffer-substring (point-at-bol) (point)))
17027 (looking-at ".*?|"))
17028 (let ((pos (point))
17029 (noalign (looking-at "[^|\n\r]* |"))
17030 (c org-table-may-need-update))
17031 (backward-delete-char N)
17032 (if (not overwrite-mode)
17033 (progn
17034 (skip-chars-forward "^|")
17035 (insert " ")
17036 (goto-char (1- pos))))
17037 ;; noalign: if there were two spaces at the end, this field
17038 ;; does not determine the width of the column.
17039 (if noalign (setq org-table-may-need-update c)))
17040 (backward-delete-char N)
17041 (org-fix-tags-on-the-fly)))
17043 (defun org-delete-char (N)
17044 "Like `delete-char', but insert whitespace at field end in tables.
17045 When deleting characters, in tables this function will insert whitespace in
17046 front of the next \"|\" separator, to keep the table aligned. The table will
17047 still be marked for re-alignment if the field did fill the entire column,
17048 because, in this case the deletion might narrow the column."
17049 (interactive "p")
17050 (if (and (org-table-p)
17051 (not (bolp))
17052 (not (= (char-after) ?|))
17053 (eq N 1))
17054 (if (looking-at ".*?|")
17055 (let ((pos (point))
17056 (noalign (looking-at "[^|\n\r]* |"))
17057 (c org-table-may-need-update))
17058 (replace-match (concat
17059 (substring (match-string 0) 1 -1)
17060 " |"))
17061 (goto-char pos)
17062 ;; noalign: if there were two spaces at the end, this field
17063 ;; does not determine the width of the column.
17064 (if noalign (setq org-table-may-need-update c)))
17065 (delete-char N))
17066 (delete-char N)
17067 (org-fix-tags-on-the-fly)))
17069 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17070 (put 'org-self-insert-command 'delete-selection t)
17071 (put 'orgtbl-self-insert-command 'delete-selection t)
17072 (put 'org-delete-char 'delete-selection 'supersede)
17073 (put 'org-delete-backward-char 'delete-selection 'supersede)
17074 (put 'org-yank 'delete-selection 'yank)
17076 ;; Make `flyspell-mode' delay after some commands
17077 (put 'org-self-insert-command 'flyspell-delayed t)
17078 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17079 (put 'org-delete-char 'flyspell-delayed t)
17080 (put 'org-delete-backward-char 'flyspell-delayed t)
17082 ;; Make pabbrev-mode expand after org-mode commands
17083 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17084 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17086 ;; How to do this: Measure non-white length of current string
17087 ;; If equal to column width, we should realign.
17089 (defun org-remap (map &rest commands)
17090 "In MAP, remap the functions given in COMMANDS.
17091 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17092 (let (new old)
17093 (while commands
17094 (setq old (pop commands) new (pop commands))
17095 (if (fboundp 'command-remapping)
17096 (org-defkey map (vector 'remap old) new)
17097 (substitute-key-definition old new map global-map)))))
17099 (when (eq org-enable-table-editor 'optimized)
17100 ;; If the user wants maximum table support, we need to hijack
17101 ;; some standard editing functions
17102 (org-remap org-mode-map
17103 'self-insert-command 'org-self-insert-command
17104 'delete-char 'org-delete-char
17105 'delete-backward-char 'org-delete-backward-char)
17106 (org-defkey org-mode-map "|" 'org-force-self-insert))
17108 (defvar org-ctrl-c-ctrl-c-hook nil
17109 "Hook for functions attaching themselves to `C-c C-c'.
17110 This can be used to add additional functionality to the C-c C-c key which
17111 executes context-dependent commands.
17112 Each function will be called with no arguments. The function must check
17113 if the context is appropriate for it to act. If yes, it should do its
17114 thing and then return a non-nil value. If the context is wrong,
17115 just do nothing and return nil.")
17117 (defvar org-tab-first-hook nil
17118 "Hook for functions to attach themselves to TAB.
17119 See `org-ctrl-c-ctrl-c-hook' for more information.
17120 This hook runs as the first action when TAB is pressed, even before
17121 `org-cycle' messes around with the `outline-regexp' to cater for
17122 inline tasks and plain list item folding.
17123 If any function in this hook returns t, any other actions that
17124 would have been caused by TAB (such as table field motion or visibility
17125 cycling) will not occur.")
17127 (defvar org-tab-after-check-for-table-hook nil
17128 "Hook for functions to attach themselves to TAB.
17129 See `org-ctrl-c-ctrl-c-hook' for more information.
17130 This hook runs after it has been established that the cursor is not in a
17131 table, but before checking if the cursor is in a headline or if global cycling
17132 should be done.
17133 If any function in this hook returns t, not other actions like visibility
17134 cycling will be done.")
17136 (defvar org-tab-after-check-for-cycling-hook nil
17137 "Hook for functions to attach themselves to TAB.
17138 See `org-ctrl-c-ctrl-c-hook' for more information.
17139 This hook runs after it has been established that not table field motion and
17140 not visibility should be done because of current context. This is probably
17141 the place where a package like yasnippets can hook in.")
17143 (defvar org-tab-before-tab-emulation-hook nil
17144 "Hook for functions to attach themselves to TAB.
17145 See `org-ctrl-c-ctrl-c-hook' for more information.
17146 This hook runs after every other options for TAB have been exhausted, but
17147 before indentation and \t insertion takes place.")
17149 (defvar org-metaleft-hook nil
17150 "Hook for functions attaching themselves to `M-left'.
17151 See `org-ctrl-c-ctrl-c-hook' for more information.")
17152 (defvar org-metaright-hook nil
17153 "Hook for functions attaching themselves to `M-right'.
17154 See `org-ctrl-c-ctrl-c-hook' for more information.")
17155 (defvar org-metaup-hook nil
17156 "Hook for functions attaching themselves to `M-up'.
17157 See `org-ctrl-c-ctrl-c-hook' for more information.")
17158 (defvar org-metadown-hook nil
17159 "Hook for functions attaching themselves to `M-down'.
17160 See `org-ctrl-c-ctrl-c-hook' for more information.")
17161 (defvar org-shiftmetaleft-hook nil
17162 "Hook for functions attaching themselves to `M-S-left'.
17163 See `org-ctrl-c-ctrl-c-hook' for more information.")
17164 (defvar org-shiftmetaright-hook nil
17165 "Hook for functions attaching themselves to `M-S-right'.
17166 See `org-ctrl-c-ctrl-c-hook' for more information.")
17167 (defvar org-shiftmetaup-hook nil
17168 "Hook for functions attaching themselves to `M-S-up'.
17169 See `org-ctrl-c-ctrl-c-hook' for more information.")
17170 (defvar org-shiftmetadown-hook nil
17171 "Hook for functions attaching themselves to `M-S-down'.
17172 See `org-ctrl-c-ctrl-c-hook' for more information.")
17173 (defvar org-metareturn-hook nil
17174 "Hook for functions attaching themselves to `M-RET'.
17175 See `org-ctrl-c-ctrl-c-hook' for more information.")
17176 (defvar org-shiftup-hook nil
17177 "Hook for functions attaching themselves to `S-up'.
17178 See `org-ctrl-c-ctrl-c-hook' for more information.")
17179 (defvar org-shiftup-final-hook nil
17180 "Hook for functions attaching themselves to `S-up'.
17181 This one runs after all other options except shift-select have been excluded.
17182 See `org-ctrl-c-ctrl-c-hook' for more information.")
17183 (defvar org-shiftdown-hook nil
17184 "Hook for functions attaching themselves to `S-down'.
17185 See `org-ctrl-c-ctrl-c-hook' for more information.")
17186 (defvar org-shiftdown-final-hook nil
17187 "Hook for functions attaching themselves to `S-down'.
17188 This one runs after all other options except shift-select have been excluded.
17189 See `org-ctrl-c-ctrl-c-hook' for more information.")
17190 (defvar org-shiftleft-hook nil
17191 "Hook for functions attaching themselves to `S-left'.
17192 See `org-ctrl-c-ctrl-c-hook' for more information.")
17193 (defvar org-shiftleft-final-hook nil
17194 "Hook for functions attaching themselves to `S-left'.
17195 This one runs after all other options except shift-select have been excluded.
17196 See `org-ctrl-c-ctrl-c-hook' for more information.")
17197 (defvar org-shiftright-hook nil
17198 "Hook for functions attaching themselves to `S-right'.
17199 See `org-ctrl-c-ctrl-c-hook' for more information.")
17200 (defvar org-shiftright-final-hook nil
17201 "Hook for functions attaching themselves to `S-right'.
17202 This one runs after all other options except shift-select have been excluded.
17203 See `org-ctrl-c-ctrl-c-hook' for more information.")
17205 (defun org-modifier-cursor-error ()
17206 "Throw an error, a modified cursor command was applied in wrong context."
17207 (error "This command is active in special context like tables, headlines or items"))
17209 (defun org-shiftselect-error ()
17210 "Throw an error because Shift-Cursor command was applied in wrong context."
17211 (if (and (boundp 'shift-select-mode) shift-select-mode)
17212 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
17213 (error "This command works only in special context like headlines or timestamps")))
17215 (defun org-call-for-shift-select (cmd)
17216 (let ((this-command-keys-shift-translated t))
17217 (call-interactively cmd)))
17219 (defun org-shifttab (&optional arg)
17220 "Global visibility cycling or move to previous table field.
17221 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17222 on context.
17223 See the individual commands for more information."
17224 (interactive "P")
17225 (cond
17226 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17227 ((integerp arg)
17228 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
17229 (message "Content view to level: %d" arg)
17230 (org-content (prefix-numeric-value arg2))
17231 (setq org-cycle-global-status 'overview)))
17232 (t (call-interactively 'org-global-cycle))))
17234 (defun org-shiftmetaleft ()
17235 "Promote subtree or delete table column.
17236 Calls `org-promote-subtree', `org-outdent-item',
17237 or `org-table-delete-column', depending on context.
17238 See the individual commands for more information."
17239 (interactive)
17240 (cond
17241 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
17242 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17243 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
17244 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
17245 (t (org-modifier-cursor-error))))
17247 (defun org-shiftmetaright ()
17248 "Demote subtree or insert table column.
17249 Calls `org-demote-subtree', `org-indent-item',
17250 or `org-table-insert-column', depending on context.
17251 See the individual commands for more information."
17252 (interactive)
17253 (cond
17254 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
17255 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17256 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
17257 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
17258 (t (org-modifier-cursor-error))))
17260 (defun org-shiftmetaup (&optional arg)
17261 "Move subtree up or kill table row.
17262 Calls `org-move-subtree-up' or `org-table-kill-row' or
17263 `org-move-item-up' depending on context. See the individual commands
17264 for more information."
17265 (interactive "P")
17266 (cond
17267 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
17268 ((org-at-table-p) (call-interactively 'org-table-kill-row))
17269 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17270 ((org-at-item-p) (call-interactively 'org-move-item-up))
17271 (t (org-modifier-cursor-error))))
17273 (defun org-shiftmetadown (&optional arg)
17274 "Move subtree down or insert table row.
17275 Calls `org-move-subtree-down' or `org-table-insert-row' or
17276 `org-move-item-down', depending on context. See the individual
17277 commands for more information."
17278 (interactive "P")
17279 (cond
17280 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
17281 ((org-at-table-p) (call-interactively 'org-table-insert-row))
17282 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17283 ((org-at-item-p) (call-interactively 'org-move-item-down))
17284 (t (org-modifier-cursor-error))))
17286 (defsubst org-hidden-tree-error ()
17287 (error
17288 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
17290 (defun org-metaleft (&optional arg)
17291 "Promote heading or move table column to left.
17292 Calls `org-do-promote' or `org-table-move-column', depending on context.
17293 With no specific context, calls the Emacs default `backward-word'.
17294 See the individual commands for more information."
17295 (interactive "P")
17296 (cond
17297 ((run-hook-with-args-until-success 'org-metaleft-hook))
17298 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
17299 ((org-with-limited-levels
17300 (or (org-on-heading-p)
17301 (and (org-region-active-p)
17302 (save-excursion
17303 (goto-char (region-beginning))
17304 (org-on-heading-p)))))
17305 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17306 (call-interactively 'org-do-promote))
17307 ;; At an inline task.
17308 ((org-on-heading-p)
17309 (call-interactively 'org-inlinetask-promote))
17310 ((or (org-at-item-p)
17311 (and (org-region-active-p)
17312 (save-excursion
17313 (goto-char (region-beginning))
17314 (org-at-item-p))))
17315 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17316 (call-interactively 'org-outdent-item))
17317 (t (call-interactively 'backward-word))))
17319 (defun org-metaright (&optional arg)
17320 "Demote subtree or move table column to right.
17321 Calls `org-do-demote' or `org-table-move-column', depending on context.
17322 With no specific context, calls the Emacs default `forward-word'.
17323 See the individual commands for more information."
17324 (interactive "P")
17325 (cond
17326 ((run-hook-with-args-until-success 'org-metaright-hook))
17327 ((org-at-table-p) (call-interactively 'org-table-move-column))
17328 ((org-with-limited-levels
17329 (or (org-on-heading-p)
17330 (and (org-region-active-p)
17331 (save-excursion
17332 (goto-char (region-beginning))
17333 (org-on-heading-p)))))
17334 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17335 (call-interactively 'org-do-demote))
17336 ;; At an inline task.
17337 ((org-on-heading-p)
17338 (call-interactively 'org-inlinetask-demote))
17339 ((or (org-at-item-p)
17340 (and (org-region-active-p)
17341 (save-excursion
17342 (goto-char (region-beginning))
17343 (org-at-item-p))))
17344 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17345 (call-interactively 'org-indent-item))
17346 (t (call-interactively 'forward-word))))
17348 (defun org-check-for-hidden (what)
17349 "Check if there are hidden headlines/items in the current visual line.
17350 WHAT can be either `headlines' or `items'. If the current line is
17351 an outline or item heading and it has a folded subtree below it,
17352 this function returns t, nil otherwise."
17353 (let ((re (cond
17354 ((eq what 'headlines) (concat "^" org-outline-regexp))
17355 ((eq what 'items) (org-item-beginning-re))
17356 (t (error "This should not happen"))))
17357 beg end)
17358 (save-excursion
17359 (catch 'exit
17360 (unless (org-region-active-p)
17361 (setq beg (point-at-bol))
17362 (beginning-of-line 2)
17363 (while (and (not (eobp)) ;; this is like `next-line'
17364 (get-char-property (1- (point)) 'invisible))
17365 (beginning-of-line 2))
17366 (setq end (point))
17367 (goto-char beg)
17368 (goto-char (point-at-eol))
17369 (setq end (max end (point)))
17370 (while (re-search-forward re end t)
17371 (if (get-char-property (match-beginning 0) 'invisible)
17372 (throw 'exit t))))
17373 nil))))
17375 (defun org-metaup (&optional arg)
17376 "Move subtree up or move table row up.
17377 Calls `org-move-subtree-up' or `org-table-move-row' or
17378 `org-move-item-up', depending on context. See the individual commands
17379 for more information."
17380 (interactive "P")
17381 (cond
17382 ((run-hook-with-args-until-success 'org-metaup-hook))
17383 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
17384 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17385 ((org-at-item-p) (call-interactively 'org-move-item-up))
17386 (t (transpose-lines 1) (beginning-of-line -1))))
17388 (defun org-metadown (&optional arg)
17389 "Move subtree down or move table row down.
17390 Calls `org-move-subtree-down' or `org-table-move-row' or
17391 `org-move-item-down', depending on context. See the individual
17392 commands for more information."
17393 (interactive "P")
17394 (cond
17395 ((run-hook-with-args-until-success 'org-metadown-hook))
17396 ((org-at-table-p) (call-interactively 'org-table-move-row))
17397 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17398 ((org-at-item-p) (call-interactively 'org-move-item-down))
17399 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
17401 (defun org-shiftup (&optional arg)
17402 "Increase item in timestamp or increase priority of current headline.
17403 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
17404 depending on context. See the individual commands for more information."
17405 (interactive "P")
17406 (cond
17407 ((run-hook-with-args-until-success 'org-shiftup-hook))
17408 ((and org-support-shift-select (org-region-active-p))
17409 (org-call-for-shift-select 'previous-line))
17410 ((org-at-timestamp-p t)
17411 (call-interactively (if org-edit-timestamp-down-means-later
17412 'org-timestamp-down 'org-timestamp-up)))
17413 ((and (not (eq org-support-shift-select 'always))
17414 org-enable-priority-commands
17415 (org-on-heading-p))
17416 (call-interactively 'org-priority-up))
17417 ((and (not org-support-shift-select) (org-at-item-p))
17418 (call-interactively 'org-previous-item))
17419 ((org-clocktable-try-shift 'up arg))
17420 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
17421 (org-support-shift-select
17422 (org-call-for-shift-select 'previous-line))
17423 (t (org-shiftselect-error))))
17425 (defun org-shiftdown (&optional arg)
17426 "Decrease item in timestamp or decrease priority of current headline.
17427 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
17428 depending on context. See the individual commands for more information."
17429 (interactive "P")
17430 (cond
17431 ((run-hook-with-args-until-success 'org-shiftdown-hook))
17432 ((and org-support-shift-select (org-region-active-p))
17433 (org-call-for-shift-select 'next-line))
17434 ((org-at-timestamp-p t)
17435 (call-interactively (if org-edit-timestamp-down-means-later
17436 'org-timestamp-up 'org-timestamp-down)))
17437 ((and (not (eq org-support-shift-select 'always))
17438 org-enable-priority-commands
17439 (org-on-heading-p))
17440 (call-interactively 'org-priority-down))
17441 ((and (not org-support-shift-select) (org-at-item-p))
17442 (call-interactively 'org-next-item))
17443 ((org-clocktable-try-shift 'down arg))
17444 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
17445 (org-support-shift-select
17446 (org-call-for-shift-select 'next-line))
17447 (t (org-shiftselect-error))))
17449 (defun org-shiftright (&optional arg)
17450 "Cycle the thing at point or in the current line, depending on context.
17451 Depending on context, this does one of the following:
17453 - switch a timestamp at point one day into the future
17454 - on a headline, switch to the next TODO keyword.
17455 - on an item, switch entire list to the next bullet type
17456 - on a property line, switch to the next allowed value
17457 - on a clocktable definition line, move time block into the future"
17458 (interactive "P")
17459 (cond
17460 ((run-hook-with-args-until-success 'org-shiftright-hook))
17461 ((and org-support-shift-select (org-region-active-p))
17462 (org-call-for-shift-select 'forward-char))
17463 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
17464 ((and (not (eq org-support-shift-select 'always))
17465 (org-on-heading-p))
17466 (let ((org-inhibit-logging
17467 (not org-treat-S-cursor-todo-selection-as-state-change))
17468 (org-inhibit-blocking
17469 (not org-treat-S-cursor-todo-selection-as-state-change)))
17470 (org-call-with-arg 'org-todo 'right)))
17471 ((or (and org-support-shift-select
17472 (not (eq org-support-shift-select 'always))
17473 (org-at-item-bullet-p))
17474 (and (not org-support-shift-select) (org-at-item-p)))
17475 (org-call-with-arg 'org-cycle-list-bullet nil))
17476 ((and (not (eq org-support-shift-select 'always))
17477 (org-at-property-p))
17478 (call-interactively 'org-property-next-allowed-value))
17479 ((org-clocktable-try-shift 'right arg))
17480 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
17481 (org-support-shift-select
17482 (org-call-for-shift-select 'forward-char))
17483 (t (org-shiftselect-error))))
17485 (defun org-shiftleft (&optional arg)
17486 "Cycle the thing at point or in the current line, depending on context.
17487 Depending on context, this does one of the following:
17489 - switch a timestamp at point one day into the past
17490 - on a headline, switch to the previous TODO keyword.
17491 - on an item, switch entire list to the previous bullet type
17492 - on a property line, switch to the previous allowed value
17493 - on a clocktable definition line, move time block into the past"
17494 (interactive "P")
17495 (cond
17496 ((run-hook-with-args-until-success 'org-shiftleft-hook))
17497 ((and org-support-shift-select (org-region-active-p))
17498 (org-call-for-shift-select 'backward-char))
17499 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
17500 ((and (not (eq org-support-shift-select 'always))
17501 (org-on-heading-p))
17502 (let ((org-inhibit-logging
17503 (not org-treat-S-cursor-todo-selection-as-state-change))
17504 (org-inhibit-blocking
17505 (not org-treat-S-cursor-todo-selection-as-state-change)))
17506 (org-call-with-arg 'org-todo 'left)))
17507 ((or (and org-support-shift-select
17508 (not (eq org-support-shift-select 'always))
17509 (org-at-item-bullet-p))
17510 (and (not org-support-shift-select) (org-at-item-p)))
17511 (org-call-with-arg 'org-cycle-list-bullet 'previous))
17512 ((and (not (eq org-support-shift-select 'always))
17513 (org-at-property-p))
17514 (call-interactively 'org-property-previous-allowed-value))
17515 ((org-clocktable-try-shift 'left arg))
17516 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
17517 (org-support-shift-select
17518 (org-call-for-shift-select 'backward-char))
17519 (t (org-shiftselect-error))))
17521 (defun org-shiftcontrolright ()
17522 "Switch to next TODO set."
17523 (interactive)
17524 (cond
17525 ((and org-support-shift-select (org-region-active-p))
17526 (org-call-for-shift-select 'forward-word))
17527 ((and (not (eq org-support-shift-select 'always))
17528 (org-on-heading-p))
17529 (org-call-with-arg 'org-todo 'nextset))
17530 (org-support-shift-select
17531 (org-call-for-shift-select 'forward-word))
17532 (t (org-shiftselect-error))))
17534 (defun org-shiftcontrolleft ()
17535 "Switch to previous TODO set."
17536 (interactive)
17537 (cond
17538 ((and org-support-shift-select (org-region-active-p))
17539 (org-call-for-shift-select 'backward-word))
17540 ((and (not (eq org-support-shift-select 'always))
17541 (org-on-heading-p))
17542 (org-call-with-arg 'org-todo 'previousset))
17543 (org-support-shift-select
17544 (org-call-for-shift-select 'backward-word))
17545 (t (org-shiftselect-error))))
17547 (defun org-shiftcontrolup ()
17548 "Change timestamps synchronously up in CLOCK log lines."
17549 (interactive)
17550 (cond ((and (not org-support-shift-select)
17551 (org-at-clock-log-p)
17552 (org-at-timestamp-p t))
17553 (org-clock-timestamps-up))
17554 (t (org-shiftselect-error))))
17556 (defun org-shiftcontroldown ()
17557 "Change timestamps synchronously down in CLOCK log lines."
17558 (interactive)
17559 (cond ((and (not org-support-shift-select)
17560 (org-at-clock-log-p)
17561 (org-at-timestamp-p t))
17562 (org-clock-timestamps-down))
17563 (t (org-shiftselect-error))))
17565 (defun org-ctrl-c-ret ()
17566 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
17567 (interactive)
17568 (cond
17569 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
17570 (t (call-interactively 'org-insert-heading))))
17572 (defun org-copy-special ()
17573 "Copy region in table or copy current subtree.
17574 Calls `org-table-copy' or `org-copy-subtree', depending on context.
17575 See the individual commands for more information."
17576 (interactive)
17577 (call-interactively
17578 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
17580 (defun org-cut-special ()
17581 "Cut region in table or cut current subtree.
17582 Calls `org-table-copy' or `org-cut-subtree', depending on context.
17583 See the individual commands for more information."
17584 (interactive)
17585 (call-interactively
17586 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
17588 (defun org-paste-special (arg)
17589 "Paste rectangular region into table, or past subtree relative to level.
17590 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
17591 See the individual commands for more information."
17592 (interactive "P")
17593 (if (org-at-table-p)
17594 (org-table-paste-rectangle)
17595 (org-paste-subtree arg)))
17597 (defun org-edit-special (&optional arg)
17598 "Call a special editor for the stuff at point.
17599 When at a table, call the formula editor with `org-table-edit-formulas'.
17600 When at the first line of an src example, call `org-edit-src-code'.
17601 When in an #+include line, visit the include file. Otherwise call
17602 `ffap' to visit the file at point."
17603 (interactive)
17604 ;; possibly prep session before editing source
17605 (when arg
17606 (let* ((info (org-babel-get-src-block-info))
17607 (lang (nth 0 info))
17608 (params (nth 2 info))
17609 (session (cdr (assoc :session params))))
17610 (when (and info session) ;; we are in a source-code block with a session
17611 (funcall
17612 (intern (concat "org-babel-prep-session:" lang)) session params))))
17613 (cond ;; proceed with `org-edit-special'
17614 ((save-excursion
17615 (beginning-of-line 1)
17616 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
17617 (find-file (org-trim (match-string 1))))
17618 ((org-edit-src-code))
17619 ((org-edit-fixed-width-region))
17620 ((org-at-table.el-p)
17621 (org-edit-src-code))
17622 ((or (org-at-table-p)
17623 (save-excursion
17624 (beginning-of-line 1)
17625 (looking-at "[ \t]*#\\+TBLFM:")))
17626 (call-interactively 'org-table-edit-formulas))
17627 (t (call-interactively 'ffap))))
17629 (defun org-ctrl-c-ctrl-c (&optional arg)
17630 "Set tags in headline, or update according to changed information at point.
17632 This command does many different things, depending on context:
17634 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
17635 this is what we do.
17637 - If the cursor is on a statistics cookie, update it.
17639 - If the cursor is in a headline, prompt for tags and insert them
17640 into the current line, aligned to `org-tags-column'. When called
17641 with prefix arg, realign all tags in the current buffer.
17643 - If the cursor is in one of the special #+KEYWORD lines, this
17644 triggers scanning the buffer for these lines and updating the
17645 information.
17647 - If the cursor is inside a table, realign the table. This command
17648 works even if the automatic table editor has been turned off.
17650 - If the cursor is on a #+TBLFM line, re-apply the formulas to
17651 the entire table.
17653 - If the cursor is at a footnote reference or definition, jump to
17654 the corresponding definition or references, respectively.
17656 - If the cursor is a the beginning of a dynamic block, update it.
17658 - If the current buffer is a capture buffer, close note and file it.
17660 - If the cursor is on a <<<target>>>, update radio targets and
17661 corresponding links in this buffer.
17663 - If the cursor is on a numbered item in a plain list, renumber the
17664 ordered list.
17666 - If the cursor is on a checkbox, toggle it.
17668 - If the cursor is on a code block, evaluate it. The variable
17669 `org-confirm-babel-evaluate' can be used to control prompting
17670 before code block evaluation, by default every code block
17671 evaluation requires confirmation. Code block evaluation can be
17672 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
17673 (interactive "P")
17674 (let ((org-enable-table-editor t))
17675 (cond
17676 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
17677 org-occur-highlights
17678 org-latex-fragment-image-overlays)
17679 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
17680 (org-remove-occur-highlights)
17681 (org-remove-latex-fragment-image-overlays)
17682 (message "Temporary highlights/overlays removed from current buffer"))
17683 ((and (local-variable-p 'org-finish-function (current-buffer))
17684 (fboundp org-finish-function))
17685 (funcall org-finish-function))
17686 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
17687 ((or (looking-at org-property-start-re)
17688 (org-at-property-p))
17689 (call-interactively 'org-property-action))
17690 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
17691 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
17692 (or (org-on-heading-p) (org-at-item-p)))
17693 (call-interactively 'org-update-statistics-cookies))
17694 ((org-on-heading-p) (call-interactively 'org-set-tags))
17695 ((org-at-table.el-p)
17696 (message "Use C-c ' to edit table.el tables"))
17697 ((org-at-table-p)
17698 (org-table-maybe-eval-formula)
17699 (if arg
17700 (call-interactively 'org-table-recalculate)
17701 (org-table-maybe-recalculate-line))
17702 (call-interactively 'org-table-align)
17703 (orgtbl-send-table 'maybe))
17704 ((or (org-footnote-at-reference-p)
17705 (org-footnote-at-definition-p))
17706 (call-interactively 'org-footnote-action))
17707 ((org-at-item-checkbox-p)
17708 ;; Cursor at a checkbox: repair list and update checkboxes. Send
17709 ;; list only if at top item.
17710 (let* ((cbox (match-string 1))
17711 (struct (org-list-struct))
17712 (old-struct (copy-tree struct))
17713 (parents (org-list-parents-alist struct))
17714 (prevs (org-list-prevs-alist struct))
17715 (orderedp (org-entry-get nil "ORDERED"))
17716 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
17717 block-item)
17718 ;; Use a light version of `org-toggle-checkbox' to avoid
17719 ;; computing list structure twice.
17720 (org-list-set-checkbox (point-at-bol) struct
17721 (cond
17722 ((equal arg '(16)) "[-]")
17723 ((equal arg '(4)) nil)
17724 ((equal "[X]" cbox) "[ ]")
17725 (t "[X]")))
17726 (org-list-struct-fix-ind struct parents)
17727 (org-list-struct-fix-bul struct prevs)
17728 (setq block-item
17729 (org-list-struct-fix-box struct parents prevs orderedp))
17730 (when block-item
17731 (message
17732 "Checkboxes were removed due to unchecked box at line %d"
17733 (org-current-line block-item)))
17734 (org-list-struct-apply-struct struct old-struct)
17735 (org-update-checkbox-count-maybe)
17736 (when firstp (org-list-send-list 'maybe))))
17737 ((org-at-item-p)
17738 ;; Cursor at an item: repair list. Do checkbox related actions
17739 ;; only if function was called with an argument. Send list only
17740 ;; if at top item.
17741 (let* ((struct (org-list-struct))
17742 (old-struct (copy-tree struct))
17743 (parents (org-list-parents-alist struct))
17744 (prevs (org-list-prevs-alist struct))
17745 (firstp (= (org-list-get-top-point struct) (point-at-bol))))
17746 (org-list-struct-fix-ind struct parents)
17747 (org-list-struct-fix-bul struct prevs)
17748 (when arg
17749 (org-list-set-checkbox (point-at-bol) struct "[ ]")
17750 (org-list-struct-fix-box struct parents prevs))
17751 (org-list-struct-apply-struct struct old-struct)
17752 (when arg (org-update-checkbox-count-maybe))
17753 (when firstp (org-list-send-list 'maybe))))
17754 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
17755 ;; Dynamic block
17756 (beginning-of-line 1)
17757 (save-excursion (org-update-dblock)))
17758 ((save-excursion
17759 (beginning-of-line 1)
17760 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
17761 (cond
17762 ((equal (match-string 1) "TBLFM")
17763 ;; Recalculate the table before this line
17764 (save-excursion
17765 (beginning-of-line 1)
17766 (skip-chars-backward " \r\n\t")
17767 (if (org-at-table-p)
17768 (org-call-with-arg 'org-table-recalculate (or arg t)))))
17770 (let ((org-inhibit-startup-visibility-stuff t)
17771 (org-startup-align-all-tables nil))
17772 (org-save-outline-visibility 'use-markers (org-mode-restart)))
17773 (message "Local setup has been refreshed"))))
17774 ((org-clock-update-time-maybe))
17775 (t (error "C-c C-c can do nothing useful at this location")))))
17777 (defun org-mode-restart ()
17778 "Restart Org-mode, to scan again for special lines.
17779 Also updates the keyword regular expressions."
17780 (interactive)
17781 (org-mode)
17782 (message "Org-mode restarted"))
17784 (defun org-kill-note-or-show-branches ()
17785 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
17786 (interactive)
17787 (if (not org-finish-function)
17788 (progn
17789 (hide-subtree)
17790 (call-interactively 'show-branches))
17791 (let ((org-note-abort t))
17792 (funcall org-finish-function))))
17794 (defun org-return (&optional indent)
17795 "Goto next table row or insert a newline.
17796 Calls `org-table-next-row' or `newline', depending on context.
17797 See the individual commands for more information."
17798 (interactive)
17799 (cond
17800 ((bobp) (if indent (newline-and-indent) (newline)))
17801 ((org-at-table-p)
17802 (org-table-justify-field-maybe)
17803 (call-interactively 'org-table-next-row))
17804 ;; when `newline-and-indent' is called within a list, make sure
17805 ;; text moved stays inside the item.
17806 ((and (org-in-item-p) indent)
17807 (if (and (org-at-item-p) (>= (point) (match-end 0)))
17808 (progn
17809 (newline)
17810 (org-indent-line-to (length (match-string 0))))
17811 (let ((ind (org-get-indentation)))
17812 (newline)
17813 (if (org-looking-back org-list-end-re)
17814 (org-indent-line-function)
17815 (org-indent-line-to ind)))))
17816 ((and org-return-follows-link
17817 (eq (get-text-property (point) 'face) 'org-link))
17818 (call-interactively 'org-open-at-point))
17819 ((and (org-at-heading-p)
17820 (looking-at
17821 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
17822 (org-show-entry)
17823 (end-of-line 1)
17824 (newline))
17825 (t (if indent (newline-and-indent) (newline)))))
17827 (defun org-return-indent ()
17828 "Goto next table row or insert a newline and indent.
17829 Calls `org-table-next-row' or `newline-and-indent', depending on
17830 context. See the individual commands for more information."
17831 (interactive)
17832 (org-return t))
17834 (defun org-ctrl-c-star ()
17835 "Compute table, or change heading status of lines.
17836 Calls `org-table-recalculate' or `org-toggle-heading',
17837 depending on context."
17838 (interactive)
17839 (cond
17840 ((org-at-table-p)
17841 (call-interactively 'org-table-recalculate))
17843 ;; Convert all lines in region to list items
17844 (call-interactively 'org-toggle-heading))))
17846 (defun org-ctrl-c-minus ()
17847 "Insert separator line in table or modify bullet status of line.
17848 Also turns a plain line or a region of lines into list items.
17849 Calls `org-table-insert-hline', `org-toggle-item', or
17850 `org-cycle-list-bullet', depending on context."
17851 (interactive)
17852 (cond
17853 ((org-at-table-p)
17854 (call-interactively 'org-table-insert-hline))
17855 ((org-region-active-p)
17856 (call-interactively 'org-toggle-item))
17857 ((org-in-item-p)
17858 (call-interactively 'org-cycle-list-bullet))
17860 (call-interactively 'org-toggle-item))))
17862 (defun org-toggle-item (arg)
17863 "Convert headings or normal lines to items, items to normal lines.
17864 If there is no active region, only the current line is considered.
17866 If the first non blank line in the region is an headline, convert
17867 all headlines to items, shifting text accordingly.
17869 If it is an item, convert all items to normal lines.
17871 If it is normal text, change region into an item. With a prefix
17872 argument ARG, change each line in region into an item."
17873 (interactive "P")
17874 (let ((shift-text
17875 (function
17876 ;; Shift text in current section to IND, from point to END.
17877 ;; The function leaves point to END line.
17878 (lambda (ind end)
17879 (let ((min-i 1000) (end (copy-marker end)))
17880 ;; First determine the minimum indentation (MIN-I) of
17881 ;; the text.
17882 (save-excursion
17883 (catch 'exit
17884 (while (< (point) end)
17885 (let ((i (org-get-indentation)))
17886 (cond
17887 ;; Skip blank lines and inline tasks.
17888 ((looking-at "^[ \t]*$"))
17889 ((looking-at "^\\*+ "))
17890 ;; We can't find less than 0 indentation.
17891 ((zerop i) (throw 'exit (setq min-i 0)))
17892 ((< i min-i) (setq min-i i))))
17893 (forward-line))))
17894 ;; Then indent each line so that a line indented to
17895 ;; MIN-I becomes indented to IND. Ignore blank lines
17896 ;; and inline tasks in the process.
17897 (let ((delta (- ind min-i)))
17898 (while (< (point) end)
17899 (unless (or (looking-at "^[ \t]*$")
17900 (looking-at "^\\*+ "))
17901 (org-indent-line-to (+ (org-get-indentation) delta)))
17902 (forward-line)))))))
17903 (skip-blanks
17904 (function
17905 ;; Return beginning of first non-blank line, starting from
17906 ;; line at POS.
17907 (lambda (pos)
17908 (save-excursion
17909 (goto-char pos)
17910 (skip-chars-forward " \r\t\n")
17911 (point-at-bol)))))
17912 beg end)
17913 ;; Determine boundaries of changes.
17914 (if (org-region-active-p)
17915 (setq beg (funcall skip-blanks (region-beginning))
17916 end (copy-marker (region-end)))
17917 (setq beg (funcall skip-blanks (point-at-bol))
17918 end (copy-marker (point-at-eol))))
17919 ;; Depending on the starting line, choose an action on the text
17920 ;; between BEG and END.
17921 (org-with-limited-levels
17922 (save-excursion
17923 (goto-char beg)
17924 (cond
17925 ;; Case 1. Start at an item: de-itemize. Note that it only
17926 ;; happens when a region is active: `org-ctrl-c-minus'
17927 ;; would call `org-cycle-list-bullet' otherwise.
17928 ((org-at-item-p)
17929 (while (< (point) end)
17930 (when (org-at-item-p)
17931 (skip-chars-forward " \t")
17932 (delete-region (point) (match-end 0)))
17933 (forward-line)))
17934 ;; Case 2. Start at an heading: convert to items.
17935 ((org-on-heading-p)
17936 (let* ((bul (org-list-bullet-string "-"))
17937 (bul-len (length bul))
17938 ;; Indentation of the first heading. It should be
17939 ;; relative to the indentation of its parent, if any.
17940 (start-ind (save-excursion
17941 (cond
17942 ((not org-adapt-indentation) 0)
17943 ((not (outline-previous-heading)) 0)
17944 (t (length (match-string 0))))))
17945 ;; Level of first heading. Further headings will be
17946 ;; compared to it to determine hierarchy in the list.
17947 (ref-level (org-reduced-level (org-outline-level))))
17948 (while (< (point) end)
17949 (let* ((level (org-reduced-level (org-outline-level)))
17950 (delta (max 0 (- level ref-level))))
17951 ;; If current headline is less indented than the first
17952 ;; one, set it as reference, in order to preserve
17953 ;; subtrees.
17954 (when (< level ref-level) (setq ref-level level))
17955 (replace-match bul t t)
17956 (org-indent-line-to (+ start-ind (* delta bul-len)))
17957 ;; Ensure all text down to END (or SECTION-END) belongs
17958 ;; to the newly created item.
17959 (let ((section-end (save-excursion
17960 (or (outline-next-heading) (point)))))
17961 (forward-line)
17962 (funcall shift-text
17963 (+ start-ind (* (1+ delta) bul-len))
17964 (min end section-end)))))))
17965 ;; Case 3. Normal line with ARG: turn each non-item line into
17966 ;; an item.
17967 (arg
17968 (while (< (point) end)
17969 (unless (or (org-on-heading-p) (org-at-item-p))
17970 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
17971 (replace-match
17972 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
17973 (forward-line)))
17974 ;; Case 4. Normal line without ARG: make the first line of
17975 ;; region an item, and shift indentation of others
17976 ;; lines to set them as item's body.
17977 (t (let* ((bul (org-list-bullet-string "-"))
17978 (bul-len (length bul))
17979 (ref-ind (org-get-indentation)))
17980 (skip-chars-forward " \t")
17981 (insert bul)
17982 (forward-line)
17983 (while (< (point) end)
17984 ;; Ensure that lines less indented than first one
17985 ;; still get included in item body.
17986 (funcall shift-text
17987 (+ ref-ind bul-len)
17988 (min end (save-excursion (or (outline-next-heading)
17989 (point)))))
17990 (forward-line)))))))))
17992 (defun org-toggle-heading (&optional nstars)
17993 "Convert headings to normal text, or items or text to headings.
17994 If there is no active region, only the current line is considered.
17996 If the first non blank line is an headline, remove the stars from
17997 all headlines in the region.
17999 If it is a plain list item, turn all plain list items into headings.
18001 If it is a normal line, turn each and every normal line (i.e. not
18002 an heading or an item) in the region into a heading.
18004 When converting a line into a heading, the number of stars is chosen
18005 such that the lines become children of the current entry. However,
18006 when a prefix argument is given, its value determines the number of
18007 stars to add."
18008 (interactive "P")
18009 (let ((skip-blanks
18010 (function
18011 ;; Return beginning of first non-blank line, starting from
18012 ;; line at POS.
18013 (lambda (pos)
18014 (save-excursion
18015 (goto-char pos)
18016 (skip-chars-forward " \r\t\n")
18017 (point-at-bol)))))
18018 beg end)
18019 ;; Determine boundaries of changes. If region ends at a bol, do
18020 ;; not consider the last line to be in the region.
18021 (if (org-region-active-p)
18022 (setq beg (funcall skip-blanks (region-beginning))
18023 end (copy-marker (save-excursion
18024 (goto-char (region-end))
18025 (if (bolp) (point) (point-at-eol)))))
18026 (setq beg (funcall skip-blanks (point-at-bol))
18027 end (copy-marker (point-at-eol))))
18028 ;; Ensure inline tasks don't count as headings.
18029 (org-with-limited-levels
18030 (save-excursion
18031 (goto-char beg)
18032 (cond
18033 ;; Case 1. Started at an heading: de-star headings.
18034 ((org-on-heading-p)
18035 (while (< (point) end)
18036 (when (org-on-heading-p t)
18037 (looking-at outline-regexp) (replace-match ""))
18038 (forward-line)))
18039 ;; Case 2. Started at an item: change items into headlines.
18040 ;; One star will be added by `org-list-to-subtree'.
18041 ((org-at-item-p)
18042 (let* ((stars (make-string
18043 (if nstars
18044 ;; subtract the star that will be added again by
18045 ;; `org-list-to-subtree'
18046 (1- (prefix-numeric-value current-prefix-arg))
18047 (or (org-current-level) 0))
18048 ?*))
18049 (add-stars
18050 (cond (nstars "") ; stars from prefix only
18051 ((equal stars "") "") ; before first heading
18052 (org-odd-levels-only "*") ; inside heading, odd
18053 (t "")))) ; inside heading, oddeven
18054 (while (< (point) end)
18055 (when (org-at-item-p)
18056 ;; Pay attention to cases when region ends before list.
18057 (let* ((struct (org-list-struct))
18058 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18059 (save-restriction
18060 (narrow-to-region (point) list-end)
18061 (insert
18062 (org-list-to-subtree
18063 (org-list-parse-list t)
18064 '(:istart (concat stars add-stars (funcall get-stars depth))
18065 :icount (concat stars add-stars (funcall get-stars depth))))))))
18066 (forward-line))))
18067 ;; Case 3. Started at normal text: make every line an heading,
18068 ;; skipping headlines and items.
18069 (t (let* ((stars (make-string
18070 (if nstars
18071 (prefix-numeric-value current-prefix-arg)
18072 (or (org-current-level) 0))
18073 ?*))
18074 (add-stars
18075 (cond (nstars "") ; stars from prefix only
18076 ((equal stars "") "*") ; before first heading
18077 (org-odd-levels-only "**") ; inside heading, odd
18078 (t "*"))) ; inside heading, oddeven
18079 (rpl (concat stars add-stars " ")))
18080 (while (< (point) end)
18081 (when (and (not (org-on-heading-p)) (not (org-at-item-p))
18082 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18083 (replace-match (concat rpl (match-string 2))))
18084 (forward-line)))))))))
18086 (defun org-meta-return (&optional arg)
18087 "Insert a new heading or wrap a region in a table.
18088 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18089 See the individual commands for more information."
18090 (interactive "P")
18091 (cond
18092 ((run-hook-with-args-until-success 'org-metareturn-hook))
18093 ((org-at-table-p)
18094 (call-interactively 'org-table-wrap-region))
18095 (t (call-interactively 'org-insert-heading))))
18097 ;;; Menu entries
18099 ;; Define the Org-mode menus
18100 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18101 '("Tbl"
18102 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18103 ["Next Field" org-cycle (org-at-table-p)]
18104 ["Previous Field" org-shifttab (org-at-table-p)]
18105 ["Next Row" org-return (org-at-table-p)]
18106 "--"
18107 ["Blank Field" org-table-blank-field (org-at-table-p)]
18108 ["Edit Field" org-table-edit-field (org-at-table-p)]
18109 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18110 "--"
18111 ("Column"
18112 ["Move Column Left" org-metaleft (org-at-table-p)]
18113 ["Move Column Right" org-metaright (org-at-table-p)]
18114 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18115 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18116 ("Row"
18117 ["Move Row Up" org-metaup (org-at-table-p)]
18118 ["Move Row Down" org-metadown (org-at-table-p)]
18119 ["Delete Row" org-shiftmetaup (org-at-table-p)]
18120 ["Insert Row" org-shiftmetadown (org-at-table-p)]
18121 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
18122 "--"
18123 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
18124 ("Rectangle"
18125 ["Copy Rectangle" org-copy-special (org-at-table-p)]
18126 ["Cut Rectangle" org-cut-special (org-at-table-p)]
18127 ["Paste Rectangle" org-paste-special (org-at-table-p)]
18128 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
18129 "--"
18130 ("Calculate"
18131 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
18132 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
18133 ["Edit Formulas" org-edit-special (org-at-table-p)]
18134 "--"
18135 ["Recalculate line" org-table-recalculate (org-at-table-p)]
18136 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
18137 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
18138 "--"
18139 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
18140 "--"
18141 ["Sum Column/Rectangle" org-table-sum
18142 (or (org-at-table-p) (org-region-active-p))]
18143 ["Which Column?" org-table-current-column (org-at-table-p)])
18144 ["Debug Formulas"
18145 org-table-toggle-formula-debugger
18146 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
18147 ["Show Col/Row Numbers"
18148 org-table-toggle-coordinate-overlays
18149 :style toggle
18150 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
18151 "--"
18152 ["Create" org-table-create (and (not (org-at-table-p))
18153 org-enable-table-editor)]
18154 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
18155 ["Import from File" org-table-import (not (org-at-table-p))]
18156 ["Export to File" org-table-export (org-at-table-p)]
18157 "--"
18158 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
18160 (easy-menu-define org-org-menu org-mode-map "Org menu"
18161 '("Org"
18162 ("Show/Hide"
18163 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
18164 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
18165 ["Sparse Tree..." org-sparse-tree t]
18166 ["Reveal Context" org-reveal t]
18167 ["Show All" show-all t]
18168 "--"
18169 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
18170 "--"
18171 ["New Heading" org-insert-heading t]
18172 ("Navigate Headings"
18173 ["Up" outline-up-heading t]
18174 ["Next" outline-next-visible-heading t]
18175 ["Previous" outline-previous-visible-heading t]
18176 ["Next Same Level" outline-forward-same-level t]
18177 ["Previous Same Level" outline-backward-same-level t]
18178 "--"
18179 ["Jump" org-goto t])
18180 ("Edit Structure"
18181 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
18182 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
18183 "--"
18184 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
18185 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
18186 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
18187 "--"
18188 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
18189 "--"
18190 ["Promote Heading" org-metaleft (not (org-at-table-p))]
18191 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
18192 ["Demote Heading" org-metaright (not (org-at-table-p))]
18193 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
18194 "--"
18195 ["Sort Region/Children" org-sort (not (org-at-table-p))]
18196 "--"
18197 ["Convert to odd levels" org-convert-to-odd-levels t]
18198 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
18199 ("Editing"
18200 ["Emphasis..." org-emphasize t]
18201 ["Edit Source Example" org-edit-special t]
18202 "--"
18203 ["Footnote new/jump" org-footnote-action t]
18204 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
18205 ("Archive"
18206 ["Archive (default method)" org-archive-subtree-default t]
18207 "--"
18208 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
18209 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
18210 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
18212 "--"
18213 ("Hyperlinks"
18214 ["Store Link (Global)" org-store-link t]
18215 ["Find existing link to here" org-occur-link-in-agenda-files t]
18216 ["Insert Link" org-insert-link t]
18217 ["Follow Link" org-open-at-point t]
18218 "--"
18219 ["Next link" org-next-link t]
18220 ["Previous link" org-previous-link t]
18221 "--"
18222 ["Descriptive Links"
18223 (progn (add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
18224 :style radio
18225 :selected (member '(org-link) buffer-invisibility-spec)]
18226 ["Literal Links"
18227 (progn
18228 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
18229 :style radio
18230 :selected (not (member '(org-link) buffer-invisibility-spec))])
18231 "--"
18232 ("TODO Lists"
18233 ["TODO/DONE/-" org-todo t]
18234 ("Select keyword"
18235 ["Next keyword" org-shiftright (org-on-heading-p)]
18236 ["Previous keyword" org-shiftleft (org-on-heading-p)]
18237 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
18238 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
18239 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
18240 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
18241 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
18242 "--"
18243 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
18244 :selected org-enforce-todo-dependencies :style toggle :active t]
18245 "Settings for tree at point"
18246 ["Do Children sequentially" org-toggle-ordered-property :style radio
18247 :selected (org-entry-get nil "ORDERED")
18248 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18249 ["Do Children parallel" org-toggle-ordered-property :style radio
18250 :selected (not (org-entry-get nil "ORDERED"))
18251 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18252 "--"
18253 ["Set Priority" org-priority t]
18254 ["Priority Up" org-shiftup t]
18255 ["Priority Down" org-shiftdown t]
18256 "--"
18257 ["Get news from all feeds" org-feed-update-all t]
18258 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
18259 ["Customize feeds" (customize-variable 'org-feed-alist) t])
18260 ("TAGS and Properties"
18261 ["Set Tags" org-set-tags-command t]
18262 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
18263 "--"
18264 ["Set property" org-set-property t]
18265 ["Column view of properties" org-columns t]
18266 ["Insert Column View DBlock" org-insert-columns-dblock t])
18267 ("Dates and Scheduling"
18268 ["Timestamp" org-time-stamp t]
18269 ["Timestamp (inactive)" org-time-stamp-inactive t]
18270 ("Change Date"
18271 ["1 Day Later" org-shiftright t]
18272 ["1 Day Earlier" org-shiftleft t]
18273 ["1 ... Later" org-shiftup t]
18274 ["1 ... Earlier" org-shiftdown t])
18275 ["Compute Time Range" org-evaluate-time-range t]
18276 ["Schedule Item" org-schedule t]
18277 ["Deadline" org-deadline t]
18278 "--"
18279 ["Custom time format" org-toggle-time-stamp-overlays
18280 :style radio :selected org-display-custom-times]
18281 "--"
18282 ["Goto Calendar" org-goto-calendar t]
18283 ["Date from Calendar" org-date-from-calendar t]
18284 "--"
18285 ["Start/Restart Timer" org-timer-start t]
18286 ["Pause/Continue Timer" org-timer-pause-or-continue t]
18287 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
18288 ["Insert Timer String" org-timer t]
18289 ["Insert Timer Item" org-timer-item t])
18290 ("Logging work"
18291 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
18292 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
18293 ["Clock out" org-clock-out t]
18294 ["Clock cancel" org-clock-cancel t]
18295 "--"
18296 ["Mark as default task" org-clock-mark-default-task t]
18297 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
18298 ["Goto running clock" org-clock-goto t]
18299 "--"
18300 ["Display times" org-clock-display t]
18301 ["Create clock table" org-clock-report t]
18302 "--"
18303 ["Record DONE time"
18304 (progn (setq org-log-done (not org-log-done))
18305 (message "Switching to %s will %s record a timestamp"
18306 (car org-done-keywords)
18307 (if org-log-done "automatically" "not")))
18308 :style toggle :selected org-log-done])
18309 "--"
18310 ["Agenda Command..." org-agenda t]
18311 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
18312 ("File List for Agenda")
18313 ("Special views current file"
18314 ["TODO Tree" org-show-todo-tree t]
18315 ["Check Deadlines" org-check-deadlines t]
18316 ["Timeline" org-timeline t]
18317 ["Tags/Property tree" org-match-sparse-tree t])
18318 "--"
18319 ["Export/Publish..." org-export t]
18320 ("LaTeX"
18321 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
18322 :selected org-cdlatex-mode]
18323 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
18324 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
18325 ["Modify math symbol" org-cdlatex-math-modify
18326 (org-inside-LaTeX-fragment-p)]
18327 ["Insert citation" org-reftex-citation t]
18328 "--"
18329 ["Template for BEAMER" org-insert-beamer-options-template t])
18330 "--"
18331 ("MobileOrg"
18332 ["Push Files and Views" org-mobile-push t]
18333 ["Get Captured and Flagged" org-mobile-pull t]
18334 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
18335 "--"
18336 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
18337 "--"
18338 ("Documentation"
18339 ["Show Version" org-version t]
18340 ["Info Documentation" org-info t])
18341 ("Customize"
18342 ["Browse Org Group" org-customize t]
18343 "--"
18344 ["Expand This Menu" org-create-customize-menu
18345 (fboundp 'customize-menu-create)])
18346 ["Send bug report" org-submit-bug-report t]
18347 "--"
18348 ("Refresh/Reload"
18349 ["Refresh setup current buffer" org-mode-restart t]
18350 ["Reload Org (after update)" org-reload t]
18351 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
18354 (defun org-info (&optional node)
18355 "Read documentation for Org-mode in the info system.
18356 With optional NODE, go directly to that node."
18357 (interactive)
18358 (info (format "(org)%s" (or node ""))))
18360 ;;;###autoload
18361 (defun org-submit-bug-report ()
18362 "Submit a bug report on Org-mode via mail.
18364 Don't hesitate to report any problems or inaccurate documentation.
18366 If you don't have setup sending mail from (X)Emacs, please copy the
18367 output buffer into your mail program, as it gives us important
18368 information about your Org-mode version and configuration."
18369 (interactive)
18370 (require 'reporter)
18371 (org-load-modules-maybe)
18372 (org-require-autoloaded-modules)
18373 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
18374 (reporter-submit-bug-report
18375 "emacs-orgmode@gnu.org"
18376 (org-version)
18377 (let (list)
18378 (save-window-excursion
18379 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
18380 (delete-other-windows)
18381 (erase-buffer)
18382 (insert "You are about to submit a bug report to the Org-mode mailing list.
18384 We would like to add your full Org-mode and Outline configuration to the
18385 bug report. This greatly simplifies the work of the maintainer and
18386 other experts on the mailing list.
18388 HOWEVER, some variables you have customized may contain private
18389 information. The names of customers, colleagues, or friends, might
18390 appear in the form of file names, tags, todo states, or search strings.
18391 If you answer yes to the prompt, you might want to check and remove
18392 such private information before sending the email.")
18393 (add-text-properties (point-min) (point-max) '(face org-warning))
18394 (when (yes-or-no-p "Include your Org-mode configuration ")
18395 (mapatoms
18396 (lambda (v)
18397 (and (boundp v)
18398 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
18399 (or (and (symbol-value v)
18400 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
18401 (and
18402 (get v 'custom-type) (get v 'standard-value)
18403 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
18404 (push v list)))))
18405 (kill-buffer (get-buffer "*Warn about privacy*"))
18406 list))
18407 nil nil
18408 "Remember to cover the basics, that is, what you expected to happen and
18409 what in fact did happen. You don't know how to make a good report? See
18411 http://orgmode.org/manual/Feedback.html#Feedback
18413 Your bug report will be posted to the Org-mode mailing list.
18414 ------------------------------------------------------------------------")
18415 (save-excursion
18416 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
18417 (replace-match "\\1Bug: \\3 [\\2]")))))
18420 (defun org-install-agenda-files-menu ()
18421 (let ((bl (buffer-list)))
18422 (save-excursion
18423 (while bl
18424 (set-buffer (pop bl))
18425 (if (org-mode-p) (setq bl nil)))
18426 (when (org-mode-p)
18427 (easy-menu-change
18428 '("Org") "File List for Agenda"
18429 (append
18430 (list
18431 ["Edit File List" (org-edit-agenda-file-list) t]
18432 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
18433 ["Remove Current File from List" org-remove-file t]
18434 ["Cycle through agenda files" org-cycle-agenda-files t]
18435 ["Occur in all agenda files" org-occur-in-agenda-files t]
18436 "--")
18437 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
18439 ;;;; Documentation
18441 ;;;###autoload
18442 (defun org-require-autoloaded-modules ()
18443 (interactive)
18444 (mapc 'require
18445 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
18446 org-docbook org-exp org-html org-icalendar
18447 org-id org-latex
18448 org-publish org-remember org-table
18449 org-timer org-xoxo)))
18451 ;;;###autoload
18452 (defun org-reload (&optional uncompiled)
18453 "Reload all org lisp files.
18454 With prefix arg UNCOMPILED, load the uncompiled versions."
18455 (interactive "P")
18456 (require 'find-func)
18457 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
18458 (dir-org (file-name-directory (org-find-library-name "org")))
18459 (dir-org-contrib (ignore-errors
18460 (file-name-directory
18461 (org-find-library-name "org-contribdir"))))
18462 (babel-files
18463 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
18464 (append (list nil "comint" "eval" "exp" "keys"
18465 "lob" "ref" "table" "tangle")
18466 (delq nil
18467 (mapcar
18468 (lambda (lang)
18469 (when (cdr lang) (symbol-name (car lang))))
18470 org-babel-load-languages)))))
18471 (files
18472 (append (directory-files dir-org t file-re)
18473 babel-files
18474 (and dir-org-contrib
18475 (directory-files dir-org-contrib t file-re))))
18476 (remove-re (concat (if (featurep 'xemacs)
18477 "org-colview" "org-colview-xemacs")
18478 "\\'")))
18479 (setq files (mapcar 'file-name-sans-extension files))
18480 (setq files (mapcar
18481 (lambda (x) (if (string-match remove-re x) nil x))
18482 files))
18483 (setq files (delq nil files))
18484 (mapc
18485 (lambda (f)
18486 (when (featurep (intern (file-name-nondirectory f)))
18487 (if (and (not uncompiled)
18488 (file-exists-p (concat f ".elc")))
18489 (load (concat f ".elc") nil nil t)
18490 (load (concat f ".el") nil nil t))))
18491 files))
18492 (org-version))
18494 ;;;###autoload
18495 (defun org-customize ()
18496 "Call the customize function with org as argument."
18497 (interactive)
18498 (org-load-modules-maybe)
18499 (org-require-autoloaded-modules)
18500 (customize-browse 'org))
18502 (defun org-create-customize-menu ()
18503 "Create a full customization menu for Org-mode, insert it into the menu."
18504 (interactive)
18505 (org-load-modules-maybe)
18506 (org-require-autoloaded-modules)
18507 (if (fboundp 'customize-menu-create)
18508 (progn
18509 (easy-menu-change
18510 '("Org") "Customize"
18511 `(["Browse Org group" org-customize t]
18512 "--"
18513 ,(customize-menu-create 'org)
18514 ["Set" Custom-set t]
18515 ["Save" Custom-save t]
18516 ["Reset to Current" Custom-reset-current t]
18517 ["Reset to Saved" Custom-reset-saved t]
18518 ["Reset to Standard Settings" Custom-reset-standard t]))
18519 (message "\"Org\"-menu now contains full customization menu"))
18520 (error "Cannot expand menu (outdated version of cus-edit.el)")))
18522 ;;;; Miscellaneous stuff
18524 ;;; Generally useful functions
18526 (defun org-get-at-bol (property)
18527 "Get text property PROPERTY at beginning of line."
18528 (get-text-property (point-at-bol) property))
18530 (defun org-find-text-property-in-string (prop s)
18531 "Return the first non-nil value of property PROP in string S."
18532 (or (get-text-property 0 prop s)
18533 (get-text-property (or (next-single-property-change 0 prop s) 0)
18534 prop s)))
18536 (defun org-display-warning (message) ;; Copied from Emacs-Muse
18537 "Display the given MESSAGE as a warning."
18538 (if (fboundp 'display-warning)
18539 (display-warning 'org message
18540 (if (featurep 'xemacs) 'warning :warning))
18541 (let ((buf (get-buffer-create "*Org warnings*")))
18542 (with-current-buffer buf
18543 (goto-char (point-max))
18544 (insert "Warning (Org): " message)
18545 (unless (bolp)
18546 (newline)))
18547 (display-buffer buf)
18548 (sit-for 0))))
18550 (defun org-eval (form)
18551 "Eval FORM and return result."
18552 (condition-case error
18553 (eval form)
18554 (error (format "%%![Error: %s]" error))))
18556 (defun org-in-commented-line ()
18557 "Is point in a line starting with `#'?"
18558 (equal (char-after (point-at-bol)) ?#))
18560 (defun org-in-indented-comment-line ()
18561 "Is point in a line starting with `#' after some white space?"
18562 (save-excursion
18563 (save-match-data
18564 (goto-char (point-at-bol))
18565 (looking-at "[ \t]*#"))))
18567 (defun org-in-verbatim-emphasis ()
18568 (save-match-data
18569 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
18571 (defun org-goto-marker-or-bmk (marker &optional bookmark)
18572 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
18573 (if (and marker (marker-buffer marker)
18574 (buffer-live-p (marker-buffer marker)))
18575 (progn
18576 (switch-to-buffer (marker-buffer marker))
18577 (if (or (> marker (point-max)) (< marker (point-min)))
18578 (widen))
18579 (goto-char marker)
18580 (org-show-context 'org-goto))
18581 (if bookmark
18582 (bookmark-jump bookmark)
18583 (error "Cannot find location"))))
18585 (defun org-quote-csv-field (s)
18586 "Quote field for inclusion in CSV material."
18587 (if (string-match "[\",]" s)
18588 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
18591 (defun org-force-self-insert (N)
18592 "Needed to enforce self-insert under remapping."
18593 (interactive "p")
18594 (self-insert-command N))
18596 (defun org-string-width (s)
18597 "Compute width of string, ignoring invisible characters.
18598 This ignores character with invisibility property `org-link', and also
18599 characters with property `org-cwidth', because these will become invisible
18600 upon the next fontification round."
18601 (let (b l)
18602 (when (or (eq t buffer-invisibility-spec)
18603 (assq 'org-link buffer-invisibility-spec))
18604 (while (setq b (text-property-any 0 (length s)
18605 'invisible 'org-link s))
18606 (setq s (concat (substring s 0 b)
18607 (substring s (or (next-single-property-change
18608 b 'invisible s) (length s)))))))
18609 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
18610 (setq s (concat (substring s 0 b)
18611 (substring s (or (next-single-property-change
18612 b 'org-cwidth s) (length s))))))
18613 (setq l (string-width s) b -1)
18614 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
18615 (setq l (- l (get-text-property b 'org-dwidth-n s))))
18618 (defun org-shorten-string (s maxlength)
18619 "Shorten string S so tht it is no longer than MAXLENGTH characters.
18620 If the string is shorter or has length MAXLENGTH, just return the
18621 original string. If it is longer, the functions finds a space in the
18622 string, breaks this string off at that locations and adds three dots
18623 as ellipsis. Including the ellipsis, the string will not be longer
18624 than MAXLENGTH. If finding a good breaking point in the string does
18625 not work, the string is just chopped off in the middle of a word
18626 if necessary."
18627 (if (<= (length s) maxlength)
18629 (let* ((n (max (- maxlength 4) 1))
18630 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
18631 (if (string-match re s)
18632 (concat (match-string 1 s) "...")
18633 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
18635 (defun org-get-indentation (&optional line)
18636 "Get the indentation of the current line, interpreting tabs.
18637 When LINE is given, assume it represents a line and compute its indentation."
18638 (if line
18639 (if (string-match "^ *" (org-remove-tabs line))
18640 (match-end 0))
18641 (save-excursion
18642 (beginning-of-line 1)
18643 (skip-chars-forward " \t")
18644 (current-column))))
18646 (defun org-get-string-indentation (s)
18647 "What indentation has S due to SPACE and TAB at the beginning of the string?"
18648 (let ((n -1) (i 0) (w tab-width) c)
18649 (catch 'exit
18650 (while (< (setq n (1+ n)) (length s))
18651 (setq c (aref s n))
18652 (cond ((= c ?\ ) (setq i (1+ i)))
18653 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
18654 (t (throw 'exit t)))))
18657 (defun org-remove-tabs (s &optional width)
18658 "Replace tabulators in S with spaces.
18659 Assumes that s is a single line, starting in column 0."
18660 (setq width (or width tab-width))
18661 (while (string-match "\t" s)
18662 (setq s (replace-match
18663 (make-string
18664 (- (* width (/ (+ (match-beginning 0) width) width))
18665 (match-beginning 0)) ?\ )
18666 t t s)))
18669 (defun org-fix-indentation (line ind)
18670 "Fix indentation in LINE.
18671 IND is a cons cell with target and minimum indentation.
18672 If the current indentation in LINE is smaller than the minimum,
18673 leave it alone. If it is larger than ind, set it to the target."
18674 (let* ((l (org-remove-tabs line))
18675 (i (org-get-indentation l))
18676 (i1 (car ind)) (i2 (cdr ind)))
18677 (if (>= i i2) (setq l (substring line i2)))
18678 (if (> i1 0)
18679 (concat (make-string i1 ?\ ) l)
18680 l)))
18682 (defun org-remove-indentation (code &optional n)
18683 "Remove the maximum common indentation from the lines in CODE.
18684 N may optionally be the number of spaces to remove."
18685 (with-temp-buffer
18686 (insert code)
18687 (org-do-remove-indentation n)
18688 (buffer-string)))
18690 (defun org-do-remove-indentation (&optional n)
18691 "Remove the maximum common indentation from the buffer."
18692 (untabify (point-min) (point-max))
18693 (let ((min 10000) re)
18694 (if n
18695 (setq min n)
18696 (goto-char (point-min))
18697 (while (re-search-forward "^ *[^ \n]" nil t)
18698 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
18699 (unless (or (= min 0) (= min 10000))
18700 (setq re (format "^ \\{%d\\}" min))
18701 (goto-char (point-min))
18702 (while (re-search-forward re nil t)
18703 (replace-match "")
18704 (end-of-line 1))
18705 min)))
18707 (defun org-fill-template (template alist)
18708 "Find each %key of ALIST in TEMPLATE and replace it."
18709 (let ((case-fold-search nil)
18710 entry key value)
18711 (setq alist (sort (copy-sequence alist)
18712 (lambda (a b) (< (length (car a)) (length (car b))))))
18713 (while (setq entry (pop alist))
18714 (setq template
18715 (replace-regexp-in-string
18716 (concat "%" (regexp-quote (car entry)))
18717 (cdr entry) template t t)))
18718 template))
18720 (defun org-base-buffer (buffer)
18721 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
18722 (if (not buffer)
18723 buffer
18724 (or (buffer-base-buffer buffer)
18725 buffer)))
18727 (defun org-trim (s)
18728 "Remove whitespace at beginning and end of string."
18729 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
18730 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
18733 (defun org-wrap (string &optional width lines)
18734 "Wrap string to either a number of lines, or a width in characters.
18735 If WIDTH is non-nil, the string is wrapped to that width, however many lines
18736 that costs. If there is a word longer than WIDTH, the text is actually
18737 wrapped to the length of that word.
18738 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
18739 many lines, whatever width that takes.
18740 The return value is a list of lines, without newlines at the end."
18741 (let* ((words (org-split-string string "[ \t\n]+"))
18742 (maxword (apply 'max (mapcar 'org-string-width words)))
18743 w ll)
18744 (cond (width
18745 (org-do-wrap words (max maxword width)))
18746 (lines
18747 (setq w maxword)
18748 (setq ll (org-do-wrap words maxword))
18749 (if (<= (length ll) lines)
18751 (setq ll words)
18752 (while (> (length ll) lines)
18753 (setq w (1+ w))
18754 (setq ll (org-do-wrap words w)))
18755 ll))
18756 (t (error "Cannot wrap this")))))
18758 (defun org-do-wrap (words width)
18759 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
18760 (let (lines line)
18761 (while words
18762 (setq line (pop words))
18763 (while (and words (< (+ (length line) (length (car words))) width))
18764 (setq line (concat line " " (pop words))))
18765 (setq lines (push line lines)))
18766 (nreverse lines)))
18768 (defun org-split-string (string &optional separators)
18769 "Splits STRING into substrings at SEPARATORS.
18770 No empty strings are returned if there are matches at the beginning
18771 and end of string."
18772 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
18773 (start 0)
18774 notfirst
18775 (list nil))
18776 (while (and (string-match rexp string
18777 (if (and notfirst
18778 (= start (match-beginning 0))
18779 (< start (length string)))
18780 (1+ start) start))
18781 (< (match-beginning 0) (length string)))
18782 (setq notfirst t)
18783 (or (eq (match-beginning 0) 0)
18784 (and (eq (match-beginning 0) (match-end 0))
18785 (eq (match-beginning 0) start))
18786 (setq list
18787 (cons (substring string start (match-beginning 0))
18788 list)))
18789 (setq start (match-end 0)))
18790 (or (eq start (length string))
18791 (setq list
18792 (cons (substring string start)
18793 list)))
18794 (nreverse list)))
18796 (defun org-quote-vert (s)
18797 "Replace \"|\" with \"\\vert\"."
18798 (while (string-match "|" s)
18799 (setq s (replace-match "\\vert" t t s)))
18802 (defun org-uuidgen-p (s)
18803 "Is S an ID created by UUIDGEN?"
18804 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
18806 (defun org-context ()
18807 "Return a list of contexts of the current cursor position.
18808 If several contexts apply, all are returned.
18809 Each context entry is a list with a symbol naming the context, and
18810 two positions indicating start and end of the context. Possible
18811 contexts are:
18813 :headline anywhere in a headline
18814 :headline-stars on the leading stars in a headline
18815 :todo-keyword on a TODO keyword (including DONE) in a headline
18816 :tags on the TAGS in a headline
18817 :priority on the priority cookie in a headline
18818 :item on the first line of a plain list item
18819 :item-bullet on the bullet/number of a plain list item
18820 :checkbox on the checkbox in a plain list item
18821 :table in an org-mode table
18822 :table-special on a special filed in a table
18823 :table-table in a table.el table
18824 :link on a hyperlink
18825 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
18826 :target on a <<target>>
18827 :radio-target on a <<<radio-target>>>
18828 :latex-fragment on a LaTeX fragment
18829 :latex-preview on a LaTeX fragment with overlayed preview image
18831 This function expects the position to be visible because it uses font-lock
18832 faces as a help to recognize the following contexts: :table-special, :link,
18833 and :keyword."
18834 (let* ((f (get-text-property (point) 'face))
18835 (faces (if (listp f) f (list f)))
18836 (p (point)) clist o)
18837 ;; First the large context
18838 (cond
18839 ((org-on-heading-p t)
18840 (push (list :headline (point-at-bol) (point-at-eol)) clist)
18841 (when (progn
18842 (beginning-of-line 1)
18843 (looking-at org-todo-line-tags-regexp))
18844 (push (org-point-in-group p 1 :headline-stars) clist)
18845 (push (org-point-in-group p 2 :todo-keyword) clist)
18846 (push (org-point-in-group p 4 :tags) clist))
18847 (goto-char p)
18848 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
18849 (if (looking-at "\\[#[A-Z0-9]\\]")
18850 (push (org-point-in-group p 0 :priority) clist)))
18852 ((org-at-item-p)
18853 (push (org-point-in-group p 2 :item-bullet) clist)
18854 (push (list :item (point-at-bol)
18855 (save-excursion (org-end-of-item) (point)))
18856 clist)
18857 (and (org-at-item-checkbox-p)
18858 (push (org-point-in-group p 0 :checkbox) clist)))
18860 ((org-at-table-p)
18861 (push (list :table (org-table-begin) (org-table-end)) clist)
18862 (if (memq 'org-formula faces)
18863 (push (list :table-special
18864 (previous-single-property-change p 'face)
18865 (next-single-property-change p 'face)) clist)))
18866 ((org-at-table-p 'any)
18867 (push (list :table-table) clist)))
18868 (goto-char p)
18870 ;; Now the small context
18871 (cond
18872 ((org-at-timestamp-p)
18873 (push (org-point-in-group p 0 :timestamp) clist))
18874 ((memq 'org-link faces)
18875 (push (list :link
18876 (previous-single-property-change p 'face)
18877 (next-single-property-change p 'face)) clist))
18878 ((memq 'org-special-keyword faces)
18879 (push (list :keyword
18880 (previous-single-property-change p 'face)
18881 (next-single-property-change p 'face)) clist))
18882 ((org-on-target-p)
18883 (push (org-point-in-group p 0 :target) clist)
18884 (goto-char (1- (match-beginning 0)))
18885 (if (looking-at org-radio-target-regexp)
18886 (push (org-point-in-group p 0 :radio-target) clist))
18887 (goto-char p))
18888 ((setq o (car (delq nil
18889 (mapcar
18890 (lambda (x)
18891 (if (memq x org-latex-fragment-image-overlays) x))
18892 (overlays-at (point))))))
18893 (push (list :latex-fragment
18894 (overlay-start o) (overlay-end o)) clist)
18895 (push (list :latex-preview
18896 (overlay-start o) (overlay-end o)) clist))
18897 ((org-inside-LaTeX-fragment-p)
18898 ;; FIXME: positions wrong.
18899 (push (list :latex-fragment (point) (point)) clist)))
18901 (setq clist (nreverse (delq nil clist)))
18902 clist))
18904 ;; FIXME: Compare with at-regexp-p Do we need both?
18905 (defun org-in-regexp (re &optional nlines visually)
18906 "Check if point is inside a match of regexp.
18907 Normally only the current line is checked, but you can include NLINES extra
18908 lines both before and after point into the search.
18909 If VISUALLY is set, require that the cursor is not after the match but
18910 really on, so that the block visually is on the match."
18911 (catch 'exit
18912 (let ((pos (point))
18913 (eol (point-at-eol (+ 1 (or nlines 0))))
18914 (inc (if visually 1 0)))
18915 (save-excursion
18916 (beginning-of-line (- 1 (or nlines 0)))
18917 (while (re-search-forward re eol t)
18918 (if (and (<= (match-beginning 0) pos)
18919 (>= (+ inc (match-end 0)) pos))
18920 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
18922 (defun org-at-regexp-p (regexp)
18923 "Is point inside a match of REGEXP in the current line?"
18924 (catch 'exit
18925 (save-excursion
18926 (let ((pos (point)) (end (point-at-eol)))
18927 (beginning-of-line 1)
18928 (while (re-search-forward regexp end t)
18929 (if (and (<= (match-beginning 0) pos)
18930 (>= (match-end 0) pos))
18931 (throw 'exit t)))
18932 nil))))
18934 (defun org-in-regexps-block-p (start-re end-re &optional bound)
18935 "Return t if the current point is between matches of START-RE and END-RE.
18936 This will also return t if point is on one of the two matches or
18937 in an unfinished block. END-RE can be a string or a form
18938 returning a string.
18940 An optional third argument bounds the search for START-RE. It
18941 defaults to previous heading or `point-min'."
18942 (let ((pos (point))
18943 (limit (or bound (save-excursion (outline-previous-heading)))))
18944 (save-excursion
18945 ;; we're on a block when point is on start-re...
18946 (or (org-at-regexp-p start-re)
18947 ;; ... or start-re can be found above...
18948 (and (re-search-backward start-re limit t)
18949 ;; ... but no end-re between start-re and point.
18950 (not (re-search-forward (eval end-re) pos t)))))))
18952 (defun org-in-block-p (names)
18953 "Is point inside any block whose name belongs to NAMES?
18955 NAMES is a list of strings containing names of blocks."
18956 (save-match-data
18957 (catch 'exit
18958 (let ((case-fold-search t))
18959 (mapc (lambda (name)
18960 (let ((n (regexp-quote name)))
18961 (when (org-in-regexps-block-p
18962 (concat "^[ \t]*#\\+begin_" n)
18963 (concat "^[ \t]*#\\+end_" n))
18964 (throw 'exit t))))
18965 names))
18966 nil)))
18968 (defun org-occur-in-agenda-files (regexp &optional nlines)
18969 "Call `multi-occur' with buffers for all agenda files."
18970 (interactive "sOrg-files matching: \np")
18971 (let* ((files (org-agenda-files))
18972 (tnames (mapcar 'file-truename files))
18973 (extra org-agenda-text-search-extra-files)
18975 (when (eq (car extra) 'agenda-archives)
18976 (setq extra (cdr extra))
18977 (setq files (org-add-archive-files files)))
18978 (while (setq f (pop extra))
18979 (unless (member (file-truename f) tnames)
18980 (add-to-list 'files f 'append)
18981 (add-to-list 'tnames (file-truename f) 'append)))
18982 (multi-occur
18983 (mapcar (lambda (x)
18984 (with-current-buffer
18985 (or (get-file-buffer x) (find-file-noselect x))
18986 (widen)
18987 (current-buffer)))
18988 files)
18989 regexp)))
18991 (if (boundp 'occur-mode-find-occurrence-hook)
18992 ;; Emacs 23
18993 (add-hook 'occur-mode-find-occurrence-hook
18994 (lambda ()
18995 (when (org-mode-p)
18996 (org-reveal))))
18997 ;; Emacs 22
18998 (defadvice occur-mode-goto-occurrence
18999 (after org-occur-reveal activate)
19000 (and (org-mode-p) (org-reveal)))
19001 (defadvice occur-mode-goto-occurrence-other-window
19002 (after org-occur-reveal activate)
19003 (and (org-mode-p) (org-reveal)))
19004 (defadvice occur-mode-display-occurrence
19005 (after org-occur-reveal activate)
19006 (when (org-mode-p)
19007 (let ((pos (occur-mode-find-occurrence)))
19008 (with-current-buffer (marker-buffer pos)
19009 (save-excursion
19010 (goto-char pos)
19011 (org-reveal)))))))
19013 (defun org-occur-link-in-agenda-files ()
19014 "Create a link and search for it in the agendas.
19015 The link is not stored in `org-stored-links', it is just created
19016 for the search purpose."
19017 (interactive)
19018 (let ((link (condition-case nil
19019 (org-store-link nil)
19020 (error "Unable to create a link to here"))))
19021 (org-occur-in-agenda-files (regexp-quote link))))
19023 (defun org-uniquify (list)
19024 "Remove duplicate elements from LIST."
19025 (let (res)
19026 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
19027 res))
19029 (defun org-delete-all (elts list)
19030 "Remove all elements in ELTS from LIST."
19031 (while elts
19032 (setq list (delete (pop elts) list)))
19033 list)
19035 (defun org-count (cl-item cl-seq)
19036 "Count the number of occurrences of ITEM in SEQ.
19037 Taken from `count' in cl-seq.el with all keyword arguments removed."
19038 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
19039 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
19040 (while (< cl-start cl-end)
19041 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
19042 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
19043 (setq cl-start (1+ cl-start)))
19044 cl-count))
19046 (defun org-remove-if (predicate seq)
19047 "Remove everything from SEQ that fulfills PREDICATE."
19048 (let (res e)
19049 (while seq
19050 (setq e (pop seq))
19051 (if (not (funcall predicate e)) (push e res)))
19052 (nreverse res)))
19054 (defun org-remove-if-not (predicate seq)
19055 "Remove everything from SEQ that does not fulfill PREDICATE."
19056 (let (res e)
19057 (while seq
19058 (setq e (pop seq))
19059 (if (funcall predicate e) (push e res)))
19060 (nreverse res)))
19062 (defun org-back-over-empty-lines ()
19063 "Move backwards over whitespace, to the beginning of the first empty line.
19064 Returns the number of empty lines passed."
19065 (let ((pos (point)))
19066 (if (cdr (assoc 'heading org-blank-before-new-entry))
19067 (skip-chars-backward " \t\n\r")
19068 (forward-line -1))
19069 (beginning-of-line 2)
19070 (goto-char (min (point) pos))
19071 (count-lines (point) pos)))
19073 (defun org-skip-whitespace ()
19074 (skip-chars-forward " \t\n\r"))
19076 (defun org-point-in-group (point group &optional context)
19077 "Check if POINT is in match-group GROUP.
19078 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
19079 match. If the match group does not exist or point is not inside it,
19080 return nil."
19081 (and (match-beginning group)
19082 (>= point (match-beginning group))
19083 (<= point (match-end group))
19084 (if context
19085 (list context (match-beginning group) (match-end group))
19086 t)))
19088 (defun org-switch-to-buffer-other-window (&rest args)
19089 "Switch to buffer in a second window on the current frame.
19090 In particular, do not allow pop-up frames.
19091 Returns the newly created buffer."
19092 (let (pop-up-frames special-display-buffer-names special-display-regexps
19093 special-display-function)
19094 (apply 'switch-to-buffer-other-window args)))
19096 (defun org-combine-plists (&rest plists)
19097 "Create a single property list from all plists in PLISTS.
19098 The process starts by copying the first list, and then setting properties
19099 from the other lists. Settings in the last list are the most significant
19100 ones and overrule settings in the other lists."
19101 (let ((rtn (copy-sequence (pop plists)))
19102 p v ls)
19103 (while plists
19104 (setq ls (pop plists))
19105 (while ls
19106 (setq p (pop ls) v (pop ls))
19107 (setq rtn (plist-put rtn p v))))
19108 rtn))
19110 (defun org-move-line-down (arg)
19111 "Move the current line down. With prefix argument, move it past ARG lines."
19112 (interactive "p")
19113 (let ((col (current-column))
19114 beg end pos)
19115 (beginning-of-line 1) (setq beg (point))
19116 (beginning-of-line 2) (setq end (point))
19117 (beginning-of-line (+ 1 arg))
19118 (setq pos (move-marker (make-marker) (point)))
19119 (insert (delete-and-extract-region beg end))
19120 (goto-char pos)
19121 (org-move-to-column col)))
19123 (defun org-move-line-up (arg)
19124 "Move the current line up. With prefix argument, move it past ARG lines."
19125 (interactive "p")
19126 (let ((col (current-column))
19127 beg end pos)
19128 (beginning-of-line 1) (setq beg (point))
19129 (beginning-of-line 2) (setq end (point))
19130 (beginning-of-line (- arg))
19131 (setq pos (move-marker (make-marker) (point)))
19132 (insert (delete-and-extract-region beg end))
19133 (goto-char pos)
19134 (org-move-to-column col)))
19136 (defun org-replace-escapes (string table)
19137 "Replace %-escapes in STRING with values in TABLE.
19138 TABLE is an association list with keys like \"%a\" and string values.
19139 The sequences in STRING may contain normal field width and padding information,
19140 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
19141 so values can contain further %-escapes if they are define later in TABLE."
19142 (let ((tbl (copy-alist table))
19143 (case-fold-search nil)
19144 (pchg 0)
19145 e re rpl)
19146 (while (setq e (pop tbl))
19147 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
19148 (when (and (cdr e) (string-match re (cdr e)))
19149 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
19150 (safe "SREF"))
19151 (add-text-properties 0 3 (list 'sref sref) safe)
19152 (setcdr e (replace-match safe t t (cdr e)))))
19153 (while (string-match re string)
19154 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
19155 (cdr e)))
19156 (setq string (replace-match rpl t t string))))
19157 (while (setq pchg (next-property-change pchg string))
19158 (let ((sref (get-text-property pchg 'sref string)))
19159 (when (and sref (string-match "SREF" string pchg))
19160 (setq string (replace-match sref t t string)))))
19161 string))
19163 (defun org-sublist (list start end)
19164 "Return a section of LIST, from START to END.
19165 Counting starts at 1."
19166 (let (rtn (c start))
19167 (setq list (nthcdr (1- start) list))
19168 (while (and list (<= c end))
19169 (push (pop list) rtn)
19170 (setq c (1+ c)))
19171 (nreverse rtn)))
19173 (defun org-find-base-buffer-visiting (file)
19174 "Like `find-buffer-visiting' but always return the base buffer and
19175 not an indirect buffer."
19176 (let ((buf (or (get-file-buffer file)
19177 (find-buffer-visiting file))))
19178 (if buf
19179 (or (buffer-base-buffer buf) buf)
19180 nil)))
19182 (defun org-image-file-name-regexp (&optional extensions)
19183 "Return regexp matching the file names of images.
19184 If EXTENSIONS is given, only match these."
19185 (if (and (not extensions) (fboundp 'image-file-name-regexp))
19186 (image-file-name-regexp)
19187 (let ((image-file-name-extensions
19188 (or extensions
19189 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
19190 "xbm" "xpm" "pbm" "pgm" "ppm"))))
19191 (concat "\\."
19192 (regexp-opt (nconc (mapcar 'upcase
19193 image-file-name-extensions)
19194 image-file-name-extensions)
19196 "\\'"))))
19198 (defun org-file-image-p (file &optional extensions)
19199 "Return non-nil if FILE is an image."
19200 (save-match-data
19201 (string-match (org-image-file-name-regexp extensions) file)))
19203 (defun org-get-cursor-date ()
19204 "Return the date at cursor in as a time.
19205 This works in the calendar and in the agenda, anywhere else it just
19206 returns the current time."
19207 (let (date day defd)
19208 (cond
19209 ((eq major-mode 'calendar-mode)
19210 (setq date (calendar-cursor-to-date)
19211 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
19212 ((eq major-mode 'org-agenda-mode)
19213 (setq day (get-text-property (point) 'day))
19214 (if day
19215 (setq date (calendar-gregorian-from-absolute day)
19216 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
19217 (nth 2 date))))))
19218 (or defd (current-time))))
19220 (defvar org-agenda-action-marker (make-marker)
19221 "Marker pointing to the entry for the next agenda action.")
19223 (defun org-mark-entry-for-agenda-action ()
19224 "Mark the current entry as target of an agenda action.
19225 Agenda actions are actions executed from the agenda with the key `k',
19226 which make use of the date at the cursor."
19227 (interactive)
19228 (move-marker org-agenda-action-marker
19229 (save-excursion (org-back-to-heading t) (point))
19230 (current-buffer))
19231 (message
19232 "Entry marked for action; press `k' at desired date in agenda or calendar"))
19234 (defun org-mark-subtree ()
19235 "Mark the current subtree.
19236 This puts point at the start of the current subtree, and mark at the end.
19238 If point is in an inline task, mark that task instead."
19239 (interactive)
19240 (let ((inline-task-p
19241 (and (featurep 'org-inlinetask)
19242 (org-inlinetask-in-task-p)))
19243 (beg))
19244 ;; Get beginning of subtree
19245 (cond
19246 (inline-task-p (org-inlinetask-goto-beginning))
19247 ((org-at-heading-p) (beginning-of-line))
19248 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
19249 (setq beg (point))
19250 ;; Get end of it
19251 (if inline-task-p
19252 (org-inlinetask-goto-end)
19253 (org-end-of-subtree))
19254 ;; Mark zone
19255 (push-mark (point) nil t)
19256 (goto-char beg)))
19258 ;;; Paragraph filling stuff.
19259 ;; We want this to be just right, so use the full arsenal.
19261 (defun org-indent-line-function ()
19262 "Indent line depending on context."
19263 (interactive)
19264 (let* ((pos (point))
19265 (itemp (org-at-item-p))
19266 (case-fold-search t)
19267 (org-drawer-regexp (or org-drawer-regexp "\000"))
19268 (inline-task-p (and (featurep 'org-inlinetask)
19269 (org-inlinetask-in-task-p)))
19270 (inline-re (and inline-task-p
19271 (org-inlinetask-outline-regexp)))
19272 column)
19273 (beginning-of-line 1)
19274 (cond
19275 ;; Comments
19276 ((looking-at "# ") (setq column 0))
19277 ;; Headings
19278 ((looking-at "\\*+ ") (setq column 0))
19279 ;; Included files
19280 ((looking-at "#\\+include:") (setq column 0))
19281 ;; Footnote definition
19282 ((looking-at org-footnote-definition-re) (setq column 0))
19283 ;; Literal examples
19284 ((looking-at "[ \t]*:[ \t]")
19285 (setq column (org-get-indentation))) ; do nothing
19286 ;; Lists
19287 ((ignore-errors (goto-char (org-in-item-p)))
19288 (setq column (if itemp
19289 (org-get-indentation)
19290 (org-list-item-body-column (point))))
19291 (goto-char pos))
19292 ;; Drawers
19293 ((and (looking-at "[ \t]*:END:")
19294 (save-excursion (re-search-backward org-drawer-regexp nil t)))
19295 (save-excursion
19296 (goto-char (1- (match-beginning 1)))
19297 (setq column (current-column))))
19298 ;; Special blocks
19299 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
19300 (save-excursion
19301 (re-search-backward
19302 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
19303 (setq column (org-get-indentation (match-string 0))))
19304 ((and (not (looking-at "[ \t]*#\\+begin_"))
19305 (org-in-regexps-block-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
19306 (save-excursion
19307 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
19308 (setq column
19309 (if (equal (downcase (match-string 1)) "src")
19310 ;; src blocks: let `org-edit-src-exit' handle them
19311 (org-get-indentation)
19312 (org-get-indentation (match-string 0)))))
19313 ;; This line has nothing special, look at the previous relevant
19314 ;; line to compute indentation
19316 (beginning-of-line 0)
19317 (while (and (not (bobp))
19318 (not (looking-at org-drawer-regexp))
19319 ;; When point started in an inline task, do not move
19320 ;; above task starting line.
19321 (not (and inline-task-p (looking-at inline-re)))
19322 ;; Skip drawers, blocks, empty lines, verbatim,
19323 ;; comments, tables, footnotes definitions, lists,
19324 ;; inline tasks.
19325 (or (and (looking-at "[ \t]*:END:")
19326 (re-search-backward org-drawer-regexp nil t))
19327 (and (looking-at "[ \t]*#\\+end_")
19328 (re-search-backward "[ \t]*#\\+begin_"nil t))
19329 (looking-at "[ \t]*[\n:#|]")
19330 (looking-at org-footnote-definition-re)
19331 (and (ignore-errors (goto-char (org-in-item-p)))
19332 (goto-char
19333 (org-list-get-top-point (org-list-struct))))
19334 (and (not inline-task-p)
19335 (featurep 'org-inlinetask)
19336 (org-inlinetask-in-task-p)
19337 (or (org-inlinetask-goto-beginning) t))))
19338 (beginning-of-line 0))
19339 (cond
19340 ;; There was an heading above.
19341 ((looking-at "\\*+[ \t]+")
19342 (if (not org-adapt-indentation)
19343 (setq column 0)
19344 (goto-char (match-end 0))
19345 (setq column (current-column))))
19346 ;; A drawer had started and is unfinished
19347 ((looking-at org-drawer-regexp)
19348 (goto-char (1- (match-beginning 1)))
19349 (setq column (current-column)))
19350 ;; Else, nothing noticeable found: get indentation and go on.
19351 (t (setq column (org-get-indentation))))))
19352 ;; Now apply indentation and move cursor accordingly
19353 (goto-char pos)
19354 (if (<= (current-column) (current-indentation))
19355 (org-indent-line-to column)
19356 (save-excursion (org-indent-line-to column)))
19357 ;; Special polishing for properties, see `org-property-format'
19358 (setq column (current-column))
19359 (beginning-of-line 1)
19360 (if (looking-at
19361 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
19362 (replace-match (concat (match-string 1)
19363 (format org-property-format
19364 (match-string 2) (match-string 3)))
19365 t t))
19366 (org-move-to-column column)))
19368 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
19369 "Variable to store copy of `adaptive-fill-regexp'.
19370 Since `adaptive-fill-regexp' is set to never match, we need to
19371 store a backup of its value before entering `org-mode' so that
19372 the functionality can be provided as a fall-back.")
19374 (defun org-set-autofill-regexps ()
19375 (interactive)
19376 ;; In the paragraph separator we include headlines, because filling
19377 ;; text in a line directly attached to a headline would otherwise
19378 ;; fill the headline as well.
19379 (org-set-local 'comment-start-skip "^#+[ \t]*")
19380 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
19381 ;; The paragraph starter includes hand-formatted lists.
19382 (org-set-local
19383 'paragraph-start
19384 (concat
19385 "\f" "\\|"
19386 "[ ]*$" "\\|"
19387 "\\*+ " "\\|"
19388 "[ \t]*#" "\\|"
19389 (org-item-re) "\\|"
19390 "[ \t]*[:|]" "\\|"
19391 "\\$\\$" "\\|"
19392 "\\\\\\(begin\\|end\\|[][]\\)"))
19393 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
19394 ;; But only if the user has not turned off tables or fixed-width regions
19395 (org-set-local
19396 'auto-fill-inhibit-regexp
19397 (concat "\\*+ \\|#\\+"
19398 "\\|[ \t]*" org-keyword-time-regexp
19399 (if (or org-enable-table-editor org-enable-fixed-width-editor)
19400 (concat
19401 "\\|[ \t]*["
19402 (if org-enable-table-editor "|" "")
19403 (if org-enable-fixed-width-editor ":" "")
19404 "]"))))
19405 ;; We use our own fill-paragraph function, to make sure that tables
19406 ;; and fixed-width regions are not wrapped. That function will pass
19407 ;; through to `fill-paragraph' when appropriate.
19408 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
19409 ;; Prevent auto-fill from inserting unwanted new items.
19410 (org-set-local 'fill-nobreak-predicate
19411 (if (memq 'org-fill-item-nobreak-p fill-nobreak-predicate)
19412 fill-nobreak-predicate
19413 (cons 'org-fill-item-nobreak-p fill-nobreak-predicate)))
19414 ;; Adaptive filling: To get full control, first make sure that
19415 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
19416 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
19417 (org-set-local 'org-adaptive-fill-regexp-backup
19418 adaptive-fill-regexp))
19419 (org-set-local 'adaptive-fill-regexp "\000")
19420 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
19421 (org-set-local 'adaptive-fill-function
19422 'org-adaptive-fill-function)
19423 (org-set-local
19424 'align-mode-rules-list
19425 '((org-in-buffer-settings
19426 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
19427 (modes . '(org-mode))))))
19429 (defun org-fill-item-nobreak-p ()
19430 "Non-nil when a line break at point would insert a new item."
19431 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
19433 (defun org-fill-paragraph (&optional justify)
19434 "Re-align a table, pass through to fill-paragraph if no table."
19435 (let ((table-p (org-at-table-p))
19436 (table.el-p (org-at-table.el-p))
19437 (itemp (org-in-item-p)))
19438 (cond ((and (equal (char-after (point-at-bol)) ?*)
19439 (save-excursion (goto-char (point-at-bol))
19440 (looking-at outline-regexp)))
19441 t) ; skip headlines
19442 (table.el-p t) ; skip table.el tables
19443 (table-p (org-table-align) t) ; align Org tables
19444 (itemp ; align text in items
19445 (let* ((struct (save-excursion (goto-char itemp)
19446 (org-list-struct)))
19447 (parents (org-list-parents-alist struct))
19448 (children (org-list-get-children itemp struct parents))
19449 beg end prev next prefix)
19450 ;; Determine in which part of item point is: before
19451 ;; first child, after last child, between two
19452 ;; sub-lists, or simply in item if there's no child.
19453 (cond
19454 ((not children)
19455 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19456 beg itemp
19457 end (org-list-get-item-end itemp struct)))
19458 ((< (point) (setq next (car children)))
19459 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19460 beg itemp
19461 end next))
19462 ((> (point) (setq prev (car (last children))))
19463 (setq beg (org-list-get-item-end prev struct)
19464 end (org-list-get-item-end itemp struct)
19465 prefix (save-excursion
19466 (goto-char beg)
19467 (skip-chars-forward " \t")
19468 (make-string (current-column) ?\ ))))
19469 (t (catch 'exit
19470 (while (setq next (pop children))
19471 (if (> (point) next)
19472 (setq prev next)
19473 (setq beg (org-list-get-item-end prev struct)
19474 end next
19475 prefix (save-excursion
19476 (goto-char beg)
19477 (skip-chars-forward " \t")
19478 (make-string (current-column) ?\ )))
19479 (throw 'exit nil))))))
19480 ;; Use `fill-paragraph' with buffer narrowed to item
19481 ;; without any child, and with our computed PREFIX.
19482 (flet ((fill-context-prefix (from to &optional flr) prefix))
19483 (save-restriction
19484 (narrow-to-region beg end)
19485 (save-excursion (fill-paragraph justify)))) t))
19486 ;; Special case where point is not in a list but is on
19487 ;; a paragraph adjacent to a list: make sure this paragraph
19488 ;; doesn't get merged with the end of the list by narrowing
19489 ;; buffer first.
19490 ((save-excursion (forward-paragraph -1)
19491 (setq itemp (org-in-item-p)))
19492 (let ((struct (save-excursion (goto-char itemp)
19493 (org-list-struct))))
19494 (save-restriction
19495 (narrow-to-region (org-list-get-bottom-point struct)
19496 (save-excursion (forward-paragraph 1)
19497 (point)))
19498 (fill-paragraph justify) t)))
19499 ;; Else simply call `fill-paragraph'.
19500 (t nil))))
19502 ;; For reference, this is the default value of adaptive-fill-regexp
19503 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
19505 (defun org-adaptive-fill-function ()
19506 "Return a fill prefix for org-mode files."
19507 (let (itemp)
19508 (save-excursion
19509 (cond
19510 ;; Comment line
19511 ((looking-at "#[ \t]+")
19512 (match-string-no-properties 0))
19513 ;; Plain list item
19514 ((org-at-item-p)
19515 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
19516 ;; Point is in a list after `backward-paragraph': original
19517 ;; point wasn't in the list, or filling would have been taken
19518 ;; care of by `org-auto-fill-function', but the list and the
19519 ;; real paragraph are not separated by a blank line. Thus, move
19520 ;; point after the list to go back to real paragraph and
19521 ;; determine fill-prefix.
19522 ((setq itemp (org-in-item-p))
19523 (goto-char itemp)
19524 (let* ((struct (org-list-struct))
19525 (bottom (org-list-get-bottom-point struct)))
19526 (goto-char bottom)
19527 (make-string (org-get-indentation) ?\ )))
19528 ;; Other text
19529 ((looking-at org-adaptive-fill-regexp-backup)
19530 (match-string-no-properties 0))))))
19532 (defun org-auto-fill-function ()
19533 "Auto-fill function."
19534 (let (itemp prefix)
19535 ;; When in a list, compute an appropriate fill-prefix and make
19536 ;; sure it will be used by `do-auto-fill'.
19537 (if (setq itemp (org-in-item-p))
19538 (progn
19539 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
19540 (flet ((fill-context-prefix (from to &optional flr) prefix))
19541 (do-auto-fill)))
19542 ;; Else just use `do-auto-fill'.
19543 (do-auto-fill))))
19545 ;;; Other stuff.
19547 (defun org-toggle-fixed-width-section (arg)
19548 "Toggle the fixed-width export.
19549 If there is no active region, the QUOTE keyword at the current headline is
19550 inserted or removed. When present, it causes the text between this headline
19551 and the next to be exported as fixed-width text, and unmodified.
19552 If there is an active region, this command adds or removes a colon as the
19553 first character of this line. If the first character of a line is a colon,
19554 this line is also exported in fixed-width font."
19555 (interactive "P")
19556 (let* ((cc 0)
19557 (regionp (org-region-active-p))
19558 (beg (if regionp (region-beginning) (point)))
19559 (end (if regionp (region-end)))
19560 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
19561 (case-fold-search nil)
19562 (re "[ \t]*\\(: \\)")
19563 off)
19564 (if regionp
19565 (save-excursion
19566 (goto-char beg)
19567 (setq cc (current-column))
19568 (beginning-of-line 1)
19569 (setq off (looking-at re))
19570 (while (> nlines 0)
19571 (setq nlines (1- nlines))
19572 (beginning-of-line 1)
19573 (cond
19574 (arg
19575 (org-move-to-column cc t)
19576 (insert ": \n")
19577 (forward-line -1))
19578 ((and off (looking-at re))
19579 (replace-match "" t t nil 1))
19580 ((not off) (org-move-to-column cc t) (insert ": ")))
19581 (forward-line 1)))
19582 (save-excursion
19583 (org-back-to-heading)
19584 (if (looking-at (concat outline-regexp
19585 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
19586 (replace-match "" t t nil 1)
19587 (if (looking-at outline-regexp)
19588 (progn
19589 (goto-char (match-end 0))
19590 (insert org-quote-string " "))))))))
19592 (defun org-reftex-citation ()
19593 "Use reftex-citation to insert a citation into the buffer.
19594 This looks for a line like
19596 #+BIBLIOGRAPHY: foo plain option:-d
19598 and derives from it that foo.bib is the bibliography file relevant
19599 for this document. It then installs the necessary environment for RefTeX
19600 to work in this buffer and calls `reftex-citation' to insert a citation
19601 into the buffer.
19603 Export of such citations to both LaTeX and HTML is handled by the contributed
19604 package org-exp-bibtex by Taru Karttunen."
19605 (interactive)
19606 (let ((reftex-docstruct-symbol 'rds)
19607 (reftex-cite-format "\\cite{%l}")
19608 rds bib)
19609 (save-excursion
19610 (save-restriction
19611 (widen)
19612 (let ((case-fold-search t)
19613 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
19614 (if (not (save-excursion
19615 (or (re-search-forward re nil t)
19616 (re-search-backward re nil t))))
19617 (error "No bibliography defined in file")
19618 (setq bib (concat (match-string 1) ".bib")
19619 rds (list (list 'bib bib)))))))
19620 (call-interactively 'reftex-citation)))
19622 ;;;; Functions extending outline functionality
19624 (defun org-beginning-of-line (&optional arg)
19625 "Go to the beginning of the current line. If that is invisible, continue
19626 to a visible line beginning. This makes the function of C-a more intuitive.
19627 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
19628 first attempt, and only move to after the tags when the cursor is already
19629 beyond the end of the headline."
19630 (interactive "P")
19631 (let ((pos (point))
19632 (special (if (consp org-special-ctrl-a/e)
19633 (car org-special-ctrl-a/e)
19634 org-special-ctrl-a/e))
19635 refpos)
19636 (if (org-bound-and-true-p line-move-visual)
19637 (beginning-of-visual-line 1)
19638 (beginning-of-line 1))
19639 (if (and arg (fboundp 'move-beginning-of-line))
19640 (call-interactively 'move-beginning-of-line)
19641 (if (bobp)
19643 (backward-char 1)
19644 (if (org-truely-invisible-p)
19645 (while (and (not (bobp)) (org-truely-invisible-p))
19646 (backward-char 1)
19647 (beginning-of-line 1))
19648 (forward-char 1))))
19649 (when special
19650 (cond
19651 ((and (looking-at org-complex-heading-regexp)
19652 (= (char-after (match-end 1)) ?\ ))
19653 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
19654 (point-at-eol)))
19655 (goto-char
19656 (if (eq special t)
19657 (cond ((> pos refpos) refpos)
19658 ((= pos (point)) refpos)
19659 (t (point)))
19660 (cond ((> pos (point)) (point))
19661 ((not (eq last-command this-command)) (point))
19662 (t refpos)))))
19663 ((org-at-item-p)
19664 (goto-char
19665 (if (eq special t)
19666 (cond ((> pos (match-end 0)) (match-end 0))
19667 ((= pos (point)) (match-end 0))
19668 (t (point)))
19669 (cond ((> pos (point)) (point))
19670 ((not (eq last-command this-command)) (point))
19671 (t (match-end 0))))))))
19672 (org-no-warnings
19673 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
19675 (defun org-end-of-line (&optional arg)
19676 "Go to the end of the line.
19677 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
19678 first attempt, and only move to after the tags when the cursor is already
19679 beyond the end of the headline."
19680 (interactive "P")
19681 (let ((special (if (consp org-special-ctrl-a/e)
19682 (cdr org-special-ctrl-a/e)
19683 org-special-ctrl-a/e)))
19684 (if (or (not special)
19685 (not (org-on-heading-p))
19686 arg)
19687 (call-interactively
19688 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
19689 ((fboundp 'move-end-of-line) 'move-end-of-line)
19690 (t 'end-of-line)))
19691 (let ((pos (point)))
19692 (beginning-of-line 1)
19693 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
19694 (if (eq special t)
19695 (if (or (< pos (match-beginning 1))
19696 (= pos (match-end 0)))
19697 (goto-char (match-beginning 1))
19698 (goto-char (match-end 0)))
19699 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
19700 (goto-char (match-end 0))
19701 (goto-char (match-beginning 1))))
19702 (call-interactively (if (fboundp 'move-end-of-line)
19703 'move-end-of-line
19704 'end-of-line)))))
19705 (org-no-warnings
19706 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
19708 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
19709 (define-key org-mode-map "\C-e" 'org-end-of-line)
19711 (defun org-backward-sentence (&optional arg)
19712 "Go to beginning of sentence, or beginning of table field.
19713 This will call `backward-sentence' or `org-table-beginning-of-field',
19714 depending on context."
19715 (interactive "P")
19716 (cond
19717 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
19718 (t (call-interactively 'backward-sentence))))
19720 (defun org-forward-sentence (&optional arg)
19721 "Go to end of sentence, or end of table field.
19722 This will call `forward-sentence' or `org-table-end-of-field',
19723 depending on context."
19724 (interactive "P")
19725 (cond
19726 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
19727 (t (call-interactively 'forward-sentence))))
19729 (define-key org-mode-map "\M-a" 'org-backward-sentence)
19730 (define-key org-mode-map "\M-e" 'org-forward-sentence)
19732 (defun org-kill-line (&optional arg)
19733 "Kill line, to tags or end of line."
19734 (interactive "P")
19735 (cond
19736 ((or (not org-special-ctrl-k)
19737 (bolp)
19738 (not (org-on-heading-p)))
19739 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
19740 org-ctrl-k-protect-subtree)
19741 (if (or (eq org-ctrl-k-protect-subtree 'error)
19742 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
19743 (error "C-k aborted - would kill hidden subtree")))
19744 (call-interactively 'kill-line))
19745 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
19746 (kill-region (point) (match-beginning 1))
19747 (org-set-tags nil t))
19748 (t (kill-region (point) (point-at-eol)))))
19750 (define-key org-mode-map "\C-k" 'org-kill-line)
19752 (defun org-yank (&optional arg)
19753 "Yank. If the kill is a subtree, treat it specially.
19754 This command will look at the current kill and check if is a single
19755 subtree, or a series of subtrees[1]. If it passes the test, and if the
19756 cursor is at the beginning of a line or after the stars of a currently
19757 empty headline, then the yank is handled specially. How exactly depends
19758 on the value of the following variables, both set by default.
19760 org-yank-folded-subtrees
19761 When set, the subtree(s) will be folded after insertion, but only
19762 if doing so would now swallow text after the yanked text.
19764 org-yank-adjusted-subtrees
19765 When set, the subtree will be promoted or demoted in order to
19766 fit into the local outline tree structure, which means that the level
19767 will be adjusted so that it becomes the smaller one of the two
19768 *visible* surrounding headings.
19770 Any prefix to this command will cause `yank' to be called directly with
19771 no special treatment. In particular, a simple \\[universal-argument] prefix \
19772 will just
19773 plainly yank the text as it is.
19775 \[1] The test checks if the first non-white line is a heading
19776 and if there are no other headings with fewer stars."
19777 (interactive "P")
19778 (org-yank-generic 'yank arg))
19780 (defun org-yank-generic (command arg)
19781 "Perform some yank-like command.
19783 This function implements the behavior described in the `org-yank'
19784 documentation. However, it has been generalized to work for any
19785 interactive command with similar behavior."
19787 ;; pretend to be command COMMAND
19788 (setq this-command command)
19790 (if arg
19791 (call-interactively command)
19793 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
19794 (and (org-kill-is-subtree-p)
19795 (or (bolp)
19796 (and (looking-at "[ \t]*$")
19797 (string-match
19798 "\\`\\*+\\'"
19799 (buffer-substring (point-at-bol) (point)))))))
19800 swallowp)
19801 (cond
19802 ((and subtreep org-yank-folded-subtrees)
19803 (let ((beg (point))
19804 end)
19805 (if (and subtreep org-yank-adjusted-subtrees)
19806 (org-paste-subtree nil nil 'for-yank)
19807 (call-interactively command))
19809 (setq end (point))
19810 (goto-char beg)
19811 (when (and (bolp) subtreep
19812 (not (setq swallowp
19813 (org-yank-folding-would-swallow-text beg end))))
19814 (or (looking-at outline-regexp)
19815 (re-search-forward (concat "^" outline-regexp) end t))
19816 (while (and (< (point) end) (looking-at outline-regexp))
19817 (hide-subtree)
19818 (org-cycle-show-empty-lines 'folded)
19819 (condition-case nil
19820 (outline-forward-same-level 1)
19821 (error (goto-char end)))))
19822 (when swallowp
19823 (message
19824 "Inserted text not folded because that would swallow text"))
19826 (goto-char end)
19827 (skip-chars-forward " \t\n\r")
19828 (beginning-of-line 1)
19829 (push-mark beg 'nomsg)))
19830 ((and subtreep org-yank-adjusted-subtrees)
19831 (let ((beg (point-at-bol)))
19832 (org-paste-subtree nil nil 'for-yank)
19833 (push-mark beg 'nomsg)))
19835 (call-interactively command))))))
19837 (defun org-yank-folding-would-swallow-text (beg end)
19838 "Would hide-subtree at BEG swallow any text after END?"
19839 (let (level)
19840 (save-excursion
19841 (goto-char beg)
19842 (when (or (looking-at outline-regexp)
19843 (re-search-forward (concat "^" outline-regexp) end t))
19844 (setq level (org-outline-level)))
19845 (goto-char end)
19846 (skip-chars-forward " \t\r\n\v\f")
19847 (if (or (eobp)
19848 (and (bolp) (looking-at org-outline-regexp)
19849 (<= (org-outline-level) level)))
19850 nil ; Nothing would be swallowed
19851 t)))) ; something would swallow
19853 (define-key org-mode-map "\C-y" 'org-yank)
19855 (defun org-truely-invisible-p ()
19856 "Check if point is at a character currently not visible.
19857 This version does not only check the character property, but also
19858 `visible-mode'."
19859 ;; Early versions of noutline don't have `outline-invisible-p'.
19860 (if (org-bound-and-true-p visible-mode)
19862 (outline-invisible-p)))
19864 (defun org-invisible-p2 ()
19865 "Check if point is at a character currently not visible."
19866 (save-excursion
19867 (if (and (eolp) (not (bobp))) (backward-char 1))
19868 ;; Early versions of noutline don't have `outline-invisible-p'.
19869 (outline-invisible-p)))
19871 (defun org-back-to-heading (&optional invisible-ok)
19872 "Call `outline-back-to-heading', but provide a better error message."
19873 (condition-case nil
19874 (outline-back-to-heading invisible-ok)
19875 (error (error "Before first headline at position %d in buffer %s"
19876 (point) (current-buffer)))))
19878 (defun org-beginning-of-defun ()
19879 "Go to the beginning of the subtree, i.e. back to the heading."
19880 (org-back-to-heading))
19881 (defun org-end-of-defun ()
19882 "Go to the end of the subtree."
19883 (org-end-of-subtree nil t))
19885 (defun org-before-first-heading-p ()
19886 "Before first heading?"
19887 (save-excursion
19888 (end-of-line)
19889 (null (re-search-backward "^\\*+ " nil t))))
19891 (defun org-on-heading-p (&optional ignored)
19892 (outline-on-heading-p t))
19893 (defun org-at-heading-p (&optional ignored)
19894 (outline-on-heading-p t))
19896 (defun org-point-at-end-of-empty-headline ()
19897 "If point is at the end of an empty headline, return t, else nil.
19898 If the heading only contains a TODO keyword, it is still still considered
19899 empty."
19900 (and (looking-at "[ \t]*$")
19901 (save-excursion
19902 (beginning-of-line 1)
19903 (let ((case-fold-search nil))
19904 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
19905 "\\)?[ \t]*$"))))))
19906 (defun org-at-heading-or-item-p ()
19907 (or (org-on-heading-p) (org-at-item-p)))
19909 (defun org-on-target-p ()
19910 (or (org-in-regexp org-radio-target-regexp)
19911 (org-in-regexp org-target-regexp)))
19913 (defun org-up-heading-all (arg)
19914 "Move to the heading line of which the present line is a subheading.
19915 This function considers both visible and invisible heading lines.
19916 With argument, move up ARG levels."
19917 (if (fboundp 'outline-up-heading-all)
19918 (outline-up-heading-all arg) ; emacs 21 version of outline.el
19919 (outline-up-heading arg t))) ; emacs 22 version of outline.el
19921 (defun org-up-heading-safe ()
19922 "Move to the heading line of which the present line is a subheading.
19923 This version will not throw an error. It will return the level of the
19924 headline found, or nil if no higher level is found.
19926 Also, this function will be a lot faster than `outline-up-heading',
19927 because it relies on stars being the outline starters. This can really
19928 make a significant difference in outlines with very many siblings."
19929 (let (start-level re)
19930 (org-back-to-heading t)
19931 (setq start-level (funcall outline-level))
19932 (if (equal start-level 1)
19934 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
19935 (if (re-search-backward re nil t)
19936 (funcall outline-level)))))
19938 (defun org-first-sibling-p ()
19939 "Is this heading the first child of its parents?"
19940 (interactive)
19941 (let ((re (concat "^" outline-regexp))
19942 level l)
19943 (unless (org-at-heading-p t)
19944 (error "Not at a heading"))
19945 (setq level (funcall outline-level))
19946 (save-excursion
19947 (if (not (re-search-backward re nil t))
19949 (setq l (funcall outline-level))
19950 (< l level)))))
19952 (defun org-goto-sibling (&optional previous)
19953 "Goto the next sibling, even if it is invisible.
19954 When PREVIOUS is set, go to the previous sibling instead. Returns t
19955 when a sibling was found. When none is found, return nil and don't
19956 move point."
19957 (let ((fun (if previous 're-search-backward 're-search-forward))
19958 (pos (point))
19959 (re (concat "^" outline-regexp))
19960 level l)
19961 (when (condition-case nil (org-back-to-heading t) (error nil))
19962 (setq level (funcall outline-level))
19963 (catch 'exit
19964 (or previous (forward-char 1))
19965 (while (funcall fun re nil t)
19966 (setq l (funcall outline-level))
19967 (when (< l level) (goto-char pos) (throw 'exit nil))
19968 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
19969 (goto-char pos)
19970 nil))))
19972 (defun org-show-siblings ()
19973 "Show all siblings of the current headline."
19974 (save-excursion
19975 (while (org-goto-sibling) (org-flag-heading nil)))
19976 (save-excursion
19977 (while (org-goto-sibling 'previous)
19978 (org-flag-heading nil))))
19980 (defun org-goto-first-child ()
19981 "Goto the first child, even if it is invisible.
19982 Return t when a child was found. Otherwise don't move point and
19983 return nil."
19984 (let (level (pos (point)) (re (concat "^" outline-regexp)))
19985 (when (condition-case nil (org-back-to-heading t) (error nil))
19986 (setq level (outline-level))
19987 (forward-char 1)
19988 (if (and (re-search-forward re nil t) (> (outline-level) level))
19989 (progn (goto-char (match-beginning 0)) t)
19990 (goto-char pos) nil))))
19992 (defun org-show-hidden-entry ()
19993 "Show an entry where even the heading is hidden."
19994 (save-excursion
19995 (org-show-entry)))
19997 (defun org-flag-heading (flag &optional entry)
19998 "Flag the current heading. FLAG non-nil means make invisible.
19999 When ENTRY is non-nil, show the entire entry."
20000 (save-excursion
20001 (org-back-to-heading t)
20002 ;; Check if we should show the entire entry
20003 (if entry
20004 (progn
20005 (org-show-entry)
20006 (save-excursion
20007 (and (outline-next-heading)
20008 (org-flag-heading nil))))
20009 (outline-flag-region (max (point-min) (1- (point)))
20010 (save-excursion (outline-end-of-heading) (point))
20011 flag))))
20013 (defun org-get-next-sibling ()
20014 "Move to next heading of the same level, and return point.
20015 If there is no such heading, return nil.
20016 This is like outline-next-sibling, but invisible headings are ok."
20017 (let ((level (funcall outline-level)))
20018 (outline-next-heading)
20019 (while (and (not (eobp)) (> (funcall outline-level) level))
20020 (outline-next-heading))
20021 (if (or (eobp) (< (funcall outline-level) level))
20023 (point))))
20025 (defun org-get-last-sibling ()
20026 "Move to previous heading of the same level, and return point.
20027 If there is no such heading, return nil."
20028 (let ((opoint (point))
20029 (level (funcall outline-level)))
20030 (outline-previous-heading)
20031 (when (and (/= (point) opoint) (outline-on-heading-p t))
20032 (while (and (> (funcall outline-level) level)
20033 (not (bobp)))
20034 (outline-previous-heading))
20035 (if (< (funcall outline-level) level)
20037 (point)))))
20039 (defun org-end-of-subtree (&optional invisible-OK to-heading)
20040 ;; This contains an exact copy of the original function, but it uses
20041 ;; `org-back-to-heading', to make it work also in invisible
20042 ;; trees. And is uses an invisible-OK argument.
20043 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
20044 ;; Furthermore, when used inside Org, finding the end of a large subtree
20045 ;; with many children and grandchildren etc, this can be much faster
20046 ;; than the outline version.
20047 (org-back-to-heading invisible-OK)
20048 (let ((first t)
20049 (level (funcall outline-level)))
20050 (if (and (org-mode-p) (< level 1000))
20051 ;; A true heading (not a plain list item), in Org-mode
20052 ;; This means we can easily find the end by looking
20053 ;; only for the right number of stars. Using a regexp to do
20054 ;; this is so much faster than using a Lisp loop.
20055 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
20056 (forward-char 1)
20057 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
20058 ;; something else, do it the slow way
20059 (while (and (not (eobp))
20060 (or first (> (funcall outline-level) level)))
20061 (setq first nil)
20062 (outline-next-heading)))
20063 (unless to-heading
20064 (if (memq (preceding-char) '(?\n ?\^M))
20065 (progn
20066 ;; Go to end of line before heading
20067 (forward-char -1)
20068 (if (memq (preceding-char) '(?\n ?\^M))
20069 ;; leave blank line before heading
20070 (forward-char -1))))))
20071 (point))
20073 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
20074 "Use Org version in org-mode, for dramatic speed-up."
20075 (if (org-mode-p)
20076 (progn
20077 (org-end-of-subtree nil t)
20078 (unless (eobp) (backward-char 1)))
20079 ad-do-it))
20081 (defun org-end-of-meta-data-and-drawers ()
20082 "Jump to the first text after meta data and drawers in the current entry.
20083 This will move over empty lines, lines with planning time stamps,
20084 clocking lines, and drawers."
20085 (org-back-to-heading t)
20086 (let ((end (save-excursion (outline-next-heading) (point)))
20087 (re (concat "\\(" org-drawer-regexp "\\)"
20088 "\\|" "[ \t]*" org-keyword-time-regexp)))
20089 (forward-line 1)
20090 (while (re-search-forward re end t)
20091 (if (not (match-end 1))
20092 ;; empty or planning line
20093 (forward-line 1)
20094 ;; a drawer, find the end
20095 (re-search-forward "^[ \t]*:END:" end 'move)
20096 (forward-line 1)))
20097 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
20098 (point)))
20100 (defun org-forward-same-level (arg &optional invisible-ok)
20101 "Move forward to the arg'th subheading at same level as this one.
20102 Stop at the first and last subheadings of a superior heading.
20103 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
20104 it wil also look at invisible ones."
20105 (interactive "p")
20106 (org-back-to-heading invisible-ok)
20107 (org-on-heading-p)
20108 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20109 (re (format "^\\*\\{1,%d\\} " level))
20111 (forward-char 1)
20112 (while (> arg 0)
20113 (while (and (re-search-forward re nil 'move)
20114 (setq l (- (match-end 0) (match-beginning 0) 1))
20115 (= l level)
20116 (not invisible-ok)
20117 (progn (backward-char 1) (outline-invisible-p)))
20118 (if (< l level) (setq arg 1)))
20119 (setq arg (1- arg)))
20120 (beginning-of-line 1)))
20122 (defun org-backward-same-level (arg &optional invisible-ok)
20123 "Move backward to the arg'th subheading at same level as this one.
20124 Stop at the first and last subheadings of a superior heading."
20125 (interactive "p")
20126 (org-back-to-heading)
20127 (org-on-heading-p)
20128 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20129 (re (format "^\\*\\{1,%d\\} " level))
20131 (while (> arg 0)
20132 (while (and (re-search-backward re nil 'move)
20133 (setq l (- (match-end 0) (match-beginning 0) 1))
20134 (= l level)
20135 (not invisible-ok)
20136 (outline-invisible-p))
20137 (if (< l level) (setq arg 1)))
20138 (setq arg (1- arg)))))
20140 (defun org-show-subtree ()
20141 "Show everything after this heading at deeper levels."
20142 (outline-flag-region
20143 (point)
20144 (save-excursion
20145 (org-end-of-subtree t t))
20146 nil))
20148 (defun org-show-entry ()
20149 "Show the body directly following this heading.
20150 Show the heading too, if it is currently invisible."
20151 (interactive)
20152 (save-excursion
20153 (condition-case nil
20154 (progn
20155 (org-back-to-heading t)
20156 (outline-flag-region
20157 (max (point-min) (1- (point)))
20158 (save-excursion
20159 (if (re-search-forward
20160 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
20161 (match-beginning 1)
20162 (point-max)))
20163 nil)
20164 (org-cycle-hide-drawers 'children))
20165 (error nil))))
20167 (defun org-make-options-regexp (kwds &optional extra)
20168 "Make a regular expression for keyword lines."
20169 (concat
20171 "#?[ \t]*\\+\\("
20172 (mapconcat 'regexp-quote kwds "\\|")
20173 (if extra (concat "\\|" extra))
20174 "\\):[ \t]*"
20175 "\\(.*\\)"))
20177 ;; Make isearch reveal the necessary context
20178 (defun org-isearch-end ()
20179 "Reveal context after isearch exits."
20180 (when isearch-success ; only if search was successful
20181 (if (featurep 'xemacs)
20182 ;; Under XEmacs, the hook is run in the correct place,
20183 ;; we directly show the context.
20184 (org-show-context 'isearch)
20185 ;; In Emacs the hook runs *before* restoring the overlays.
20186 ;; So we have to use a one-time post-command-hook to do this.
20187 ;; (Emacs 22 has a special variable, see function `org-mode')
20188 (unless (and (boundp 'isearch-mode-end-hook-quit)
20189 isearch-mode-end-hook-quit)
20190 ;; Only when the isearch was not quitted.
20191 (org-add-hook 'post-command-hook 'org-isearch-post-command
20192 'append 'local)))))
20194 (defun org-isearch-post-command ()
20195 "Remove self from hook, and show context."
20196 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
20197 (org-show-context 'isearch))
20200 ;;;; Integration with and fixes for other packages
20202 ;;; Imenu support
20204 (defvar org-imenu-markers nil
20205 "All markers currently used by Imenu.")
20206 (make-variable-buffer-local 'org-imenu-markers)
20208 (defun org-imenu-new-marker (&optional pos)
20209 "Return a new marker for use by Imenu, and remember the marker."
20210 (let ((m (make-marker)))
20211 (move-marker m (or pos (point)))
20212 (push m org-imenu-markers)
20215 (defun org-imenu-get-tree ()
20216 "Produce the index for Imenu."
20217 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
20218 (setq org-imenu-markers nil)
20219 (let* ((n org-imenu-depth)
20220 (re (concat "^" outline-regexp))
20221 (subs (make-vector (1+ n) nil))
20222 (last-level 0)
20223 m level head)
20224 (save-excursion
20225 (save-restriction
20226 (widen)
20227 (goto-char (point-max))
20228 (while (re-search-backward re nil t)
20229 (setq level (org-reduced-level (funcall outline-level)))
20230 (when (<= level n)
20231 (looking-at org-complex-heading-regexp)
20232 (setq head (org-link-display-format
20233 (org-match-string-no-properties 4))
20234 m (org-imenu-new-marker))
20235 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
20236 (if (>= level last-level)
20237 (push (cons head m) (aref subs level))
20238 (push (cons head (aref subs (1+ level))) (aref subs level))
20239 (loop for i from (1+ level) to n do (aset subs i nil)))
20240 (setq last-level level)))))
20241 (aref subs 1)))
20243 (eval-after-load "imenu"
20244 '(progn
20245 (add-hook 'imenu-after-jump-hook
20246 (lambda ()
20247 (if (org-mode-p)
20248 (org-show-context 'org-goto))))))
20250 (defun org-link-display-format (link)
20251 "Replace a link with either the description, or the link target
20252 if no description is present"
20253 (save-match-data
20254 (if (string-match org-bracket-link-analytic-regexp link)
20255 (replace-match (if (match-end 5)
20256 (match-string 5 link)
20257 (concat (match-string 1 link)
20258 (match-string 3 link)))
20259 nil t link)
20260 link)))
20262 ;; Speedbar support
20264 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
20265 "Overlay marking the agenda restriction line in speedbar.")
20266 (overlay-put org-speedbar-restriction-lock-overlay
20267 'face 'org-agenda-restriction-lock)
20268 (overlay-put org-speedbar-restriction-lock-overlay
20269 'help-echo "Agendas are currently limited to this item.")
20270 (org-detach-overlay org-speedbar-restriction-lock-overlay)
20272 (defun org-speedbar-set-agenda-restriction ()
20273 "Restrict future agenda commands to the location at point in speedbar.
20274 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
20275 (interactive)
20276 (require 'org-agenda)
20277 (let (p m tp np dir txt)
20278 (cond
20279 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20280 'org-imenu t))
20281 (setq m (get-text-property p 'org-imenu-marker))
20282 (with-current-buffer (marker-buffer m)
20283 (goto-char m)
20284 (org-agenda-set-restriction-lock 'subtree)))
20285 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20286 'speedbar-function 'speedbar-find-file))
20287 (setq tp (previous-single-property-change
20288 (1+ p) 'speedbar-function)
20289 np (next-single-property-change
20290 tp 'speedbar-function)
20291 dir (speedbar-line-directory)
20292 txt (buffer-substring-no-properties (or tp (point-min))
20293 (or np (point-max))))
20294 (with-current-buffer (find-file-noselect
20295 (let ((default-directory dir))
20296 (expand-file-name txt)))
20297 (unless (org-mode-p)
20298 (error "Cannot restrict to non-Org-mode file"))
20299 (org-agenda-set-restriction-lock 'file)))
20300 (t (error "Don't know how to restrict Org-mode's agenda")))
20301 (move-overlay org-speedbar-restriction-lock-overlay
20302 (point-at-bol) (point-at-eol))
20303 (setq current-prefix-arg nil)
20304 (org-agenda-maybe-redo)))
20306 (eval-after-load "speedbar"
20307 '(progn
20308 (speedbar-add-supported-extension ".org")
20309 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
20310 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
20311 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
20312 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
20313 (add-hook 'speedbar-visiting-tag-hook
20314 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
20316 ;;; Fixes and Hacks for problems with other packages
20318 ;; Make flyspell not check words in links, to not mess up our keymap
20319 (defun org-mode-flyspell-verify ()
20320 "Don't let flyspell put overlays at active buttons, or on
20321 {todo,all-time,additional-option-like}-keywords."
20322 (let ((pos (max (1- (point)) (point-min)))
20323 (word (thing-at-point 'word)))
20324 (and (not (get-text-property pos 'keymap))
20325 (not (get-text-property pos 'org-no-flyspell))
20326 (not (member word org-todo-keywords-1))
20327 (not (member word org-all-time-keywords))
20328 (not (member word org-additional-option-like-keywords)))))
20330 (defun org-remove-flyspell-overlays-in (beg end)
20331 "Remove flyspell overlays in region."
20332 (and (org-bound-and-true-p flyspell-mode)
20333 (fboundp 'flyspell-delete-region-overlays)
20334 (flyspell-delete-region-overlays beg end))
20335 (add-text-properties beg end '(org-no-flyspell t)))
20337 ;; Make `bookmark-jump' shows the jump location if it was hidden.
20338 (eval-after-load "bookmark"
20339 '(if (boundp 'bookmark-after-jump-hook)
20340 ;; We can use the hook
20341 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
20342 ;; Hook not available, use advice
20343 (defadvice bookmark-jump (after org-make-visible activate)
20344 "Make the position visible."
20345 (org-bookmark-jump-unhide))))
20347 ;; Make sure saveplace shows the location if it was hidden
20348 (eval-after-load "saveplace"
20349 '(defadvice save-place-find-file-hook (after org-make-visible activate)
20350 "Make the position visible."
20351 (org-bookmark-jump-unhide)))
20353 ;; Make sure ecb shows the location if it was hidden
20354 (eval-after-load "ecb"
20355 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
20356 "Make hierarchy visible when jumping into location from ECB tree buffer."
20357 (if (org-mode-p)
20358 (org-show-context))))
20360 (defun org-bookmark-jump-unhide ()
20361 "Unhide the current position, to show the bookmark location."
20362 (and (org-mode-p)
20363 (or (outline-invisible-p)
20364 (save-excursion (goto-char (max (point-min) (1- (point))))
20365 (outline-invisible-p)))
20366 (org-show-context 'bookmark-jump)))
20368 ;; Make session.el ignore our circular variable
20369 (eval-after-load "session"
20370 '(add-to-list 'session-globals-exclude 'org-mark-ring))
20372 ;;;; Experimental code
20374 (defun org-closed-in-range ()
20375 "Sparse tree of items closed in a certain time range.
20376 Still experimental, may disappear in the future."
20377 (interactive)
20378 ;; Get the time interval from the user.
20379 (let* ((time1 (org-float-time
20380 (org-read-date nil 'to-time nil "Starting date: ")))
20381 (time2 (org-float-time
20382 (org-read-date nil 'to-time nil "End date:")))
20383 ;; callback function
20384 (callback (lambda ()
20385 (let ((time
20386 (org-float-time
20387 (apply 'encode-time
20388 (org-parse-time-string
20389 (match-string 1))))))
20390 ;; check if time in interval
20391 (and (>= time time1) (<= time time2))))))
20392 ;; make tree, check each match with the callback
20393 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
20395 ;;;; Finish up
20397 (provide 'org)
20399 (run-hooks 'org-load-hook)
20401 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
20403 ;;; org.el ends here