* org.el (org-refile): minor rewriting.
[org-mode.git] / lisp / org.el
blob8c105345afbbd993efd4d4367a44a63e51cb26e1
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', in
1094 which case Org will look at the surrounding headings/items and try to
1095 make an 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 (min (point-max) (1+ end))
5211 '(face org-meta-line)) ; 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 (min (point-max) (1+ end1))
5226 '(face org-block))) ; 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 or entries at point to another heading.
10335 The list of target headings is compiled using the information in
10336 `org-refile-targets', which see.
10338 At the target location, the entry is filed as a subitem of the target
10339 heading. Depending on `org-reverse-note-order', the new subitem will
10340 either be the first or the last subitem.
10342 If there is an active region, all entries in that region will be moved.
10343 However, the region must fulfill the requirement that the first heading
10344 is the first one sets the top-level of the moved text - at most siblings
10345 below it are allowed.
10347 With prefix arg GOTO, the command will only visit the target location
10348 and not actually move anything.
10350 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10351 go to the location where the last refiling operation has put the subtree.
10352 With a prefix argument of `2', refile to the running clock.
10354 RFLOC can be a refile location obtained in a different way.
10356 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10358 If you are using target caching (see `org-refile-use-cache'),
10359 You have to clear the target cache in order to find new targets.
10360 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10361 prefix argument (`C-u C-u C-u C-c C-w')."
10363 (interactive "P")
10364 (if (member goto '(0 (64)))
10365 (org-refile-cache-clear)
10366 (let* ((cbuf (current-buffer))
10367 (regionp (org-region-active-p))
10368 (region-start (and regionp (region-beginning)))
10369 (region-end (and regionp (region-end)))
10370 (region-length (and regionp (- region-end region-start)))
10371 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10372 pos it nbuf file re level reversed)
10373 (setq last-command nil)
10374 (when regionp
10375 (goto-char region-start)
10376 (or (bolp) (goto-char (point-at-bol)))
10377 (setq region-start (point))
10378 (unless (org-kill-is-subtree-p
10379 (buffer-substring region-start region-end))
10380 (error "The region is not a (sequence of) subtree(s)")))
10381 (if (equal goto '(16))
10382 (org-refile-goto-last-stored)
10383 (when (or
10384 (and (equal goto 2)
10385 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10386 (prog1
10387 (setq it (list (or org-clock-heading "running clock")
10388 (buffer-file-name
10389 (marker-buffer org-clock-hd-marker))
10391 (marker-position org-clock-hd-marker)))
10392 (setq goto nil)))
10393 (setq it (or rfloc
10394 (save-excursion
10395 (org-refile-get-location
10396 (if goto "Goto" "Refile to") default-buffer
10397 org-refile-allow-creating-parent-nodes)))))
10398 (setq file (nth 1 it)
10399 re (nth 2 it)
10400 pos (nth 3 it))
10401 (if (and (not goto)
10403 (equal (buffer-file-name) file)
10404 (if regionp
10405 (and (>= pos region-start)
10406 (<= pos region-end))
10407 (and (>= pos (point))
10408 (< pos (save-excursion
10409 (org-end-of-subtree t t))))))
10410 (error "Cannot refile to position inside the tree or region"))
10412 (setq nbuf (or (find-buffer-visiting file)
10413 (find-file-noselect file)))
10414 (if goto
10415 (progn
10416 (switch-to-buffer nbuf)
10417 (goto-char pos)
10418 (org-show-context 'org-goto))
10419 (if regionp
10420 (progn
10421 (org-kill-new (buffer-substring region-start region-end))
10422 (org-save-markers-in-region region-start region-end))
10423 (org-copy-subtree 1 nil t))
10424 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10425 (find-file-noselect file)))
10426 (setq reversed (org-notes-order-reversed-p))
10427 (save-excursion
10428 (save-restriction
10429 (widen)
10430 (if pos
10431 (progn
10432 (goto-char pos)
10433 (looking-at outline-regexp)
10434 (setq level (org-get-valid-level (funcall outline-level) 1))
10435 (goto-char
10436 (if reversed
10437 (or (outline-next-heading) (point-max))
10438 (or (save-excursion (org-get-next-sibling))
10439 (org-end-of-subtree t t)
10440 (point-max)))))
10441 (setq level 1)
10442 (if (not reversed)
10443 (goto-char (point-max))
10444 (goto-char (point-min))
10445 (or (outline-next-heading) (goto-char (point-max)))))
10446 (if (not (bolp)) (newline))
10447 (org-paste-subtree level)
10448 (when org-log-refile
10449 (org-add-log-setup 'refile nil nil 'findpos
10450 org-log-refile)
10451 (unless (eq org-log-refile 'note)
10452 (save-excursion (org-add-log-note))))
10453 (and org-auto-align-tags (org-set-tags nil t))
10454 (bookmark-set "org-refile-last-stored")
10455 ;; If we are refiling for capture, make sure that the
10456 ;; last-capture pointers point here
10457 (when (org-bound-and-true-p org-refile-for-capture)
10458 (bookmark-set "org-capture-last-stored-marker")
10459 (move-marker org-capture-last-stored-marker (point)))
10460 (if (fboundp 'deactivate-mark) (deactivate-mark))
10461 (run-hooks 'org-after-refile-insert-hook))))
10462 (if regionp
10463 (delete-region (point) (+ (point) region-length))
10464 (org-cut-subtree))
10465 (when (featurep 'org-inlinetask)
10466 (org-inlinetask-remove-END-maybe))
10467 (setq org-markers-to-move nil)
10468 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10470 (defun org-refile-goto-last-stored ()
10471 "Go to the location where the last refile was stored."
10472 (interactive)
10473 (bookmark-jump "org-refile-last-stored")
10474 (message "This is the location of the last refile"))
10476 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
10477 "Prompt the user for a refile location, using PROMPT.
10478 PROMPT should not be suffixed with a colon and a space, because
10479 this function appends the default value from
10480 `org-refile-history' automatically, if that is not empty."
10481 (let ((org-refile-targets org-refile-targets)
10482 (org-refile-use-outline-path org-refile-use-outline-path))
10483 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
10484 (unless org-refile-target-table
10485 (error "No refile targets"))
10486 (let* ((prompt (concat prompt
10487 (and (car org-refile-history)
10488 (concat " (default " (car org-refile-history) ")"))
10489 ": "))
10490 (cbuf (current-buffer))
10491 (partial-completion-mode nil)
10492 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10493 (cfunc (if (and org-refile-use-outline-path
10494 org-outline-path-complete-in-steps)
10495 'org-olpath-completing-read
10496 'org-icompleting-read))
10497 (extra (if org-refile-use-outline-path "/" ""))
10498 (filename (and cfn (expand-file-name cfn)))
10499 (tbl (mapcar
10500 (lambda (x)
10501 (if (and (not (member org-refile-use-outline-path
10502 '(file full-file-path)))
10503 (not (equal filename (nth 1 x))))
10504 (cons (concat (car x) extra " ("
10505 (file-name-nondirectory (nth 1 x)) ")")
10506 (cdr x))
10507 (cons (concat (car x) extra) (cdr x))))
10508 org-refile-target-table))
10509 (completion-ignore-case t)
10510 pa answ parent-target child parent old-hist)
10511 (setq old-hist org-refile-history)
10512 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10513 nil 'org-refile-history (car org-refile-history)))
10514 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10515 (org-refile-check-position pa)
10516 (if pa
10517 (progn
10518 (when (or (not org-refile-history)
10519 (not (eq old-hist org-refile-history))
10520 (not (equal (car pa) (car org-refile-history))))
10521 (setq org-refile-history
10522 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10523 org-refile-history
10524 (cdr org-refile-history))))
10525 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10526 (pop org-refile-history)))
10528 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10529 (progn
10530 (setq parent (match-string 1 answ)
10531 child (match-string 2 answ))
10532 (setq parent-target (or (assoc parent tbl)
10533 (assoc (concat parent "/") tbl)))
10534 (when (and parent-target
10535 (or (eq new-nodes t)
10536 (and (eq new-nodes 'confirm)
10537 (y-or-n-p (format "Create new node \"%s\"? "
10538 child)))))
10539 (org-refile-new-child parent-target child)))
10540 (error "Invalid target location")))))
10542 (defun org-refile-check-position (refile-pointer)
10543 "Check if the refile pointer matches the readline to which it points."
10544 (let* ((file (nth 1 refile-pointer))
10545 (re (nth 2 refile-pointer))
10546 (pos (nth 3 refile-pointer))
10547 buffer)
10548 (when (org-string-nw-p re)
10549 (setq buffer (if (markerp pos)
10550 (marker-buffer pos)
10551 (or (find-buffer-visiting file)
10552 (find-file-noselect file))))
10553 (with-current-buffer buffer
10554 (save-excursion
10555 (save-restriction
10556 (widen)
10557 (goto-char pos)
10558 (beginning-of-line 1)
10559 (unless (org-looking-at-p re)
10560 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10562 (defun org-refile-new-child (parent-target child)
10563 "Use refile target PARENT-TARGET to add new CHILD below it."
10564 (unless parent-target
10565 (error "Cannot find parent for new node"))
10566 (let ((file (nth 1 parent-target))
10567 (pos (nth 3 parent-target))
10568 level)
10569 (with-current-buffer (or (find-buffer-visiting file)
10570 (find-file-noselect file))
10571 (save-excursion
10572 (save-restriction
10573 (widen)
10574 (if pos
10575 (goto-char pos)
10576 (goto-char (point-max))
10577 (if (not (bolp)) (newline)))
10578 (when (looking-at outline-regexp)
10579 (setq level (funcall outline-level))
10580 (org-end-of-subtree t t))
10581 (org-back-over-empty-lines)
10582 (insert "\n" (make-string
10583 (if pos (org-get-valid-level level 1) 1) ?*)
10584 " " child "\n")
10585 (beginning-of-line 0)
10586 (list (concat (car parent-target) "/" child) file "" (point)))))))
10588 (defun org-olpath-completing-read (prompt collection &rest args)
10589 "Read an outline path like a file name."
10590 (let ((thetable collection)
10591 (org-completion-use-ido nil) ; does not work with ido.
10592 (org-completion-use-iswitchb nil)) ; or iswitchb
10593 (apply
10594 'org-icompleting-read prompt
10595 (lambda (string predicate &optional flag)
10596 (let (rtn r f (l (length string)))
10597 (cond
10598 ((eq flag nil)
10599 ;; try completion
10600 (try-completion string thetable))
10601 ((eq flag t)
10602 ;; all-completions
10603 (setq rtn (all-completions string thetable predicate))
10604 (mapcar
10605 (lambda (x)
10606 (setq r (substring x l))
10607 (if (string-match " ([^)]*)$" x)
10608 (setq f (match-string 0 x))
10609 (setq f ""))
10610 (if (string-match "/" r)
10611 (concat string (substring r 0 (match-end 0)) f)
10613 rtn))
10614 ((eq flag 'lambda)
10615 ;; exact match?
10616 (assoc string thetable)))
10618 args)))
10620 ;;;; Dynamic blocks
10622 (defun org-find-dblock (name)
10623 "Find the first dynamic block with name NAME in the buffer.
10624 If not found, stay at current position and return nil."
10625 (let (pos)
10626 (save-excursion
10627 (goto-char (point-min))
10628 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10629 nil t)
10630 (match-beginning 0))))
10631 (if pos (goto-char pos))
10632 pos))
10634 (defconst org-dblock-start-re
10635 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10636 "Matches the start line of a dynamic block, with parameters.")
10638 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10639 "Matches the end of a dynamic block.")
10641 (defun org-create-dblock (plist)
10642 "Create a dynamic block section, with parameters taken from PLIST.
10643 PLIST must contain a :name entry which is used as name of the block."
10644 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10645 (end-of-line 1)
10646 (newline))
10647 (let ((col (current-column))
10648 (name (plist-get plist :name)))
10649 (insert "#+BEGIN: " name)
10650 (while plist
10651 (if (eq (car plist) :name)
10652 (setq plist (cddr plist))
10653 (insert " " (prin1-to-string (pop plist)))))
10654 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10655 (beginning-of-line -2)))
10657 (defun org-prepare-dblock ()
10658 "Prepare dynamic block for refresh.
10659 This empties the block, puts the cursor at the insert position and returns
10660 the property list including an extra property :name with the block name."
10661 (unless (looking-at org-dblock-start-re)
10662 (error "Not at a dynamic block"))
10663 (let* ((begdel (1+ (match-end 0)))
10664 (name (org-no-properties (match-string 1)))
10665 (params (append (list :name name)
10666 (read (concat "(" (match-string 3) ")")))))
10667 (save-excursion
10668 (beginning-of-line 1)
10669 (skip-chars-forward " \t")
10670 (setq params (plist-put params :indentation-column (current-column))))
10671 (unless (re-search-forward org-dblock-end-re nil t)
10672 (error "Dynamic block not terminated"))
10673 (setq params
10674 (append params
10675 (list :content (buffer-substring
10676 begdel (match-beginning 0)))))
10677 (delete-region begdel (match-beginning 0))
10678 (goto-char begdel)
10679 (open-line 1)
10680 params))
10682 (defun org-map-dblocks (&optional command)
10683 "Apply COMMAND to all dynamic blocks in the current buffer.
10684 If COMMAND is not given, use `org-update-dblock'."
10685 (let ((cmd (or command 'org-update-dblock)))
10686 (save-excursion
10687 (goto-char (point-min))
10688 (while (re-search-forward org-dblock-start-re nil t)
10689 (goto-char (match-beginning 0))
10690 (save-excursion
10691 (condition-case nil
10692 (funcall cmd)
10693 (error (message "Error during update of dynamic block"))))
10694 (unless (re-search-forward org-dblock-end-re nil t)
10695 (error "Dynamic block not terminated"))))))
10697 (defun org-dblock-update (&optional arg)
10698 "User command for updating dynamic blocks.
10699 Update the dynamic block at point. With prefix ARG, update all dynamic
10700 blocks in the buffer."
10701 (interactive "P")
10702 (if arg
10703 (org-update-all-dblocks)
10704 (or (looking-at org-dblock-start-re)
10705 (org-beginning-of-dblock))
10706 (org-update-dblock)))
10708 (defun org-update-dblock ()
10709 "Update the dynamic block at point.
10710 This means to empty the block, parse for parameters and then call
10711 the correct writing function."
10712 (interactive)
10713 (save-window-excursion
10714 (let* ((pos (point))
10715 (line (org-current-line))
10716 (params (org-prepare-dblock))
10717 (name (plist-get params :name))
10718 (indent (plist-get params :indentation-column))
10719 (cmd (intern (concat "org-dblock-write:" name))))
10720 (message "Updating dynamic block `%s' at line %d..." name line)
10721 (funcall cmd params)
10722 (message "Updating dynamic block `%s' at line %d...done" name line)
10723 (goto-char pos)
10724 (when (and indent (> indent 0))
10725 (setq indent (make-string indent ?\ ))
10726 (save-excursion
10727 (org-beginning-of-dblock)
10728 (forward-line 1)
10729 (while (not (looking-at org-dblock-end-re))
10730 (insert indent)
10731 (beginning-of-line 2))
10732 (when (looking-at org-dblock-end-re)
10733 (and (looking-at "[ \t]+")
10734 (replace-match ""))
10735 (insert indent)))))))
10737 (defun org-beginning-of-dblock ()
10738 "Find the beginning of the dynamic block at point.
10739 Error if there is no such block at point."
10740 (let ((pos (point))
10741 beg)
10742 (end-of-line 1)
10743 (if (and (re-search-backward org-dblock-start-re nil t)
10744 (setq beg (match-beginning 0))
10745 (re-search-forward org-dblock-end-re nil t)
10746 (> (match-end 0) pos))
10747 (goto-char beg)
10748 (goto-char pos)
10749 (error "Not in a dynamic block"))))
10751 (defun org-update-all-dblocks ()
10752 "Update all dynamic blocks in the buffer.
10753 This function can be used in a hook."
10754 (interactive)
10755 (when (org-mode-p)
10756 (org-map-dblocks 'org-update-dblock)))
10759 ;;;; Completion
10761 (defconst org-additional-option-like-keywords
10762 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
10763 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
10764 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
10765 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
10766 "BEGIN:" "END:"
10767 "ORGTBL" "TBLFM:" "TBLNAME:"
10768 "BEGIN_EXAMPLE" "END_EXAMPLE"
10769 "BEGIN_QUOTE" "END_QUOTE"
10770 "BEGIN_VERSE" "END_VERSE"
10771 "BEGIN_CENTER" "END_CENTER"
10772 "BEGIN_SRC" "END_SRC"
10773 "BEGIN_RESULT" "END_RESULT"
10774 "SOURCE:" "SRCNAME:" "FUNCTION:"
10775 "RESULTS:" "DATA:"
10776 "HEADER:" "HEADERS:"
10777 "BABEL:"
10778 "CATEGORY:" "COLUMNS:" "PROPERTY:"
10779 "CAPTION:" "LABEL:"
10780 "SETUPFILE:"
10781 "INCLUDE:"
10782 "BIND:"
10783 "MACRO:"))
10785 (defcustom org-structure-template-alist
10787 ("s" "#+begin_src ?\n\n#+end_src"
10788 "<src lang=\"?\">\n\n</src>")
10789 ("e" "#+begin_example\n?\n#+end_example"
10790 "<example>\n?\n</example>")
10791 ("q" "#+begin_quote\n?\n#+end_quote"
10792 "<quote>\n?\n</quote>")
10793 ("v" "#+begin_verse\n?\n#+end_verse"
10794 "<verse>\n?\n/verse>")
10795 ("c" "#+begin_center\n?\n#+end_center"
10796 "<center>\n?\n/center>")
10797 ("l" "#+begin_latex\n?\n#+end_latex"
10798 "<literal style=\"latex\">\n?\n</literal>")
10799 ("L" "#+latex: "
10800 "<literal style=\"latex\">?</literal>")
10801 ("h" "#+begin_html\n?\n#+end_html"
10802 "<literal style=\"html\">\n?\n</literal>")
10803 ("H" "#+html: "
10804 "<literal style=\"html\">?</literal>")
10805 ("a" "#+begin_ascii\n?\n#+end_ascii")
10806 ("A" "#+ascii: ")
10807 ("i" "#+index: ?"
10808 "#+index: ?")
10809 ("I" "#+include %file ?"
10810 "<include file=%file markup=\"?\">")
10812 "Structure completion elements.
10813 This is a list of abbreviation keys and values. The value gets inserted
10814 if you type `<' followed by the key and then press the completion key,
10815 usually `M-TAB'. %file will be replaced by a file name after prompting
10816 for the file using completion. The cursor will be placed at the position
10817 of the `?` in the template.
10818 There are two templates for each key, the first uses the original Org syntax,
10819 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
10820 the default when the /org-mtags.el/ module has been loaded. See also the
10821 variable `org-mtags-prefer-muse-templates'.
10822 This is an experimental feature, it is undecided if it is going to stay in."
10823 :group 'org-completion
10824 :type '(repeat
10825 (string :tag "Key")
10826 (string :tag "Template")
10827 (string :tag "Muse Template")))
10829 (defun org-try-structure-completion ()
10830 "Try to complete a structure template before point.
10831 This looks for strings like \"<e\" on an otherwise empty line and
10832 expands them."
10833 (let ((l (buffer-substring (point-at-bol) (point)))
10835 (when (and (looking-at "[ \t]*$")
10836 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
10837 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
10838 (org-complete-expand-structure-template (+ -1 (point-at-bol)
10839 (match-beginning 1)) a)
10840 t)))
10842 (defun org-complete-expand-structure-template (start cell)
10843 "Expand a structure template."
10844 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
10845 (rpl (nth (if musep 2 1) cell))
10846 (ind ""))
10847 (delete-region start (point))
10848 (when (string-match "\\`#\\+" rpl)
10849 (cond
10850 ((bolp))
10851 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
10852 (setq ind (buffer-substring (point-at-bol) (point))))
10853 (t (newline))))
10854 (setq start (point))
10855 (if (string-match "%file" rpl)
10856 (setq rpl (replace-match
10857 (concat
10858 "\""
10859 (save-match-data
10860 (abbreviate-file-name (read-file-name "Include file: ")))
10861 "\"")
10862 t t rpl)))
10863 (setq rpl (mapconcat 'identity (split-string rpl "\n")
10864 (concat "\n" ind)))
10865 (insert rpl)
10866 (if (re-search-backward "\\?" start t) (delete-char 1))))
10868 ;;;; TODO, DEADLINE, Comments
10870 (defun org-toggle-comment ()
10871 "Change the COMMENT state of an entry."
10872 (interactive)
10873 (save-excursion
10874 (org-back-to-heading)
10875 (let (case-fold-search)
10876 (if (looking-at (concat outline-regexp
10877 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10878 (replace-match "" t t nil 1)
10879 (if (looking-at outline-regexp)
10880 (progn
10881 (goto-char (match-end 0))
10882 (insert org-comment-string " ")))))))
10884 (defvar org-last-todo-state-is-todo nil
10885 "This is non-nil when the last TODO state change led to a TODO state.
10886 If the last change removed the TODO tag or switched to DONE, then
10887 this is nil.")
10889 (defvar org-setting-tags nil) ; dynamically skipped
10891 (defvar org-todo-setup-filter-hook nil
10892 "Hook for functions that pre-filter todo specs.
10893 Each function takes a todo spec and returns either nil or the spec
10894 transformed into canonical form." )
10896 (defvar org-todo-get-default-hook nil
10897 "Hook for functions that get a default item for todo.
10898 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
10899 nil or a string to be used for the todo mark." )
10901 (defvar org-agenda-headline-snapshot-before-repeat)
10903 (defun org-todo (&optional arg)
10904 "Change the TODO state of an item.
10905 The state of an item is given by a keyword at the start of the heading,
10906 like
10907 *** TODO Write paper
10908 *** DONE Call mom
10910 The different keywords are specified in the variable `org-todo-keywords'.
10911 By default the available states are \"TODO\" and \"DONE\".
10912 So for this example: when the item starts with TODO, it is changed to DONE.
10913 When it starts with DONE, the DONE is removed. And when neither TODO nor
10914 DONE are present, add TODO at the beginning of the heading.
10916 With \\[universal-argument] prefix arg, use completion to determine the new \
10917 state.
10918 With numeric prefix arg, switch to that state.
10919 With a double \\[universal-argument] prefix, switch to the next set of TODO \
10920 keywords (nextset).
10921 With a triple \\[universal-argument] prefix, circumvent any state blocking.
10923 For calling through lisp, arg is also interpreted in the following way:
10924 'none -> empty state
10925 \"\"(empty string) -> switch to empty state
10926 'done -> switch to DONE
10927 'nextset -> switch to the next set of keywords
10928 'previousset -> switch to the previous set of keywords
10929 \"WAITING\" -> switch to the specified keyword, but only if it
10930 really is a member of `org-todo-keywords'."
10931 (interactive "P")
10932 (if (equal arg '(16)) (setq arg 'nextset))
10933 (let ((org-blocker-hook org-blocker-hook)
10934 (case-fold-search nil))
10935 (when (equal arg '(64))
10936 (setq arg nil org-blocker-hook nil))
10937 (when (and org-blocker-hook
10938 (or org-inhibit-blocking
10939 (org-entry-get nil "NOBLOCKING")))
10940 (setq org-blocker-hook nil))
10941 (save-excursion
10942 (catch 'exit
10943 (org-back-to-heading t)
10944 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
10945 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
10946 (looking-at " *"))
10947 (let* ((match-data (match-data))
10948 (startpos (point-at-bol))
10949 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
10950 (org-log-done org-log-done)
10951 (org-log-repeat org-log-repeat)
10952 (org-todo-log-states org-todo-log-states)
10953 (this (match-string 1))
10954 (hl-pos (match-beginning 0))
10955 (head (org-get-todo-sequence-head this))
10956 (ass (assoc head org-todo-kwd-alist))
10957 (interpret (nth 1 ass))
10958 (done-word (nth 3 ass))
10959 (final-done-word (nth 4 ass))
10960 (last-state (or this ""))
10961 (completion-ignore-case t)
10962 (member (member this org-todo-keywords-1))
10963 (tail (cdr member))
10964 (state (cond
10965 ((and org-todo-key-trigger
10966 (or (and (equal arg '(4))
10967 (eq org-use-fast-todo-selection 'prefix))
10968 (and (not arg) org-use-fast-todo-selection
10969 (not (eq org-use-fast-todo-selection
10970 'prefix)))))
10971 ;; Use fast selection
10972 (org-fast-todo-selection))
10973 ((and (equal arg '(4))
10974 (or (not org-use-fast-todo-selection)
10975 (not org-todo-key-trigger)))
10976 ;; Read a state with completion
10977 (org-icompleting-read
10978 "State: " (mapcar (lambda(x) (list x))
10979 org-todo-keywords-1)
10980 nil t))
10981 ((eq arg 'right)
10982 (if this
10983 (if tail (car tail) nil)
10984 (car org-todo-keywords-1)))
10985 ((eq arg 'left)
10986 (if (equal member org-todo-keywords-1)
10988 (if this
10989 (nth (- (length org-todo-keywords-1)
10990 (length tail) 2)
10991 org-todo-keywords-1)
10992 (org-last org-todo-keywords-1))))
10993 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10994 (setq arg nil))) ; hack to fall back to cycling
10995 (arg
10996 ;; user or caller requests a specific state
10997 (cond
10998 ((equal arg "") nil)
10999 ((eq arg 'none) nil)
11000 ((eq arg 'done) (or done-word (car org-done-keywords)))
11001 ((eq arg 'nextset)
11002 (or (car (cdr (member head org-todo-heads)))
11003 (car org-todo-heads)))
11004 ((eq arg 'previousset)
11005 (let ((org-todo-heads (reverse org-todo-heads)))
11006 (or (car (cdr (member head org-todo-heads)))
11007 (car org-todo-heads))))
11008 ((car (member arg org-todo-keywords-1)))
11009 ((stringp arg)
11010 (error "State `%s' not valid in this file" arg))
11011 ((nth (1- (prefix-numeric-value arg))
11012 org-todo-keywords-1))))
11013 ((null member) (or head (car org-todo-keywords-1)))
11014 ((equal this final-done-word) nil) ;; -> make empty
11015 ((null tail) nil) ;; -> first entry
11016 ((memq interpret '(type priority))
11017 (if (eq this-command last-command)
11018 (car tail)
11019 (if (> (length tail) 0)
11020 (or done-word (car org-done-keywords))
11021 nil)))
11023 (car tail))))
11024 (state (or
11025 (run-hook-with-args-until-success
11026 'org-todo-get-default-hook state last-state)
11027 state))
11028 (next (if state (concat " " state " ") " "))
11029 (change-plist (list :type 'todo-state-change :from this :to state
11030 :position startpos))
11031 dolog now-done-p)
11032 (when org-blocker-hook
11033 (setq org-last-todo-state-is-todo
11034 (not (member this org-done-keywords)))
11035 (unless (save-excursion
11036 (save-match-data
11037 (org-with-wide-buffer
11038 (run-hook-with-args-until-failure
11039 'org-blocker-hook change-plist))))
11040 (if (org-called-interactively-p 'interactive)
11041 (error "TODO state change from %s to %s blocked" this state)
11042 ;; fail silently
11043 (message "TODO state change from %s to %s blocked" this state)
11044 (throw 'exit nil))))
11045 (store-match-data match-data)
11046 (replace-match next t t)
11047 (unless (pos-visible-in-window-p hl-pos)
11048 (message "TODO state changed to %s" (org-trim next)))
11049 (unless head
11050 (setq head (org-get-todo-sequence-head state)
11051 ass (assoc head org-todo-kwd-alist)
11052 interpret (nth 1 ass)
11053 done-word (nth 3 ass)
11054 final-done-word (nth 4 ass)))
11055 (when (memq arg '(nextset previousset))
11056 (message "Keyword-Set %d/%d: %s"
11057 (- (length org-todo-sets) -1
11058 (length (memq (assoc state org-todo-sets) org-todo-sets)))
11059 (length org-todo-sets)
11060 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11061 (setq org-last-todo-state-is-todo
11062 (not (member state org-done-keywords)))
11063 (setq now-done-p (and (member state org-done-keywords)
11064 (not (member this org-done-keywords))))
11065 (and logging (org-local-logging logging))
11066 (when (and (or org-todo-log-states org-log-done)
11067 (not (eq org-inhibit-logging t))
11068 (not (memq arg '(nextset previousset))))
11069 ;; we need to look at recording a time and note
11070 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
11071 (nth 2 (assoc this org-todo-log-states))))
11072 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11073 (setq dolog 'time))
11074 (when (and state
11075 (member state org-not-done-keywords)
11076 (not (member this org-not-done-keywords)))
11077 ;; This is now a todo state and was not one before
11078 ;; If there was a CLOSED time stamp, get rid of it.
11079 (org-add-planning-info nil nil 'closed))
11080 (when (and now-done-p org-log-done)
11081 ;; It is now done, and it was not done before
11082 (org-add-planning-info 'closed (org-current-time))
11083 (if (and (not dolog) (eq 'note org-log-done))
11084 (org-add-log-setup 'done state this 'findpos 'note)))
11085 (when (and state dolog)
11086 ;; This is a non-nil state, and we need to log it
11087 (org-add-log-setup 'state state this 'findpos dolog)))
11088 ;; Fixup tag positioning
11089 (org-todo-trigger-tag-changes state)
11090 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11091 (when org-provide-todo-statistics
11092 (org-update-parent-todo-statistics))
11093 (run-hooks 'org-after-todo-state-change-hook)
11094 (if (and arg (not (member state org-done-keywords)))
11095 (setq head (org-get-todo-sequence-head state)))
11096 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11097 ;; Do we need to trigger a repeat?
11098 (when now-done-p
11099 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11100 ;; This is for the agenda, take a snapshot of the headline.
11101 (save-match-data
11102 (setq org-agenda-headline-snapshot-before-repeat
11103 (org-get-heading))))
11104 (org-auto-repeat-maybe state))
11105 ;; Fixup cursor location if close to the keyword
11106 (if (and (outline-on-heading-p)
11107 (not (bolp))
11108 (save-excursion (beginning-of-line 1)
11109 (looking-at org-todo-line-regexp))
11110 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11111 (progn
11112 (goto-char (or (match-end 2) (match-end 1)))
11113 (and (looking-at " ") (just-one-space))))
11114 (when org-trigger-hook
11115 (save-excursion
11116 (run-hook-with-args 'org-trigger-hook change-plist))))))))
11118 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11119 "Block turning an entry into a TODO, using the hierarchy.
11120 This checks whether the current task should be blocked from state
11121 changes. Such blocking occurs when:
11123 1. The task has children which are not all in a completed state.
11125 2. A task has a parent with the property :ORDERED:, and there
11126 are siblings prior to the current task with incomplete
11127 status.
11129 3. The parent of the task is blocked because it has siblings that should
11130 be done first, or is child of a block grandparent TODO entry."
11132 (if (not org-enforce-todo-dependencies)
11133 t ; if locally turned off don't block
11134 (catch 'dont-block
11135 ;; If this is not a todo state change, or if this entry is already DONE,
11136 ;; do not block
11137 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11138 (member (plist-get change-plist :from)
11139 (cons 'done org-done-keywords))
11140 (member (plist-get change-plist :to)
11141 (cons 'todo org-not-done-keywords))
11142 (not (plist-get change-plist :to)))
11143 (throw 'dont-block t))
11144 ;; If this task has children, and any are undone, it's blocked
11145 (save-excursion
11146 (org-back-to-heading t)
11147 (let ((this-level (funcall outline-level)))
11148 (outline-next-heading)
11149 (let ((child-level (funcall outline-level)))
11150 (while (and (not (eobp))
11151 (> child-level this-level))
11152 ;; this todo has children, check whether they are all
11153 ;; completed
11154 (if (and (not (org-entry-is-done-p))
11155 (org-entry-is-todo-p))
11156 (throw 'dont-block nil))
11157 (outline-next-heading)
11158 (setq child-level (funcall outline-level))))))
11159 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11160 ;; any previous siblings are undone, it's blocked
11161 (save-excursion
11162 (org-back-to-heading t)
11163 (let* ((pos (point))
11164 (parent-pos (and (org-up-heading-safe) (point))))
11165 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11166 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11167 (forward-line 1)
11168 (re-search-forward org-not-done-heading-regexp pos t))
11169 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11170 ;; Search further up the hierarchy, to see if an anchestor is blocked
11171 (while t
11172 (goto-char parent-pos)
11173 (if (not (looking-at org-not-done-heading-regexp))
11174 (throw 'dont-block t)) ; do not block, parent is not a TODO
11175 (setq pos (point))
11176 (setq parent-pos (and (org-up-heading-safe) (point)))
11177 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11178 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11179 (forward-line 1)
11180 (re-search-forward org-not-done-heading-regexp pos t))
11181 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11183 (defcustom org-track-ordered-property-with-tag nil
11184 "Should the ORDERED property also be shown as a tag?
11185 The ORDERED property decides if an entry should require subtasks to be
11186 completed in sequence. Since a property is not very visible, setting
11187 this option means that toggling the ORDERED property with the command
11188 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11189 not relevant for the behavior, but it makes things more visible.
11191 Note that toggling the tag with tags commands will not change the property
11192 and therefore not influence behavior!
11194 This can be t, meaning the tag ORDERED should be used, It can also be a
11195 string to select a different tag for this task."
11196 :group 'org-todo
11197 :type '(choice
11198 (const :tag "No tracking" nil)
11199 (const :tag "Track with ORDERED tag" t)
11200 (string :tag "Use other tag")))
11202 (defun org-toggle-ordered-property ()
11203 "Toggle the ORDERED property of the current entry.
11204 For better visibility, you can track the value of this property with a tag.
11205 See variable `org-track-ordered-property-with-tag'."
11206 (interactive)
11207 (let* ((t1 org-track-ordered-property-with-tag)
11208 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11209 (save-excursion
11210 (org-back-to-heading)
11211 (if (org-entry-get nil "ORDERED")
11212 (progn
11213 (org-delete-property "ORDERED")
11214 (and tag (org-toggle-tag tag 'off))
11215 (message "Subtasks can be completed in arbitrary order"))
11216 (org-entry-put nil "ORDERED" "t")
11217 (and tag (org-toggle-tag tag 'on))
11218 (message "Subtasks must be completed in sequence")))))
11220 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11221 (defun org-block-todo-from-checkboxes (change-plist)
11222 "Block turning an entry into a TODO, using checkboxes.
11223 This checks whether the current task should be blocked from state
11224 changes because there are unchecked boxes in this entry."
11225 (if (not org-enforce-todo-checkbox-dependencies)
11226 t ; if locally turned off don't block
11227 (catch 'dont-block
11228 ;; If this is not a todo state change, or if this entry is already DONE,
11229 ;; do not block
11230 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11231 (member (plist-get change-plist :from)
11232 (cons 'done org-done-keywords))
11233 (member (plist-get change-plist :to)
11234 (cons 'todo org-not-done-keywords))
11235 (not (plist-get change-plist :to)))
11236 (throw 'dont-block t))
11237 ;; If this task has checkboxes that are not checked, it's blocked
11238 (save-excursion
11239 (org-back-to-heading t)
11240 (let ((beg (point)) end)
11241 (outline-next-heading)
11242 (setq end (point))
11243 (goto-char beg)
11244 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
11245 end t)
11246 (progn
11247 (if (boundp 'org-blocked-by-checkboxes)
11248 (setq org-blocked-by-checkboxes t))
11249 (throw 'dont-block nil)))))
11250 t))) ; do not block
11252 (defun org-entry-blocked-p ()
11253 "Is the current entry blocked?"
11254 (if (org-entry-get nil "NOBLOCKING")
11255 nil ;; Never block this entry
11256 (not
11257 (run-hook-with-args-until-failure
11258 'org-blocker-hook
11259 (list :type 'todo-state-change
11260 :position (point)
11261 :from 'todo
11262 :to 'done)))))
11264 (defun org-update-statistics-cookies (all)
11265 "Update the statistics cookie, either from TODO or from checkboxes.
11266 This should be called with the cursor in a line with a statistics cookie."
11267 (interactive "P")
11268 (if all
11269 (progn
11270 (org-update-checkbox-count 'all)
11271 (org-map-entries 'org-update-parent-todo-statistics))
11272 (if (not (org-on-heading-p))
11273 (org-update-checkbox-count)
11274 (let ((pos (move-marker (make-marker) (point)))
11275 end l1 l2)
11276 (ignore-errors (org-back-to-heading t))
11277 (if (not (org-on-heading-p))
11278 (org-update-checkbox-count)
11279 (setq l1 (org-outline-level))
11280 (setq end (save-excursion
11281 (outline-next-heading)
11282 (if (org-on-heading-p) (setq l2 (org-outline-level)))
11283 (point)))
11284 (if (and (save-excursion
11285 (re-search-forward
11286 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11287 (not (save-excursion (re-search-forward
11288 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11289 (org-update-checkbox-count)
11290 (if (and l2 (> l2 l1))
11291 (progn
11292 (goto-char end)
11293 (org-update-parent-todo-statistics))
11294 (goto-char pos)
11295 (beginning-of-line 1)
11296 (while (re-search-forward
11297 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11298 (point-at-eol) t)
11299 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11300 (goto-char pos)
11301 (move-marker pos nil)))))
11303 (defvar org-entry-property-inherited-from) ;; defined below
11304 (defun org-update-parent-todo-statistics ()
11305 "Update any statistics cookie in the parent of the current headline.
11306 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11307 the entire subtree and this will travel up the hierarchy and update
11308 statistics everywhere."
11309 (interactive)
11310 (let* ((lim 0) prop
11311 (recursive (or (not org-hierarchical-todo-statistics)
11312 (string-match
11313 "\\<recursive\\>"
11314 (or (setq prop (org-entry-get
11315 nil "COOKIE_DATA" 'inherit)) ""))))
11316 (lim (or (and prop (marker-position
11317 org-entry-property-inherited-from))
11318 lim))
11319 (first t)
11320 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11321 level ltoggle l1 new ndel
11322 (cnt-all 0) (cnt-done 0) is-percent kwd
11323 checkbox-beg ov ovs ove cookie-present)
11324 (catch 'exit
11325 (save-excursion
11326 (beginning-of-line 1)
11327 (if (org-at-heading-p)
11328 (setq ltoggle (funcall outline-level))
11329 (error "This should not happen"))
11330 (while (and (setq level (org-up-heading-safe))
11331 (or recursive first)
11332 (>= (point) lim))
11333 (setq first nil cookie-present nil)
11334 (unless (and level
11335 (not (string-match
11336 "\\<checkbox\\>"
11337 (downcase
11338 (or (org-entry-get
11339 nil "COOKIE_DATA")
11340 "")))))
11341 (throw 'exit nil))
11342 (while (re-search-forward box-re (point-at-eol) t)
11343 (setq cnt-all 0 cnt-done 0 cookie-present t)
11344 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11345 (save-match-data
11346 (unless (outline-next-heading) (throw 'exit nil))
11347 (while (and (looking-at org-complex-heading-regexp)
11348 (> (setq l1 (length (match-string 1))) level))
11349 (setq kwd (and (or recursive (= l1 ltoggle))
11350 (match-string 2)))
11351 (if (or (eq org-provide-todo-statistics 'all-headlines)
11352 (and (listp org-provide-todo-statistics)
11353 (or (member kwd org-provide-todo-statistics)
11354 (member kwd org-done-keywords))))
11355 (setq cnt-all (1+ cnt-all))
11356 (if (eq org-provide-todo-statistics t)
11357 (and kwd (setq cnt-all (1+ cnt-all)))))
11358 (and (member kwd org-done-keywords)
11359 (setq cnt-done (1+ cnt-done)))
11360 (outline-next-heading)))
11361 (setq new
11362 (if is-percent
11363 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11364 (format "[%d/%d]" cnt-done cnt-all))
11365 ndel (- (match-end 0) checkbox-beg))
11366 ;; handle overlays when updating cookie from column view
11367 (when (setq ov (car (overlays-at checkbox-beg)))
11368 (setq ovs (overlay-start ov) ove (overlay-end ov))
11369 (delete-overlay ov))
11370 (goto-char checkbox-beg)
11371 (insert new)
11372 (delete-region (point) (+ (point) ndel))
11373 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11374 (when ov (move-overlay ov ovs ove)))
11375 (when cookie-present
11376 (run-hook-with-args 'org-after-todo-statistics-hook
11377 cnt-done (- cnt-all cnt-done))))))
11378 (run-hooks 'org-todo-statistics-hook)))
11380 (defvar org-after-todo-statistics-hook nil
11381 "Hook that is called after a TODO statistics cookie has been updated.
11382 Each function is called with two arguments: the number of not-done entries
11383 and the number of done entries.
11385 For example, the following function, when added to this hook, will switch
11386 an entry to DONE when all children are done, and back to TODO when new
11387 entries are set to a TODO status. Note that this hook is only called
11388 when there is a statistics cookie in the headline!
11390 (defun org-summary-todo (n-done n-not-done)
11391 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11392 (let (org-log-done org-log-states) ; turn off logging
11393 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11396 (defvar org-todo-statistics-hook nil
11397 "Hook that is run whenever Org thinks TODO statistics should be updated.
11398 This hook runs even if there is no statistics cookie present, in which case
11399 `org-after-todo-statistics-hook' would not run.")
11401 (defun org-todo-trigger-tag-changes (state)
11402 "Apply the changes defined in `org-todo-state-tags-triggers'."
11403 (let ((l org-todo-state-tags-triggers)
11404 changes)
11405 (when (or (not state) (equal state ""))
11406 (setq changes (append changes (cdr (assoc "" l)))))
11407 (when (and (stringp state) (> (length state) 0))
11408 (setq changes (append changes (cdr (assoc state l)))))
11409 (when (member state org-not-done-keywords)
11410 (setq changes (append changes (cdr (assoc 'todo l)))))
11411 (when (member state org-done-keywords)
11412 (setq changes (append changes (cdr (assoc 'done l)))))
11413 (dolist (c changes)
11414 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11416 (defun org-local-logging (value)
11417 "Get logging settings from a property VALUE."
11418 (let* (words w a)
11419 ;; directly set the variables, they are already local.
11420 (setq org-log-done nil
11421 org-log-repeat nil
11422 org-todo-log-states nil)
11423 (setq words (org-split-string value))
11424 (while (setq w (pop words))
11425 (cond
11426 ((setq a (assoc w org-startup-options))
11427 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11428 (set (nth 1 a) (nth 2 a))))
11429 ((setq a (org-extract-log-state-settings w))
11430 (and (member (car a) org-todo-keywords-1)
11431 (push a org-todo-log-states)))))))
11433 (defun org-get-todo-sequence-head (kwd)
11434 "Return the head of the TODO sequence to which KWD belongs.
11435 If KWD is not set, check if there is a text property remembering the
11436 right sequence."
11437 (let (p)
11438 (cond
11439 ((not kwd)
11440 (or (get-text-property (point-at-bol) 'org-todo-head)
11441 (progn
11442 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11443 nil (point-at-eol)))
11444 (get-text-property p 'org-todo-head))))
11445 ((not (member kwd org-todo-keywords-1))
11446 (car org-todo-keywords-1))
11447 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11449 (defun org-fast-todo-selection ()
11450 "Fast TODO keyword selection with single keys.
11451 Returns the new TODO keyword, or nil if no state change should occur."
11452 (let* ((fulltable org-todo-key-alist)
11453 (done-keywords org-done-keywords) ;; needed for the faces.
11454 (maxlen (apply 'max (mapcar
11455 (lambda (x)
11456 (if (stringp (car x)) (string-width (car x)) 0))
11457 fulltable)))
11458 (expert nil)
11459 (fwidth (+ maxlen 3 1 3))
11460 (ncol (/ (- (window-width) 4) fwidth))
11461 tg cnt e c tbl
11462 groups ingroup)
11463 (save-excursion
11464 (save-window-excursion
11465 (if expert
11466 (set-buffer (get-buffer-create " *Org todo*"))
11467 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11468 (erase-buffer)
11469 (org-set-local 'org-done-keywords done-keywords)
11470 (setq tbl fulltable cnt 0)
11471 (while (setq e (pop tbl))
11472 (cond
11473 ((equal e '(:startgroup))
11474 (push '() groups) (setq ingroup t)
11475 (when (not (= cnt 0))
11476 (setq cnt 0)
11477 (insert "\n"))
11478 (insert "{ "))
11479 ((equal e '(:endgroup))
11480 (setq ingroup nil cnt 0)
11481 (insert "}\n"))
11482 ((equal e '(:newline))
11483 (when (not (= cnt 0))
11484 (setq cnt 0)
11485 (insert "\n")
11486 (setq e (car tbl))
11487 (while (equal (car tbl) '(:newline))
11488 (insert "\n")
11489 (setq tbl (cdr tbl)))))
11491 (setq tg (car e) c (cdr e))
11492 (if ingroup (push tg (car groups)))
11493 (setq tg (org-add-props tg nil 'face
11494 (org-get-todo-face tg)))
11495 (if (and (= cnt 0) (not ingroup)) (insert " "))
11496 (insert "[" c "] " tg (make-string
11497 (- fwidth 4 (length tg)) ?\ ))
11498 (when (= (setq cnt (1+ cnt)) ncol)
11499 (insert "\n")
11500 (if ingroup (insert " "))
11501 (setq cnt 0)))))
11502 (insert "\n")
11503 (goto-char (point-min))
11504 (if (not expert) (org-fit-window-to-buffer))
11505 (message "[a-z..]:Set [SPC]:clear")
11506 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11507 (cond
11508 ((or (= c ?\C-g)
11509 (and (= c ?q) (not (rassoc c fulltable))))
11510 (setq quit-flag t))
11511 ((= c ?\ ) nil)
11512 ((setq e (rassoc c fulltable) tg (car e))
11514 (t (setq quit-flag t)))))))
11516 (defun org-entry-is-todo-p ()
11517 (member (org-get-todo-state) org-not-done-keywords))
11519 (defun org-entry-is-done-p ()
11520 (member (org-get-todo-state) org-done-keywords))
11522 (defun org-get-todo-state ()
11523 (save-excursion
11524 (org-back-to-heading t)
11525 (and (looking-at org-todo-line-regexp)
11526 (match-end 2)
11527 (match-string 2))))
11529 (defun org-at-date-range-p (&optional inactive-ok)
11530 "Is the cursor inside a date range?"
11531 (interactive)
11532 (save-excursion
11533 (catch 'exit
11534 (let ((pos (point)))
11535 (skip-chars-backward "^[<\r\n")
11536 (skip-chars-backward "<[")
11537 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11538 (>= (match-end 0) pos)
11539 (throw 'exit t))
11540 (skip-chars-backward "^<[\r\n")
11541 (skip-chars-backward "<[")
11542 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11543 (>= (match-end 0) pos)
11544 (throw 'exit t)))
11545 nil)))
11547 (defun org-get-repeat (&optional tagline)
11548 "Check if there is a deadline/schedule with repeater in this entry."
11549 (save-match-data
11550 (save-excursion
11551 (org-back-to-heading t)
11552 (and (re-search-forward (if tagline
11553 (concat tagline "\\s-*" org-repeat-re)
11554 org-repeat-re)
11555 (org-entry-end-position) t)
11556 (match-string-no-properties 1)))))
11558 (defvar org-last-changed-timestamp)
11559 (defvar org-last-inserted-timestamp)
11560 (defvar org-log-post-message)
11561 (defvar org-log-note-purpose)
11562 (defvar org-log-note-how)
11563 (defvar org-log-note-extra)
11564 (defun org-auto-repeat-maybe (done-word)
11565 "Check if the current headline contains a repeated deadline/schedule.
11566 If yes, set TODO state back to what it was and change the base date
11567 of repeating deadline/scheduled time stamps to new date.
11568 This function is run automatically after each state change to a DONE state."
11569 ;; last-state is dynamically scoped into this function
11570 (let* ((repeat (org-get-repeat))
11571 (aa (assoc last-state org-todo-kwd-alist))
11572 (interpret (nth 1 aa))
11573 (head (nth 2 aa))
11574 (whata '(("d" . day) ("m" . month) ("y" . year)))
11575 (msg "Entry repeats: ")
11576 (org-log-done nil)
11577 (org-todo-log-states nil)
11578 re type n what ts time to-state)
11579 (when repeat
11580 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11581 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11582 org-todo-repeat-to-state))
11583 (unless (and to-state (member to-state org-todo-keywords-1))
11584 (setq to-state (if (eq interpret 'type) last-state head)))
11585 (org-todo to-state)
11586 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11587 (org-entry-put nil "LAST_REPEAT" (format-time-string
11588 (org-time-stamp-format t t))))
11589 (when org-log-repeat
11590 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11591 (memq 'org-add-log-note post-command-hook))
11592 ;; OK, we are already setup for some record
11593 (if (eq org-log-repeat 'note)
11594 ;; make sure we take a note, not only a time stamp
11595 (setq org-log-note-how 'note))
11596 ;; Set up for taking a record
11597 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11598 last-state
11599 'findpos org-log-repeat)))
11600 (org-back-to-heading t)
11601 (org-add-planning-info nil nil 'closed)
11602 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11603 org-deadline-time-regexp "\\)\\|\\("
11604 org-ts-regexp "\\)"))
11605 (while (re-search-forward
11606 re (save-excursion (outline-next-heading) (point)) t)
11607 (setq type (if (match-end 1) org-scheduled-string
11608 (if (match-end 3) org-deadline-string "Plain:"))
11609 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11610 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11611 (setq n (string-to-number (match-string 2 ts))
11612 what (match-string 3 ts))
11613 (if (equal what "w") (setq n (* n 7) what "d"))
11614 ;; Preparation, see if we need to modify the start date for the change
11615 (when (match-end 1)
11616 (setq time (save-match-data (org-time-string-to-time ts)))
11617 (cond
11618 ((equal (match-string 1 ts) ".")
11619 ;; Shift starting date to today
11620 (org-timestamp-change
11621 (- (time-to-days (current-time)) (time-to-days time))
11622 'day))
11623 ((equal (match-string 1 ts) "+")
11624 (let ((nshiftmax 10) (nshift 0))
11625 (while (or (= nshift 0)
11626 (<= (time-to-days time)
11627 (time-to-days (current-time))))
11628 (when (= (incf nshift) nshiftmax)
11629 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11630 (error "Abort")))
11631 (org-timestamp-change n (cdr (assoc what whata)))
11632 (org-at-timestamp-p t)
11633 (setq ts (match-string 1))
11634 (setq time (save-match-data (org-time-string-to-time ts)))))
11635 (org-timestamp-change (- n) (cdr (assoc what whata)))
11636 ;; rematch, so that we have everything in place for the real shift
11637 (org-at-timestamp-p t)
11638 (setq ts (match-string 1))
11639 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11640 (org-timestamp-change n (cdr (assoc what whata)))
11641 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11642 (setq org-log-post-message msg)
11643 (message "%s" msg))))
11645 (defun org-show-todo-tree (arg)
11646 "Make a compact tree which shows all headlines marked with TODO.
11647 The tree will show the lines where the regexp matches, and all higher
11648 headlines above the match.
11649 With a \\[universal-argument] prefix, prompt for a regexp to match.
11650 With a numeric prefix N, construct a sparse tree for the Nth element
11651 of `org-todo-keywords-1'."
11652 (interactive "P")
11653 (let ((case-fold-search nil)
11654 (kwd-re
11655 (cond ((null arg) org-not-done-regexp)
11656 ((equal arg '(4))
11657 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11658 (mapcar 'list org-todo-keywords-1))))
11659 (concat "\\("
11660 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11661 "\\)\\>")))
11662 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11663 (regexp-quote (nth (1- (prefix-numeric-value arg))
11664 org-todo-keywords-1)))
11665 (t (error "Invalid prefix argument: %s" arg)))))
11666 (message "%d TODO entries found"
11667 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
11669 (defun org-deadline (&optional remove time)
11670 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11671 With argument REMOVE, remove any deadline from the item.
11672 When TIME is set, it should be an internal time specification, and the
11673 scheduling will use the corresponding date."
11674 (interactive "P")
11675 (let* ((old-date (org-entry-get nil "DEADLINE"))
11676 (repeater (and old-date
11677 (string-match
11678 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11679 old-date)
11680 (match-string 1 old-date))))
11681 (if remove
11682 (progn
11683 (when (and old-date org-log-redeadline)
11684 (org-add-log-setup 'deldeadline nil old-date 'findpos
11685 org-log-redeadline))
11686 (org-remove-timestamp-with-keyword org-deadline-string)
11687 (message "Item no longer has a deadline."))
11688 (org-add-planning-info 'deadline time 'closed)
11689 (when (and old-date org-log-redeadline
11690 (not (equal old-date
11691 (substring org-last-inserted-timestamp 1 -1))))
11692 (org-add-log-setup 'redeadline nil old-date 'findpos
11693 org-log-redeadline))
11694 (when repeater
11695 (save-excursion
11696 (org-back-to-heading t)
11697 (when (re-search-forward (concat org-deadline-string " "
11698 org-last-inserted-timestamp)
11699 (save-excursion
11700 (outline-next-heading) (point)) t)
11701 (goto-char (1- (match-end 0)))
11702 (insert " " repeater)
11703 (setq org-last-inserted-timestamp
11704 (concat (substring org-last-inserted-timestamp 0 -1)
11705 " " repeater
11706 (substring org-last-inserted-timestamp -1))))))
11707 (message "Deadline on %s" org-last-inserted-timestamp))))
11709 (defun org-schedule (&optional remove time)
11710 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11711 With argument REMOVE, remove any scheduling date from the item.
11712 When TIME is set, it should be an internal time specification, and the
11713 scheduling will use the corresponding date."
11714 (interactive "P")
11715 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11716 (repeater (and old-date
11717 (string-match
11718 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11719 old-date)
11720 (match-string 1 old-date))))
11721 (if remove
11722 (progn
11723 (when (and old-date org-log-reschedule)
11724 (org-add-log-setup 'delschedule nil old-date 'findpos
11725 org-log-reschedule))
11726 (org-remove-timestamp-with-keyword org-scheduled-string)
11727 (message "Item is no longer scheduled."))
11728 (org-add-planning-info 'scheduled time 'closed)
11729 (when (and old-date org-log-reschedule
11730 (not (equal old-date
11731 (substring org-last-inserted-timestamp 1 -1))))
11732 (org-add-log-setup 'reschedule nil old-date 'findpos
11733 org-log-reschedule))
11734 (when repeater
11735 (save-excursion
11736 (org-back-to-heading t)
11737 (when (re-search-forward (concat org-scheduled-string " "
11738 org-last-inserted-timestamp)
11739 (save-excursion
11740 (outline-next-heading) (point)) t)
11741 (goto-char (1- (match-end 0)))
11742 (insert " " repeater)
11743 (setq org-last-inserted-timestamp
11744 (concat (substring org-last-inserted-timestamp 0 -1)
11745 " " repeater
11746 (substring org-last-inserted-timestamp -1))))))
11747 (message "Scheduled to %s" org-last-inserted-timestamp))))
11749 (defun org-get-scheduled-time (pom &optional inherit)
11750 "Get the scheduled time as a time tuple, of a format suitable
11751 for calling org-schedule with, or if there is no scheduling,
11752 returns nil."
11753 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
11754 (when time
11755 (apply 'encode-time (org-parse-time-string time)))))
11757 (defun org-get-deadline-time (pom &optional inherit)
11758 "Get the deadline as a time tuple, of a format suitable for
11759 calling org-deadline with, or if there is no scheduling, returns
11760 nil."
11761 (let ((time (org-entry-get pom "DEADLINE" inherit)))
11762 (when time
11763 (apply 'encode-time (org-parse-time-string time)))))
11765 (defun org-remove-timestamp-with-keyword (keyword)
11766 "Remove all time stamps with KEYWORD in the current entry."
11767 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
11768 beg)
11769 (save-excursion
11770 (org-back-to-heading t)
11771 (setq beg (point))
11772 (outline-next-heading)
11773 (while (re-search-backward re beg t)
11774 (replace-match "")
11775 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
11776 (equal (char-before) ?\ ))
11777 (backward-delete-char 1)
11778 (if (string-match "^[ \t]*$" (buffer-substring
11779 (point-at-bol) (point-at-eol)))
11780 (delete-region (point-at-bol)
11781 (min (point-max) (1+ (point-at-eol))))))))))
11783 (defun org-add-planning-info (what &optional time &rest remove)
11784 "Insert new timestamp with keyword in the line directly after the headline.
11785 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11786 If non is given, the user is prompted for a date.
11787 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11788 be removed."
11789 (interactive)
11790 (let (org-time-was-given org-end-time-was-given ts
11791 end default-time default-input)
11793 (catch 'exit
11794 (when (and (not time) (memq what '(scheduled deadline)))
11795 ;; Try to get a default date/time from existing timestamp
11796 (save-excursion
11797 (org-back-to-heading t)
11798 (setq end (save-excursion (outline-next-heading) (point)))
11799 (when (re-search-forward (if (eq what 'scheduled)
11800 org-scheduled-time-regexp
11801 org-deadline-time-regexp)
11802 end t)
11803 (setq ts (match-string 1)
11804 default-time
11805 (apply 'encode-time (org-parse-time-string ts))
11806 default-input (and ts (org-get-compact-tod ts))))))
11807 (when what
11808 ;; If necessary, get the time from the user
11809 (setq time (or time (org-read-date nil 'to-time nil nil
11810 default-time default-input))))
11812 (when (and org-insert-labeled-timestamps-at-point
11813 (member what '(scheduled deadline)))
11814 (insert
11815 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11816 (org-insert-time-stamp time org-time-was-given
11817 nil nil nil (list org-end-time-was-given))
11818 (setq what nil))
11819 (save-excursion
11820 (save-restriction
11821 (let (col list elt ts buffer-invisibility-spec)
11822 (org-back-to-heading t)
11823 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11824 (goto-char (match-end 1))
11825 (setq col (current-column))
11826 (goto-char (match-end 0))
11827 (if (eobp) (insert "\n") (forward-char 1))
11828 (when (and (not what)
11829 (not (looking-at
11830 (concat "[ \t]*"
11831 org-keyword-time-not-clock-regexp))))
11832 ;; Nothing to add, nothing to remove...... :-)
11833 (throw 'exit nil))
11834 (if (and (not (looking-at outline-regexp))
11835 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11836 "[^\r\n]*"))
11837 (not (equal (match-string 1) org-clock-string)))
11838 (narrow-to-region (match-beginning 0) (match-end 0))
11839 (insert-before-markers "\n")
11840 (backward-char 1)
11841 (narrow-to-region (point) (point))
11842 (and org-adapt-indentation (org-indent-to-column col)))
11843 ;; Check if we have to remove something.
11844 (setq list (cons what remove))
11845 (while list
11846 (setq elt (pop list))
11847 (when (or (and (eq elt 'scheduled)
11848 (re-search-forward org-scheduled-time-regexp nil t))
11849 (and (eq elt 'deadline)
11850 (re-search-forward org-deadline-time-regexp nil t))
11851 (and (eq elt 'closed)
11852 (re-search-forward org-closed-time-regexp nil t)))
11853 (replace-match "")
11854 (if (looking-at "--+<[^>]+>") (replace-match ""))))
11855 (and (looking-at "^[ \t]+") (replace-match ""))
11856 (and org-adapt-indentation (bolp) (org-indent-to-column col))
11857 (when what
11858 (insert
11859 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
11860 (cond ((eq what 'scheduled) org-scheduled-string)
11861 ((eq what 'deadline) org-deadline-string)
11862 ((eq what 'closed) org-closed-string))
11863 " ")
11864 (setq ts (org-insert-time-stamp
11865 time
11866 (or org-time-was-given
11867 (and (eq what 'closed) org-log-done-with-time))
11868 (eq what 'closed)
11869 nil nil (list org-end-time-was-given)))
11870 (insert
11871 (if (not (or (bolp) (eq (char-before) ?\ )
11872 (memq (char-after) '(32 10))
11873 (eobp))) " " ""))
11874 (end-of-line 1))
11875 (goto-char (point-min))
11876 (widen)
11877 (if (and (looking-at "[ \t]*\n")
11878 (equal (char-before) ?\n))
11879 (delete-region (1- (point)) (point-at-eol)))
11880 ts))))))
11882 (defvar org-log-note-marker (make-marker))
11883 (defvar org-log-note-purpose nil)
11884 (defvar org-log-note-state nil)
11885 (defvar org-log-note-previous-state nil)
11886 (defvar org-log-note-how nil)
11887 (defvar org-log-note-extra nil)
11888 (defvar org-log-note-window-configuration nil)
11889 (defvar org-log-note-return-to (make-marker))
11890 (defvar org-log-post-message nil
11891 "Message to be displayed after a log note has been stored.
11892 The auto-repeater uses this.")
11894 (defun org-add-note ()
11895 "Add a note to the current entry.
11896 This is done in the same way as adding a state change note."
11897 (interactive)
11898 (org-add-log-setup 'note nil nil 'findpos nil))
11900 (defvar org-property-end-re)
11901 (defun org-add-log-setup (&optional purpose state prev-state
11902 findpos how extra)
11903 "Set up the post command hook to take a note.
11904 If this is about to TODO state change, the new state is expected in STATE.
11905 When FINDPOS is non-nil, find the correct position for the note in
11906 the current entry. If not, assume that it can be inserted at point.
11907 HOW is an indicator what kind of note should be created.
11908 EXTRA is additional text that will be inserted into the notes buffer."
11909 (let* ((org-log-into-drawer (org-log-into-drawer))
11910 (drawer (cond ((stringp org-log-into-drawer)
11911 org-log-into-drawer)
11912 (org-log-into-drawer "LOGBOOK")
11913 (t nil))))
11914 (save-restriction
11915 (save-excursion
11916 (when findpos
11917 (org-back-to-heading t)
11918 (narrow-to-region (point) (save-excursion
11919 (outline-next-heading) (point)))
11920 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11921 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11922 "[^\r\n]*\\)?"))
11923 (goto-char (match-end 0))
11924 (cond
11925 (drawer
11926 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
11927 nil t)
11928 (progn
11929 (goto-char (match-end 0))
11930 (or org-log-states-order-reversed
11931 (and (re-search-forward org-property-end-re nil t)
11932 (goto-char (1- (match-beginning 0))))))
11933 (insert "\n:" drawer ":\n:END:")
11934 (beginning-of-line 0)
11935 (org-indent-line-function)
11936 (beginning-of-line 2)
11937 (org-indent-line-function)
11938 (end-of-line 0)))
11939 ((and org-log-state-notes-insert-after-drawers
11940 (save-excursion
11941 (forward-line) (looking-at org-drawer-regexp)))
11942 (forward-line)
11943 (while (looking-at org-drawer-regexp)
11944 (goto-char (match-end 0))
11945 (re-search-forward org-property-end-re (point-max) t)
11946 (forward-line))
11947 (forward-line -1)))
11948 (unless org-log-states-order-reversed
11949 (and (= (char-after) ?\n) (forward-char 1))
11950 (org-skip-over-state-notes)
11951 (skip-chars-backward " \t\n\r")))
11952 (move-marker org-log-note-marker (point))
11953 (setq org-log-note-purpose purpose
11954 org-log-note-state state
11955 org-log-note-previous-state prev-state
11956 org-log-note-how how
11957 org-log-note-extra extra)
11958 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
11960 (defun org-skip-over-state-notes ()
11961 "Skip past the list of State notes in an entry."
11962 (if (looking-at "\n[ \t]*- State") (forward-char 1))
11963 (when (ignore-errors (goto-char (org-in-item-p)))
11964 (let* ((struct (org-list-struct))
11965 (prevs (org-list-prevs-alist struct)))
11966 (while (looking-at "[ \t]*- State")
11967 (goto-char (or (org-list-get-next-item (point) struct prevs)
11968 (org-list-get-item-end (point) struct)))))))
11970 (defun org-add-log-note (&optional purpose)
11971 "Pop up a window for taking a note, and add this note later at point."
11972 (remove-hook 'post-command-hook 'org-add-log-note)
11973 (setq org-log-note-window-configuration (current-window-configuration))
11974 (delete-other-windows)
11975 (move-marker org-log-note-return-to (point))
11976 (switch-to-buffer (marker-buffer org-log-note-marker))
11977 (goto-char org-log-note-marker)
11978 (org-switch-to-buffer-other-window "*Org Note*")
11979 (erase-buffer)
11980 (if (memq org-log-note-how '(time state))
11981 (let (current-prefix-arg) (org-store-log-note))
11982 (let ((org-inhibit-startup t)) (org-mode))
11983 (insert (format "# Insert note for %s.
11984 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
11985 (cond
11986 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11987 ((eq org-log-note-purpose 'done) "closed todo item")
11988 ((eq org-log-note-purpose 'state)
11989 (format "state change from \"%s\" to \"%s\""
11990 (or org-log-note-previous-state "")
11991 (or org-log-note-state "")))
11992 ((eq org-log-note-purpose 'reschedule)
11993 "rescheduling")
11994 ((eq org-log-note-purpose 'delschedule)
11995 "no longer scheduled")
11996 ((eq org-log-note-purpose 'redeadline)
11997 "changing deadline")
11998 ((eq org-log-note-purpose 'deldeadline)
11999 "removing deadline")
12000 ((eq org-log-note-purpose 'refile)
12001 "refiling")
12002 ((eq org-log-note-purpose 'note)
12003 "this entry")
12004 (t (error "This should not happen")))))
12005 (if org-log-note-extra (insert org-log-note-extra))
12006 (org-set-local 'org-finish-function 'org-store-log-note)))
12008 (defvar org-note-abort nil) ; dynamically scoped
12009 (defun org-store-log-note ()
12010 "Finish taking a log note, and insert it to where it belongs."
12011 (let ((txt (buffer-string))
12012 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12013 lines ind bul)
12014 (kill-buffer (current-buffer))
12015 (while (string-match "\\`#.*\n[ \t\n]*" txt)
12016 (setq txt (replace-match "" t t txt)))
12017 (if (string-match "\\s-+\\'" txt)
12018 (setq txt (replace-match "" t t txt)))
12019 (setq lines (org-split-string txt "\n"))
12020 (when (and note (string-match "\\S-" note))
12021 (setq note
12022 (org-replace-escapes
12023 note
12024 (list (cons "%u" (user-login-name))
12025 (cons "%U" user-full-name)
12026 (cons "%t" (format-time-string
12027 (org-time-stamp-format 'long 'inactive)
12028 (current-time)))
12029 (cons "%T" (format-time-string
12030 (org-time-stamp-format 'long nil)
12031 (current-time)))
12032 (cons "%s" (if org-log-note-state
12033 (concat "\"" org-log-note-state "\"")
12034 ""))
12035 (cons "%S" (if org-log-note-previous-state
12036 (concat "\"" org-log-note-previous-state "\"")
12037 "\"\"")))))
12038 (if lines (setq note (concat note " \\\\")))
12039 (push note lines))
12040 (when (or current-prefix-arg org-note-abort)
12041 (when org-log-into-drawer
12042 (org-remove-empty-drawer-at
12043 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12044 org-log-note-marker))
12045 (setq lines nil))
12046 (when lines
12047 (with-current-buffer (marker-buffer org-log-note-marker)
12048 (save-excursion
12049 (goto-char org-log-note-marker)
12050 (move-marker org-log-note-marker nil)
12051 (end-of-line 1)
12052 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12053 (setq ind (save-excursion
12054 (if (ignore-errors (goto-char (org-in-item-p)))
12055 (let ((struct (org-list-struct)))
12056 (org-list-get-ind
12057 (org-list-get-top-point struct) struct))
12058 (skip-chars-backward " \r\t\n")
12059 (cond
12060 ((and (org-at-heading-p)
12061 org-adapt-indentation)
12062 (1+ (org-current-level)))
12063 ((org-at-heading-p) 0)
12064 (t (org-get-indentation))))))
12065 (setq bul (org-list-bullet-string "-"))
12066 (org-indent-line-to ind)
12067 (insert bul (pop lines))
12068 (let ((ind-body (+ (length bul) ind)))
12069 (while lines
12070 (insert "\n")
12071 (org-indent-line-to ind-body)
12072 (insert (pop lines))))
12073 (message "Note stored")
12074 (org-back-to-heading t)
12075 (org-cycle-hide-drawers 'children)))))
12076 (set-window-configuration org-log-note-window-configuration)
12077 (with-current-buffer (marker-buffer org-log-note-return-to)
12078 (goto-char org-log-note-return-to))
12079 (move-marker org-log-note-return-to nil)
12080 (and org-log-post-message (message "%s" org-log-post-message)))
12082 (defun org-remove-empty-drawer-at (drawer pos)
12083 "Remove an empty drawer DRAWER at position POS.
12084 POS may also be a marker."
12085 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12086 (save-excursion
12087 (save-restriction
12088 (widen)
12089 (goto-char pos)
12090 (if (org-in-regexp
12091 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12092 (replace-match ""))))))
12094 (defun org-sparse-tree (&optional arg)
12095 "Create a sparse tree, prompt for the details.
12096 This command can create sparse trees. You first need to select the type
12097 of match used to create the tree:
12099 t Show all TODO entries.
12100 T Show entries with a specific TODO keyword.
12101 m Show entries selected by a tags/property match.
12102 p Enter a property name and its value (both with completion on existing
12103 names/values) and show entries with that property.
12104 r Show entries matching a regular expression (`/' can be used as well)
12105 d Show deadlines due within `org-deadline-warning-days'.
12106 b Show deadlines and scheduled items before a date.
12107 a Show deadlines and scheduled items after a date."
12108 (interactive "P")
12109 (let (ans kwd value)
12110 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date")
12111 (setq ans (read-char-exclusive))
12112 (cond
12113 ((equal ans ?d)
12114 (call-interactively 'org-check-deadlines))
12115 ((equal ans ?b)
12116 (call-interactively 'org-check-before-date))
12117 ((equal ans ?a)
12118 (call-interactively 'org-check-after-date))
12119 ((equal ans ?t)
12120 (org-show-todo-tree nil))
12121 ((equal ans ?T)
12122 (org-show-todo-tree '(4)))
12123 ((member ans '(?T ?m))
12124 (call-interactively 'org-match-sparse-tree))
12125 ((member ans '(?p ?P))
12126 (setq kwd (org-icompleting-read "Property: "
12127 (mapcar 'list (org-buffer-property-keys))))
12128 (setq value (org-icompleting-read "Value: "
12129 (mapcar 'list (org-property-values kwd))))
12130 (unless (string-match "\\`{.*}\\'" value)
12131 (setq value (concat "\"" value "\"")))
12132 (org-match-sparse-tree arg (concat kwd "=" value)))
12133 ((member ans '(?r ?R ?/))
12134 (call-interactively 'org-occur))
12135 (t (error "No such sparse tree command \"%c\"" ans)))))
12137 (defvar org-occur-highlights nil
12138 "List of overlays used for occur matches.")
12139 (make-variable-buffer-local 'org-occur-highlights)
12140 (defvar org-occur-parameters nil
12141 "Parameters of the active org-occur calls.
12142 This is a list, each call to org-occur pushes as cons cell,
12143 containing the regular expression and the callback, onto the list.
12144 The list can contain several entries if `org-occur' has been called
12145 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12146 will only contain one set of parameters. When the highlights are
12147 removed (for example with `C-c C-c', or with the next edit (depending
12148 on `org-remove-highlights-with-change'), this variable is emptied
12149 as well.")
12150 (make-variable-buffer-local 'org-occur-parameters)
12152 (defun org-occur (regexp &optional keep-previous callback)
12153 "Make a compact tree which shows all matches of REGEXP.
12154 The tree will show the lines where the regexp matches, and all higher
12155 headlines above the match. It will also show the heading after the match,
12156 to make sure editing the matching entry is easy.
12157 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12158 call to `org-occur' will be kept, to allow stacking of calls to this
12159 command.
12160 If CALLBACK is non-nil, it is a function which is called to confirm
12161 that the match should indeed be shown."
12162 (interactive "sRegexp: \nP")
12163 (when (equal regexp "")
12164 (error "Regexp cannot be empty"))
12165 (unless keep-previous
12166 (org-remove-occur-highlights nil nil t))
12167 (push (cons regexp callback) org-occur-parameters)
12168 (let ((cnt 0))
12169 (save-excursion
12170 (goto-char (point-min))
12171 (if (or (not keep-previous) ; do not want to keep
12172 (not org-occur-highlights)) ; no previous matches
12173 ;; hide everything
12174 (org-overview))
12175 (while (re-search-forward regexp nil t)
12176 (when (or (not callback)
12177 (save-match-data (funcall callback)))
12178 (setq cnt (1+ cnt))
12179 (when org-highlight-sparse-tree-matches
12180 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12181 (org-show-context 'occur-tree))))
12182 (when org-remove-highlights-with-change
12183 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12184 nil 'local))
12185 (unless org-sparse-tree-open-archived-trees
12186 (org-hide-archived-subtrees (point-min) (point-max)))
12187 (run-hooks 'org-occur-hook)
12188 (if (org-called-interactively-p 'interactive)
12189 (message "%d match(es) for regexp %s" cnt regexp))
12190 cnt))
12192 (defun org-occur-next-match (&optional n reset)
12193 "Function for `next-error-function' to find sparse tree matches.
12194 N is the number of matches to move, when negative move backwards.
12195 RESET is entirely ignored - this function always goes back to the
12196 starting point when no match is found."
12197 (let* ((limit (if (< n 0) (point-min) (point-max)))
12198 (search-func (if (< n 0)
12199 'previous-single-char-property-change
12200 'next-single-char-property-change))
12201 (n (abs n))
12202 (pos (point))
12204 (catch 'exit
12205 (while (setq p1 (funcall search-func (point) 'org-type))
12206 (when (equal p1 limit)
12207 (goto-char pos)
12208 (error "No more matches"))
12209 (when (equal (get-char-property p1 'org-type) 'org-occur)
12210 (setq n (1- n))
12211 (when (= n 0)
12212 (goto-char p1)
12213 (throw 'exit (point))))
12214 (goto-char p1))
12215 (goto-char p1)
12216 (error "No more matches"))))
12218 (defun org-show-context (&optional key)
12219 "Make sure point and context are visible.
12220 How much context is shown depends upon the variables
12221 `org-show-hierarchy-above', `org-show-following-heading'. and
12222 `org-show-siblings'."
12223 (let ((heading-p (org-on-heading-p t))
12224 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12225 (following-p (org-get-alist-option org-show-following-heading key))
12226 (entry-p (org-get-alist-option org-show-entry-below key))
12227 (siblings-p (org-get-alist-option org-show-siblings key)))
12228 (catch 'exit
12229 ;; Show heading or entry text
12230 (if (and heading-p (not entry-p))
12231 (org-flag-heading nil) ; only show the heading
12232 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12233 (org-show-hidden-entry))) ; show entire entry
12234 (when following-p
12235 ;; Show next sibling, or heading below text
12236 (save-excursion
12237 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12238 (org-flag-heading nil))))
12239 (when siblings-p (org-show-siblings))
12240 (when hierarchy-p
12241 ;; show all higher headings, possibly with siblings
12242 (save-excursion
12243 (while (and (condition-case nil
12244 (progn (org-up-heading-all 1) t)
12245 (error nil))
12246 (not (bobp)))
12247 (org-flag-heading nil)
12248 (when siblings-p (org-show-siblings))))))))
12250 (defvar org-reveal-start-hook nil
12251 "Hook run before revealing a location.")
12253 (defun org-reveal (&optional siblings)
12254 "Show current entry, hierarchy above it, and the following headline.
12255 This can be used to show a consistent set of context around locations
12256 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12257 not t for the search context.
12259 With optional argument SIBLINGS, on each level of the hierarchy all
12260 siblings are shown. This repairs the tree structure to what it would
12261 look like when opened with hierarchical calls to `org-cycle'.
12262 With double optional argument \\[universal-argument] \\[universal-argument], \
12263 go to the parent and show the
12264 entire tree."
12265 (interactive "P")
12266 (run-hooks 'org-reveal-start-hook)
12267 (let ((org-show-hierarchy-above t)
12268 (org-show-following-heading t)
12269 (org-show-siblings (if siblings t org-show-siblings)))
12270 (org-show-context nil))
12271 (when (equal siblings '(16))
12272 (save-excursion
12273 (when (org-up-heading-safe)
12274 (org-show-subtree)
12275 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12277 (defun org-highlight-new-match (beg end)
12278 "Highlight from BEG to END and mark the highlight is an occur headline."
12279 (let ((ov (make-overlay beg end)))
12280 (overlay-put ov 'face 'secondary-selection)
12281 (overlay-put ov 'org-type 'org-occur)
12282 (push ov org-occur-highlights)))
12284 (defun org-remove-occur-highlights (&optional beg end noremove)
12285 "Remove the occur highlights from the buffer.
12286 BEG and END are ignored. If NOREMOVE is nil, remove this function
12287 from the `before-change-functions' in the current buffer."
12288 (interactive)
12289 (unless org-inhibit-highlight-removal
12290 (mapc 'delete-overlay org-occur-highlights)
12291 (setq org-occur-highlights nil)
12292 (setq org-occur-parameters nil)
12293 (unless noremove
12294 (remove-hook 'before-change-functions
12295 'org-remove-occur-highlights 'local))))
12297 ;;;; Priorities
12299 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12300 "Regular expression matching the priority indicator.")
12302 (defvar org-remove-priority-next-time nil)
12304 (defun org-priority-up ()
12305 "Increase the priority of the current item."
12306 (interactive)
12307 (org-priority 'up))
12309 (defun org-priority-down ()
12310 "Decrease the priority of the current item."
12311 (interactive)
12312 (org-priority 'down))
12314 (defun org-priority (&optional action)
12315 "Change the priority of an item by ARG.
12316 ACTION can be `set', `up', `down', or a character."
12317 (interactive)
12318 (unless org-enable-priority-commands
12319 (error "Priority commands are disabled"))
12320 (setq action (or action 'set))
12321 (let (current new news have remove)
12322 (save-excursion
12323 (org-back-to-heading t)
12324 (if (looking-at org-priority-regexp)
12325 (setq current (string-to-char (match-string 2))
12326 have t))
12327 (cond
12328 ((eq action 'remove)
12329 (setq remove t new ?\ ))
12330 ((or (eq action 'set)
12331 (if (featurep 'xemacs) (characterp action) (integerp action)))
12332 (if (not (eq action 'set))
12333 (setq new action)
12334 (message "Priority %c-%c, SPC to remove: "
12335 org-highest-priority org-lowest-priority)
12336 (save-match-data
12337 (setq new (read-char-exclusive))))
12338 (if (and (= (upcase org-highest-priority) org-highest-priority)
12339 (= (upcase org-lowest-priority) org-lowest-priority))
12340 (setq new (upcase new)))
12341 (cond ((equal new ?\ ) (setq remove t))
12342 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12343 (error "Priority must be between `%c' and `%c'"
12344 org-highest-priority org-lowest-priority))))
12345 ((eq action 'up)
12346 (setq new (if have
12347 (1- current) ; normal cycling
12348 ;; last priority was empty
12349 (if (eq last-command this-command)
12350 org-lowest-priority ; wrap around empty to lowest
12351 ;; default
12352 (if org-priority-start-cycle-with-default
12353 org-default-priority
12354 (1- org-default-priority))))))
12355 ((eq action 'down)
12356 (setq new (if have
12357 (1+ current) ; normal cycling
12358 ;; last priority was empty
12359 (if (eq last-command this-command)
12360 org-highest-priority ; wrap around empty to highest
12361 ;; default
12362 (if org-priority-start-cycle-with-default
12363 org-default-priority
12364 (1+ org-default-priority))))))
12365 (t (error "Invalid action")))
12366 (if (or (< (upcase new) org-highest-priority)
12367 (> (upcase new) org-lowest-priority))
12368 (if (and (memq action '(up down))
12369 (not have) (not (eq last-command this-command)))
12370 ;; `new' is from default priority
12371 (error
12372 "The default can not be set, see `org-default-priority' why")
12373 ;; normal cycling: `new' is beyond highest/lowest priority
12374 ;; and is wrapped around to the empty priority
12375 (setq remove t)))
12376 (setq news (format "%c" new))
12377 (if have
12378 (if remove
12379 (replace-match "" t t nil 1)
12380 (replace-match news t t nil 2))
12381 (if remove
12382 (error "No priority cookie found in line")
12383 (let ((case-fold-search nil))
12384 (looking-at org-todo-line-regexp))
12385 (if (match-end 2)
12386 (progn
12387 (goto-char (match-end 2))
12388 (insert " [#" news "]"))
12389 (goto-char (match-beginning 3))
12390 (insert "[#" news "] "))))
12391 (org-preserve-lc (org-set-tags nil 'align)))
12392 (if remove
12393 (message "Priority removed")
12394 (message "Priority of current item set to %s" news))))
12396 (defun org-get-priority (s)
12397 "Find priority cookie and return priority."
12398 (if (functionp org-get-priority-function)
12399 (funcall org-get-priority-function)
12400 (save-match-data
12401 (if (not (string-match org-priority-regexp s))
12402 (* 1000 (- org-lowest-priority org-default-priority))
12403 (* 1000 (- org-lowest-priority
12404 (string-to-char (match-string 2 s))))))))
12406 ;;;; Tags
12408 (defvar org-agenda-archives-mode)
12409 (defvar org-map-continue-from nil
12410 "Position from where mapping should continue.
12411 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
12413 (defvar org-scanner-tags nil
12414 "The current tag list while the tags scanner is running.")
12415 (defvar org-trust-scanner-tags nil
12416 "Should `org-get-tags-at' use the tags for the scanner.
12417 This is for internal dynamical scoping only.
12418 When this is non-nil, the function `org-get-tags-at' will return the value
12419 of `org-scanner-tags' instead of building the list by itself. This
12420 can lead to large speed-ups when the tags scanner is used in a file with
12421 many entries, and when the list of tags is retrieved, for example to
12422 obtain a list of properties. Building the tags list for each entry in such
12423 a file becomes an N^2 operation - but with this variable set, it scales
12424 as N.")
12426 (defun org-scan-tags (action matcher &optional todo-only)
12427 "Scan headline tags with inheritance and produce output ACTION.
12429 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12430 or `agenda' to produce an entry list for an agenda view. It can also be
12431 a Lisp form or a function that should be called at each matched headline, in
12432 this case the return value is a list of all return values from these calls.
12434 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12435 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12436 only lines with a TODO keyword are included in the output."
12437 (require 'org-agenda)
12438 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
12439 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12440 (org-re
12441 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12442 (props (list 'face 'default
12443 'done-face 'org-agenda-done
12444 'undone-face 'default
12445 'mouse-face 'highlight
12446 'org-not-done-regexp org-not-done-regexp
12447 'org-todo-regexp org-todo-regexp
12448 'help-echo
12449 (format "mouse-2 or RET jump to org file %s"
12450 (abbreviate-file-name
12451 (or (buffer-file-name (buffer-base-buffer))
12452 (buffer-name (buffer-base-buffer)))))))
12453 (case-fold-search nil)
12454 (org-map-continue-from nil)
12455 lspos tags tags-list
12456 (tags-alist (list (cons 0 org-file-tags)))
12457 (llast 0) rtn rtn1 level category i txt
12458 todo marker entry priority)
12459 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12460 (setq action (list 'lambda nil action)))
12461 (save-excursion
12462 (goto-char (point-min))
12463 (when (eq action 'sparse-tree)
12464 (org-overview)
12465 (org-remove-occur-highlights))
12466 (while (re-search-forward re nil t)
12467 (catch :skip
12468 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12469 tags (if (match-end 4) (org-match-string-no-properties 4)))
12470 (goto-char (setq lspos (match-beginning 0)))
12471 (setq level (org-reduced-level (funcall outline-level))
12472 category (org-get-category))
12473 (setq i llast llast level)
12474 ;; remove tag lists from same and sublevels
12475 (while (>= i level)
12476 (when (setq entry (assoc i tags-alist))
12477 (setq tags-alist (delete entry tags-alist)))
12478 (setq i (1- i)))
12479 ;; add the next tags
12480 (when tags
12481 (setq tags (org-split-string tags ":")
12482 tags-alist
12483 (cons (cons level tags) tags-alist)))
12484 ;; compile tags for current headline
12485 (setq tags-list
12486 (if org-use-tag-inheritance
12487 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12488 tags)
12489 org-scanner-tags tags-list)
12490 (when org-use-tag-inheritance
12491 (setcdr (car tags-alist)
12492 (mapcar (lambda (x)
12493 (setq x (copy-sequence x))
12494 (org-add-prop-inherited x))
12495 (cdar tags-alist))))
12496 (when (and tags org-use-tag-inheritance
12497 (or (not (eq t org-use-tag-inheritance))
12498 org-tags-exclude-from-inheritance))
12499 ;; selective inheritance, remove uninherited ones
12500 (setcdr (car tags-alist)
12501 (org-remove-uninherited-tags (cdar tags-alist))))
12502 (when (and
12504 ;; eval matcher only when the todo condition is OK
12505 (and (or (not todo-only) (member todo org-not-done-keywords))
12506 (let ((case-fold-search t)) (eval matcher)))
12508 ;; Call the skipper, but return t if it does not skip,
12509 ;; so that the `and' form continues evaluating
12510 (progn
12511 (unless (eq action 'sparse-tree) (org-agenda-skip))
12514 ;; Check if timestamps are deselecting this entry
12515 (or (not todo-only)
12516 (and (member todo org-not-done-keywords)
12517 (or (not org-agenda-tags-todo-honor-ignore-options)
12518 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12520 ;; Extra check for the archive tag
12521 ;; FIXME: Does the skipper already do this????
12523 (not (member org-archive-tag tags-list))
12524 ;; we have an archive tag, should we use this anyway?
12525 (or (not org-agenda-skip-archived-trees)
12526 (and (eq action 'agenda) org-agenda-archives-mode))))
12528 ;; select this headline
12530 (cond
12531 ((eq action 'sparse-tree)
12532 (and org-highlight-sparse-tree-matches
12533 (org-get-heading) (match-end 0)
12534 (org-highlight-new-match
12535 (match-beginning 0) (match-beginning 1)))
12536 (org-show-context 'tags-tree))
12537 ((eq action 'agenda)
12538 (setq txt (org-format-agenda-item
12540 (concat
12541 (if (eq org-tags-match-list-sublevels 'indented)
12542 (make-string (1- level) ?.) "")
12543 (org-get-heading))
12544 category
12545 tags-list
12547 priority (org-get-priority txt))
12548 (goto-char lspos)
12549 (setq marker (org-agenda-new-marker))
12550 (org-add-props txt props
12551 'org-marker marker 'org-hd-marker marker 'org-category category
12552 'todo-state todo
12553 'priority priority 'type "tagsmatch")
12554 (push txt rtn))
12555 ((functionp action)
12556 (setq org-map-continue-from nil)
12557 (save-excursion
12558 (setq rtn1 (funcall action))
12559 (push rtn1 rtn)))
12560 (t (error "Invalid action")))
12562 ;; if we are to skip sublevels, jump to end of subtree
12563 (unless org-tags-match-list-sublevels
12564 (org-end-of-subtree t)
12565 (backward-char 1))))
12566 ;; Get the correct position from where to continue
12567 (if org-map-continue-from
12568 (goto-char org-map-continue-from)
12569 (and (= (point) lspos) (end-of-line 1)))))
12570 (when (and (eq action 'sparse-tree)
12571 (not org-sparse-tree-open-archived-trees))
12572 (org-hide-archived-subtrees (point-min) (point-max)))
12573 (nreverse rtn)))
12575 (defun org-remove-uninherited-tags (tags)
12576 "Remove all tags that are not inherited from the list TAGS."
12577 (cond
12578 ((eq org-use-tag-inheritance t)
12579 (if org-tags-exclude-from-inheritance
12580 (org-delete-all org-tags-exclude-from-inheritance tags)
12581 tags))
12582 ((not org-use-tag-inheritance) nil)
12583 ((stringp org-use-tag-inheritance)
12584 (delq nil (mapcar
12585 (lambda (x)
12586 (if (and (string-match org-use-tag-inheritance x)
12587 (not (member x org-tags-exclude-from-inheritance)))
12588 x nil))
12589 tags)))
12590 ((listp org-use-tag-inheritance)
12591 (delq nil (mapcar
12592 (lambda (x)
12593 (if (member x org-use-tag-inheritance) x nil))
12594 tags)))))
12596 (defvar todo-only) ;; dynamically scoped
12598 (defun org-match-sparse-tree (&optional todo-only match)
12599 "Create a sparse tree according to tags string MATCH.
12600 MATCH can contain positive and negative selection of tags, like
12601 \"+WORK+URGENT-WITHBOSS\".
12602 If optional argument TODO-ONLY is non-nil, only select lines that are
12603 also TODO lines."
12604 (interactive "P")
12605 (org-prepare-agenda-buffers (list (current-buffer)))
12606 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12608 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12610 (defvar org-cached-props nil)
12611 (defun org-cached-entry-get (pom property)
12612 (if (or (eq t org-use-property-inheritance)
12613 (and (stringp org-use-property-inheritance)
12614 (string-match org-use-property-inheritance property))
12615 (and (listp org-use-property-inheritance)
12616 (member property org-use-property-inheritance)))
12617 ;; Caching is not possible, check it directly
12618 (org-entry-get pom property 'inherit)
12619 ;; Get all properties, so that we can do complicated checks easily
12620 (cdr (assoc property (or org-cached-props
12621 (setq org-cached-props
12622 (org-entry-properties pom)))))))
12624 (defun org-global-tags-completion-table (&optional files)
12625 "Return the list of all tags in all agenda buffer/files.
12626 Optional FILES argument is a list of files to which can be used
12627 instead of the agenda files."
12628 (save-excursion
12629 (org-uniquify
12630 (delq nil
12631 (apply 'append
12632 (mapcar
12633 (lambda (file)
12634 (set-buffer (find-file-noselect file))
12635 (append (org-get-buffer-tags)
12636 (mapcar (lambda (x) (if (stringp (car-safe x))
12637 (list (car-safe x)) nil))
12638 org-tag-alist)))
12639 (if (and files (car files))
12640 files
12641 (org-agenda-files))))))))
12643 (defun org-make-tags-matcher (match)
12644 "Create the TAGS/TODO matcher form for the selection string MATCH."
12645 ;; todo-only is scoped dynamically into this function, and the function
12646 ;; may change it if the matcher asks for it.
12647 (unless match
12648 ;; Get a new match request, with completion
12649 (let ((org-last-tags-completion-table
12650 (org-global-tags-completion-table)))
12651 (setq match (org-completing-read-no-i
12652 "Match: " 'org-tags-completion-function nil nil nil
12653 'org-tags-history))))
12655 ;; Parse the string and create a lisp form
12656 (let ((match0 match)
12657 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
12658 minus tag mm
12659 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12660 orterms term orlist re-p str-p level-p level-op time-p
12661 prop-p pn pv po gv rest)
12662 (if (string-match "/+" match)
12663 ;; match contains also a todo-matching request
12664 (progn
12665 (setq tagsmatch (substring match 0 (match-beginning 0))
12666 todomatch (substring match (match-end 0)))
12667 (if (string-match "^!" todomatch)
12668 (setq todo-only t todomatch (substring todomatch 1)))
12669 (if (string-match "^\\s-*$" todomatch)
12670 (setq todomatch nil)))
12671 ;; only matching tags
12672 (setq tagsmatch match todomatch nil))
12674 ;; Make the tags matcher
12675 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12676 (setq tagsmatcher t)
12677 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12678 (while (setq term (pop orterms))
12679 (while (and (equal (substring term -1) "\\") orterms)
12680 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12681 (while (string-match re term)
12682 (setq rest (substring term (match-end 0))
12683 minus (and (match-end 1)
12684 (equal (match-string 1 term) "-"))
12685 tag (save-match-data (replace-regexp-in-string
12686 "\\\\-" "-"
12687 (match-string 2 term)))
12688 re-p (equal (string-to-char tag) ?{)
12689 level-p (match-end 4)
12690 prop-p (match-end 5)
12691 mm (cond
12692 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12693 (level-p
12694 (setq level-op (org-op-to-function (match-string 3 term)))
12695 `(,level-op level ,(string-to-number
12696 (match-string 4 term))))
12697 (prop-p
12698 (setq pn (match-string 5 term)
12699 po (match-string 6 term)
12700 pv (match-string 7 term)
12701 re-p (equal (string-to-char pv) ?{)
12702 str-p (equal (string-to-char pv) ?\")
12703 time-p (save-match-data
12704 (string-match "^\"[[<].*[]>]\"$" pv))
12705 pv (if (or re-p str-p) (substring pv 1 -1) pv))
12706 (if time-p (setq pv (org-matcher-time pv)))
12707 (setq po (org-op-to-function po (if time-p 'time str-p)))
12708 (cond
12709 ((equal pn "CATEGORY")
12710 (setq gv '(get-text-property (point) 'org-category)))
12711 ((equal pn "TODO")
12712 (setq gv 'todo))
12714 (setq gv `(org-cached-entry-get nil ,pn))))
12715 (if re-p
12716 (if (eq po 'org<>)
12717 `(not (string-match ,pv (or ,gv "")))
12718 `(string-match ,pv (or ,gv "")))
12719 (if str-p
12720 `(,po (or ,gv "") ,pv)
12721 `(,po (string-to-number (or ,gv ""))
12722 ,(string-to-number pv) ))))
12723 (t `(member ,tag tags-list)))
12724 mm (if minus (list 'not mm) mm)
12725 term rest)
12726 (push mm tagsmatcher))
12727 (push (if (> (length tagsmatcher) 1)
12728 (cons 'and tagsmatcher)
12729 (car tagsmatcher))
12730 orlist)
12731 (setq tagsmatcher nil))
12732 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
12733 (setq tagsmatcher
12734 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
12735 ;; Make the todo matcher
12736 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
12737 (setq todomatcher t)
12738 (setq orterms (org-split-string todomatch "|") orlist nil)
12739 (while (setq term (pop orterms))
12740 (while (string-match re term)
12741 (setq minus (and (match-end 1)
12742 (equal (match-string 1 term) "-"))
12743 kwd (match-string 2 term)
12744 re-p (equal (string-to-char kwd) ?{)
12745 term (substring term (match-end 0))
12746 mm (if re-p
12747 `(string-match ,(substring kwd 1 -1) todo)
12748 (list 'equal 'todo kwd))
12749 mm (if minus (list 'not mm) mm))
12750 (push mm todomatcher))
12751 (push (if (> (length todomatcher) 1)
12752 (cons 'and todomatcher)
12753 (car todomatcher))
12754 orlist)
12755 (setq todomatcher nil))
12756 (setq todomatcher (if (> (length orlist) 1)
12757 (cons 'or orlist) (car orlist))))
12759 ;; Return the string and lisp forms of the matcher
12760 (setq matcher (if todomatcher
12761 (list 'and tagsmatcher todomatcher)
12762 tagsmatcher))
12763 (cons match0 matcher)))
12765 (defun org-op-to-function (op &optional stringp)
12766 "Turn an operator into the appropriate function."
12767 (setq op
12768 (cond
12769 ((equal op "<" ) '(< string< org-time<))
12770 ((equal op ">" ) '(> org-string> org-time>))
12771 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
12772 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
12773 ((member op '("=" "==")) '(= string= org-time=))
12774 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
12775 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
12777 (defun org<> (a b) (not (= a b)))
12778 (defun org-string<= (a b) (or (string= a b) (string< a b)))
12779 (defun org-string>= (a b) (not (string< a b)))
12780 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
12781 (defun org-string<> (a b) (not (string= 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) (>= a b)))
12787 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
12788 (defun org-2ft (s)
12789 "Convert S to a floating point time.
12790 If S is already a number, just return it. If it is a string, parse
12791 it as a time string and apply `float-time' to it. If S is nil, just return 0."
12792 (cond
12793 ((numberp s) s)
12794 ((stringp s)
12795 (condition-case nil
12796 (float-time (apply 'encode-time (org-parse-time-string s)))
12797 (error 0.)))
12798 (t 0.)))
12800 (defun org-time-today ()
12801 "Time in seconds today at 0:00.
12802 Returns the float number of seconds since the beginning of the
12803 epoch to the beginning of today (00:00)."
12804 (float-time (apply 'encode-time
12805 (append '(0 0 0) (nthcdr 3 (decode-time))))))
12807 (defun org-matcher-time (s)
12808 "Interpret a time comparison value."
12809 (save-match-data
12810 (cond
12811 ((string= s "<now>") (float-time))
12812 ((string= s "<today>") (org-time-today))
12813 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
12814 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
12815 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
12816 (+ (org-time-today)
12817 (* (string-to-number (match-string 1 s))
12818 (cdr (assoc (match-string 2 s)
12819 '(("d" . 86400.0) ("w" . 604800.0)
12820 ("m" . 2678400.0) ("y" . 31557600.0)))))))
12821 (t (org-2ft s)))))
12823 (defun org-match-any-p (re list)
12824 "Does re match any element of list?"
12825 (setq list (mapcar (lambda (x) (string-match re x)) list))
12826 (delq nil list))
12828 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
12829 (defvar org-tags-overlay (make-overlay 1 1))
12830 (org-detach-overlay org-tags-overlay)
12832 (defun org-get-local-tags-at (&optional pos)
12833 "Get a list of tags defined in the current headline."
12834 (org-get-tags-at pos 'local))
12836 (defun org-get-local-tags ()
12837 "Get a list of tags defined in the current headline."
12838 (org-get-tags-at nil 'local))
12840 (defun org-get-tags-at (&optional pos local)
12841 "Get a list of all headline tags applicable at POS.
12842 POS defaults to point. If tags are inherited, the list contains
12843 the targets in the same sequence as the headlines appear, i.e.
12844 the tags of the current headline come last.
12845 When LOCAL is non-nil, only return tags from the current headline,
12846 ignore inherited ones."
12847 (interactive)
12848 (if (and org-trust-scanner-tags
12849 (or (not pos) (equal pos (point)))
12850 (not local))
12851 org-scanner-tags
12852 (let (tags ltags lastpos parent)
12853 (save-excursion
12854 (save-restriction
12855 (widen)
12856 (goto-char (or pos (point)))
12857 (save-match-data
12858 (catch 'done
12859 (condition-case nil
12860 (progn
12861 (org-back-to-heading t)
12862 (while (not (equal lastpos (point)))
12863 (setq lastpos (point))
12864 (when (looking-at
12865 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
12866 (setq ltags (org-split-string
12867 (org-match-string-no-properties 1) ":"))
12868 (when parent
12869 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
12870 (setq tags (append
12871 (if parent
12872 (org-remove-uninherited-tags ltags)
12873 ltags)
12874 tags)))
12875 (or org-use-tag-inheritance (throw 'done t))
12876 (if local (throw 'done t))
12877 (or (org-up-heading-safe) (error nil))
12878 (setq parent t)))
12879 (error nil)))))
12880 (if local
12881 tags
12882 (append (org-remove-uninherited-tags org-file-tags) tags))))))
12884 (defun org-add-prop-inherited (s)
12885 (add-text-properties 0 (length s) '(inherited t) s)
12888 (defun org-toggle-tag (tag &optional onoff)
12889 "Toggle the tag TAG for the current line.
12890 If ONOFF is `on' or `off', don't toggle but set to this state."
12891 (let (res current)
12892 (save-excursion
12893 (org-back-to-heading t)
12894 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
12895 (point-at-eol) t)
12896 (progn
12897 (setq current (match-string 1))
12898 (replace-match ""))
12899 (setq current ""))
12900 (setq current (nreverse (org-split-string current ":")))
12901 (cond
12902 ((eq onoff 'on)
12903 (setq res t)
12904 (or (member tag current) (push tag current)))
12905 ((eq onoff 'off)
12906 (or (not (member tag current)) (setq current (delete tag current))))
12907 (t (if (member tag current)
12908 (setq current (delete tag current))
12909 (setq res t)
12910 (push tag current))))
12911 (end-of-line 1)
12912 (if current
12913 (progn
12914 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
12915 (org-set-tags nil t))
12916 (delete-horizontal-space))
12917 (run-hooks 'org-after-tags-change-hook))
12918 res))
12920 (defun org-align-tags-here (to-col)
12921 ;; Assumes that this is a headline
12922 (let ((pos (point)) (col (current-column)) ncol tags-l p)
12923 (beginning-of-line 1)
12924 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
12925 (< pos (match-beginning 2)))
12926 (progn
12927 (setq tags-l (- (match-end 2) (match-beginning 2)))
12928 (goto-char (match-beginning 1))
12929 (insert " ")
12930 (delete-region (point) (1+ (match-beginning 2)))
12931 (setq ncol (max (1+ (current-column))
12932 (1+ col)
12933 (if (> to-col 0)
12934 to-col
12935 (- (abs to-col) tags-l))))
12936 (setq p (point))
12937 (insert (make-string (- ncol (current-column)) ?\ ))
12938 (setq ncol (current-column))
12939 (when indent-tabs-mode (tabify p (point-at-eol)))
12940 (org-move-to-column (min ncol col) t))
12941 (goto-char pos))))
12943 (defun org-set-tags-command (&optional arg just-align)
12944 "Call the set-tags command for the current entry."
12945 (interactive "P")
12946 (if (org-on-heading-p)
12947 (org-set-tags arg just-align)
12948 (save-excursion
12949 (org-back-to-heading t)
12950 (org-set-tags arg just-align))))
12952 (defun org-set-tags-to (data)
12953 "Set the tags of the current entry to DATA, replacing the current tags.
12954 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
12955 If DATA is nil or the empty string, any tags will be removed."
12956 (interactive "sTags: ")
12957 (setq data
12958 (cond
12959 ((eq data nil) "")
12960 ((equal data "") "")
12961 ((stringp data)
12962 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
12963 ":"))
12964 ((listp data)
12965 (concat ":" (mapconcat 'identity data ":") ":"))
12966 (t nil)))
12967 (when data
12968 (save-excursion
12969 (org-back-to-heading t)
12970 (when (looking-at org-complex-heading-regexp)
12971 (if (match-end 5)
12972 (progn
12973 (goto-char (match-beginning 5))
12974 (insert data)
12975 (delete-region (point) (point-at-eol))
12976 (org-set-tags nil 'align))
12977 (goto-char (point-at-eol))
12978 (insert " " data)
12979 (org-set-tags nil 'align)))
12980 (beginning-of-line 1)
12981 (if (looking-at ".*?\\([ \t]+\\)$")
12982 (delete-region (match-beginning 1) (match-end 1))))))
12984 (defun org-align-all-tags ()
12985 "Align the tags i all headings."
12986 (interactive)
12987 (save-excursion
12988 (or (ignore-errors (org-back-to-heading t))
12989 (outline-next-heading))
12990 (if (org-on-heading-p)
12991 (org-set-tags t)
12992 (message "No headings"))))
12994 (defvar org-indent-indentation-per-level)
12995 (defun org-set-tags (&optional arg just-align)
12996 "Set the tags for the current headline.
12997 With prefix ARG, realign all tags in headings in the current buffer."
12998 (interactive "P")
12999 (let* ((re (concat "^" outline-regexp))
13000 (current (org-get-tags-string))
13001 (col (current-column))
13002 (org-setting-tags t)
13003 table current-tags inherited-tags ; computed below when needed
13004 tags p0 c0 c1 rpl di tc level)
13005 (if arg
13006 (save-excursion
13007 (goto-char (point-min))
13008 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13009 (while (re-search-forward re nil t)
13010 (org-set-tags nil t)
13011 (end-of-line 1)))
13012 (message "All tags realigned to column %d" org-tags-column))
13013 (if just-align
13014 (setq tags current)
13015 ;; Get a new set of tags from the user
13016 (save-excursion
13017 (setq table (append org-tag-persistent-alist
13018 (or org-tag-alist (org-get-buffer-tags))
13019 (and
13020 org-complete-tags-always-offer-all-agenda-tags
13021 (org-global-tags-completion-table
13022 (org-agenda-files))))
13023 org-last-tags-completion-table table
13024 current-tags (org-split-string current ":")
13025 inherited-tags (nreverse
13026 (nthcdr (length current-tags)
13027 (nreverse (org-get-tags-at))))
13028 tags
13029 (if (or (eq t org-use-fast-tag-selection)
13030 (and org-use-fast-tag-selection
13031 (delq nil (mapcar 'cdr table))))
13032 (org-fast-tag-selection
13033 current-tags inherited-tags table
13034 (if org-fast-tag-selection-include-todo
13035 org-todo-key-alist))
13036 (let ((org-add-colon-after-tag-completion t))
13037 (org-trim
13038 (org-icompleting-read "Tags: "
13039 'org-tags-completion-function
13040 nil nil current 'org-tags-history))))))
13041 (while (string-match "[-+&]+" tags)
13042 ;; No boolean logic, just a list
13043 (setq tags (replace-match ":" t t tags))))
13045 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13047 (if org-tags-sort-function
13048 (setq tags (mapconcat 'identity
13049 (sort (org-split-string
13050 tags (org-re "[^[:alnum:]_@#%]+"))
13051 org-tags-sort-function) ":")))
13053 (if (string-match "\\`[\t ]*\\'" tags)
13054 (setq tags "")
13055 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13056 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13058 ;; Insert new tags at the correct column
13059 (beginning-of-line 1)
13060 (setq level (or (and (looking-at org-outline-regexp)
13061 (- (match-end 0) (point) 1))
13063 (cond
13064 ((and (equal current "") (equal tags "")))
13065 ((re-search-forward
13066 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13067 (point-at-eol) t)
13068 (if (equal tags "")
13069 (setq rpl "")
13070 (goto-char (match-beginning 0))
13071 (setq c0 (current-column)
13072 ;; compute offset for the case of org-indent-mode active
13073 di (if org-indent-mode
13074 (* (1- org-indent-indentation-per-level) (1- level))
13076 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13077 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13078 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13079 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13080 (replace-match rpl t t)
13081 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13082 tags)
13083 (t (error "Tags alignment failed")))
13084 (org-move-to-column col)
13085 (unless just-align
13086 (run-hooks 'org-after-tags-change-hook)))))
13088 (defun org-change-tag-in-region (beg end tag off)
13089 "Add or remove TAG for each entry in the region.
13090 This works in the agenda, and also in an org-mode buffer."
13091 (interactive
13092 (list (region-beginning) (region-end)
13093 (let ((org-last-tags-completion-table
13094 (if (org-mode-p)
13095 (org-get-buffer-tags)
13096 (org-global-tags-completion-table))))
13097 (org-icompleting-read
13098 "Tag: " 'org-tags-completion-function nil nil nil
13099 'org-tags-history))
13100 (progn
13101 (message "[s]et or [r]emove? ")
13102 (equal (read-char-exclusive) ?r))))
13103 (if (fboundp 'deactivate-mark) (deactivate-mark))
13104 (let ((agendap (equal major-mode 'org-agenda-mode))
13105 l1 l2 m buf pos newhead (cnt 0))
13106 (goto-char end)
13107 (setq l2 (1- (org-current-line)))
13108 (goto-char beg)
13109 (setq l1 (org-current-line))
13110 (loop for l from l1 to l2 do
13111 (org-goto-line l)
13112 (setq m (get-text-property (point) 'org-hd-marker))
13113 (when (or (and (org-mode-p) (org-on-heading-p))
13114 (and agendap m))
13115 (setq buf (if agendap (marker-buffer m) (current-buffer))
13116 pos (if agendap m (point)))
13117 (with-current-buffer buf
13118 (save-excursion
13119 (save-restriction
13120 (goto-char pos)
13121 (setq cnt (1+ cnt))
13122 (org-toggle-tag tag (if off 'off 'on))
13123 (setq newhead (org-get-heading)))))
13124 (and agendap (org-agenda-change-all-lines newhead m))))
13125 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13127 (defun org-tags-completion-function (string predicate &optional flag)
13128 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13129 (confirm (lambda (x) (stringp (car x)))))
13130 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13131 (setq s1 (match-string 1 string)
13132 s2 (match-string 2 string))
13133 (setq s1 "" s2 string))
13134 (cond
13135 ((eq flag nil)
13136 ;; try completion
13137 (setq rtn (try-completion s2 ctable confirm))
13138 (if (stringp rtn)
13139 (setq rtn
13140 (concat s1 s2 (substring rtn (length s2))
13141 (if (and org-add-colon-after-tag-completion
13142 (assoc rtn ctable))
13143 ":" ""))))
13144 rtn)
13145 ((eq flag t)
13146 ;; all-completions
13147 (all-completions s2 ctable confirm)
13149 ((eq flag 'lambda)
13150 ;; exact match?
13151 (assoc s2 ctable)))
13154 (defun org-fast-tag-insert (kwd tags face &optional end)
13155 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13156 (insert (format "%-12s" (concat kwd ":"))
13157 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13158 (or end "")))
13160 (defun org-fast-tag-show-exit (flag)
13161 (save-excursion
13162 (org-goto-line 3)
13163 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13164 (replace-match ""))
13165 (when flag
13166 (end-of-line 1)
13167 (org-move-to-column (- (window-width) 19) t)
13168 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13170 (defun org-set-current-tags-overlay (current prefix)
13171 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13172 (if (featurep 'xemacs)
13173 (org-overlay-display org-tags-overlay (concat prefix s)
13174 'secondary-selection)
13175 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13176 (org-overlay-display org-tags-overlay (concat prefix s)))))
13178 (defvar org-last-tag-selection-key nil)
13179 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13180 "Fast tag selection with single keys.
13181 CURRENT is the current list of tags in the headline, INHERITED is the
13182 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13183 possibly with grouping information. TODO-TABLE is a similar table with
13184 TODO keywords, should these have keys assigned to them.
13185 If the keys are nil, a-z are automatically assigned.
13186 Returns the new tags string, or nil to not change the current settings."
13187 (let* ((fulltable (append table todo-table))
13188 (maxlen (apply 'max (mapcar
13189 (lambda (x)
13190 (if (stringp (car x)) (string-width (car x)) 0))
13191 fulltable)))
13192 (buf (current-buffer))
13193 (expert (eq org-fast-tag-selection-single-key 'expert))
13194 (buffer-tags nil)
13195 (fwidth (+ maxlen 3 1 3))
13196 (ncol (/ (- (window-width) 4) fwidth))
13197 (i-face 'org-done)
13198 (c-face 'org-todo)
13199 tg cnt e c char c1 c2 ntable tbl rtn
13200 ov-start ov-end ov-prefix
13201 (exit-after-next org-fast-tag-selection-single-key)
13202 (done-keywords org-done-keywords)
13203 groups ingroup)
13204 (save-excursion
13205 (beginning-of-line 1)
13206 (if (looking-at
13207 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13208 (setq ov-start (match-beginning 1)
13209 ov-end (match-end 1)
13210 ov-prefix "")
13211 (setq ov-start (1- (point-at-eol))
13212 ov-end (1+ ov-start))
13213 (skip-chars-forward "^\n\r")
13214 (setq ov-prefix
13215 (concat
13216 (buffer-substring (1- (point)) (point))
13217 (if (> (current-column) org-tags-column)
13219 (make-string (- org-tags-column (current-column)) ?\ ))))))
13220 (move-overlay org-tags-overlay ov-start ov-end)
13221 (save-window-excursion
13222 (if expert
13223 (set-buffer (get-buffer-create " *Org tags*"))
13224 (delete-other-windows)
13225 (split-window-vertically)
13226 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13227 (erase-buffer)
13228 (org-set-local 'org-done-keywords done-keywords)
13229 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13230 (org-fast-tag-insert "Current" current c-face "\n\n")
13231 (org-fast-tag-show-exit exit-after-next)
13232 (org-set-current-tags-overlay current ov-prefix)
13233 (setq tbl fulltable char ?a cnt 0)
13234 (while (setq e (pop tbl))
13235 (cond
13236 ((equal (car e) :startgroup)
13237 (push '() groups) (setq ingroup t)
13238 (when (not (= cnt 0))
13239 (setq cnt 0)
13240 (insert "\n"))
13241 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13242 ((equal (car e) :endgroup)
13243 (setq ingroup nil cnt 0)
13244 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13245 ((equal e '(:newline))
13246 (when (not (= cnt 0))
13247 (setq cnt 0)
13248 (insert "\n")
13249 (setq e (car tbl))
13250 (while (equal (car tbl) '(:newline))
13251 (insert "\n")
13252 (setq tbl (cdr tbl)))))
13254 (setq tg (copy-sequence (car e)) c2 nil)
13255 (if (cdr e)
13256 (setq c (cdr e))
13257 ;; automatically assign a character.
13258 (setq c1 (string-to-char
13259 (downcase (substring
13260 tg (if (= (string-to-char tg) ?@) 1 0)))))
13261 (if (or (rassoc c1 ntable) (rassoc c1 table))
13262 (while (or (rassoc char ntable) (rassoc char table))
13263 (setq char (1+ char)))
13264 (setq c2 c1))
13265 (setq c (or c2 char)))
13266 (if ingroup (push tg (car groups)))
13267 (setq tg (org-add-props tg nil 'face
13268 (cond
13269 ((not (assoc tg table))
13270 (org-get-todo-face tg))
13271 ((member tg current) c-face)
13272 ((member tg inherited) i-face)
13273 (t nil))))
13274 (if (and (= cnt 0) (not ingroup)) (insert " "))
13275 (insert "[" c "] " tg (make-string
13276 (- fwidth 4 (length tg)) ?\ ))
13277 (push (cons tg c) ntable)
13278 (when (= (setq cnt (1+ cnt)) ncol)
13279 (insert "\n")
13280 (if ingroup (insert " "))
13281 (setq cnt 0)))))
13282 (setq ntable (nreverse ntable))
13283 (insert "\n")
13284 (goto-char (point-min))
13285 (if (not expert) (org-fit-window-to-buffer))
13286 (setq rtn
13287 (catch 'exit
13288 (while t
13289 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13290 (if (not groups) "no " "")
13291 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13292 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13293 (setq org-last-tag-selection-key c)
13294 (cond
13295 ((= c ?\r) (throw 'exit t))
13296 ((= c ?!)
13297 (setq groups (not groups))
13298 (goto-char (point-min))
13299 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13300 ((= c ?\C-c)
13301 (if (not expert)
13302 (org-fast-tag-show-exit
13303 (setq exit-after-next (not exit-after-next)))
13304 (setq expert nil)
13305 (delete-other-windows)
13306 (set-window-buffer (split-window-vertically) " *Org tags*")
13307 (org-switch-to-buffer-other-window " *Org tags*")
13308 (org-fit-window-to-buffer)))
13309 ((or (= c ?\C-g)
13310 (and (= c ?q) (not (rassoc c ntable))))
13311 (org-detach-overlay org-tags-overlay)
13312 (setq quit-flag t))
13313 ((= c ?\ )
13314 (setq current nil)
13315 (if exit-after-next (setq exit-after-next 'now)))
13316 ((= c ?\t)
13317 (condition-case nil
13318 (setq tg (org-icompleting-read
13319 "Tag: "
13320 (or buffer-tags
13321 (with-current-buffer buf
13322 (org-get-buffer-tags)))))
13323 (quit (setq tg "")))
13324 (when (string-match "\\S-" tg)
13325 (add-to-list 'buffer-tags (list tg))
13326 (if (member tg current)
13327 (setq current (delete tg current))
13328 (push tg current)))
13329 (if exit-after-next (setq exit-after-next 'now)))
13330 ((setq e (rassoc c todo-table) tg (car e))
13331 (with-current-buffer buf
13332 (save-excursion (org-todo tg)))
13333 (if exit-after-next (setq exit-after-next 'now)))
13334 ((setq e (rassoc c ntable) tg (car e))
13335 (if (member tg current)
13336 (setq current (delete tg current))
13337 (loop for g in groups do
13338 (if (member tg g)
13339 (mapc (lambda (x)
13340 (setq current (delete x current)))
13341 g)))
13342 (push tg current))
13343 (if exit-after-next (setq exit-after-next 'now))))
13345 ;; Create a sorted list
13346 (setq current
13347 (sort current
13348 (lambda (a b)
13349 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13350 (if (eq exit-after-next 'now) (throw 'exit t))
13351 (goto-char (point-min))
13352 (beginning-of-line 2)
13353 (delete-region (point) (point-at-eol))
13354 (org-fast-tag-insert "Current" current c-face)
13355 (org-set-current-tags-overlay current ov-prefix)
13356 (while (re-search-forward
13357 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13358 (setq tg (match-string 1))
13359 (add-text-properties
13360 (match-beginning 1) (match-end 1)
13361 (list 'face
13362 (cond
13363 ((member tg current) c-face)
13364 ((member tg inherited) i-face)
13365 (t (get-text-property (match-beginning 1) 'face))))))
13366 (goto-char (point-min)))))
13367 (org-detach-overlay org-tags-overlay)
13368 (if rtn
13369 (mapconcat 'identity current ":")
13370 nil))))
13372 (defun org-get-tags-string ()
13373 "Get the TAGS string in the current headline."
13374 (unless (org-on-heading-p t)
13375 (error "Not on a heading"))
13376 (save-excursion
13377 (beginning-of-line 1)
13378 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13379 (org-match-string-no-properties 1)
13380 "")))
13382 (defun org-get-tags ()
13383 "Get the list of tags specified in the current headline."
13384 (org-split-string (org-get-tags-string) ":"))
13386 (defun org-get-buffer-tags ()
13387 "Get a table of all tags used in the buffer, for completion."
13388 (let (tags)
13389 (save-excursion
13390 (goto-char (point-min))
13391 (while (re-search-forward
13392 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13393 (when (equal (char-after (point-at-bol 0)) ?*)
13394 (mapc (lambda (x) (add-to-list 'tags x))
13395 (org-split-string (org-match-string-no-properties 1) ":")))))
13396 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13397 (mapcar 'list tags)))
13399 ;;;; The mapping API
13401 ;;;###autoload
13402 (defun org-map-entries (func &optional match scope &rest skip)
13403 "Call FUNC at each headline selected by MATCH in SCOPE.
13405 FUNC is a function or a lisp form. The function will be called without
13406 arguments, with the cursor positioned at the beginning of the headline.
13407 The return values of all calls to the function will be collected and
13408 returned as a list.
13410 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13411 does not need to preserve point. After evaluation, the cursor will be
13412 moved to the end of the line (presumably of the headline of the
13413 processed entry) and search continues from there. Under some
13414 circumstances, this may not produce the wanted results. For example,
13415 if you have removed (e.g. archived) the current (sub)tree it could
13416 mean that the next entry will be skipped entirely. In such cases, you
13417 can specify the position from where search should continue by making
13418 FUNC set the variable `org-map-continue-from' to the desired buffer
13419 position.
13421 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13422 Only headlines that are matched by this query will be considered during
13423 the iteration. When MATCH is nil or t, all headlines will be
13424 visited by the iteration.
13426 SCOPE determines the scope of this command. It can be any of:
13428 nil The current buffer, respecting the restriction if any
13429 tree The subtree started with the entry at point
13430 file The current buffer, without restriction
13431 file-with-archives
13432 The current buffer, and any archives associated with it
13433 agenda All agenda files
13434 agenda-with-archives
13435 All agenda files with any archive files associated with them
13436 \(file1 file2 ...)
13437 If this is a list, all files in the list will be scanned
13439 The remaining args are treated as settings for the skipping facilities of
13440 the scanner. The following items can be given here:
13442 archive skip trees with the archive tag.
13443 comment skip trees with the COMMENT keyword
13444 function or Emacs Lisp form:
13445 will be used as value for `org-agenda-skip-function', so whenever
13446 the function returns t, FUNC will not be called for that
13447 entry and search will continue from the point where the
13448 function leaves it.
13450 If your function needs to retrieve the tags including inherited tags
13451 at the *current* entry, you can use the value of the variable
13452 `org-scanner-tags' which will be much faster than getting the value
13453 with `org-get-tags-at'. If your function gets properties with
13454 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13455 to t around the call to `org-entry-properties' to get the same speedup.
13456 Note that if your function moves around to retrieve tags and properties at
13457 a *different* entry, you cannot use these techniques."
13458 (let* ((org-agenda-archives-mode nil) ; just to make sure
13459 (org-agenda-skip-archived-trees (memq 'archive skip))
13460 (org-agenda-skip-comment-trees (memq 'comment skip))
13461 (org-agenda-skip-function
13462 (car (org-delete-all '(comment archive) skip)))
13463 (org-tags-match-list-sublevels t)
13464 matcher file res
13465 org-todo-keywords-for-agenda
13466 org-done-keywords-for-agenda
13467 org-todo-keyword-alist-for-agenda
13468 org-drawers-for-agenda
13469 org-tag-alist-for-agenda)
13471 (cond
13472 ((eq match t) (setq matcher t))
13473 ((eq match nil) (setq matcher t))
13474 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13476 (save-excursion
13477 (save-restriction
13478 (when (eq scope 'tree)
13479 (org-back-to-heading t)
13480 (org-narrow-to-subtree)
13481 (setq scope nil))
13483 (if (not scope)
13484 (progn
13485 (org-prepare-agenda-buffers
13486 (list (buffer-file-name (current-buffer))))
13487 (setq res (org-scan-tags func matcher)))
13488 ;; Get the right scope
13489 (cond
13490 ((and scope (listp scope) (symbolp (car scope)))
13491 (setq scope (eval scope)))
13492 ((eq scope 'agenda)
13493 (setq scope (org-agenda-files t)))
13494 ((eq scope 'agenda-with-archives)
13495 (setq scope (org-agenda-files t))
13496 (setq scope (org-add-archive-files scope)))
13497 ((eq scope 'file)
13498 (setq scope (list (buffer-file-name))))
13499 ((eq scope 'file-with-archives)
13500 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13501 (org-prepare-agenda-buffers scope)
13502 (while (setq file (pop scope))
13503 (with-current-buffer (org-find-base-buffer-visiting file)
13504 (save-excursion
13505 (save-restriction
13506 (widen)
13507 (goto-char (point-min))
13508 (setq res (append res (org-scan-tags func matcher))))))))))
13509 res))
13511 ;;;; Properties
13513 ;;; Setting and retrieving properties
13515 (defconst org-special-properties
13516 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13517 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13518 "The special properties valid in Org-mode.
13520 These are properties that are not defined in the property drawer,
13521 but in some other way.")
13523 (defconst org-default-properties
13524 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13525 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13526 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13527 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13528 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13529 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13530 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13531 "Some properties that are used by Org-mode for various purposes.
13532 Being in this list makes sure that they are offered for completion.")
13534 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13535 "Regular expression matching the first line of a property drawer.")
13537 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13538 "Regular expression matching the last line of a property drawer.")
13540 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13541 "Regular expression matching the first line of a property drawer.")
13543 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13544 "Regular expression matching the first line of a property drawer.")
13546 (defconst org-property-drawer-re
13547 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13548 org-property-end-re "\\)\n?")
13549 "Matches an entire property drawer.")
13551 (defconst org-clock-drawer-re
13552 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13553 org-property-end-re "\\)\n?")
13554 "Matches an entire clock drawer.")
13556 (defsubst org-re-property (property)
13557 "Return a regexp matching PROPERTY.
13558 Match group 1 will be set to the value "
13559 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
13561 (defun org-property-action ()
13562 "Do an action on properties."
13563 (interactive)
13564 (let (c)
13565 (org-at-property-p)
13566 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13567 (setq c (read-char-exclusive))
13568 (cond
13569 ((equal c ?s)
13570 (call-interactively 'org-set-property))
13571 ((equal c ?d)
13572 (call-interactively 'org-delete-property))
13573 ((equal c ?D)
13574 (call-interactively 'org-delete-property-globally))
13575 ((equal c ?c)
13576 (call-interactively 'org-compute-property-at-point))
13577 (t (error "No such property action %c" c)))))
13579 (defun org-set-effort (&optional value)
13580 "Set the effort property of the current entry.
13581 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13582 allowed value."
13583 (interactive "P")
13584 (if (equal value 0) (setq value 10))
13585 (let* ((completion-ignore-case t)
13586 (prop org-effort-property)
13587 (cur (org-entry-get nil prop))
13588 (allowed (org-property-get-allowed-values nil prop 'table))
13589 (existing (mapcar 'list (org-property-values prop)))
13591 (val (cond
13592 ((stringp value) value)
13593 ((and allowed (integerp value))
13594 (or (car (nth (1- value) allowed))
13595 (car (org-last allowed))))
13596 (allowed
13597 (message "Select 1-9,0, [RET%s]: %s"
13598 (if cur (concat "=" cur) "")
13599 (mapconcat 'car allowed " "))
13600 (setq rpl (read-char-exclusive))
13601 (if (equal rpl ?\r)
13603 (setq rpl (- rpl ?0))
13604 (if (equal rpl 0) (setq rpl 10))
13605 (if (and (> rpl 0) (<= rpl (length allowed)))
13606 (car (nth (1- rpl) allowed))
13607 (org-completing-read "Effort: " allowed nil))))
13609 (let (org-completion-use-ido org-completion-use-iswitchb)
13610 (org-completing-read
13611 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13612 (concat "[" cur "]") "")
13613 ": ")
13614 existing nil nil "" nil cur))))))
13615 (unless (equal (org-entry-get nil prop) val)
13616 (org-entry-put nil prop val))
13617 (message "%s is now %s" prop val)))
13619 (defun org-at-property-p ()
13620 "Is cursor inside a property drawer?"
13621 (save-excursion
13622 (beginning-of-line 1)
13623 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13624 (save-match-data ;; Used by calling procedures
13625 (let ((p (point))
13626 (range (unless (org-before-first-heading-p)
13627 (org-get-property-block))))
13628 (and range (<= (car range) p) (< p (cdr range))))))))
13630 (defun org-get-property-block (&optional beg end force)
13631 "Return the (beg . end) range of the body of the property drawer.
13632 BEG and END can be beginning and end of subtree, if not given
13633 they will be found.
13634 If the drawer does not exist and FORCE is non-nil, create the drawer."
13635 (catch 'exit
13636 (save-excursion
13637 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13638 (end (or end (progn (outline-next-heading) (point)))))
13639 (goto-char beg)
13640 (if (re-search-forward org-property-start-re end t)
13641 (setq beg (1+ (match-end 0)))
13642 (if force
13643 (save-excursion
13644 (org-insert-property-drawer)
13645 (setq end (progn (outline-next-heading) (point))))
13646 (throw 'exit nil))
13647 (goto-char beg)
13648 (if (re-search-forward org-property-start-re end t)
13649 (setq beg (1+ (match-end 0)))))
13650 (if (re-search-forward org-property-end-re end t)
13651 (setq end (match-beginning 0))
13652 (or force (throw 'exit nil))
13653 (goto-char beg)
13654 (setq end beg)
13655 (org-indent-line-function)
13656 (insert ":END:\n"))
13657 (cons beg end)))))
13659 (defun org-entry-properties (&optional pom which specific)
13660 "Get all properties of the entry at point-or-marker POM.
13661 This includes the TODO keyword, the tags, time strings for deadline,
13662 scheduled, and clocking, and any additional properties defined in the
13663 entry. The return value is an alist, keys may occur multiple times
13664 if the property key was used several times.
13665 POM may also be nil, in which case the current entry is used.
13666 If WHICH is nil or `all', get all properties. If WHICH is
13667 `special' or `standard', only get that subclass. If WHICH
13668 is a string only get exactly this property. SPECIFIC can be a string, the
13669 specific property we are interested in. Specifying it can speed
13670 things up because then unnecessary parsing is avoided."
13671 (setq which (or which 'all))
13672 (org-with-point-at pom
13673 (let ((clockstr (substring org-clock-string 0 -1))
13674 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13675 (case-fold-search nil)
13676 beg end range props sum-props key key1 value string clocksum)
13677 (save-excursion
13678 (when (condition-case nil
13679 (and (org-mode-p) (org-back-to-heading t))
13680 (error nil))
13681 (setq beg (point))
13682 (setq sum-props (get-text-property (point) 'org-summaries))
13683 (setq clocksum (get-text-property (point) :org-clock-minutes))
13684 (outline-next-heading)
13685 (setq end (point))
13686 (when (memq which '(all special))
13687 ;; Get the special properties, like TODO and tags
13688 (goto-char beg)
13689 (when (and (or (not specific) (string= specific "TODO"))
13690 (looking-at org-todo-line-regexp) (match-end 2))
13691 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13692 (when (and (or (not specific) (string= specific "PRIORITY"))
13693 (looking-at org-priority-regexp))
13694 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13695 (when (or (not specific) (string= specific "FILE"))
13696 (push (cons "FILE" buffer-file-name) props))
13697 (when (and (or (not specific) (string= specific "TAGS"))
13698 (setq value (org-get-tags-string))
13699 (string-match "\\S-" value))
13700 (push (cons "TAGS" value) props))
13701 (when (and (or (not specific) (string= specific "ALLTAGS"))
13702 (setq value (org-get-tags-at)))
13703 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
13704 ":"))
13705 props))
13706 (when (or (not specific) (string= specific "BLOCKED"))
13707 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
13708 (when (or (not specific)
13709 (member specific
13710 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
13711 "TIMESTAMP" "TIMESTAMP_IA")))
13712 (catch 'match
13713 (while (re-search-forward org-maybe-keyword-time-regexp end t)
13714 (setq key (if (match-end 1)
13715 (substring (org-match-string-no-properties 1)
13716 0 -1))
13717 string (if (equal key clockstr)
13718 (org-no-properties
13719 (org-trim
13720 (buffer-substring
13721 (match-beginning 3) (goto-char
13722 (point-at-eol)))))
13723 (substring (org-match-string-no-properties 3)
13724 1 -1)))
13725 ;; Get the correct property name from the key. This is
13726 ;; necessary if the user has configured time keywords.
13727 (setq key1 (concat key ":"))
13728 (cond
13729 ((not key)
13730 (setq key
13731 (if (= (char-after (match-beginning 3)) ?\[)
13732 "TIMESTAMP_IA" "TIMESTAMP")))
13733 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
13734 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
13735 ((equal key1 org-closed-string) (setq key "CLOSED"))
13736 ((equal key1 org-clock-string) (setq key "CLOCK")))
13737 (if (and specific (equal key specific) (not (equal key "CLOCK")))
13738 (progn
13739 (push (cons key string) props)
13740 ;; no need to search further if match is found
13741 (throw 'match t))
13742 (when (or (equal key "CLOCK") (not (assoc key props)))
13743 (push (cons key string) props))))))
13746 (when (memq which '(all standard))
13747 ;; Get the standard properties, like :PROP: ...
13748 (setq range (org-get-property-block beg end))
13749 (when range
13750 (goto-char (car range))
13751 (while (re-search-forward
13752 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
13753 (cdr range) t)
13754 (setq key (org-match-string-no-properties 1)
13755 value (org-trim (or (org-match-string-no-properties 2) "")))
13756 (unless (member key excluded)
13757 (push (cons key (or value "")) props)))))
13758 (if clocksum
13759 (push (cons "CLOCKSUM"
13760 (org-columns-number-to-string (/ (float clocksum) 60.)
13761 'add_times))
13762 props))
13763 (unless (assoc "CATEGORY" props)
13764 (push (cons "CATEGORY" (org-get-category)) props))
13765 (append sum-props (nreverse props)))))))
13767 (defun org-entry-get (pom property &optional inherit literal-nil)
13768 "Get value of PROPERTY for entry at point-or-marker POM.
13769 If INHERIT is non-nil and the entry does not have the property,
13770 then also check higher levels of the hierarchy.
13771 If INHERIT is the symbol `selective', use inheritance only if the setting
13772 in `org-use-property-inheritance' selects PROPERTY for inheritance.
13773 If the property is present but empty, the return value is the empty string.
13774 If the property is not present at all, nil is returned.
13776 If LITERAL-NIL is set, return the string value \"nil\" as a string,
13777 do not interpret it as the list atom nil. This is used for inheritance
13778 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
13779 (org-with-point-at pom
13780 (if (and inherit (if (eq inherit 'selective)
13781 (org-property-inherit-p property)
13783 (org-entry-get-with-inheritance property literal-nil)
13784 (if (member property org-special-properties)
13785 ;; We need a special property. Use `org-entry-properties' to
13786 ;; retrieve it, but specify the wanted property
13787 (cdr (assoc property (org-entry-properties nil 'special property)))
13788 (let ((range (unless (org-before-first-heading-p)
13789 (org-get-property-block))))
13790 (if (and range
13791 (goto-char (car range))
13792 (re-search-forward
13793 (org-re-property property)
13794 (cdr range) t))
13795 ;; Found the property, return it.
13796 (if (match-end 1)
13797 (if literal-nil
13798 (org-match-string-no-properties 1)
13799 (org-not-nil (org-match-string-no-properties 1)))
13800 "")))))))
13802 (defun org-property-or-variable-value (var &optional inherit)
13803 "Check if there is a property fixing the value of VAR.
13804 If yes, return this value. If not, return the current value of the variable."
13805 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13806 (if (and prop (stringp prop) (string-match "\\S-" prop))
13807 (read prop)
13808 (symbol-value var))))
13810 (defun org-entry-delete (pom property)
13811 "Delete the property PROPERTY from entry at point-or-marker POM."
13812 (org-with-point-at pom
13813 (if (member property org-special-properties)
13814 nil ; cannot delete these properties.
13815 (let ((range (org-get-property-block)))
13816 (if (and range
13817 (goto-char (car range))
13818 (re-search-forward
13819 (org-re-property property)
13820 (cdr range) t))
13821 (progn
13822 (delete-region (match-beginning 0) (1+ (point-at-eol)))
13824 nil)))))
13826 ;; Multi-values properties are properties that contain multiple values
13827 ;; These values are assumed to be single words, separated by whitespace.
13828 (defun org-entry-add-to-multivalued-property (pom property value)
13829 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
13830 (let* ((old (org-entry-get pom property))
13831 (values (and old (org-split-string old "[ \t]"))))
13832 (setq value (org-entry-protect-space value))
13833 (unless (member value values)
13834 (setq values (cons value values))
13835 (org-entry-put pom property
13836 (mapconcat 'identity values " ")))))
13838 (defun org-entry-remove-from-multivalued-property (pom property value)
13839 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
13840 (let* ((old (org-entry-get pom property))
13841 (values (and old (org-split-string old "[ \t]"))))
13842 (setq value (org-entry-protect-space value))
13843 (when (member value values)
13844 (setq values (delete value values))
13845 (org-entry-put pom property
13846 (mapconcat 'identity values " ")))))
13848 (defun org-entry-member-in-multivalued-property (pom property value)
13849 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
13850 (let* ((old (org-entry-get pom property))
13851 (values (and old (org-split-string old "[ \t]"))))
13852 (setq value (org-entry-protect-space value))
13853 (member value values)))
13855 (defun org-entry-get-multivalued-property (pom property)
13856 "Return a list of values in a multivalued property."
13857 (let* ((value (org-entry-get pom property))
13858 (values (and value (org-split-string value "[ \t]"))))
13859 (mapcar 'org-entry-restore-space values)))
13861 (defun org-entry-put-multivalued-property (pom property &rest values)
13862 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
13863 VALUES should be a list of strings. Spaces will be protected."
13864 (org-entry-put pom property
13865 (mapconcat 'org-entry-protect-space values " "))
13866 (let* ((value (org-entry-get pom property))
13867 (values (and value (org-split-string value "[ \t]"))))
13868 (mapcar 'org-entry-restore-space values)))
13870 (defun org-entry-protect-space (s)
13871 "Protect spaces and newline in string S."
13872 (while (string-match " " s)
13873 (setq s (replace-match "%20" t t s)))
13874 (while (string-match "\n" s)
13875 (setq s (replace-match "%0A" t t s)))
13878 (defun org-entry-restore-space (s)
13879 "Restore spaces and newline in string S."
13880 (while (string-match "%20" s)
13881 (setq s (replace-match " " t t s)))
13882 (while (string-match "%0A" s)
13883 (setq s (replace-match "\n" t t s)))
13886 (defvar org-entry-property-inherited-from (make-marker)
13887 "Marker pointing to the entry from where a property was inherited.
13888 Each call to `org-entry-get-with-inheritance' will set this marker to the
13889 location of the entry where the inheritance search matched. If there was
13890 no match, the marker will point nowhere.
13891 Note that also `org-entry-get' calls this function, if the INHERIT flag
13892 is set.")
13894 (defun org-entry-get-with-inheritance (property &optional literal-nil)
13895 "Get entry property, and search higher levels if not present.
13896 The search will stop at the first ancestor which has the property defined.
13897 If the value found is \"nil\", return nil to show that the property
13898 should be considered as undefined (this is the meaning of nil here).
13899 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
13900 (move-marker org-entry-property-inherited-from nil)
13901 (let (tmp)
13902 (unless (org-before-first-heading-p)
13903 (save-excursion
13904 (save-restriction
13905 (widen)
13906 (catch 'ex
13907 (while t
13908 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
13909 (org-back-to-heading t)
13910 (move-marker org-entry-property-inherited-from (point))
13911 (throw 'ex tmp))
13912 (or (org-up-heading-safe) (throw 'ex nil)))))))
13913 (setq tmp (or tmp
13914 (cdr (assoc property org-file-properties))
13915 (cdr (assoc property org-global-properties))
13916 (cdr (assoc property org-global-properties-fixed))))
13917 (if literal-nil tmp (org-not-nil tmp))))
13919 (defvar org-property-changed-functions nil
13920 "Hook called when the value of a property has changed.
13921 Each hook function should accept two arguments, the name of the property
13922 and the new value.")
13924 (defun org-entry-put (pom property value)
13925 "Set PROPERTY to VALUE for entry at point-or-marker POM."
13926 (org-with-point-at pom
13927 (org-back-to-heading t)
13928 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
13929 range)
13930 (cond
13931 ((equal property "TODO")
13932 (when (and (stringp value) (string-match "\\S-" value)
13933 (not (member value org-todo-keywords-1)))
13934 (error "\"%s\" is not a valid TODO state" value))
13935 (if (or (not value)
13936 (not (string-match "\\S-" value)))
13937 (setq value 'none))
13938 (org-todo value)
13939 (org-set-tags nil 'align))
13940 ((equal property "PRIORITY")
13941 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
13942 (string-to-char value) ?\ ))
13943 (org-set-tags nil 'align))
13944 ((equal property "SCHEDULED")
13945 (if (re-search-forward org-scheduled-time-regexp end t)
13946 (cond
13947 ((eq value 'earlier) (org-timestamp-change -1 'day))
13948 ((eq value 'later) (org-timestamp-change 1 'day))
13949 (t (call-interactively 'org-schedule)))
13950 (call-interactively 'org-schedule)))
13951 ((equal property "DEADLINE")
13952 (if (re-search-forward org-deadline-time-regexp end t)
13953 (cond
13954 ((eq value 'earlier) (org-timestamp-change -1 'day))
13955 ((eq value 'later) (org-timestamp-change 1 'day))
13956 (t (call-interactively 'org-deadline)))
13957 (call-interactively 'org-deadline)))
13958 ((member property org-special-properties)
13959 (error "The %s property can not yet be set with `org-entry-put'"
13960 property))
13961 (t ; a non-special property
13962 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
13963 (setq range (org-get-property-block beg end 'force))
13964 (goto-char (car range))
13965 (if (re-search-forward
13966 (org-re-property property) (cdr range) t)
13967 (progn
13968 (delete-region (match-beginning 0) (match-end 0))
13969 (goto-char (match-beginning 0)))
13970 (goto-char (cdr range))
13971 (insert "\n")
13972 (backward-char 1)
13973 (org-indent-line-function))
13974 (insert ":" property ":")
13975 (and value (insert " " value))
13976 (org-indent-line-function)))))
13977 (run-hook-with-args 'org-property-changed-functions property value)))
13979 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
13980 "Get all property keys in the current buffer.
13981 With INCLUDE-SPECIALS, also list the special properties that reflect things
13982 like tags and TODO state.
13983 With INCLUDE-DEFAULTS, also include properties that has special meaning
13984 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
13985 and others.
13986 With INCLUDE-COLUMNS, also include property names given in COLUMN
13987 formats in the current buffer."
13988 (let (rtn range cfmt s p)
13989 (save-excursion
13990 (save-restriction
13991 (widen)
13992 (goto-char (point-min))
13993 (while (re-search-forward org-property-start-re nil t)
13994 (setq range (org-get-property-block))
13995 (goto-char (car range))
13996 (while (re-search-forward
13997 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
13998 (cdr range) t)
13999 (add-to-list 'rtn (org-match-string-no-properties 1)))
14000 (outline-next-heading))))
14002 (when include-specials
14003 (setq rtn (append org-special-properties rtn)))
14005 (when include-defaults
14006 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14007 (add-to-list 'rtn org-effort-property))
14009 (when include-columns
14010 (save-excursion
14011 (save-restriction
14012 (widen)
14013 (goto-char (point-min))
14014 (while (re-search-forward
14015 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14016 nil t)
14017 (setq cfmt (match-string 2) s 0)
14018 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14019 cfmt s)
14020 (setq s (match-end 0)
14021 p (match-string 1 cfmt))
14022 (unless (or (equal p "ITEM")
14023 (member p org-special-properties))
14024 (add-to-list 'rtn (match-string 1 cfmt))))))))
14026 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14028 (defun org-property-values (key)
14029 "Return a list of all values of property KEY in the current buffer."
14030 (save-excursion
14031 (save-restriction
14032 (widen)
14033 (goto-char (point-min))
14034 (let ((re (org-re-property key))
14035 values)
14036 (while (re-search-forward re nil t)
14037 (add-to-list 'values (org-trim (match-string 1))))
14038 (delete "" values)))))
14040 (defun org-insert-property-drawer ()
14041 "Insert a property drawer into the current entry."
14042 (interactive)
14043 (org-back-to-heading t)
14044 (looking-at outline-regexp)
14045 (let ((indent (if org-adapt-indentation
14046 (- (match-end 0)(match-beginning 0))
14048 (beg (point))
14049 (re (concat "^[ \t]*" org-keyword-time-regexp))
14050 end hiddenp)
14051 (outline-next-heading)
14052 (setq end (point))
14053 (goto-char beg)
14054 (while (re-search-forward re end t))
14055 (setq hiddenp (outline-invisible-p))
14056 (end-of-line 1)
14057 (and (equal (char-after) ?\n) (forward-char 1))
14058 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14059 (if (member (match-string 1) '("CLOCK:" ":END:"))
14060 ;; just skip this line
14061 (beginning-of-line 2)
14062 ;; Drawer start, find the end
14063 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14064 (beginning-of-line 1)))
14065 (org-skip-over-state-notes)
14066 (skip-chars-backward " \t\n\r")
14067 (if (eq (char-before) ?*) (forward-char 1))
14068 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14069 (beginning-of-line 0)
14070 (org-indent-to-column indent)
14071 (beginning-of-line 2)
14072 (org-indent-to-column indent)
14073 (beginning-of-line 0)
14074 (if hiddenp
14075 (save-excursion
14076 (org-back-to-heading t)
14077 (hide-entry))
14078 (org-flag-drawer t))))
14080 (defvar org-property-set-functions-alist nil
14081 "Property set function alist.
14082 Each entry should have the following format:
14084 (PROPERTY . READ-FUNCTION)
14086 The read function will be called with the same argument as
14087 `org-completing-read'.")
14089 (defun org-set-property-function (property)
14090 "Get the function that should be used to set PROPERTY.
14091 This is computed according to `org-property-set-functions-alist'."
14092 (or (cdr (assoc property org-property-set-functions-alist))
14093 'org-completing-read))
14095 (defun org-read-property-value (property)
14096 "Read PROPERTY value from user."
14097 (let* ((completion-ignore-case t)
14098 (allowed (org-property-get-allowed-values nil property 'table))
14099 (cur (org-entry-get nil property))
14100 (prompt (concat property " value"
14101 (if (and cur (string-match "\\S-" cur))
14102 (concat " [" cur "]") "") ": "))
14103 (set-function (org-set-property-function property))
14104 (val (if allowed
14105 (funcall set-function prompt allowed nil
14106 (not (get-text-property 0 'org-unrestricted
14107 (caar allowed))))
14108 (let (org-completion-use-ido org-completion-use-iswitchb)
14109 (funcall set-function prompt
14110 (mapcar 'list (org-property-values property))
14111 nil nil "" nil cur)))))
14112 (if (equal val "")
14114 val)))
14116 (defun org-read-property-name ()
14117 "Read a property name."
14118 (let* ((completion-ignore-case t)
14119 (keys (org-buffer-property-keys nil t t))
14120 (default-prop (or (save-excursion
14121 (save-match-data
14122 (beginning-of-line)
14123 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14124 (null (string= (match-string 1) "END"))
14125 (match-string 1))))
14126 org-last-set-property))
14127 (property (org-icompleting-read
14128 (concat "Property"
14129 (if default-prop (concat " [" default-prop "]") "")
14130 ": ")
14131 (mapcar 'list keys)
14132 nil nil nil nil
14133 default-prop
14135 (if (member property keys)
14136 property
14137 (or (cdr (assoc (downcase property)
14138 (mapcar (lambda (x) (cons (downcase x) x))
14139 keys)))
14140 property))))
14142 (defvar org-last-set-property nil)
14143 (defun org-set-property (property value)
14144 "In the current entry, set PROPERTY to VALUE.
14145 When called interactively, this will prompt for a property name, offering
14146 completion on existing and default properties. And then it will prompt
14147 for a value, offering completion either on allowed values (via an inherited
14148 xxx_ALL property) or on existing values in other instances of this property
14149 in the current file."
14150 (interactive (list nil nil))
14151 (let* ((property (or property (org-read-property-name)))
14152 (value (or value (org-read-property-value property))))
14153 (setq org-last-set-property property)
14154 (unless (equal (org-entry-get nil property) value)
14155 (org-entry-put nil property value))))
14157 (defun org-delete-property (property)
14158 "In the current entry, delete PROPERTY."
14159 (interactive
14160 (let* ((completion-ignore-case t)
14161 (prop (org-icompleting-read "Property: "
14162 (org-entry-properties nil 'standard))))
14163 (list prop)))
14164 (message "Property %s %s" property
14165 (if (org-entry-delete nil property)
14166 "deleted"
14167 "was not present in the entry")))
14169 (defun org-delete-property-globally (property)
14170 "Remove PROPERTY globally, from all entries."
14171 (interactive
14172 (let* ((completion-ignore-case t)
14173 (prop (org-icompleting-read
14174 "Globally remove property: "
14175 (mapcar 'list (org-buffer-property-keys)))))
14176 (list prop)))
14177 (save-excursion
14178 (save-restriction
14179 (widen)
14180 (goto-char (point-min))
14181 (let ((cnt 0))
14182 (while (re-search-forward
14183 (org-re-property property)
14184 nil t)
14185 (setq cnt (1+ cnt))
14186 (replace-match ""))
14187 (message "Property \"%s\" removed from %d entries" property cnt)))))
14189 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14191 (defun org-compute-property-at-point ()
14192 "Compute the property at point.
14193 This looks for an enclosing column format, extracts the operator and
14194 then applies it to the property in the column format's scope."
14195 (interactive)
14196 (unless (org-at-property-p)
14197 (error "Not at a property"))
14198 (let ((prop (org-match-string-no-properties 2)))
14199 (org-columns-get-format-and-top-level)
14200 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14201 (error "No operator defined for property %s" prop))
14202 (org-columns-compute prop)))
14204 (defvar org-property-allowed-value-functions nil
14205 "Hook for functions supplying allowed values for a specific property.
14206 The functions must take a single argument, the name of the property, and
14207 return a flat list of allowed values. If \":ETC\" is one of
14208 the values, this means that these values are intended as defaults for
14209 completion, but that other values should be allowed too.
14210 The functions must return nil if they are not responsible for this
14211 property.")
14213 (defun org-property-get-allowed-values (pom property &optional table)
14214 "Get allowed values for the property PROPERTY.
14215 When TABLE is non-nil, return an alist that can directly be used for
14216 completion."
14217 (let (vals)
14218 (cond
14219 ((equal property "TODO")
14220 (setq vals (org-with-point-at pom
14221 (append org-todo-keywords-1 '("")))))
14222 ((equal property "PRIORITY")
14223 (let ((n org-lowest-priority))
14224 (while (>= n org-highest-priority)
14225 (push (char-to-string n) vals)
14226 (setq n (1- n)))))
14227 ((member property org-special-properties))
14228 ((setq vals (run-hook-with-args-until-success
14229 'org-property-allowed-value-functions property)))
14231 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14232 (when (and vals (string-match "\\S-" vals))
14233 (setq vals (car (read-from-string (concat "(" vals ")"))))
14234 (setq vals (mapcar (lambda (x)
14235 (cond ((stringp x) x)
14236 ((numberp x) (number-to-string x))
14237 ((symbolp x) (symbol-name x))
14238 (t "???")))
14239 vals)))))
14240 (when (member ":ETC" vals)
14241 (setq vals (remove ":ETC" vals))
14242 (org-add-props (car vals) '(org-unrestricted t)))
14243 (if table (mapcar 'list vals) vals)))
14245 (defun org-property-previous-allowed-value (&optional previous)
14246 "Switch to the next allowed value for this property."
14247 (interactive)
14248 (org-property-next-allowed-value t))
14250 (defun org-property-next-allowed-value (&optional previous)
14251 "Switch to the next allowed value for this property."
14252 (interactive)
14253 (unless (org-at-property-p)
14254 (error "Not at a property"))
14255 (let* ((key (match-string 2))
14256 (value (match-string 3))
14257 (allowed (or (org-property-get-allowed-values (point) key)
14258 (and (member value '("[ ]" "[-]" "[X]"))
14259 '("[ ]" "[X]"))))
14260 nval)
14261 (unless allowed
14262 (error "Allowed values for this property have not been defined"))
14263 (if previous (setq allowed (reverse allowed)))
14264 (if (member value allowed)
14265 (setq nval (car (cdr (member value allowed)))))
14266 (setq nval (or nval (car allowed)))
14267 (if (equal nval value)
14268 (error "Only one allowed value for this property"))
14269 (org-at-property-p)
14270 (replace-match (concat " :" key ": " nval) t t)
14271 (org-indent-line-function)
14272 (beginning-of-line 1)
14273 (skip-chars-forward " \t")
14274 (run-hook-with-args 'org-property-changed-functions key nval)))
14276 (defun org-find-olp (path &optional this-buffer)
14277 "Return a marker pointing to the entry at outline path OLP.
14278 If anything goes wrong, throw an error.
14279 You can wrap this call to catch the error like this:
14281 (condition-case msg
14282 (org-mobile-locate-entry (match-string 4))
14283 (error (nth 1 msg)))
14285 The return value will then be either a string with the error message,
14286 or a marker if everything is OK.
14288 If THIS-BUFFER is set, the outline path does not contain a file,
14289 only headings."
14290 (let* ((file (if this-buffer buffer-file-name (pop path)))
14291 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14292 (level 1)
14293 (lmin 1)
14294 (lmax 1)
14295 limit re end found pos heading cnt flevel)
14296 (unless buffer (error "File not found :%s" file))
14297 (with-current-buffer buffer
14298 (save-excursion
14299 (save-restriction
14300 (widen)
14301 (setq limit (point-max))
14302 (goto-char (point-min))
14303 (while (setq heading (pop path))
14304 (setq re (format org-complex-heading-regexp-format
14305 (regexp-quote heading)))
14306 (setq cnt 0 pos (point))
14307 (while (re-search-forward re end t)
14308 (setq level (- (match-end 1) (match-beginning 1)))
14309 (if (and (>= level lmin) (<= level lmax))
14310 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14311 (when (= cnt 0) (error "Heading not found on level %d: %s"
14312 lmax heading))
14313 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14314 lmax heading))
14315 (goto-char found)
14316 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14317 (setq end (save-excursion (org-end-of-subtree t t))))
14318 (when (org-on-heading-p)
14319 (move-marker (make-marker) (point))))))))
14321 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14322 "Find node HEADING in BUFFER.
14323 Return a marker to the heading if it was found, or nil if not.
14324 If POS-ONLY is set, return just the position instead of a marker.
14326 The heading text must match exact, but it may have a TODO keyword,
14327 a priority cookie and tags in the standard locations."
14328 (with-current-buffer (or buffer (current-buffer))
14329 (save-excursion
14330 (save-restriction
14331 (widen)
14332 (goto-char (point-min))
14333 (let (case-fold-search)
14334 (if (re-search-forward
14335 (format org-complex-heading-regexp-format
14336 (regexp-quote heading)) nil t)
14337 (if pos-only
14338 (match-beginning 0)
14339 (move-marker (make-marker) (match-beginning 0)))))))))
14341 (defun org-find-exact-heading-in-directory (heading &optional dir)
14342 "Find Org node headline HEADING in all .org files in directory DIR.
14343 When the target headline is found, return a marker to this location."
14344 (let ((files (directory-files (or dir default-directory)
14345 nil "\\`[^.#].*\\.org\\'"))
14346 file visiting m buffer)
14347 (catch 'found
14348 (while (setq file (pop files))
14349 (message "trying %s" file)
14350 (setq visiting (org-find-base-buffer-visiting file))
14351 (setq buffer (or visiting (find-file-noselect file)))
14352 (setq m (org-find-exact-headline-in-buffer
14353 heading buffer))
14354 (when (and (not m) (not visiting)) (kill-buffer buffer))
14355 (and m (throw 'found m))))))
14357 (defun org-find-entry-with-id (ident)
14358 "Locate the entry that contains the ID property with exact value IDENT.
14359 IDENT can be a string, a symbol or a number, this function will search for
14360 the string representation of it.
14361 Return the position where this entry starts, or nil if there is no such entry."
14362 (interactive "sID: ")
14363 (let ((id (cond
14364 ((stringp ident) ident)
14365 ((symbol-name ident) (symbol-name ident))
14366 ((numberp ident) (number-to-string ident))
14367 (t (error "IDENT %s must be a string, symbol or number" ident))))
14368 (case-fold-search nil))
14369 (save-excursion
14370 (save-restriction
14371 (widen)
14372 (goto-char (point-min))
14373 (when (re-search-forward
14374 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14375 nil t)
14376 (org-back-to-heading t)
14377 (point))))))
14379 ;;;; Timestamps
14381 (defvar org-last-changed-timestamp nil)
14382 (defvar org-last-inserted-timestamp nil
14383 "The last time stamp inserted with `org-insert-time-stamp'.")
14384 (defvar org-time-was-given) ; dynamically scoped parameter
14385 (defvar org-end-time-was-given) ; dynamically scoped parameter
14386 (defvar org-ts-what) ; dynamically scoped parameter
14388 (defun org-time-stamp (arg &optional inactive)
14389 "Prompt for a date/time and insert a time stamp.
14390 If the user specifies a time like HH:MM, or if this command is called
14391 with a prefix argument, the time stamp will contain date and time.
14392 Otherwise, only the date will be included. All parts of a date not
14393 specified by the user will be filled in from the current date/time.
14394 So if you press just return without typing anything, the time stamp
14395 will represent the current date/time. If there is already a timestamp
14396 at the cursor, it will be modified."
14397 (interactive "P")
14398 (let* ((ts nil)
14399 (default-time
14400 ;; Default time is either today, or, when entering a range,
14401 ;; the range start.
14402 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14403 (save-excursion
14404 (re-search-backward
14405 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14406 (- (point) 20) t)))
14407 (apply 'encode-time (org-parse-time-string (match-string 1)))
14408 (current-time)))
14409 (default-input (and ts (org-get-compact-tod ts)))
14410 (repeater (save-excursion
14411 (save-match-data
14412 (beginning-of-line)
14413 (when (re-search-forward
14414 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14415 (save-excursion (progn (end-of-line) (point))) t)
14416 (match-string 0)))))
14417 org-time-was-given org-end-time-was-given time)
14418 (cond
14419 ((and (org-at-timestamp-p t)
14420 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14421 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14422 (insert "--")
14423 (setq time (let ((this-command this-command))
14424 (org-read-date arg 'totime nil nil
14425 default-time default-input)))
14426 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14427 ((org-at-timestamp-p t)
14428 (setq time (let ((this-command this-command))
14429 (org-read-date arg 'totime nil nil default-time default-input)))
14430 (when (org-at-timestamp-p t) ; just to get the match data
14431 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14432 (replace-match "")
14433 (setq org-last-changed-timestamp
14434 (org-insert-time-stamp
14435 time (or org-time-was-given arg)
14436 inactive nil nil (list org-end-time-was-given)))
14437 (when repeater (goto-char (1- (point))) (insert " " repeater)
14438 (setq org-last-changed-timestamp
14439 (concat (substring org-last-inserted-timestamp 0 -1)
14440 " " repeater ">"))))
14441 (message "Timestamp updated"))
14443 (setq time (let ((this-command this-command))
14444 (org-read-date arg 'totime nil nil default-time default-input)))
14445 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14446 nil nil (list org-end-time-was-given))))))
14448 ;; FIXME: can we use this for something else, like computing time differences?
14449 (defun org-get-compact-tod (s)
14450 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14451 (let* ((t1 (match-string 1 s))
14452 (h1 (string-to-number (match-string 2 s)))
14453 (m1 (string-to-number (match-string 3 s)))
14454 (t2 (and (match-end 4) (match-string 5 s)))
14455 (h2 (and t2 (string-to-number (match-string 6 s))))
14456 (m2 (and t2 (string-to-number (match-string 7 s))))
14457 dh dm)
14458 (if (not t2)
14460 (setq dh (- h2 h1) dm (- m2 m1))
14461 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14462 (concat t1 "+" (number-to-string dh)
14463 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14465 (defun org-time-stamp-inactive (&optional arg)
14466 "Insert an inactive time stamp.
14467 An inactive time stamp is enclosed in square brackets instead of angle
14468 brackets. It is inactive in the sense that it does not trigger agenda entries,
14469 does not link to the calendar and cannot be changed with the S-cursor keys.
14470 So these are more for recording a certain time/date."
14471 (interactive "P")
14472 (org-time-stamp arg 'inactive))
14474 (defvar org-date-ovl (make-overlay 1 1))
14475 (overlay-put org-date-ovl 'face 'org-warning)
14476 (org-detach-overlay org-date-ovl)
14478 (defvar org-ans1) ; dynamically scoped parameter
14479 (defvar org-ans2) ; dynamically scoped parameter
14481 (defvar org-plain-time-of-day-regexp) ; defined below
14483 (defvar org-overriding-default-time nil) ; dynamically scoped
14484 (defvar org-read-date-overlay nil)
14485 (defvar org-dcst nil) ; dynamically scoped
14486 (defvar org-read-date-history nil)
14487 (defvar org-read-date-final-answer nil)
14488 (defvar org-read-date-analyze-futurep nil)
14489 (defvar org-read-date-analyze-forced-year nil)
14491 (defun org-read-date (&optional with-time to-time from-string prompt
14492 default-time default-input)
14493 "Read a date, possibly a time, and make things smooth for the user.
14494 The prompt will suggest to enter an ISO date, but you can also enter anything
14495 which will at least partially be understood by `parse-time-string'.
14496 Unrecognized parts of the date will default to the current day, month, year,
14497 hour and minute. If this command is called to replace a timestamp at point,
14498 of to enter the second timestamp of a range, the default time is taken
14499 from the existing stamp. Furthermore, the command prefers the future,
14500 so if you are giving a date where the year is not given, and the day-month
14501 combination is already past in the current year, it will assume you
14502 mean next year. For details, see the manual. A few examples:
14504 3-2-5 --> 2003-02-05
14505 feb 15 --> currentyear-02-15
14506 2/15 --> currentyear-02-15
14507 sep 12 9 --> 2009-09-12
14508 12:45 --> today 12:45
14509 22 sept 0:34 --> currentyear-09-22 0:34
14510 12 --> currentyear-currentmonth-12
14511 Fri --> nearest Friday (today or later)
14512 etc.
14514 Furthermore you can specify a relative date by giving, as the *first* thing
14515 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14516 change in days weeks, months, years.
14517 With a single plus or minus, the date is relative to today. With a double
14518 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14519 +4d --> four days from today
14520 +4 --> same as above
14521 +2w --> two weeks from today
14522 ++5 --> five days from default date
14524 The function understands only English month and weekday abbreviations,
14525 but this can be configured with the variables `parse-time-months' and
14526 `parse-time-weekdays'.
14528 While prompting, a calendar is popped up - you can also select the
14529 date with the mouse (button 1). The calendar shows a period of three
14530 months. To scroll it to other months, use the keys `>' and `<'.
14531 If you don't like the calendar, turn it off with
14532 \(setq org-read-date-popup-calendar nil)
14534 With optional argument TO-TIME, the date will immediately be converted
14535 to an internal time.
14536 With an optional argument WITH-TIME, the prompt will suggest to also
14537 insert a time. Note that when WITH-TIME is not set, you can still
14538 enter a time, and this function will inform the calling routine about
14539 this change. The calling routine may then choose to change the format
14540 used to insert the time stamp into the buffer to include the time.
14541 With optional argument FROM-STRING, read from this string instead from
14542 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14543 the time/date that is used for everything that is not specified by the
14544 user."
14545 (require 'parse-time)
14546 (let* ((org-time-stamp-rounding-minutes
14547 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14548 (org-dcst org-display-custom-times)
14549 (ct (org-current-time))
14550 (def (or org-overriding-default-time default-time ct))
14551 (defdecode (decode-time def))
14552 (dummy (progn
14553 (when (< (nth 2 defdecode) org-extend-today-until)
14554 (setcar (nthcdr 2 defdecode) -1)
14555 (setcar (nthcdr 1 defdecode) 59)
14556 (setq def (apply 'encode-time defdecode)
14557 defdecode (decode-time def)))))
14558 (calendar-frame-setup nil)
14559 (calendar-setup nil)
14560 (calendar-move-hook nil)
14561 (calendar-view-diary-initially-flag nil)
14562 (calendar-view-holidays-initially-flag nil)
14563 (timestr (format-time-string
14564 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14565 (prompt (concat (if prompt (concat prompt " ") "")
14566 (format "Date+time [%s]: " timestr)))
14567 ans (org-ans0 "") org-ans1 org-ans2 final)
14569 (cond
14570 (from-string (setq ans from-string))
14571 (org-read-date-popup-calendar
14572 (save-excursion
14573 (save-window-excursion
14574 (calendar)
14575 (unwind-protect
14576 (progn
14577 (calendar-forward-day (- (time-to-days def)
14578 (calendar-absolute-from-gregorian
14579 (calendar-current-date))))
14580 (org-eval-in-calendar nil t)
14581 (let* ((old-map (current-local-map))
14582 (map (copy-keymap calendar-mode-map))
14583 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14584 (org-defkey map (kbd "RET") 'org-calendar-select)
14585 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14586 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14587 (org-defkey minibuffer-local-map [(meta shift left)]
14588 (lambda () (interactive)
14589 (org-eval-in-calendar '(calendar-backward-month 1))))
14590 (org-defkey minibuffer-local-map [(meta shift right)]
14591 (lambda () (interactive)
14592 (org-eval-in-calendar '(calendar-forward-month 1))))
14593 (org-defkey minibuffer-local-map [(meta shift up)]
14594 (lambda () (interactive)
14595 (org-eval-in-calendar '(calendar-backward-year 1))))
14596 (org-defkey minibuffer-local-map [(meta shift down)]
14597 (lambda () (interactive)
14598 (org-eval-in-calendar '(calendar-forward-year 1))))
14599 (org-defkey minibuffer-local-map [?\e (shift left)]
14600 (lambda () (interactive)
14601 (org-eval-in-calendar '(calendar-backward-month 1))))
14602 (org-defkey minibuffer-local-map [?\e (shift right)]
14603 (lambda () (interactive)
14604 (org-eval-in-calendar '(calendar-forward-month 1))))
14605 (org-defkey minibuffer-local-map [?\e (shift up)]
14606 (lambda () (interactive)
14607 (org-eval-in-calendar '(calendar-backward-year 1))))
14608 (org-defkey minibuffer-local-map [?\e (shift down)]
14609 (lambda () (interactive)
14610 (org-eval-in-calendar '(calendar-forward-year 1))))
14611 (org-defkey minibuffer-local-map [(shift up)]
14612 (lambda () (interactive)
14613 (org-eval-in-calendar '(calendar-backward-week 1))))
14614 (org-defkey minibuffer-local-map [(shift down)]
14615 (lambda () (interactive)
14616 (org-eval-in-calendar '(calendar-forward-week 1))))
14617 (org-defkey minibuffer-local-map [(shift left)]
14618 (lambda () (interactive)
14619 (org-eval-in-calendar '(calendar-backward-day 1))))
14620 (org-defkey minibuffer-local-map [(shift right)]
14621 (lambda () (interactive)
14622 (org-eval-in-calendar '(calendar-forward-day 1))))
14623 (org-defkey minibuffer-local-map ">"
14624 (lambda () (interactive)
14625 (org-eval-in-calendar '(scroll-calendar-left 1))))
14626 (org-defkey minibuffer-local-map "<"
14627 (lambda () (interactive)
14628 (org-eval-in-calendar '(scroll-calendar-right 1))))
14629 (org-defkey minibuffer-local-map "\C-v"
14630 (lambda () (interactive)
14631 (org-eval-in-calendar
14632 '(calendar-scroll-left-three-months 1))))
14633 (org-defkey minibuffer-local-map "\M-v"
14634 (lambda () (interactive)
14635 (org-eval-in-calendar
14636 '(calendar-scroll-right-three-months 1))))
14637 (run-hooks 'org-read-date-minibuffer-setup-hook)
14638 (unwind-protect
14639 (progn
14640 (use-local-map map)
14641 (add-hook 'post-command-hook 'org-read-date-display)
14642 (setq org-ans0 (read-string prompt default-input
14643 'org-read-date-history nil))
14644 ;; org-ans0: from prompt
14645 ;; org-ans1: from mouse click
14646 ;; org-ans2: from calendar motion
14647 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14648 (remove-hook 'post-command-hook 'org-read-date-display)
14649 (use-local-map old-map)
14650 (when org-read-date-overlay
14651 (delete-overlay org-read-date-overlay)
14652 (setq org-read-date-overlay nil)))))
14653 (bury-buffer "*Calendar*")))))
14655 (t ; Naked prompt only
14656 (unwind-protect
14657 (setq ans (read-string prompt default-input
14658 'org-read-date-history timestr))
14659 (when org-read-date-overlay
14660 (delete-overlay org-read-date-overlay)
14661 (setq org-read-date-overlay nil)))))
14663 (setq final (org-read-date-analyze ans def defdecode))
14665 (when org-read-date-analyze-forced-year
14666 (message "Year was forced into %s"
14667 (if org-read-date-force-compatible-dates
14668 "compatible range (1970-2037)"
14669 "range representable on this machine"))
14670 (ding))
14672 ;; One round trip to get rid of 34th of August and stuff like that....
14673 (setq final (decode-time (apply 'encode-time final)))
14675 (setq org-read-date-final-answer ans)
14677 (if to-time
14678 (apply 'encode-time final)
14679 (if (and (boundp 'org-time-was-given) org-time-was-given)
14680 (format "%04d-%02d-%02d %02d:%02d"
14681 (nth 5 final) (nth 4 final) (nth 3 final)
14682 (nth 2 final) (nth 1 final))
14683 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
14685 (defvar def)
14686 (defvar defdecode)
14687 (defvar with-time)
14688 (defun org-read-date-display ()
14689 "Display the current date prompt interpretation in the minibuffer."
14690 (when org-read-date-display-live
14691 (when org-read-date-overlay
14692 (delete-overlay org-read-date-overlay))
14693 (let ((p (point)))
14694 (end-of-line 1)
14695 (while (not (equal (buffer-substring
14696 (max (point-min) (- (point) 4)) (point))
14697 " "))
14698 (insert " "))
14699 (goto-char p))
14700 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
14701 " " (or org-ans1 org-ans2)))
14702 (org-end-time-was-given nil)
14703 (f (org-read-date-analyze ans def defdecode))
14704 (fmts (if org-dcst
14705 org-time-stamp-custom-formats
14706 org-time-stamp-formats))
14707 (fmt (if (or with-time
14708 (and (boundp 'org-time-was-given) org-time-was-given))
14709 (cdr fmts)
14710 (car fmts)))
14711 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
14712 (when (and org-end-time-was-given
14713 (string-match org-plain-time-of-day-regexp txt))
14714 (setq txt (concat (substring txt 0 (match-end 0)) "-"
14715 org-end-time-was-given
14716 (substring txt (match-end 0)))))
14717 (when org-read-date-analyze-futurep
14718 (setq txt (concat txt " (=>F)")))
14719 (setq org-read-date-overlay
14720 (make-overlay (1- (point-at-eol)) (point-at-eol)))
14721 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
14723 (defun org-read-date-analyze (ans def defdecode)
14724 "Analyze the combined answer of the date prompt."
14725 ;; FIXME: cleanup and comment
14726 (let ((nowdecode (decode-time (current-time)))
14727 delta deltan deltaw deltadef year month day
14728 hour minute second wday pm h2 m2 tl wday1
14729 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
14730 (setq org-read-date-analyze-futurep nil
14731 org-read-date-analyze-forced-year nil)
14732 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
14733 (setq ans "+0"))
14735 (when (setq delta (org-read-date-get-relative ans (current-time) def))
14736 (setq ans (replace-match "" t t ans)
14737 deltan (car delta)
14738 deltaw (nth 1 delta)
14739 deltadef (nth 2 delta)))
14741 ;; Check if there is an iso week date in there
14742 ;; If yes, store the info and postpone interpreting it until the rest
14743 ;; of the parsing is done
14744 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
14745 (setq iso-year (if (match-end 1)
14746 (org-small-year-to-year
14747 (string-to-number (match-string 1 ans))))
14748 iso-weekday (if (match-end 3)
14749 (string-to-number (match-string 3 ans)))
14750 iso-week (string-to-number (match-string 2 ans)))
14751 (setq ans (replace-match "" t t ans)))
14753 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
14754 (when (string-match
14755 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
14756 (setq year (if (match-end 2)
14757 (string-to-number (match-string 2 ans))
14758 (progn (setq kill-year t)
14759 (string-to-number (format-time-string "%Y"))))
14760 month (string-to-number (match-string 3 ans))
14761 day (string-to-number (match-string 4 ans)))
14762 (if (< year 100) (setq year (+ 2000 year)))
14763 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14764 t nil ans)))
14766 ;; Help matching dottet european dates
14767 (when (string-match
14768 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
14769 (setq year (if (match-end 3)
14770 (string-to-number (match-string 3 ans))
14771 (progn (setq kill-year t)
14772 (string-to-number (format-time-string "%Y"))))
14773 day (string-to-number (match-string 1 ans))
14774 month (string-to-number (match-string 2 ans))
14775 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14776 t nil ans)))
14778 ;; Help matching american dates, like 5/30 or 5/30/7
14779 (when (string-match
14780 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
14781 (setq year (if (match-end 4)
14782 (string-to-number (match-string 4 ans))
14783 (progn (setq kill-year t)
14784 (string-to-number (format-time-string "%Y"))))
14785 month (string-to-number (match-string 1 ans))
14786 day (string-to-number (match-string 2 ans)))
14787 (if (< year 100) (setq year (+ 2000 year)))
14788 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14789 t nil ans)))
14790 ;; Help matching am/pm times, because `parse-time-string' does not do that.
14791 ;; If there is a time with am/pm, and *no* time without it, we convert
14792 ;; so that matching will be successful.
14793 (loop for i from 1 to 2 do ; twice, for end time as well
14794 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
14795 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
14796 (setq hour (string-to-number (match-string 1 ans))
14797 minute (if (match-end 3)
14798 (string-to-number (match-string 3 ans))
14800 pm (equal ?p
14801 (string-to-char (downcase (match-string 4 ans)))))
14802 (if (and (= hour 12) (not pm))
14803 (setq hour 0)
14804 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
14805 (setq ans (replace-match (format "%02d:%02d" hour minute)
14806 t t ans))))
14808 ;; Check if a time range is given as a duration
14809 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
14810 (setq hour (string-to-number (match-string 1 ans))
14811 h2 (+ hour (string-to-number (match-string 3 ans)))
14812 minute (string-to-number (match-string 2 ans))
14813 m2 (+ minute (if (match-end 5) (string-to-number
14814 (match-string 5 ans))0)))
14815 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
14816 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
14817 t t ans)))
14819 ;; Check if there is a time range
14820 (when (boundp 'org-end-time-was-given)
14821 (setq org-time-was-given nil)
14822 (when (and (string-match org-plain-time-of-day-regexp ans)
14823 (match-end 8))
14824 (setq org-end-time-was-given (match-string 8 ans))
14825 (setq ans (concat (substring ans 0 (match-beginning 7))
14826 (substring ans (match-end 7))))))
14828 (setq tl (parse-time-string ans)
14829 day (or (nth 3 tl) (nth 3 defdecode))
14830 month (or (nth 4 tl)
14831 (if (and org-read-date-prefer-future
14832 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
14833 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
14834 (nth 4 defdecode)))
14835 year (or (and (not kill-year) (nth 5 tl))
14836 (if (and org-read-date-prefer-future
14837 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
14838 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
14839 (nth 5 defdecode)))
14840 hour (or (nth 2 tl) (nth 2 defdecode))
14841 minute (or (nth 1 tl) (nth 1 defdecode))
14842 second (or (nth 0 tl) 0)
14843 wday (nth 6 tl))
14845 (when (and (eq org-read-date-prefer-future 'time)
14846 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
14847 (equal day (nth 3 nowdecode))
14848 (equal month (nth 4 nowdecode))
14849 (equal year (nth 5 nowdecode))
14850 (nth 2 tl)
14851 (or (< (nth 2 tl) (nth 2 nowdecode))
14852 (and (= (nth 2 tl) (nth 2 nowdecode))
14853 (nth 1 tl)
14854 (< (nth 1 tl) (nth 1 nowdecode)))))
14855 (setq day (1+ day)
14856 futurep t))
14858 ;; Special date definitions below
14859 (cond
14860 (iso-week
14861 ;; There was an iso week
14862 (require 'cal-iso)
14863 (setq futurep nil)
14864 (setq year (or iso-year year)
14865 day (or iso-weekday wday 1)
14866 wday nil ; to make sure that the trigger below does not match
14867 iso-date (calendar-gregorian-from-absolute
14868 (calendar-absolute-from-iso
14869 (list iso-week day year))))
14870 ; FIXME: Should we also push ISO weeks into the future?
14871 ; (when (and org-read-date-prefer-future
14872 ; (not iso-year)
14873 ; (< (calendar-absolute-from-gregorian iso-date)
14874 ; (time-to-days (current-time))))
14875 ; (setq year (1+ year)
14876 ; iso-date (calendar-gregorian-from-absolute
14877 ; (calendar-absolute-from-iso
14878 ; (list iso-week day year)))))
14879 (setq month (car iso-date)
14880 year (nth 2 iso-date)
14881 day (nth 1 iso-date)))
14882 (deltan
14883 (setq futurep nil)
14884 (unless deltadef
14885 (let ((now (decode-time (current-time))))
14886 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
14887 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
14888 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
14889 ((equal deltaw "m") (setq month (+ month deltan)))
14890 ((equal deltaw "y") (setq year (+ year deltan)))))
14891 ((and wday (not (nth 3 tl)))
14892 (setq futurep nil)
14893 ;; Weekday was given, but no day, so pick that day in the week
14894 ;; on or after the derived date.
14895 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
14896 (unless (equal wday wday1)
14897 (setq day (+ day (% (- wday wday1 -7) 7))))))
14898 (if (and (boundp 'org-time-was-given)
14899 (nth 2 tl))
14900 (setq org-time-was-given t))
14901 (if (< year 100) (setq year (+ 2000 year)))
14902 ;; Check of the date is representable
14903 (if org-read-date-force-compatible-dates
14904 (progn
14905 (if (< year 1970)
14906 (setq year 1970 org-read-date-analyze-forced-year t))
14907 (if (> year 2037)
14908 (setq year 2037 org-read-date-analyze-forced-year t)))
14909 (condition-case nil
14910 (ignore (encode-time second minute hour day month year))
14911 (error
14912 (setq year (nth 5 defdecode))
14913 (setq org-read-date-analyze-forced-year t))))
14914 (setq org-read-date-analyze-futurep futurep)
14915 (list second minute hour day month year)))
14917 (defvar parse-time-weekdays)
14919 (defun org-read-date-get-relative (s today default)
14920 "Check string S for special relative date string.
14921 TODAY and DEFAULT are internal times, for today and for a default.
14922 Return shift list (N what def-flag)
14923 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
14924 N is the number of WHATs to shift.
14925 DEF-FLAG is t when a double ++ or -- indicates shift relative to
14926 the DEFAULT date rather than TODAY."
14927 (when (and
14928 (string-match
14929 (concat
14930 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
14931 "\\([0-9]+\\)?"
14932 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
14933 "\\([ \t]\\|$\\)") s)
14934 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
14935 (let* ((dir (if (> (match-end 1) (match-beginning 1))
14936 (string-to-char (substring (match-string 1 s) -1))
14937 ?+))
14938 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
14939 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
14940 (what (if (match-end 3) (match-string 3 s) "d"))
14941 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
14942 (date (if rel default today))
14943 (wday (nth 6 (decode-time date)))
14944 delta)
14945 (if wday1
14946 (progn
14947 (setq delta (mod (+ 7 (- wday1 wday)) 7))
14948 (if (= dir ?-) (setq delta (- delta 7)))
14949 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
14950 (list delta "d" rel))
14951 (list (* n (if (= dir ?-) -1 1)) what rel)))))
14953 (defun org-order-calendar-date-args (arg1 arg2 arg3)
14954 "Turn a user-specified date into the internal representation.
14955 The internal representation needed by the calendar is (month day year).
14956 This is a wrapper to handle the brain-dead convention in calendar that
14957 user function argument order change dependent on argument order."
14958 (if (boundp 'calendar-date-style)
14959 (cond
14960 ((eq calendar-date-style 'american)
14961 (list arg1 arg2 arg3))
14962 ((eq calendar-date-style 'european)
14963 (list arg2 arg1 arg3))
14964 ((eq calendar-date-style 'iso)
14965 (list arg2 arg3 arg1)))
14966 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
14967 (if (org-bound-and-true-p european-calendar-style)
14968 (list arg2 arg1 arg3)
14969 (list arg1 arg2 arg3)))))
14971 (defun org-eval-in-calendar (form &optional keepdate)
14972 "Eval FORM in the calendar window and return to current window.
14973 Also, store the cursor date in variable org-ans2."
14974 (let ((sf (selected-frame))
14975 (sw (selected-window)))
14976 (select-window (get-buffer-window "*Calendar*" t))
14977 (eval form)
14978 (when (and (not keepdate) (calendar-cursor-to-date))
14979 (let* ((date (calendar-cursor-to-date))
14980 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14981 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
14982 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
14983 (select-window sw)
14984 (org-select-frame-set-input-focus sf)))
14986 (defun org-calendar-select ()
14987 "Return to `org-read-date' with the date currently selected.
14988 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14989 (interactive)
14990 (when (calendar-cursor-to-date)
14991 (let* ((date (calendar-cursor-to-date))
14992 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14993 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14994 (if (active-minibuffer-window) (exit-minibuffer))))
14996 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
14997 "Insert a date stamp for the date given by the internal TIME.
14998 WITH-HM means use the stamp format that includes the time of the day.
14999 INACTIVE means use square brackets instead of angular ones, so that the
15000 stamp will not contribute to the agenda.
15001 PRE and POST are optional strings to be inserted before and after the
15002 stamp.
15003 The command returns the inserted time stamp."
15004 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15005 stamp)
15006 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15007 (insert-before-markers (or pre ""))
15008 (when (listp extra)
15009 (setq extra (car extra))
15010 (if (and (stringp extra)
15011 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15012 (setq extra (format "-%02d:%02d"
15013 (string-to-number (match-string 1 extra))
15014 (string-to-number (match-string 2 extra))))
15015 (setq extra nil)))
15016 (when extra
15017 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15018 (insert-before-markers (setq stamp (format-time-string fmt time)))
15019 (insert-before-markers (or post ""))
15020 (setq org-last-inserted-timestamp stamp)))
15022 (defun org-toggle-time-stamp-overlays ()
15023 "Toggle the use of custom time stamp formats."
15024 (interactive)
15025 (setq org-display-custom-times (not org-display-custom-times))
15026 (unless org-display-custom-times
15027 (let ((p (point-min)) (bmp (buffer-modified-p)))
15028 (while (setq p (next-single-property-change p 'display))
15029 (if (and (get-text-property p 'display)
15030 (eq (get-text-property p 'face) 'org-date))
15031 (remove-text-properties
15032 p (setq p (next-single-property-change p 'display))
15033 '(display t))))
15034 (set-buffer-modified-p bmp)))
15035 (if (featurep 'xemacs)
15036 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15037 (org-restart-font-lock)
15038 (setq org-table-may-need-update t)
15039 (if org-display-custom-times
15040 (message "Time stamps are overlayed with custom format")
15041 (message "Time stamp overlays removed")))
15043 (defun org-display-custom-time (beg end)
15044 "Overlay modified time stamp format over timestamp between BEG and END."
15045 (let* ((ts (buffer-substring beg end))
15046 t1 w1 with-hm tf time str w2 (off 0))
15047 (save-match-data
15048 (setq t1 (org-parse-time-string ts t))
15049 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15050 (setq off (- (match-end 0) (match-beginning 0)))))
15051 (setq end (- end off))
15052 (setq w1 (- end beg)
15053 with-hm (and (nth 1 t1) (nth 2 t1))
15054 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15055 time (org-fix-decoded-time t1)
15056 str (org-add-props
15057 (format-time-string
15058 (substring tf 1 -1) (apply 'encode-time time))
15059 nil 'mouse-face 'highlight)
15060 w2 (length str))
15061 (if (not (= w2 w1))
15062 (add-text-properties (1+ beg) (+ 2 beg)
15063 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15064 (if (featurep 'xemacs)
15065 (progn
15066 (put-text-property beg end 'invisible t)
15067 (put-text-property beg end 'end-glyph (make-glyph str)))
15068 (put-text-property beg end 'display str))))
15070 (defun org-translate-time (string)
15071 "Translate all timestamps in STRING to custom format.
15072 But do this only if the variable `org-display-custom-times' is set."
15073 (when org-display-custom-times
15074 (save-match-data
15075 (let* ((start 0)
15076 (re org-ts-regexp-both)
15077 t1 with-hm inactive tf time str beg end)
15078 (while (setq start (string-match re string start))
15079 (setq beg (match-beginning 0)
15080 end (match-end 0)
15081 t1 (save-match-data
15082 (org-parse-time-string (substring string beg end) t))
15083 with-hm (and (nth 1 t1) (nth 2 t1))
15084 inactive (equal (substring string beg (1+ beg)) "[")
15085 tf (funcall (if with-hm 'cdr 'car)
15086 org-time-stamp-custom-formats)
15087 time (org-fix-decoded-time t1)
15088 str (format-time-string
15089 (concat
15090 (if inactive "[" "<") (substring tf 1 -1)
15091 (if inactive "]" ">"))
15092 (apply 'encode-time time))
15093 string (replace-match str t t string)
15094 start (+ start (length str)))))))
15095 string)
15097 (defun org-fix-decoded-time (time)
15098 "Set 0 instead of nil for the first 6 elements of time.
15099 Don't touch the rest."
15100 (let ((n 0))
15101 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15103 (defun org-days-to-time (timestamp-string)
15104 "Difference between TIMESTAMP-STRING and now in days."
15105 (- (time-to-days (org-time-string-to-time timestamp-string))
15106 (time-to-days (current-time))))
15108 (defun org-deadline-close (timestamp-string &optional ndays)
15109 "Is the time in TIMESTAMP-STRING close to the current date?"
15110 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15111 (and (< (org-days-to-time timestamp-string) ndays)
15112 (not (org-entry-is-done-p))))
15114 (defun org-get-wdays (ts)
15115 "Get the deadline lead time appropriate for timestring TS."
15116 (cond
15117 ((<= org-deadline-warning-days 0)
15118 ;; 0 or negative, enforce this value no matter what
15119 (- org-deadline-warning-days))
15120 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15121 ;; lead time is specified.
15122 (floor (* (string-to-number (match-string 1 ts))
15123 (cdr (assoc (match-string 2 ts)
15124 '(("d" . 1) ("w" . 7)
15125 ("m" . 30.4) ("y" . 365.25)))))))
15126 ;; go for the default.
15127 (t org-deadline-warning-days)))
15129 (defun org-calendar-select-mouse (ev)
15130 "Return to `org-read-date' with the date currently selected.
15131 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15132 (interactive "e")
15133 (mouse-set-point ev)
15134 (when (calendar-cursor-to-date)
15135 (let* ((date (calendar-cursor-to-date))
15136 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15137 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15138 (if (active-minibuffer-window) (exit-minibuffer))))
15140 (defun org-check-deadlines (ndays)
15141 "Check if there are any deadlines due or past due.
15142 A deadline is considered due if it happens within `org-deadline-warning-days'
15143 days from today's date. If the deadline appears in an entry marked DONE,
15144 it is not shown. The prefix arg NDAYS can be used to test that many
15145 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15146 (interactive "P")
15147 (let* ((org-warn-days
15148 (cond
15149 ((equal ndays '(4)) 100000)
15150 (ndays (prefix-numeric-value ndays))
15151 (t (abs org-deadline-warning-days))))
15152 (case-fold-search nil)
15153 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15154 (callback
15155 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15157 (message "%d deadlines past-due or due within %d days"
15158 (org-occur regexp nil callback)
15159 org-warn-days)))
15161 (defun org-check-before-date (date)
15162 "Check if there are deadlines or scheduled entries before DATE."
15163 (interactive (list (org-read-date)))
15164 (let ((case-fold-search nil)
15165 (regexp (concat "\\<\\(" org-deadline-string
15166 "\\|" org-scheduled-string
15167 "\\) *<\\([^>]+\\)>"))
15168 (callback
15169 (lambda () (time-less-p
15170 (org-time-string-to-time (match-string 2))
15171 (org-time-string-to-time date)))))
15172 (message "%d entries before %s"
15173 (org-occur regexp nil callback) date)))
15175 (defun org-check-after-date (date)
15176 "Check if there are deadlines or scheduled entries after DATE."
15177 (interactive (list (org-read-date)))
15178 (let ((case-fold-search nil)
15179 (regexp (concat "\\<\\(" org-deadline-string
15180 "\\|" org-scheduled-string
15181 "\\) *<\\([^>]+\\)>"))
15182 (callback
15183 (lambda () (not
15184 (time-less-p
15185 (org-time-string-to-time (match-string 2))
15186 (org-time-string-to-time date))))))
15187 (message "%d entries after %s"
15188 (org-occur regexp nil callback) date)))
15190 (defun org-evaluate-time-range (&optional to-buffer)
15191 "Evaluate a time range by computing the difference between start and end.
15192 Normally the result is just printed in the echo area, but with prefix arg
15193 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15194 If the time range is actually in a table, the result is inserted into the
15195 next column.
15196 For time difference computation, a year is assumed to be exactly 365
15197 days in order to avoid rounding problems."
15198 (interactive "P")
15200 (org-clock-update-time-maybe)
15201 (save-excursion
15202 (unless (org-at-date-range-p t)
15203 (goto-char (point-at-bol))
15204 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15205 (if (not (org-at-date-range-p t))
15206 (error "Not at a time-stamp range, and none found in current line")))
15207 (let* ((ts1 (match-string 1))
15208 (ts2 (match-string 2))
15209 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15210 (match-end (match-end 0))
15211 (time1 (org-time-string-to-time ts1))
15212 (time2 (org-time-string-to-time ts2))
15213 (t1 (org-float-time time1))
15214 (t2 (org-float-time time2))
15215 (diff (abs (- t2 t1)))
15216 (negative (< (- t2 t1) 0))
15217 ;; (ys (floor (* 365 24 60 60)))
15218 (ds (* 24 60 60))
15219 (hs (* 60 60))
15220 (fy "%dy %dd %02d:%02d")
15221 (fy1 "%dy %dd")
15222 (fd "%dd %02d:%02d")
15223 (fd1 "%dd")
15224 (fh "%02d:%02d")
15225 y d h m align)
15226 (if havetime
15227 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15229 d (floor (/ diff ds)) diff (mod diff ds)
15230 h (floor (/ diff hs)) diff (mod diff hs)
15231 m (floor (/ diff 60)))
15232 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15234 d (floor (+ (/ diff ds) 0.5))
15235 h 0 m 0))
15236 (if (not to-buffer)
15237 (message "%s" (org-make-tdiff-string y d h m))
15238 (if (org-at-table-p)
15239 (progn
15240 (goto-char match-end)
15241 (setq align t)
15242 (and (looking-at " *|") (goto-char (match-end 0))))
15243 (goto-char match-end))
15244 (if (looking-at
15245 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15246 (replace-match ""))
15247 (if negative (insert " -"))
15248 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15249 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15250 (insert " " (format fh h m))))
15251 (if align (org-table-align))
15252 (message "Time difference inserted")))))
15254 (defun org-make-tdiff-string (y d h m)
15255 (let ((fmt "")
15256 (l nil))
15257 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15258 l (push y l)))
15259 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15260 l (push d l)))
15261 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15262 l (push h l)))
15263 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15264 l (push m l)))
15265 (apply 'format fmt (nreverse l))))
15267 (defun org-time-string-to-time (s)
15268 (apply 'encode-time (org-parse-time-string s)))
15269 (defun org-time-string-to-seconds (s)
15270 (org-float-time (org-time-string-to-time s)))
15272 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
15273 "Convert a time stamp to an absolute day number.
15274 If there is a specifier for a cyclic time stamp, get the closest date to
15275 DAYNR.
15276 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15277 The variable date is bound by the calendar when this is called."
15278 (cond
15279 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15280 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15281 daynr
15282 (+ daynr 1000)))
15283 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15284 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15285 (time-to-days (current-time))) (match-string 0 s)
15286 prefer show-all))
15287 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
15289 (defun org-days-to-iso-week (days)
15290 "Return the iso week number."
15291 (require 'cal-iso)
15292 (car (calendar-iso-from-absolute days)))
15294 (defun org-small-year-to-year (year)
15295 "Convert 2-digit years into 4-digit years.
15296 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15297 The year 2000 cannot be abbreviated. Any year larger than 99
15298 is returned unchanged."
15299 (if (< year 38)
15300 (setq year (+ 2000 year))
15301 (if (< year 100)
15302 (setq year (+ 1900 year))))
15303 year)
15305 (defun org-time-from-absolute (d)
15306 "Return the time corresponding to date D.
15307 D may be an absolute day number, or a calendar-type list (month day year)."
15308 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15309 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15311 (defun org-calendar-holiday ()
15312 "List of holidays, for Diary display in Org-mode."
15313 (require 'holidays)
15314 (let ((hl (funcall
15315 (if (fboundp 'calendar-check-holidays)
15316 'calendar-check-holidays 'check-calendar-holidays) date)))
15317 (if hl (mapconcat 'identity hl "; "))))
15319 (defun org-diary-sexp-entry (sexp entry date)
15320 "Process a SEXP diary ENTRY for DATE."
15321 (require 'diary-lib)
15322 (let ((result (if calendar-debug-sexp
15323 (let ((stack-trace-on-error t))
15324 (eval (car (read-from-string sexp))))
15325 (condition-case nil
15326 (eval (car (read-from-string sexp)))
15327 (error
15328 (beep)
15329 (message "Bad sexp at line %d in %s: %s"
15330 (org-current-line)
15331 (buffer-file-name) sexp)
15332 (sleep-for 2))))))
15333 (cond ((stringp result) (split-string result "; "))
15334 ((and (consp result)
15335 (not (consp (cdr result)))
15336 (stringp (cdr result))) (cdr result))
15337 ((and (consp result)
15338 (stringp (car result))) result)
15339 (result entry)
15340 (t nil))))
15342 (defun org-diary-to-ical-string (frombuf)
15343 "Get iCalendar entries from diary entries in buffer FROMBUF.
15344 This uses the icalendar.el library."
15345 (let* ((tmpdir (if (featurep 'xemacs)
15346 (temp-directory)
15347 temporary-file-directory))
15348 (tmpfile (make-temp-name
15349 (expand-file-name "orgics" tmpdir)))
15350 buf rtn b e)
15351 (with-current-buffer frombuf
15352 (icalendar-export-region (point-min) (point-max) tmpfile)
15353 (setq buf (find-buffer-visiting tmpfile))
15354 (set-buffer buf)
15355 (goto-char (point-min))
15356 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15357 (setq b (match-beginning 0)))
15358 (goto-char (point-max))
15359 (if (re-search-backward "^END:VEVENT" nil t)
15360 (setq e (match-end 0)))
15361 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15362 (kill-buffer buf)
15363 (delete-file tmpfile)
15364 rtn))
15366 (defun org-closest-date (start current change prefer show-all)
15367 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15368 When PREFER is `past', return a date that is either CURRENT or past.
15369 When PREFER is `future', return a date that is either CURRENT or future.
15370 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15371 ;; Make the proper lists from the dates
15372 (catch 'exit
15373 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15374 dn dw sday cday n1 n2 n0
15375 d m y y1 y2 date1 date2 nmonths nm ny m2)
15377 (setq start (org-date-to-gregorian start)
15378 current (org-date-to-gregorian
15379 (if show-all
15380 current
15381 (time-to-days (current-time))))
15382 sday (calendar-absolute-from-gregorian start)
15383 cday (calendar-absolute-from-gregorian current))
15385 (if (<= cday sday) (throw 'exit sday))
15387 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15388 (setq dn (string-to-number (match-string 1 change))
15389 dw (cdr (assoc (match-string 2 change) a1)))
15390 (error "Invalid change specifier: %s" change))
15391 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15392 (cond
15393 ((eq dw 'day)
15394 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15395 n2 (+ n1 dn)))
15396 ((eq dw 'year)
15397 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15398 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15399 (setq date1 (list m d y1)
15400 n1 (calendar-absolute-from-gregorian date1)
15401 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15402 n2 (calendar-absolute-from-gregorian date2)))
15403 ((eq dw 'month)
15404 ;; approx number of month between the two dates
15405 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15406 ;; How often does dn fit in there?
15407 (setq d (nth 1 start) m (car start) y (nth 2 start)
15408 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15409 m (+ m nm)
15410 ny (floor (/ m 12))
15411 y (+ y ny)
15412 m (- m (* ny 12)))
15413 (while (> m 12) (setq m (- m 12) y (1+ y)))
15414 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15415 (setq m2 (+ m dn) y2 y)
15416 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15417 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15418 (while (<= n2 cday)
15419 (setq n1 n2 m m2 y y2)
15420 (setq m2 (+ m dn) y2 y)
15421 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15422 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15423 ;; Make sure n1 is the earlier date
15424 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15425 (if show-all
15426 (cond
15427 ((eq prefer 'past) (if (= cday n2) n2 n1))
15428 ((eq prefer 'future) (if (= cday n1) n1 n2))
15429 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15430 (cond
15431 ((eq prefer 'past) (if (= cday n2) n2 n1))
15432 ((eq prefer 'future) (if (= cday n1) n1 n2))
15433 (t (if (= cday n1) n1 n2)))))))
15435 (defun org-date-to-gregorian (date)
15436 "Turn any specification of DATE into a Gregorian date for the calendar."
15437 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15438 ((and (listp date) (= (length date) 3)) date)
15439 ((stringp date)
15440 (setq date (org-parse-time-string date))
15441 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15442 ((listp date)
15443 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15445 (defun org-parse-time-string (s &optional nodefault)
15446 "Parse the standard Org-mode time string.
15447 This should be a lot faster than the normal `parse-time-string'.
15448 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15449 hour and minute fields will be nil if not given."
15450 (if (string-match org-ts-regexp0 s)
15451 (list 0
15452 (if (or (match-beginning 8) (not nodefault))
15453 (string-to-number (or (match-string 8 s) "0")))
15454 (if (or (match-beginning 7) (not nodefault))
15455 (string-to-number (or (match-string 7 s) "0")))
15456 (string-to-number (match-string 4 s))
15457 (string-to-number (match-string 3 s))
15458 (string-to-number (match-string 2 s))
15459 nil nil nil)
15460 (error "Not a standard Org-mode time string: %s" s)))
15462 (defun org-timestamp-up (&optional arg)
15463 "Increase the date item at the cursor by one.
15464 If the cursor is on the year, change the year. If it is on the month,
15465 the day or the time, change that.
15466 With prefix ARG, change by that many units."
15467 (interactive "p")
15468 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15470 (defun org-timestamp-down (&optional arg)
15471 "Decrease the date item at the cursor by one.
15472 If the cursor is on the year, change the year. If it is on the month,
15473 the day or the time, change that.
15474 With prefix ARG, change by that many units."
15475 (interactive "p")
15476 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15478 (defun org-timestamp-up-day (&optional arg)
15479 "Increase the date in the time stamp by one day.
15480 With prefix ARG, change that many days."
15481 (interactive "p")
15482 (if (and (not (org-at-timestamp-p t))
15483 (org-on-heading-p))
15484 (org-todo 'up)
15485 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15487 (defun org-timestamp-down-day (&optional arg)
15488 "Decrease the date in the time stamp by one day.
15489 With prefix ARG, change that many days."
15490 (interactive "p")
15491 (if (and (not (org-at-timestamp-p t))
15492 (org-on-heading-p))
15493 (org-todo 'down)
15494 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15496 (defun org-at-timestamp-p (&optional inactive-ok)
15497 "Determine if the cursor is in or at a timestamp."
15498 (interactive)
15499 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15500 (pos (point))
15501 (ans (or (looking-at tsr)
15502 (save-excursion
15503 (skip-chars-backward "^[<\n\r\t")
15504 (if (> (point) (point-min)) (backward-char 1))
15505 (and (looking-at tsr)
15506 (> (- (match-end 0) pos) -1))))))
15507 (and ans
15508 (boundp 'org-ts-what)
15509 (setq org-ts-what
15510 (cond
15511 ((= pos (match-beginning 0)) 'bracket)
15512 ((= pos (1- (match-end 0))) 'bracket)
15513 ((org-pos-in-match-range pos 2) 'year)
15514 ((org-pos-in-match-range pos 3) 'month)
15515 ((org-pos-in-match-range pos 7) 'hour)
15516 ((org-pos-in-match-range pos 8) 'minute)
15517 ((or (org-pos-in-match-range pos 4)
15518 (org-pos-in-match-range pos 5)) 'day)
15519 ((and (> pos (or (match-end 8) (match-end 5)))
15520 (< pos (match-end 0)))
15521 (- pos (or (match-end 8) (match-end 5))))
15522 (t 'day))))
15523 ans))
15525 (defun org-toggle-timestamp-type ()
15526 "Toggle the type (<active> or [inactive]) of a time stamp."
15527 (interactive)
15528 (when (org-at-timestamp-p t)
15529 (let ((beg (match-beginning 0)) (end (match-end 0))
15530 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
15531 (save-excursion
15532 (goto-char beg)
15533 (while (re-search-forward "[][<>]" end t)
15534 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
15535 t t)))
15536 (message "Timestamp is now %sactive"
15537 (if (equal (char-after beg) ?<) "" "in")))))
15539 (defun org-timestamp-change (n &optional what updown)
15540 "Change the date in the time stamp at point.
15541 The date will be changed by N times WHAT. WHAT can be `day', `month',
15542 `year', `minute', `second'. If WHAT is not given, the cursor position
15543 in the timestamp determines what will be changed."
15544 (let ((pos (point))
15545 with-hm inactive
15546 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
15547 org-ts-what
15548 extra rem
15549 ts time time0)
15550 (if (not (org-at-timestamp-p t))
15551 (error "Not at a timestamp"))
15552 (if (and (not what) (eq org-ts-what 'bracket))
15553 (org-toggle-timestamp-type)
15554 (if (and (not what) (not (eq org-ts-what 'day))
15555 org-display-custom-times
15556 (get-text-property (point) 'display)
15557 (not (get-text-property (1- (point)) 'display)))
15558 (setq org-ts-what 'day))
15559 (setq org-ts-what (or what org-ts-what)
15560 inactive (= (char-after (match-beginning 0)) ?\[)
15561 ts (match-string 0))
15562 (replace-match "")
15563 (if (string-match
15564 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
15566 (setq extra (match-string 1 ts)))
15567 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15568 (setq with-hm t))
15569 (setq time0 (org-parse-time-string ts))
15570 (when (and updown
15571 (eq org-ts-what 'minute)
15572 (not current-prefix-arg))
15573 ;; This looks like s-up and s-down. Change by one rounding step.
15574 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
15575 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
15576 (setcar (cdr time0) (+ (nth 1 time0)
15577 (if (> n 0) (- rem) (- dm rem))))))
15578 (setq time
15579 (encode-time (or (car time0) 0)
15580 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
15581 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
15582 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
15583 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
15584 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
15585 (nthcdr 6 time0)))
15586 (when (and (member org-ts-what '(hour minute))
15587 extra
15588 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
15589 (setq extra (org-modify-ts-extra
15590 extra
15591 (if (eq org-ts-what 'hour) 2 5)
15592 n dm)))
15593 (when (integerp org-ts-what)
15594 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
15595 (if (eq what 'calendar)
15596 (let ((cal-date (org-get-date-from-calendar)))
15597 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15598 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15599 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15600 (setcar time0 (or (car time0) 0))
15601 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15602 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15603 (setq time (apply 'encode-time time0))))
15604 (setq org-last-changed-timestamp
15605 (org-insert-time-stamp time with-hm inactive nil nil extra))
15606 (org-clock-update-time-maybe)
15607 (goto-char pos)
15608 ;; Try to recenter the calendar window, if any
15609 (if (and org-calendar-follow-timestamp-change
15610 (get-buffer-window "*Calendar*" t)
15611 (memq org-ts-what '(day month year)))
15612 (org-recenter-calendar (time-to-days time))))))
15614 (defun org-modify-ts-extra (s pos n dm)
15615 "Change the different parts of the lead-time and repeat fields in timestamp."
15616 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15617 ng h m new rem)
15618 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15619 (cond
15620 ((or (org-pos-in-match-range pos 2)
15621 (org-pos-in-match-range pos 3))
15622 (setq m (string-to-number (match-string 3 s))
15623 h (string-to-number (match-string 2 s)))
15624 (if (org-pos-in-match-range pos 2)
15625 (setq h (+ h n))
15626 (setq n (* dm (org-no-warnings (signum n))))
15627 (when (not (= 0 (setq rem (% m dm))))
15628 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
15629 (setq m (+ m n)))
15630 (if (< m 0) (setq m (+ m 60) h (1- h)))
15631 (if (> m 59) (setq m (- m 60) h (1+ h)))
15632 (setq h (min 24 (max 0 h)))
15633 (setq ng 1 new (format "-%02d:%02d" h m)))
15634 ((org-pos-in-match-range pos 6)
15635 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15636 ((org-pos-in-match-range pos 5)
15637 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
15639 ((org-pos-in-match-range pos 9)
15640 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
15641 ((org-pos-in-match-range pos 8)
15642 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
15644 (when ng
15645 (setq s (concat
15646 (substring s 0 (match-beginning ng))
15648 (substring s (match-end ng))))))
15651 (defun org-recenter-calendar (date)
15652 "If the calendar is visible, recenter it to DATE."
15653 (let* ((win (selected-window))
15654 (cwin (get-buffer-window "*Calendar*" t))
15655 (calendar-move-hook nil))
15656 (when cwin
15657 (select-window cwin)
15658 (calendar-goto-date (if (listp date) date
15659 (calendar-gregorian-from-absolute date)))
15660 (select-window win))))
15662 (defun org-goto-calendar (&optional arg)
15663 "Go to the Emacs calendar at the current date.
15664 If there is a time stamp in the current line, go to that date.
15665 A prefix ARG can be used to force the current date."
15666 (interactive "P")
15667 (let ((tsr org-ts-regexp) diff
15668 (calendar-move-hook nil)
15669 (calendar-view-holidays-initially-flag nil)
15670 (calendar-view-diary-initially-flag nil))
15671 (if (or (org-at-timestamp-p)
15672 (save-excursion
15673 (beginning-of-line 1)
15674 (looking-at (concat ".*" tsr))))
15675 (let ((d1 (time-to-days (current-time)))
15676 (d2 (time-to-days
15677 (org-time-string-to-time (match-string 1)))))
15678 (setq diff (- d2 d1))))
15679 (calendar)
15680 (calendar-goto-today)
15681 (if (and diff (not arg)) (calendar-forward-day diff))))
15683 (defun org-get-date-from-calendar ()
15684 "Return a list (month day year) of date at point in calendar."
15685 (with-current-buffer "*Calendar*"
15686 (save-match-data
15687 (calendar-cursor-to-date))))
15689 (defun org-date-from-calendar ()
15690 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
15691 If there is already a time stamp at the cursor position, update it."
15692 (interactive)
15693 (if (org-at-timestamp-p t)
15694 (org-timestamp-change 0 'calendar)
15695 (let ((cal-date (org-get-date-from-calendar)))
15696 (org-insert-time-stamp
15697 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
15699 (defun org-minutes-to-hh:mm-string (m)
15700 "Compute H:MM from a number of minutes."
15701 (let ((h (/ m 60)))
15702 (setq m (- m (* 60 h)))
15703 (format org-time-clocksum-format h m)))
15705 (defun org-hh:mm-string-to-minutes (s)
15706 "Convert a string H:MM to a number of minutes.
15707 If the string is just a number, interpret it as minutes.
15708 In fact, the first hh:mm or number in the string will be taken,
15709 there can be extra stuff in the string.
15710 If no number is found, the return value is 0."
15711 (cond
15712 ((integerp s) s)
15713 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
15714 (+ (* (string-to-number (match-string 1 s)) 60)
15715 (string-to-number (match-string 2 s))))
15716 ((string-match "\\([0-9]+\\)" s)
15717 (string-to-number (match-string 1 s)))
15718 (t 0)))
15720 (defcustom org-effort-durations
15721 `(("h" . 60)
15722 ("d" . ,(* 60 8))
15723 ("w" . ,(* 60 8 5))
15724 ("m" . ,(* 60 8 5 4))
15725 ("y" . ,(* 60 8 5 40)))
15726 "Conversion factor to minutes for an effort modifier.
15728 Each entry has the form (MODIFIER . MINUTES).
15730 In an effort string, a number followed by MODIFIER is multiplied
15731 by the specified number of MINUTES to obtain an effort in
15732 minutes.
15734 For example, if the value of this variable is ((\"hours\" . 60)), then an
15735 effort string \"2hours\" is equivalent to 120 minutes."
15736 :group 'org-agenda
15737 :type '(alist :key-type (string :tag "Modifier")
15738 :value-type (number :tag "Minutes")))
15740 (defun org-duration-string-to-minutes (s)
15741 "Convert a duration string S to minutes.
15743 A bare number is interpreted as minutes, modifiers can be set by
15744 customizing `org-effort-durations' (which see).
15746 Entries containing a colon are interpreted as H:MM by
15747 `org-hh:mm-string-to-minutes'."
15748 (let ((result 0)
15749 (re (concat "\\([0-9]+\\) *\\("
15750 (regexp-opt (mapcar 'car org-effort-durations))
15751 "\\)")))
15752 (while (string-match re s)
15753 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
15754 (string-to-number (match-string 1 s))))
15755 (setq s (replace-match "" nil t s)))
15756 (incf result (org-hh:mm-string-to-minutes s))
15757 result))
15759 ;;;; Files
15761 (defun org-save-all-org-buffers ()
15762 "Save all Org-mode buffers without user confirmation."
15763 (interactive)
15764 (message "Saving all Org-mode buffers...")
15765 (save-some-buffers t 'org-mode-p)
15766 (when (featurep 'org-id) (org-id-locations-save))
15767 (message "Saving all Org-mode buffers... done"))
15769 (defun org-revert-all-org-buffers ()
15770 "Revert all Org-mode buffers.
15771 Prompt for confirmation when there are unsaved changes.
15772 Be sure you know what you are doing before letting this function
15773 overwrite your changes.
15775 This function is useful in a setup where one tracks org files
15776 with a version control system, to revert on one machine after pulling
15777 changes from another. I believe the procedure must be like this:
15779 1. M-x org-save-all-org-buffers
15780 2. Pull changes from the other machine, resolve conflicts
15781 3. M-x org-revert-all-org-buffers"
15782 (interactive)
15783 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
15784 (error "Abort"))
15785 (save-excursion
15786 (save-window-excursion
15787 (mapc
15788 (lambda (b)
15789 (when (and (with-current-buffer b (org-mode-p))
15790 (with-current-buffer b buffer-file-name))
15791 (switch-to-buffer b)
15792 (revert-buffer t 'no-confirm)))
15793 (buffer-list))
15794 (when (and (featurep 'org-id) org-id-track-globally)
15795 (org-id-locations-load)))))
15797 ;;;; Agenda files
15799 ;;;###autoload
15800 (defun org-switchb (&optional arg)
15801 "Switch between Org buffers.
15802 With a prefix argument, restrict available to files.
15803 With two prefix arguments, restrict available buffers to agenda files.
15805 Defaults to `iswitchb' for buffer name completion.
15806 Set `org-completion-use-ido' to make it use ido instead."
15807 (interactive "P")
15808 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
15809 ((equal arg '(16)) (org-buffer-list 'agenda))
15810 (t (org-buffer-list))))
15811 (org-completion-use-iswitchb org-completion-use-iswitchb)
15812 (org-completion-use-ido org-completion-use-ido))
15813 (unless (or org-completion-use-ido org-completion-use-iswitchb)
15814 (setq org-completion-use-iswitchb t))
15815 (switch-to-buffer
15816 (org-icompleting-read "Org buffer: "
15817 (mapcar 'list (mapcar 'buffer-name blist))
15818 nil t))))
15820 ;;; Define some older names previously used for this functionality
15821 ;;;###autoload
15822 (defalias 'org-ido-switchb 'org-switchb)
15823 ;;;###autoload
15824 (defalias 'org-iswitchb 'org-switchb)
15826 (defun org-buffer-list (&optional predicate exclude-tmp)
15827 "Return a list of Org buffers.
15828 PREDICATE can be `export', `files' or `agenda'.
15830 export restrict the list to Export buffers.
15831 files restrict the list to buffers visiting Org files.
15832 agenda restrict the list to buffers visiting agenda files.
15834 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
15835 (let* ((bfn nil)
15836 (agenda-files (and (eq predicate 'agenda)
15837 (mapcar 'file-truename (org-agenda-files t))))
15838 (filter
15839 (cond
15840 ((eq predicate 'files)
15841 (lambda (b) (with-current-buffer b (org-mode-p))))
15842 ((eq predicate 'export)
15843 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
15844 ((eq predicate 'agenda)
15845 (lambda (b)
15846 (with-current-buffer b
15847 (and (org-mode-p)
15848 (setq bfn (buffer-file-name b))
15849 (member (file-truename bfn) agenda-files)))))
15850 (t (lambda (b) (with-current-buffer b
15851 (or (org-mode-p)
15852 (string-match "\*Org .*Export"
15853 (buffer-name b)))))))))
15854 (delq nil
15855 (mapcar
15856 (lambda(b)
15857 (if (and (funcall filter b)
15858 (or (not exclude-tmp)
15859 (not (string-match "tmp" (buffer-name b)))))
15861 nil))
15862 (buffer-list)))))
15864 (defun org-agenda-files (&optional unrestricted archives)
15865 "Get the list of agenda files.
15866 Optional UNRESTRICTED means return the full list even if a restriction
15867 is currently in place.
15868 When ARCHIVES is t, include all archive files that are really being
15869 used by the agenda files. If ARCHIVE is `ifmode', do this only if
15870 `org-agenda-archives-mode' is t."
15871 (let ((files
15872 (cond
15873 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
15874 ((stringp org-agenda-files) (org-read-agenda-file-list))
15875 ((listp org-agenda-files) org-agenda-files)
15876 (t (error "Invalid value of `org-agenda-files'")))))
15877 (setq files (apply 'append
15878 (mapcar (lambda (f)
15879 (if (file-directory-p f)
15880 (directory-files
15881 f t org-agenda-file-regexp)
15882 (list f)))
15883 files)))
15884 (when org-agenda-skip-unavailable-files
15885 (setq files (delq nil
15886 (mapcar (function
15887 (lambda (file)
15888 (and (file-readable-p file) file)))
15889 files))))
15890 (when (or (eq archives t)
15891 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
15892 (setq files (org-add-archive-files files)))
15893 files))
15895 (defun org-agenda-file-p (&optional file)
15896 "Return non-nil, if FILE is an agenda file.
15897 If FILE is omitted, use the file associated with the current
15898 buffer."
15899 (member (or file (buffer-file-name))
15900 (org-agenda-files t)))
15902 (defun org-edit-agenda-file-list ()
15903 "Edit the list of agenda files.
15904 Depending on setup, this either uses customize to edit the variable
15905 `org-agenda-files', or it visits the file that is holding the list. In the
15906 latter case, the buffer is set up in a way that saving it automatically kills
15907 the buffer and restores the previous window configuration."
15908 (interactive)
15909 (if (stringp org-agenda-files)
15910 (let ((cw (current-window-configuration)))
15911 (find-file org-agenda-files)
15912 (org-set-local 'org-window-configuration cw)
15913 (org-add-hook 'after-save-hook
15914 (lambda ()
15915 (set-window-configuration
15916 (prog1 org-window-configuration
15917 (kill-buffer (current-buffer))))
15918 (org-install-agenda-files-menu)
15919 (message "New agenda file list installed"))
15920 nil 'local)
15921 (message "%s" (substitute-command-keys
15922 "Edit list and finish with \\[save-buffer]")))
15923 (customize-variable 'org-agenda-files)))
15925 (defun org-store-new-agenda-file-list (list)
15926 "Set new value for the agenda file list and save it correctly."
15927 (if (stringp org-agenda-files)
15928 (let ((fe (org-read-agenda-file-list t)) b u)
15929 (while (setq b (find-buffer-visiting org-agenda-files))
15930 (kill-buffer b))
15931 (with-temp-file org-agenda-files
15932 (insert
15933 (mapconcat
15934 (lambda (f) ;; Keep un-expanded entries.
15935 (if (setq u (assoc f fe))
15936 (cdr u)
15938 list "\n")
15939 "\n")))
15940 (let ((org-mode-hook nil) (org-inhibit-startup t)
15941 (org-insert-mode-line-in-empty-file nil))
15942 (setq org-agenda-files list)
15943 (customize-save-variable 'org-agenda-files org-agenda-files))))
15945 (defun org-read-agenda-file-list (&optional pair-with-expansion)
15946 "Read the list of agenda files from a file.
15947 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
15948 filenames, used by `org-store-new-agenda-file-list' to write back
15949 un-expanded file names."
15950 (when (file-directory-p org-agenda-files)
15951 (error "`org-agenda-files' cannot be a single directory"))
15952 (when (stringp org-agenda-files)
15953 (with-temp-buffer
15954 (insert-file-contents org-agenda-files)
15955 (mapcar
15956 (lambda (f)
15957 (let ((e (expand-file-name (substitute-in-file-name f)
15958 org-directory)))
15959 (if pair-with-expansion
15960 (cons e f)
15961 e)))
15962 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
15964 ;;;###autoload
15965 (defun org-cycle-agenda-files ()
15966 "Cycle through the files in `org-agenda-files'.
15967 If the current buffer visits an agenda file, find the next one in the list.
15968 If the current buffer does not, find the first agenda file."
15969 (interactive)
15970 (let* ((fs (org-agenda-files t))
15971 (files (append fs (list (car fs))))
15972 (tcf (if buffer-file-name (file-truename buffer-file-name)))
15973 file)
15974 (unless files (error "No agenda files"))
15975 (catch 'exit
15976 (while (setq file (pop files))
15977 (if (equal (file-truename file) tcf)
15978 (when (car files)
15979 (find-file (car files))
15980 (throw 'exit t))))
15981 (find-file (car fs)))
15982 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
15984 (defun org-agenda-file-to-front (&optional to-end)
15985 "Move/add the current file to the top of the agenda file list.
15986 If the file is not present in the list, it is added to the front. If it is
15987 present, it is moved there. With optional argument TO-END, add/move to the
15988 end of the list."
15989 (interactive "P")
15990 (let ((org-agenda-skip-unavailable-files nil)
15991 (file-alist (mapcar (lambda (x)
15992 (cons (file-truename x) x))
15993 (org-agenda-files t)))
15994 (ctf (file-truename buffer-file-name))
15995 x had)
15996 (setq x (assoc ctf file-alist) had x)
15998 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
15999 (if to-end
16000 (setq file-alist (append (delq x file-alist) (list x)))
16001 (setq file-alist (cons x (delq x file-alist))))
16002 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16003 (org-install-agenda-files-menu)
16004 (message "File %s to %s of agenda file list"
16005 (if had "moved" "added") (if to-end "end" "front"))))
16007 (defun org-remove-file (&optional file)
16008 "Remove current file from the list of files in variable `org-agenda-files'.
16009 These are the files which are being checked for agenda entries.
16010 Optional argument FILE means use this file instead of the current."
16011 (interactive)
16012 (let* ((org-agenda-skip-unavailable-files nil)
16013 (file (or file buffer-file-name))
16014 (true-file (file-truename file))
16015 (afile (abbreviate-file-name file))
16016 (files (delq nil (mapcar
16017 (lambda (x)
16018 (if (equal true-file
16019 (file-truename x))
16020 nil x))
16021 (org-agenda-files t)))))
16022 (if (not (= (length files) (length (org-agenda-files t))))
16023 (progn
16024 (org-store-new-agenda-file-list files)
16025 (org-install-agenda-files-menu)
16026 (message "Removed file: %s" afile))
16027 (message "File was not in list: %s (not removed)" afile))))
16029 (defun org-file-menu-entry (file)
16030 (vector file (list 'find-file file) t))
16032 (defun org-check-agenda-file (file)
16033 "Make sure FILE exists. If not, ask user what to do."
16034 (when (not (file-exists-p file))
16035 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16036 (abbreviate-file-name file))
16037 (let ((r (downcase (read-char-exclusive))))
16038 (cond
16039 ((equal r ?r)
16040 (org-remove-file file)
16041 (throw 'nextfile t))
16042 (t (error "Abort"))))))
16044 (defun org-get-agenda-file-buffer (file)
16045 "Get a buffer visiting FILE. If the buffer needs to be created, add
16046 it to the list of buffers which might be released later."
16047 (let ((buf (org-find-base-buffer-visiting file)))
16048 (if buf
16049 buf ; just return it
16050 ;; Make a new buffer and remember it
16051 (setq buf (find-file-noselect file))
16052 (if buf (push buf org-agenda-new-buffers))
16053 buf)))
16055 (defun org-release-buffers (blist)
16056 "Release all buffers in list, asking the user for confirmation when needed.
16057 When a buffer is unmodified, it is just killed. When modified, it is saved
16058 \(if the user agrees) and then killed."
16059 (let (buf file)
16060 (while (setq buf (pop blist))
16061 (setq file (buffer-file-name buf))
16062 (when (and (buffer-modified-p buf)
16063 file
16064 (y-or-n-p (format "Save file %s? " file)))
16065 (with-current-buffer buf (save-buffer)))
16066 (kill-buffer buf))))
16068 (defun org-prepare-agenda-buffers (files)
16069 "Create buffers for all agenda files, protect archived trees and comments."
16070 (interactive)
16071 (let ((pa '(:org-archived t))
16072 (pc '(:org-comment t))
16073 (pall '(:org-archived t :org-comment t))
16074 (inhibit-read-only t)
16075 (rea (concat ":" org-archive-tag ":"))
16076 bmp file re)
16077 (save-excursion
16078 (save-restriction
16079 (while (setq file (pop files))
16080 (catch 'nextfile
16081 (if (bufferp file)
16082 (set-buffer file)
16083 (org-check-agenda-file file)
16084 (set-buffer (org-get-agenda-file-buffer file)))
16085 (widen)
16086 (setq bmp (buffer-modified-p))
16087 (org-refresh-category-properties)
16088 (setq org-todo-keywords-for-agenda
16089 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16090 (setq org-done-keywords-for-agenda
16091 (append org-done-keywords-for-agenda org-done-keywords))
16092 (setq org-todo-keyword-alist-for-agenda
16093 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16094 (setq org-drawers-for-agenda
16095 (append org-drawers-for-agenda org-drawers))
16096 (setq org-tag-alist-for-agenda
16097 (append org-tag-alist-for-agenda org-tag-alist))
16099 (save-excursion
16100 (remove-text-properties (point-min) (point-max) pall)
16101 (when org-agenda-skip-archived-trees
16102 (goto-char (point-min))
16103 (while (re-search-forward rea nil t)
16104 (if (org-on-heading-p t)
16105 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16106 (goto-char (point-min))
16107 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
16108 (while (re-search-forward re nil t)
16109 (add-text-properties
16110 (match-beginning 0) (org-end-of-subtree t) pc)))
16111 (set-buffer-modified-p bmp)))))
16112 (setq org-todo-keywords-for-agenda
16113 (org-uniquify org-todo-keywords-for-agenda))
16114 (setq org-todo-keyword-alist-for-agenda
16115 (org-uniquify org-todo-keyword-alist-for-agenda)
16116 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16118 ;;;; Embedded LaTeX
16120 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16121 "Keymap for the minor `org-cdlatex-mode'.")
16123 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16124 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16125 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16126 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16127 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16129 (defvar org-cdlatex-texmathp-advice-is-done nil
16130 "Flag remembering if we have applied the advice to texmathp already.")
16132 (define-minor-mode org-cdlatex-mode
16133 "Toggle the minor `org-cdlatex-mode'.
16134 This mode supports entering LaTeX environment and math in LaTeX fragments
16135 in Org-mode.
16136 \\{org-cdlatex-mode-map}"
16137 nil " OCDL" nil
16138 (when org-cdlatex-mode (require 'cdlatex))
16139 (unless org-cdlatex-texmathp-advice-is-done
16140 (setq org-cdlatex-texmathp-advice-is-done t)
16141 (defadvice texmathp (around org-math-always-on activate)
16142 "Always return t in org-mode buffers.
16143 This is because we want to insert math symbols without dollars even outside
16144 the LaTeX math segments. If Orgmode thinks that point is actually inside
16145 an embedded LaTeX fragment, let texmathp do its job.
16146 \\[org-cdlatex-mode-map]"
16147 (interactive)
16148 (let (p)
16149 (cond
16150 ((not (org-mode-p)) ad-do-it)
16151 ((eq this-command 'cdlatex-math-symbol)
16152 (setq ad-return-value t
16153 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16155 (let ((p (org-inside-LaTeX-fragment-p)))
16156 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16157 (setq ad-return-value t
16158 texmathp-why '("Org-mode embedded math" . 0))
16159 (if p ad-do-it)))))))))
16161 (defun turn-on-org-cdlatex ()
16162 "Unconditionally turn on `org-cdlatex-mode'."
16163 (org-cdlatex-mode 1))
16165 (defun org-inside-LaTeX-fragment-p ()
16166 "Test if point is inside a LaTeX fragment.
16167 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16168 sequence appearing also before point.
16169 Even though the matchers for math are configurable, this function assumes
16170 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16171 delimiters are skipped when they have been removed by customization.
16172 The return value is nil, or a cons cell with the delimiter and the
16173 position of this delimiter.
16175 This function does a reasonably good job, but can locally be fooled by
16176 for example currency specifications. For example it will assume being in
16177 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16178 fragments that are properly closed, but during editing, we have to live
16179 with the uncertainty caused by missing closing delimiters. This function
16180 looks only before point, not after."
16181 (catch 'exit
16182 (let ((pos (point))
16183 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16184 (lim (progn
16185 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16186 (point)))
16187 dd-on str (start 0) m re)
16188 (goto-char pos)
16189 (when dodollar
16190 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16191 re (nth 1 (assoc "$" org-latex-regexps)))
16192 (while (string-match re str start)
16193 (cond
16194 ((= (match-end 0) (length str))
16195 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16196 ((= (match-end 0) (- (length str) 5))
16197 (throw 'exit nil))
16198 (t (setq start (match-end 0))))))
16199 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16200 (goto-char pos)
16201 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16202 (and (match-beginning 2) (throw 'exit nil))
16203 ;; count $$
16204 (while (re-search-backward "\\$\\$" lim t)
16205 (setq dd-on (not dd-on)))
16206 (goto-char pos)
16207 (if dd-on (cons "$$" m))))))
16209 (defun org-inside-latex-macro-p ()
16210 "Is point inside a LaTeX macro or its arguments?"
16211 (save-match-data
16212 (org-in-regexp
16213 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16215 (defun org-try-cdlatex-tab ()
16216 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16217 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16218 - inside a LaTeX fragment, or
16219 - after the first word in a line, where an abbreviation expansion could
16220 insert a LaTeX environment."
16221 (when org-cdlatex-mode
16222 (cond
16223 ((save-excursion
16224 (skip-chars-backward "a-zA-Z0-9*")
16225 (skip-chars-backward " \t")
16226 (bolp))
16227 (cdlatex-tab) t)
16228 ((org-inside-LaTeX-fragment-p)
16229 (cdlatex-tab) t)
16230 (t nil))))
16232 (defun org-cdlatex-underscore-caret (&optional arg)
16233 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16234 Revert to the normal definition outside of these fragments."
16235 (interactive "P")
16236 (if (org-inside-LaTeX-fragment-p)
16237 (call-interactively 'cdlatex-sub-superscript)
16238 (let (org-cdlatex-mode)
16239 (call-interactively (key-binding (vector last-input-event))))))
16241 (defun org-cdlatex-math-modify (&optional arg)
16242 "Execute `cdlatex-math-modify' in LaTeX fragments.
16243 Revert to the normal definition outside of these fragments."
16244 (interactive "P")
16245 (if (org-inside-LaTeX-fragment-p)
16246 (call-interactively 'cdlatex-math-modify)
16247 (let (org-cdlatex-mode)
16248 (call-interactively (key-binding (vector last-input-event))))))
16250 (defvar org-latex-fragment-image-overlays nil
16251 "List of overlays carrying the images of latex fragments.")
16252 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16254 (defun org-remove-latex-fragment-image-overlays ()
16255 "Remove all overlays with LaTeX fragment images in current buffer."
16256 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16257 (setq org-latex-fragment-image-overlays nil))
16259 (defun org-preview-latex-fragment (&optional subtree)
16260 "Preview the LaTeX fragment at point, or all locally or globally.
16261 If the cursor is in a LaTeX fragment, create the image and overlay
16262 it over the source code. If there is no fragment at point, display
16263 all fragments in the current text, from one headline to the next. With
16264 prefix SUBTREE, display all fragments in the current subtree. With a
16265 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16266 the cursor is before the first headline,
16267 display all fragments in the buffer.
16268 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16269 (interactive "P")
16270 (org-remove-latex-fragment-image-overlays)
16271 (save-excursion
16272 (save-restriction
16273 (let (beg end at msg)
16274 (cond
16275 ((or (equal subtree '(16))
16276 (not (save-excursion
16277 (re-search-backward (concat "^" outline-regexp) nil t))))
16278 (setq beg (point-min) end (point-max)
16279 msg "Creating images for buffer...%s"))
16280 ((equal subtree '(4))
16281 (org-back-to-heading)
16282 (setq beg (point) end (org-end-of-subtree t)
16283 msg "Creating images for subtree...%s"))
16285 (if (setq at (org-inside-LaTeX-fragment-p))
16286 (goto-char (max (point-min) (- (cdr at) 2)))
16287 (org-back-to-heading))
16288 (setq beg (point) end (progn (outline-next-heading) (point))
16289 msg (if at "Creating image...%s"
16290 "Creating images for entry...%s"))))
16291 (message msg "")
16292 (narrow-to-region beg end)
16293 (goto-char beg)
16294 (org-format-latex
16295 (concat "ltxpng/" (file-name-sans-extension
16296 (file-name-nondirectory
16297 buffer-file-name)))
16298 default-directory 'overlays msg at 'forbuffer 'dvipng)
16299 (message msg "done. Use `C-c C-c' to remove images.")))))
16301 (defvar org-latex-regexps
16302 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16303 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16304 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16305 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16306 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16307 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16308 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16309 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16310 "Regular expressions for matching embedded LaTeX.")
16312 (defvar org-export-have-math nil) ;; dynamic scoping
16313 (defun org-format-latex (prefix &optional dir overlays msg at
16314 forbuffer processing-type)
16315 "Replace LaTeX fragments with links to an image, and produce images.
16316 Some of the options can be changed using the variable
16317 `org-format-latex-options'."
16318 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16319 (let* ((prefixnodir (file-name-nondirectory prefix))
16320 (absprefix (expand-file-name prefix dir))
16321 (todir (file-name-directory absprefix))
16322 (opt org-format-latex-options)
16323 (matchers (plist-get opt :matchers))
16324 (re-list org-latex-regexps)
16325 (org-format-latex-header-extra
16326 (plist-get (org-infile-export-plist) :latex-header-extra))
16327 (cnt 0) txt hash link beg end re e checkdir
16328 executables-checked string
16329 m n block linkfile movefile ov)
16330 ;; Check the different regular expressions
16331 (while (setq e (pop re-list))
16332 (setq m (car e) re (nth 1 e) n (nth 2 e)
16333 block (if (nth 3 e) "\n\n" ""))
16334 (when (member m matchers)
16335 (goto-char (point-min))
16336 (while (re-search-forward re nil t)
16337 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16338 (not (get-text-property (match-beginning n)
16339 'org-protected))
16340 (or (not overlays)
16341 (not (eq (get-char-property (match-beginning n)
16342 'org-overlay-type)
16343 'org-latex-overlay))))
16344 (setq org-export-have-math t)
16345 (cond
16346 ((eq processing-type 'verbatim)
16347 ;; Leave the text verbatim, just protect it
16348 (add-text-properties (match-beginning n) (match-end n)
16349 '(org-protected t)))
16350 ((eq processing-type 'mathjax)
16351 ;; Prepare for MathJax processing
16352 (setq string (match-string n))
16353 (if (member m '("$" "$1"))
16354 (save-excursion
16355 (delete-region (match-beginning n) (match-end n))
16356 (goto-char (match-beginning n))
16357 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16358 "\\)")
16359 '(org-protected t))))
16360 (add-text-properties (match-beginning n) (match-end n)
16361 '(org-protected t))))
16362 ((or (eq processing-type 'dvipng) t)
16363 ;; Process to an image
16364 (setq txt (match-string n)
16365 beg (match-beginning n) end (match-end n)
16366 cnt (1+ cnt))
16367 (let (print-length print-level) ; make sure full list is printed
16368 (setq hash (sha1 (prin1-to-string
16369 (list org-format-latex-header
16370 org-format-latex-header-extra
16371 org-export-latex-default-packages-alist
16372 org-export-latex-packages-alist
16373 org-format-latex-options
16374 forbuffer txt)))
16375 linkfile (format "%s_%s.png" prefix hash)
16376 movefile (format "%s_%s.png" absprefix hash)))
16377 (setq link (concat block "[[file:" linkfile "]]" block))
16378 (if msg (message msg cnt))
16379 (goto-char beg)
16380 (unless checkdir ; make sure the directory exists
16381 (setq checkdir t)
16382 (or (file-directory-p todir) (make-directory todir t)))
16384 (unless executables-checked
16385 (org-check-external-command
16386 "latex" "needed to convert LaTeX fragments to images")
16387 (org-check-external-command
16388 "dvipng" "needed to convert LaTeX fragments to images")
16389 (setq executables-checked t))
16391 (unless (file-exists-p movefile)
16392 (org-create-formula-image
16393 txt movefile opt forbuffer))
16394 (if overlays
16395 (progn
16396 (mapc (lambda (o)
16397 (if (eq (overlay-get o 'org-overlay-type)
16398 'org-latex-overlay)
16399 (delete-overlay o)))
16400 (overlays-in beg end))
16401 (setq ov (make-overlay beg end))
16402 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16403 (if (featurep 'xemacs)
16404 (progn
16405 (overlay-put ov 'invisible t)
16406 (overlay-put
16407 ov 'end-glyph
16408 (make-glyph (vector 'png :file movefile))))
16409 (overlay-put
16410 ov 'display
16411 (list 'image :type 'png :file movefile :ascent 'center)))
16412 (push ov org-latex-fragment-image-overlays)
16413 (goto-char end))
16414 (delete-region beg end)
16415 (insert (org-add-props link
16416 (list 'org-latex-src
16417 (replace-regexp-in-string
16418 "\"" "" txt)))))))))))))
16420 ;; This function borrows from Ganesh Swami's latex2png.el
16421 (defun org-create-formula-image (string tofile options buffer)
16422 "This calls dvipng."
16423 (require 'org-latex)
16424 (let* ((tmpdir (if (featurep 'xemacs)
16425 (temp-directory)
16426 temporary-file-directory))
16427 (texfilebase (make-temp-name
16428 (expand-file-name "orgtex" tmpdir)))
16429 (texfile (concat texfilebase ".tex"))
16430 (dvifile (concat texfilebase ".dvi"))
16431 (pngfile (concat texfilebase ".png"))
16432 (fnh (if (featurep 'xemacs)
16433 (font-height (get-face-font 'default))
16434 (face-attribute 'default :height nil)))
16435 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
16436 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
16437 (fg (or (plist-get options (if buffer :foreground :html-foreground))
16438 "Black"))
16439 (bg (or (plist-get options (if buffer :background :html-background))
16440 "Transparent")))
16441 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
16442 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
16443 (with-temp-file texfile
16444 (insert (org-splice-latex-header
16445 org-format-latex-header
16446 org-export-latex-default-packages-alist
16447 org-export-latex-packages-alist t
16448 org-format-latex-header-extra))
16449 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
16450 (require 'org-latex)
16451 (org-export-latex-fix-inputenc))
16452 (let ((dir default-directory))
16453 (condition-case nil
16454 (progn
16455 (cd tmpdir)
16456 (call-process "latex" nil nil nil texfile))
16457 (error nil))
16458 (cd dir))
16459 (if (not (file-exists-p dvifile))
16460 (progn (message "Failed to create dvi file from %s" texfile) nil)
16461 (condition-case nil
16462 (call-process "dvipng" nil nil nil
16463 "-fg" fg "-bg" bg
16464 "-D" dpi
16465 ;;"-x" scale "-y" scale
16466 "-T" "tight"
16467 "-o" pngfile
16468 dvifile)
16469 (error nil))
16470 (if (not (file-exists-p pngfile))
16471 (if org-format-latex-signal-error
16472 (error "Failed to create png file from %s" texfile)
16473 (message "Failed to create png file from %s" texfile)
16474 nil)
16475 ;; Use the requested file name and clean up
16476 (copy-file pngfile tofile 'replace)
16477 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16478 (delete-file (concat texfilebase e)))
16479 pngfile))))
16481 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
16482 "Fill a LaTeX header template TPL.
16483 In the template, the following place holders will be recognized:
16485 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
16486 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
16487 [PACKAGES] \\usepackage statements for PKG
16488 [NO-PACKAGES] do not include PKG
16489 [EXTRA] the string EXTRA
16490 [NO-EXTRA] do not include EXTRA
16492 For backward compatibility, if both the positive and the negative place
16493 holder is missing, the positive one (without the \"NO-\") will be
16494 assumed to be present at the end of the template.
16495 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
16496 EXTRA is a string.
16497 SNIPPETS-P indicates if this is run to create snippet images for HTML."
16498 (let (rpl (end ""))
16499 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
16500 (setq rpl (if (or (match-end 1) (not def-pkg))
16501 "" (org-latex-packages-to-string def-pkg snippets-p t))
16502 tpl (replace-match rpl t t tpl))
16503 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
16505 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
16506 (setq rpl (if (or (match-end 1) (not pkg))
16507 "" (org-latex-packages-to-string pkg snippets-p t))
16508 tpl (replace-match rpl t t tpl))
16509 (if pkg (setq end
16510 (concat end "\n"
16511 (org-latex-packages-to-string pkg snippets-p)))))
16513 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
16514 (setq rpl (if (or (match-end 1) (not extra))
16515 "" (concat extra "\n"))
16516 tpl (replace-match rpl t t tpl))
16517 (if (and extra (string-match "\\S-" extra))
16518 (setq end (concat end "\n" extra))))
16520 (if (string-match "\\S-" end)
16521 (concat tpl "\n" end)
16522 tpl)))
16524 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
16525 "Turn an alist of packages into a string with the \\usepackage macros."
16526 (setq pkg (mapconcat (lambda(p)
16527 (cond
16528 ((stringp p) p)
16529 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
16530 (format "%% Package %s omitted" (cadr p)))
16531 ((equal "" (car p))
16532 (format "\\usepackage{%s}" (cadr p)))
16534 (format "\\usepackage[%s]{%s}"
16535 (car p) (cadr p)))))
16537 "\n"))
16538 (if newline (concat pkg "\n") pkg))
16540 (defun org-dvipng-color (attr)
16541 "Return an rgb color specification for dvipng."
16542 (apply 'format "rgb %s %s %s"
16543 (mapcar 'org-normalize-color
16544 (color-values (face-attribute 'default attr nil)))))
16546 (defun org-normalize-color (value)
16547 "Return string to be used as color value for an RGB component."
16548 (format "%g" (/ value 65535.0)))
16550 ;; Image display
16553 (defvar org-inline-image-overlays nil)
16554 (make-variable-buffer-local 'org-inline-image-overlays)
16556 (defun org-toggle-inline-images (&optional include-linked)
16557 "Toggle the display of inline images.
16558 INCLUDE-LINKED is passed to `org-display-inline-images'."
16559 (interactive "P")
16560 (if org-inline-image-overlays
16561 (progn
16562 (org-remove-inline-images)
16563 (message "Inline image display turned off"))
16564 (org-display-inline-images include-linked)
16565 (if org-inline-image-overlays
16566 (message "%d images displayed inline"
16567 (length org-inline-image-overlays))
16568 (message "No images to display inline"))))
16570 (defun org-display-inline-images (&optional include-linked refresh beg end)
16571 "Display inline images.
16572 Normally only links without a description part are inlined, because this
16573 is how it will work for export. When INCLUDE-LINKED is set, also links
16574 with a description part will be inlined. This can be nice for a quick
16575 look at those images, but it does not reflect what exported files will look
16576 like.
16577 When REFRESH is set, refresh existing images between BEG and END.
16578 This will create new image displays only if necessary.
16579 BEG and END default to the buffer boundaries."
16580 (interactive "P")
16581 (unless refresh
16582 (org-remove-inline-images)
16583 (if (fboundp 'clear-image-cache) (clear-image-cache)))
16584 (save-excursion
16585 (save-restriction
16586 (widen)
16587 (setq beg (or beg (point-min)) end (or end (point-max)))
16588 (goto-char (point-min))
16589 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
16590 (substring (org-image-file-name-regexp) 0 -2)
16591 "\\)\\]" (if include-linked "" "\\]")))
16592 old file ov img)
16593 (while (re-search-forward re end t)
16594 (setq old (get-char-property-and-overlay (match-beginning 1)
16595 'org-image-overlay))
16596 (setq file (expand-file-name
16597 (concat (or (match-string 3) "") (match-string 4))))
16598 (when (file-exists-p file)
16599 (if (and (car-safe old) refresh)
16600 (image-refresh (overlay-get (cdr old) 'display))
16601 (setq img (save-match-data (create-image file)))
16602 (when img
16603 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
16604 (overlay-put ov 'display img)
16605 (overlay-put ov 'face 'default)
16606 (overlay-put ov 'org-image-overlay t)
16607 (overlay-put ov 'modification-hooks
16608 (list 'org-display-inline-modification-hook))
16609 (push ov org-inline-image-overlays)))))))))
16611 (defun org-display-inline-modification-hook (ov after beg end &optional len)
16612 "Remove inline-display overlay if a corresponding region is modified."
16613 (let ((inhibit-modification-hooks t))
16614 (when (and ov after)
16615 (delete ov org-inline-image-overlays)
16616 (delete-overlay ov))))
16618 (defun org-remove-inline-images ()
16619 "Remove inline display of images."
16620 (interactive)
16621 (mapc 'delete-overlay org-inline-image-overlays)
16622 (setq org-inline-image-overlays nil))
16624 ;;;; Key bindings
16626 ;; Make `C-c C-x' a prefix key
16627 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
16629 ;; TAB key with modifiers
16630 (org-defkey org-mode-map "\C-i" 'org-cycle)
16631 (org-defkey org-mode-map [(tab)] 'org-cycle)
16632 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
16633 (org-defkey org-mode-map [(meta tab)] 'pcomplete)
16634 (org-defkey org-mode-map "\M-\t" 'pcomplete)
16635 (org-defkey org-mode-map "\M-\C-i" 'pcomplete)
16636 ;; The following line is necessary under Suse GNU/Linux
16637 (unless (featurep 'xemacs)
16638 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
16639 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
16640 (define-key org-mode-map [backtab] 'org-shifttab)
16642 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
16643 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
16644 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
16646 ;; Cursor keys with modifiers
16647 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
16648 (org-defkey org-mode-map [(meta right)] 'org-metaright)
16649 (org-defkey org-mode-map [(meta up)] 'org-metaup)
16650 (org-defkey org-mode-map [(meta down)] 'org-metadown)
16652 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
16653 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
16654 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
16655 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
16657 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
16658 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
16659 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
16660 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
16662 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
16663 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
16664 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
16665 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
16667 ;; Babel keys
16668 (define-key org-mode-map org-babel-key-prefix org-babel-map)
16669 (mapc (lambda (pair)
16670 (define-key org-babel-map (car pair) (cdr pair)))
16671 org-babel-key-bindings)
16673 ;;; Extra keys for tty access.
16674 ;; We only set them when really needed because otherwise the
16675 ;; menus don't show the simple keys
16677 (when (or org-use-extra-keys
16678 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
16679 (not window-system))
16680 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
16681 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
16682 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
16683 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
16684 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
16685 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
16686 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
16687 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
16688 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
16689 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
16690 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
16691 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
16692 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
16693 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
16694 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
16695 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
16696 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
16697 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
16698 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
16699 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
16700 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
16701 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
16702 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
16703 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
16704 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
16705 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
16706 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
16707 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
16709 ;; All the other keys
16711 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
16712 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
16713 (if (boundp 'narrow-map)
16714 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
16715 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
16716 (if (boundp 'narrow-map)
16717 (org-defkey narrow-map "b" 'org-narrow-to-block)
16718 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
16719 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
16720 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
16721 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
16722 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
16723 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
16724 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
16725 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
16726 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
16727 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
16728 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
16729 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
16730 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
16731 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
16732 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
16733 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
16734 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
16735 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
16736 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
16737 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
16738 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
16739 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
16740 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
16741 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
16742 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
16743 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
16744 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
16745 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
16746 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
16747 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
16748 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
16749 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
16750 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
16751 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
16752 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
16753 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
16754 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
16755 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
16756 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
16757 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
16758 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
16759 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16760 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
16761 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
16762 (org-defkey org-mode-map "\C-c^" 'org-sort)
16763 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
16764 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
16765 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
16766 (org-defkey org-mode-map "\C-m" 'org-return)
16767 (org-defkey org-mode-map "\C-j" 'org-return-indent)
16768 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
16769 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
16770 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
16771 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
16772 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
16773 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
16774 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
16775 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
16776 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
16777 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
16778 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
16779 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
16780 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
16781 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
16782 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
16783 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
16784 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
16785 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
16786 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
16787 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
16788 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
16790 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
16791 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
16792 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
16793 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
16795 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
16796 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
16797 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
16798 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
16799 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
16800 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
16801 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
16802 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
16803 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
16804 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
16805 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
16806 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
16807 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
16808 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
16809 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
16810 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
16811 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
16812 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
16814 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
16815 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
16816 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
16817 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
16818 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
16820 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
16822 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
16824 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
16825 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
16827 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
16830 (when (featurep 'xemacs)
16831 (org-defkey org-mode-map 'button3 'popup-mode-menu))
16834 (defconst org-speed-commands-default
16836 ("Outline Navigation")
16837 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
16838 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
16839 ("f" . (org-speed-move-safe 'org-forward-same-level))
16840 ("b" . (org-speed-move-safe 'org-backward-same-level))
16841 ("u" . (org-speed-move-safe 'outline-up-heading))
16842 ("j" . org-goto)
16843 ("g" . (org-refile t))
16844 ("Outline Visibility")
16845 ("c" . org-cycle)
16846 ("C" . org-shifttab)
16847 (" " . org-display-outline-path)
16848 ("Outline Structure Editing")
16849 ("U" . org-shiftmetaup)
16850 ("D" . org-shiftmetadown)
16851 ("r" . org-metaright)
16852 ("l" . org-metaleft)
16853 ("R" . org-shiftmetaright)
16854 ("L" . org-shiftmetaleft)
16855 ("i" . (progn (forward-char 1) (call-interactively
16856 'org-insert-heading-respect-content)))
16857 ("^" . org-sort)
16858 ("w" . org-refile)
16859 ("a" . org-archive-subtree-default-with-confirmation)
16860 ("." . org-mark-subtree)
16861 ("Clock Commands")
16862 ("I" . org-clock-in)
16863 ("O" . org-clock-out)
16864 ("Meta Data Editing")
16865 ("t" . org-todo)
16866 ("0" . (org-priority ?\ ))
16867 ("1" . (org-priority ?A))
16868 ("2" . (org-priority ?B))
16869 ("3" . (org-priority ?C))
16870 (";" . org-set-tags-command)
16871 ("e" . org-set-effort)
16872 ("Agenda Views etc")
16873 ("v" . org-agenda)
16874 ("/" . org-sparse-tree)
16875 ("Misc")
16876 ("o" . org-open-at-point)
16877 ("?" . org-speed-command-help)
16878 ("<" . (org-agenda-set-restriction-lock 'subtree))
16879 (">" . (org-agenda-remove-restriction-lock))
16881 "The default speed commands.")
16883 (defun org-print-speed-command (e)
16884 (if (> (length (car e)) 1)
16885 (progn
16886 (princ "\n")
16887 (princ (car e))
16888 (princ "\n")
16889 (princ (make-string (length (car e)) ?-))
16890 (princ "\n"))
16891 (princ (car e))
16892 (princ " ")
16893 (if (symbolp (cdr e))
16894 (princ (symbol-name (cdr e)))
16895 (prin1 (cdr e)))
16896 (princ "\n")))
16898 (defun org-speed-command-help ()
16899 "Show the available speed commands."
16900 (interactive)
16901 (if (not org-use-speed-commands)
16902 (error "Speed commands are not activated, customize `org-use-speed-commands'")
16903 (with-output-to-temp-buffer "*Help*"
16904 (princ "User-defined Speed commands\n===========================\n")
16905 (mapc 'org-print-speed-command org-speed-commands-user)
16906 (princ "\n")
16907 (princ "Built-in Speed commands\n=======================\n")
16908 (mapc 'org-print-speed-command org-speed-commands-default))
16909 (with-current-buffer "*Help*"
16910 (setq truncate-lines t))))
16912 (defun org-speed-move-safe (cmd)
16913 "Execute CMD, but make sure that the cursor always ends up in a headline.
16914 If not, return to the original position and throw an error."
16915 (interactive)
16916 (let ((pos (point)))
16917 (call-interactively cmd)
16918 (unless (and (bolp) (org-on-heading-p))
16919 (goto-char pos)
16920 (error "Boundary reached while executing %s" cmd))))
16922 (defvar org-self-insert-command-undo-counter 0)
16924 (defvar org-table-auto-blank-field) ; defined in org-table.el
16925 (defvar org-speed-command nil)
16927 (defun org-speed-command-default-hook (keys)
16928 "Hook for activating single-letter speed commands.
16929 `org-speed-commands-default' specifies a minimal command set. Use
16930 `org-speed-commands-user' for further customization."
16931 (when (or (and (bolp) (looking-at outline-regexp))
16932 (and (functionp org-use-speed-commands)
16933 (funcall org-use-speed-commands)))
16934 (cdr (assoc keys (append org-speed-commands-user
16935 org-speed-commands-default)))))
16937 (defun org-babel-speed-command-hook (keys)
16938 "Hook for activating single-letter code block commands."
16939 (when (and (bolp) (looking-at org-babel-src-block-regexp))
16940 (cdr (assoc keys org-babel-key-bindings))))
16942 (defcustom org-speed-command-hook
16943 '(org-speed-command-default-hook org-babel-speed-command-hook)
16944 "Hook for activating speed commands at strategic locations.
16945 Hook functions are called in sequence until a valid handler is
16946 found.
16948 Each hook takes a single argument, a user-pressed command key
16949 which is also a `self-insert-command' from the global map.
16951 Within the hook, examine the cursor position and the command key
16952 and return nil or a valid handler as appropriate. Handler could
16953 be one of an interactive command, a function, or a form.
16955 Set `org-use-speed-commands' to non-nil value to enable this
16956 hook. The default setting is `org-speed-command-default-hook'."
16957 :group 'org-structure
16958 :type 'hook)
16960 (defun org-self-insert-command (N)
16961 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
16962 If the cursor is in a table looking at whitespace, the whitespace is
16963 overwritten, and the table is not marked as requiring realignment."
16964 (interactive "p")
16965 (cond
16966 ((and org-use-speed-commands
16967 (setq org-speed-command
16968 (run-hook-with-args-until-success
16969 'org-speed-command-hook (this-command-keys))))
16970 (cond
16971 ((commandp org-speed-command)
16972 (setq this-command org-speed-command)
16973 (call-interactively org-speed-command))
16974 ((functionp org-speed-command)
16975 (funcall org-speed-command))
16976 ((and org-speed-command (listp org-speed-command))
16977 (eval org-speed-command))
16978 (t (let (org-use-speed-commands)
16979 (call-interactively 'org-self-insert-command)))))
16980 ((and
16981 (org-table-p)
16982 (progn
16983 ;; check if we blank the field, and if that triggers align
16984 (and (featurep 'org-table) org-table-auto-blank-field
16985 (member last-command
16986 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
16987 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
16988 ;; got extra space, this field does not determine column width
16989 (let (org-table-may-need-update) (org-table-blank-field))
16990 ;; no extra space, this field may determine column width
16991 (org-table-blank-field)))
16993 (eq N 1)
16994 (looking-at "[^|\n]* |"))
16995 (let (org-table-may-need-update)
16996 (goto-char (1- (match-end 0)))
16997 (delete-char -1)
16998 (goto-char (match-beginning 0))
16999 (self-insert-command N)))
17001 (setq org-table-may-need-update t)
17002 (self-insert-command N)
17003 (org-fix-tags-on-the-fly)
17004 (if org-self-insert-cluster-for-undo
17005 (if (not (eq last-command 'org-self-insert-command))
17006 (setq org-self-insert-command-undo-counter 1)
17007 (if (>= org-self-insert-command-undo-counter 20)
17008 (setq org-self-insert-command-undo-counter 1)
17009 (and (> org-self-insert-command-undo-counter 0)
17010 buffer-undo-list (listp buffer-undo-list)
17011 (not (cadr buffer-undo-list)) ; remove nil entry
17012 (setcdr buffer-undo-list (cddr buffer-undo-list)))
17013 (setq org-self-insert-command-undo-counter
17014 (1+ org-self-insert-command-undo-counter))))))))
17016 (defun org-fix-tags-on-the-fly ()
17017 (when (and (equal (char-after (point-at-bol)) ?*)
17018 (org-on-heading-p))
17019 (org-align-tags-here org-tags-column)))
17021 (defun org-delete-backward-char (N)
17022 "Like `delete-backward-char', insert whitespace at field end in tables.
17023 When deleting backwards, in tables this function will insert whitespace in
17024 front of the next \"|\" separator, to keep the table aligned. The table will
17025 still be marked for re-alignment if the field did fill the entire column,
17026 because, in this case the deletion might narrow the column."
17027 (interactive "p")
17028 (if (and (org-table-p)
17029 (eq N 1)
17030 (string-match "|" (buffer-substring (point-at-bol) (point)))
17031 (looking-at ".*?|"))
17032 (let ((pos (point))
17033 (noalign (looking-at "[^|\n\r]* |"))
17034 (c org-table-may-need-update))
17035 (backward-delete-char N)
17036 (if (not overwrite-mode)
17037 (progn
17038 (skip-chars-forward "^|")
17039 (insert " ")
17040 (goto-char (1- pos))))
17041 ;; noalign: if there were two spaces at the end, this field
17042 ;; does not determine the width of the column.
17043 (if noalign (setq org-table-may-need-update c)))
17044 (backward-delete-char N)
17045 (org-fix-tags-on-the-fly)))
17047 (defun org-delete-char (N)
17048 "Like `delete-char', but insert whitespace at field end in tables.
17049 When deleting characters, in tables this function will insert whitespace in
17050 front of the next \"|\" separator, to keep the table aligned. The table will
17051 still be marked for re-alignment if the field did fill the entire column,
17052 because, in this case the deletion might narrow the column."
17053 (interactive "p")
17054 (if (and (org-table-p)
17055 (not (bolp))
17056 (not (= (char-after) ?|))
17057 (eq N 1))
17058 (if (looking-at ".*?|")
17059 (let ((pos (point))
17060 (noalign (looking-at "[^|\n\r]* |"))
17061 (c org-table-may-need-update))
17062 (replace-match (concat
17063 (substring (match-string 0) 1 -1)
17064 " |"))
17065 (goto-char pos)
17066 ;; noalign: if there were two spaces at the end, this field
17067 ;; does not determine the width of the column.
17068 (if noalign (setq org-table-may-need-update c)))
17069 (delete-char N))
17070 (delete-char N)
17071 (org-fix-tags-on-the-fly)))
17073 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17074 (put 'org-self-insert-command 'delete-selection t)
17075 (put 'orgtbl-self-insert-command 'delete-selection t)
17076 (put 'org-delete-char 'delete-selection 'supersede)
17077 (put 'org-delete-backward-char 'delete-selection 'supersede)
17078 (put 'org-yank 'delete-selection 'yank)
17080 ;; Make `flyspell-mode' delay after some commands
17081 (put 'org-self-insert-command 'flyspell-delayed t)
17082 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17083 (put 'org-delete-char 'flyspell-delayed t)
17084 (put 'org-delete-backward-char 'flyspell-delayed t)
17086 ;; Make pabbrev-mode expand after org-mode commands
17087 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17088 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17090 ;; How to do this: Measure non-white length of current string
17091 ;; If equal to column width, we should realign.
17093 (defun org-remap (map &rest commands)
17094 "In MAP, remap the functions given in COMMANDS.
17095 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17096 (let (new old)
17097 (while commands
17098 (setq old (pop commands) new (pop commands))
17099 (if (fboundp 'command-remapping)
17100 (org-defkey map (vector 'remap old) new)
17101 (substitute-key-definition old new map global-map)))))
17103 (when (eq org-enable-table-editor 'optimized)
17104 ;; If the user wants maximum table support, we need to hijack
17105 ;; some standard editing functions
17106 (org-remap org-mode-map
17107 'self-insert-command 'org-self-insert-command
17108 'delete-char 'org-delete-char
17109 'delete-backward-char 'org-delete-backward-char)
17110 (org-defkey org-mode-map "|" 'org-force-self-insert))
17112 (defvar org-ctrl-c-ctrl-c-hook nil
17113 "Hook for functions attaching themselves to `C-c C-c'.
17114 This can be used to add additional functionality to the C-c C-c key which
17115 executes context-dependent commands.
17116 Each function will be called with no arguments. The function must check
17117 if the context is appropriate for it to act. If yes, it should do its
17118 thing and then return a non-nil value. If the context is wrong,
17119 just do nothing and return nil.")
17121 (defvar org-tab-first-hook nil
17122 "Hook for functions to attach themselves to TAB.
17123 See `org-ctrl-c-ctrl-c-hook' for more information.
17124 This hook runs as the first action when TAB is pressed, even before
17125 `org-cycle' messes around with the `outline-regexp' to cater for
17126 inline tasks and plain list item folding.
17127 If any function in this hook returns t, any other actions that
17128 would have been caused by TAB (such as table field motion or visibility
17129 cycling) will not occur.")
17131 (defvar org-tab-after-check-for-table-hook nil
17132 "Hook for functions to attach themselves to TAB.
17133 See `org-ctrl-c-ctrl-c-hook' for more information.
17134 This hook runs after it has been established that the cursor is not in a
17135 table, but before checking if the cursor is in a headline or if global cycling
17136 should be done.
17137 If any function in this hook returns t, not other actions like visibility
17138 cycling will be done.")
17140 (defvar org-tab-after-check-for-cycling-hook nil
17141 "Hook for functions to attach themselves to TAB.
17142 See `org-ctrl-c-ctrl-c-hook' for more information.
17143 This hook runs after it has been established that not table field motion and
17144 not visibility should be done because of current context. This is probably
17145 the place where a package like yasnippets can hook in.")
17147 (defvar org-tab-before-tab-emulation-hook nil
17148 "Hook for functions to attach themselves to TAB.
17149 See `org-ctrl-c-ctrl-c-hook' for more information.
17150 This hook runs after every other options for TAB have been exhausted, but
17151 before indentation and \t insertion takes place.")
17153 (defvar org-metaleft-hook nil
17154 "Hook for functions attaching themselves to `M-left'.
17155 See `org-ctrl-c-ctrl-c-hook' for more information.")
17156 (defvar org-metaright-hook nil
17157 "Hook for functions attaching themselves to `M-right'.
17158 See `org-ctrl-c-ctrl-c-hook' for more information.")
17159 (defvar org-metaup-hook nil
17160 "Hook for functions attaching themselves to `M-up'.
17161 See `org-ctrl-c-ctrl-c-hook' for more information.")
17162 (defvar org-metadown-hook nil
17163 "Hook for functions attaching themselves to `M-down'.
17164 See `org-ctrl-c-ctrl-c-hook' for more information.")
17165 (defvar org-shiftmetaleft-hook nil
17166 "Hook for functions attaching themselves to `M-S-left'.
17167 See `org-ctrl-c-ctrl-c-hook' for more information.")
17168 (defvar org-shiftmetaright-hook nil
17169 "Hook for functions attaching themselves to `M-S-right'.
17170 See `org-ctrl-c-ctrl-c-hook' for more information.")
17171 (defvar org-shiftmetaup-hook nil
17172 "Hook for functions attaching themselves to `M-S-up'.
17173 See `org-ctrl-c-ctrl-c-hook' for more information.")
17174 (defvar org-shiftmetadown-hook nil
17175 "Hook for functions attaching themselves to `M-S-down'.
17176 See `org-ctrl-c-ctrl-c-hook' for more information.")
17177 (defvar org-metareturn-hook nil
17178 "Hook for functions attaching themselves to `M-RET'.
17179 See `org-ctrl-c-ctrl-c-hook' for more information.")
17180 (defvar org-shiftup-hook nil
17181 "Hook for functions attaching themselves to `S-up'.
17182 See `org-ctrl-c-ctrl-c-hook' for more information.")
17183 (defvar org-shiftup-final-hook nil
17184 "Hook for functions attaching themselves to `S-up'.
17185 This one runs after all other options except shift-select have been excluded.
17186 See `org-ctrl-c-ctrl-c-hook' for more information.")
17187 (defvar org-shiftdown-hook nil
17188 "Hook for functions attaching themselves to `S-down'.
17189 See `org-ctrl-c-ctrl-c-hook' for more information.")
17190 (defvar org-shiftdown-final-hook nil
17191 "Hook for functions attaching themselves to `S-down'.
17192 This one runs after all other options except shift-select have been excluded.
17193 See `org-ctrl-c-ctrl-c-hook' for more information.")
17194 (defvar org-shiftleft-hook nil
17195 "Hook for functions attaching themselves to `S-left'.
17196 See `org-ctrl-c-ctrl-c-hook' for more information.")
17197 (defvar org-shiftleft-final-hook nil
17198 "Hook for functions attaching themselves to `S-left'.
17199 This one runs after all other options except shift-select have been excluded.
17200 See `org-ctrl-c-ctrl-c-hook' for more information.")
17201 (defvar org-shiftright-hook nil
17202 "Hook for functions attaching themselves to `S-right'.
17203 See `org-ctrl-c-ctrl-c-hook' for more information.")
17204 (defvar org-shiftright-final-hook nil
17205 "Hook for functions attaching themselves to `S-right'.
17206 This one runs after all other options except shift-select have been excluded.
17207 See `org-ctrl-c-ctrl-c-hook' for more information.")
17209 (defun org-modifier-cursor-error ()
17210 "Throw an error, a modified cursor command was applied in wrong context."
17211 (error "This command is active in special context like tables, headlines or items"))
17213 (defun org-shiftselect-error ()
17214 "Throw an error because Shift-Cursor command was applied in wrong context."
17215 (if (and (boundp 'shift-select-mode) shift-select-mode)
17216 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
17217 (error "This command works only in special context like headlines or timestamps")))
17219 (defun org-call-for-shift-select (cmd)
17220 (let ((this-command-keys-shift-translated t))
17221 (call-interactively cmd)))
17223 (defun org-shifttab (&optional arg)
17224 "Global visibility cycling or move to previous table field.
17225 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17226 on context.
17227 See the individual commands for more information."
17228 (interactive "P")
17229 (cond
17230 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17231 ((integerp arg)
17232 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
17233 (message "Content view to level: %d" arg)
17234 (org-content (prefix-numeric-value arg2))
17235 (setq org-cycle-global-status 'overview)))
17236 (t (call-interactively 'org-global-cycle))))
17238 (defun org-shiftmetaleft ()
17239 "Promote subtree or delete table column.
17240 Calls `org-promote-subtree', `org-outdent-item',
17241 or `org-table-delete-column', depending on context.
17242 See the individual commands for more information."
17243 (interactive)
17244 (cond
17245 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
17246 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17247 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
17248 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
17249 (t (org-modifier-cursor-error))))
17251 (defun org-shiftmetaright ()
17252 "Demote subtree or insert table column.
17253 Calls `org-demote-subtree', `org-indent-item',
17254 or `org-table-insert-column', depending on context.
17255 See the individual commands for more information."
17256 (interactive)
17257 (cond
17258 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
17259 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17260 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
17261 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
17262 (t (org-modifier-cursor-error))))
17264 (defun org-shiftmetaup (&optional arg)
17265 "Move subtree up or kill table row.
17266 Calls `org-move-subtree-up' or `org-table-kill-row' or
17267 `org-move-item-up' depending on context. See the individual commands
17268 for more information."
17269 (interactive "P")
17270 (cond
17271 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
17272 ((org-at-table-p) (call-interactively 'org-table-kill-row))
17273 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17274 ((org-at-item-p) (call-interactively 'org-move-item-up))
17275 (t (org-modifier-cursor-error))))
17277 (defun org-shiftmetadown (&optional arg)
17278 "Move subtree down or insert table row.
17279 Calls `org-move-subtree-down' or `org-table-insert-row' or
17280 `org-move-item-down', depending on context. See the individual
17281 commands for more information."
17282 (interactive "P")
17283 (cond
17284 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
17285 ((org-at-table-p) (call-interactively 'org-table-insert-row))
17286 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17287 ((org-at-item-p) (call-interactively 'org-move-item-down))
17288 (t (org-modifier-cursor-error))))
17290 (defsubst org-hidden-tree-error ()
17291 (error
17292 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
17294 (defun org-metaleft (&optional arg)
17295 "Promote heading or move table column to left.
17296 Calls `org-do-promote' or `org-table-move-column', depending on context.
17297 With no specific context, calls the Emacs default `backward-word'.
17298 See the individual commands for more information."
17299 (interactive "P")
17300 (cond
17301 ((run-hook-with-args-until-success 'org-metaleft-hook))
17302 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
17303 ((org-with-limited-levels
17304 (or (org-on-heading-p)
17305 (and (org-region-active-p)
17306 (save-excursion
17307 (goto-char (region-beginning))
17308 (org-on-heading-p)))))
17309 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17310 (call-interactively 'org-do-promote))
17311 ;; At an inline task.
17312 ((org-on-heading-p)
17313 (call-interactively 'org-inlinetask-promote))
17314 ((or (org-at-item-p)
17315 (and (org-region-active-p)
17316 (save-excursion
17317 (goto-char (region-beginning))
17318 (org-at-item-p))))
17319 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17320 (call-interactively 'org-outdent-item))
17321 (t (call-interactively 'backward-word))))
17323 (defun org-metaright (&optional arg)
17324 "Demote subtree or move table column to right.
17325 Calls `org-do-demote' or `org-table-move-column', depending on context.
17326 With no specific context, calls the Emacs default `forward-word'.
17327 See the individual commands for more information."
17328 (interactive "P")
17329 (cond
17330 ((run-hook-with-args-until-success 'org-metaright-hook))
17331 ((org-at-table-p) (call-interactively 'org-table-move-column))
17332 ((org-with-limited-levels
17333 (or (org-on-heading-p)
17334 (and (org-region-active-p)
17335 (save-excursion
17336 (goto-char (region-beginning))
17337 (org-on-heading-p)))))
17338 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17339 (call-interactively 'org-do-demote))
17340 ;; At an inline task.
17341 ((org-on-heading-p)
17342 (call-interactively 'org-inlinetask-demote))
17343 ((or (org-at-item-p)
17344 (and (org-region-active-p)
17345 (save-excursion
17346 (goto-char (region-beginning))
17347 (org-at-item-p))))
17348 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17349 (call-interactively 'org-indent-item))
17350 (t (call-interactively 'forward-word))))
17352 (defun org-check-for-hidden (what)
17353 "Check if there are hidden headlines/items in the current visual line.
17354 WHAT can be either `headlines' or `items'. If the current line is
17355 an outline or item heading and it has a folded subtree below it,
17356 this function returns t, nil otherwise."
17357 (let ((re (cond
17358 ((eq what 'headlines) (concat "^" org-outline-regexp))
17359 ((eq what 'items) (org-item-beginning-re))
17360 (t (error "This should not happen"))))
17361 beg end)
17362 (save-excursion
17363 (catch 'exit
17364 (unless (org-region-active-p)
17365 (setq beg (point-at-bol))
17366 (beginning-of-line 2)
17367 (while (and (not (eobp)) ;; this is like `next-line'
17368 (get-char-property (1- (point)) 'invisible))
17369 (beginning-of-line 2))
17370 (setq end (point))
17371 (goto-char beg)
17372 (goto-char (point-at-eol))
17373 (setq end (max end (point)))
17374 (while (re-search-forward re end t)
17375 (if (get-char-property (match-beginning 0) 'invisible)
17376 (throw 'exit t))))
17377 nil))))
17379 (defun org-metaup (&optional arg)
17380 "Move subtree up or move table row up.
17381 Calls `org-move-subtree-up' or `org-table-move-row' or
17382 `org-move-item-up', depending on context. See the individual commands
17383 for more information."
17384 (interactive "P")
17385 (cond
17386 ((run-hook-with-args-until-success 'org-metaup-hook))
17387 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
17388 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17389 ((org-at-item-p) (call-interactively 'org-move-item-up))
17390 (t (transpose-lines 1) (beginning-of-line -1))))
17392 (defun org-metadown (&optional arg)
17393 "Move subtree down or move table row down.
17394 Calls `org-move-subtree-down' or `org-table-move-row' or
17395 `org-move-item-down', depending on context. See the individual
17396 commands for more information."
17397 (interactive "P")
17398 (cond
17399 ((run-hook-with-args-until-success 'org-metadown-hook))
17400 ((org-at-table-p) (call-interactively 'org-table-move-row))
17401 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17402 ((org-at-item-p) (call-interactively 'org-move-item-down))
17403 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
17405 (defun org-shiftup (&optional arg)
17406 "Increase item in timestamp or increase priority of current headline.
17407 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
17408 depending on context. See the individual commands for more information."
17409 (interactive "P")
17410 (cond
17411 ((run-hook-with-args-until-success 'org-shiftup-hook))
17412 ((and org-support-shift-select (org-region-active-p))
17413 (org-call-for-shift-select 'previous-line))
17414 ((org-at-timestamp-p t)
17415 (call-interactively (if org-edit-timestamp-down-means-later
17416 'org-timestamp-down 'org-timestamp-up)))
17417 ((and (not (eq org-support-shift-select 'always))
17418 org-enable-priority-commands
17419 (org-on-heading-p))
17420 (call-interactively 'org-priority-up))
17421 ((and (not org-support-shift-select) (org-at-item-p))
17422 (call-interactively 'org-previous-item))
17423 ((org-clocktable-try-shift 'up arg))
17424 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
17425 (org-support-shift-select
17426 (org-call-for-shift-select 'previous-line))
17427 (t (org-shiftselect-error))))
17429 (defun org-shiftdown (&optional arg)
17430 "Decrease item in timestamp or decrease priority of current headline.
17431 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
17432 depending on context. See the individual commands for more information."
17433 (interactive "P")
17434 (cond
17435 ((run-hook-with-args-until-success 'org-shiftdown-hook))
17436 ((and org-support-shift-select (org-region-active-p))
17437 (org-call-for-shift-select 'next-line))
17438 ((org-at-timestamp-p t)
17439 (call-interactively (if org-edit-timestamp-down-means-later
17440 'org-timestamp-up 'org-timestamp-down)))
17441 ((and (not (eq org-support-shift-select 'always))
17442 org-enable-priority-commands
17443 (org-on-heading-p))
17444 (call-interactively 'org-priority-down))
17445 ((and (not org-support-shift-select) (org-at-item-p))
17446 (call-interactively 'org-next-item))
17447 ((org-clocktable-try-shift 'down arg))
17448 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
17449 (org-support-shift-select
17450 (org-call-for-shift-select 'next-line))
17451 (t (org-shiftselect-error))))
17453 (defun org-shiftright (&optional arg)
17454 "Cycle the thing at point or in the current line, depending on context.
17455 Depending on context, this does one of the following:
17457 - switch a timestamp at point one day into the future
17458 - on a headline, switch to the next TODO keyword.
17459 - on an item, switch entire list to the next bullet type
17460 - on a property line, switch to the next allowed value
17461 - on a clocktable definition line, move time block into the future"
17462 (interactive "P")
17463 (cond
17464 ((run-hook-with-args-until-success 'org-shiftright-hook))
17465 ((and org-support-shift-select (org-region-active-p))
17466 (org-call-for-shift-select 'forward-char))
17467 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
17468 ((and (not (eq org-support-shift-select 'always))
17469 (org-on-heading-p))
17470 (let ((org-inhibit-logging
17471 (not org-treat-S-cursor-todo-selection-as-state-change))
17472 (org-inhibit-blocking
17473 (not org-treat-S-cursor-todo-selection-as-state-change)))
17474 (org-call-with-arg 'org-todo 'right)))
17475 ((or (and org-support-shift-select
17476 (not (eq org-support-shift-select 'always))
17477 (org-at-item-bullet-p))
17478 (and (not org-support-shift-select) (org-at-item-p)))
17479 (org-call-with-arg 'org-cycle-list-bullet nil))
17480 ((and (not (eq org-support-shift-select 'always))
17481 (org-at-property-p))
17482 (call-interactively 'org-property-next-allowed-value))
17483 ((org-clocktable-try-shift 'right arg))
17484 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
17485 (org-support-shift-select
17486 (org-call-for-shift-select 'forward-char))
17487 (t (org-shiftselect-error))))
17489 (defun org-shiftleft (&optional arg)
17490 "Cycle the thing at point or in the current line, depending on context.
17491 Depending on context, this does one of the following:
17493 - switch a timestamp at point one day into the past
17494 - on a headline, switch to the previous TODO keyword.
17495 - on an item, switch entire list to the previous bullet type
17496 - on a property line, switch to the previous allowed value
17497 - on a clocktable definition line, move time block into the past"
17498 (interactive "P")
17499 (cond
17500 ((run-hook-with-args-until-success 'org-shiftleft-hook))
17501 ((and org-support-shift-select (org-region-active-p))
17502 (org-call-for-shift-select 'backward-char))
17503 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
17504 ((and (not (eq org-support-shift-select 'always))
17505 (org-on-heading-p))
17506 (let ((org-inhibit-logging
17507 (not org-treat-S-cursor-todo-selection-as-state-change))
17508 (org-inhibit-blocking
17509 (not org-treat-S-cursor-todo-selection-as-state-change)))
17510 (org-call-with-arg 'org-todo 'left)))
17511 ((or (and org-support-shift-select
17512 (not (eq org-support-shift-select 'always))
17513 (org-at-item-bullet-p))
17514 (and (not org-support-shift-select) (org-at-item-p)))
17515 (org-call-with-arg 'org-cycle-list-bullet 'previous))
17516 ((and (not (eq org-support-shift-select 'always))
17517 (org-at-property-p))
17518 (call-interactively 'org-property-previous-allowed-value))
17519 ((org-clocktable-try-shift 'left arg))
17520 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
17521 (org-support-shift-select
17522 (org-call-for-shift-select 'backward-char))
17523 (t (org-shiftselect-error))))
17525 (defun org-shiftcontrolright ()
17526 "Switch to next TODO set."
17527 (interactive)
17528 (cond
17529 ((and org-support-shift-select (org-region-active-p))
17530 (org-call-for-shift-select 'forward-word))
17531 ((and (not (eq org-support-shift-select 'always))
17532 (org-on-heading-p))
17533 (org-call-with-arg 'org-todo 'nextset))
17534 (org-support-shift-select
17535 (org-call-for-shift-select 'forward-word))
17536 (t (org-shiftselect-error))))
17538 (defun org-shiftcontrolleft ()
17539 "Switch to previous TODO set."
17540 (interactive)
17541 (cond
17542 ((and org-support-shift-select (org-region-active-p))
17543 (org-call-for-shift-select 'backward-word))
17544 ((and (not (eq org-support-shift-select 'always))
17545 (org-on-heading-p))
17546 (org-call-with-arg 'org-todo 'previousset))
17547 (org-support-shift-select
17548 (org-call-for-shift-select 'backward-word))
17549 (t (org-shiftselect-error))))
17551 (defun org-shiftcontrolup ()
17552 "Change timestamps synchronously up in CLOCK log lines."
17553 (interactive)
17554 (cond ((and (not org-support-shift-select)
17555 (org-at-clock-log-p)
17556 (org-at-timestamp-p t))
17557 (org-clock-timestamps-up))
17558 (t (org-shiftselect-error))))
17560 (defun org-shiftcontroldown ()
17561 "Change timestamps synchronously down in CLOCK log lines."
17562 (interactive)
17563 (cond ((and (not org-support-shift-select)
17564 (org-at-clock-log-p)
17565 (org-at-timestamp-p t))
17566 (org-clock-timestamps-down))
17567 (t (org-shiftselect-error))))
17569 (defun org-ctrl-c-ret ()
17570 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
17571 (interactive)
17572 (cond
17573 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
17574 (t (call-interactively 'org-insert-heading))))
17576 (defun org-copy-special ()
17577 "Copy region in table or copy current subtree.
17578 Calls `org-table-copy' or `org-copy-subtree', depending on context.
17579 See the individual commands for more information."
17580 (interactive)
17581 (call-interactively
17582 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
17584 (defun org-cut-special ()
17585 "Cut region in table or cut current subtree.
17586 Calls `org-table-copy' or `org-cut-subtree', depending on context.
17587 See the individual commands for more information."
17588 (interactive)
17589 (call-interactively
17590 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
17592 (defun org-paste-special (arg)
17593 "Paste rectangular region into table, or past subtree relative to level.
17594 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
17595 See the individual commands for more information."
17596 (interactive "P")
17597 (if (org-at-table-p)
17598 (org-table-paste-rectangle)
17599 (org-paste-subtree arg)))
17601 (defun org-edit-special (&optional arg)
17602 "Call a special editor for the stuff at point.
17603 When at a table, call the formula editor with `org-table-edit-formulas'.
17604 When at the first line of an src example, call `org-edit-src-code'.
17605 When in an #+include line, visit the include file. Otherwise call
17606 `ffap' to visit the file at point."
17607 (interactive)
17608 ;; possibly prep session before editing source
17609 (when arg
17610 (let* ((info (org-babel-get-src-block-info))
17611 (lang (nth 0 info))
17612 (params (nth 2 info))
17613 (session (cdr (assoc :session params))))
17614 (when (and info session) ;; we are in a source-code block with a session
17615 (funcall
17616 (intern (concat "org-babel-prep-session:" lang)) session params))))
17617 (cond ;; proceed with `org-edit-special'
17618 ((save-excursion
17619 (beginning-of-line 1)
17620 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
17621 (find-file (org-trim (match-string 1))))
17622 ((org-edit-src-code))
17623 ((org-edit-fixed-width-region))
17624 ((org-at-table.el-p)
17625 (org-edit-src-code))
17626 ((or (org-at-table-p)
17627 (save-excursion
17628 (beginning-of-line 1)
17629 (looking-at "[ \t]*#\\+TBLFM:")))
17630 (call-interactively 'org-table-edit-formulas))
17631 (t (call-interactively 'ffap))))
17633 (defun org-ctrl-c-ctrl-c (&optional arg)
17634 "Set tags in headline, or update according to changed information at point.
17636 This command does many different things, depending on context:
17638 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
17639 this is what we do.
17641 - If the cursor is on a statistics cookie, update it.
17643 - If the cursor is in a headline, prompt for tags and insert them
17644 into the current line, aligned to `org-tags-column'. When called
17645 with prefix arg, realign all tags in the current buffer.
17647 - If the cursor is in one of the special #+KEYWORD lines, this
17648 triggers scanning the buffer for these lines and updating the
17649 information.
17651 - If the cursor is inside a table, realign the table. This command
17652 works even if the automatic table editor has been turned off.
17654 - If the cursor is on a #+TBLFM line, re-apply the formulas to
17655 the entire table.
17657 - If the cursor is at a footnote reference or definition, jump to
17658 the corresponding definition or references, respectively.
17660 - If the cursor is a the beginning of a dynamic block, update it.
17662 - If the current buffer is a capture buffer, close note and file it.
17664 - If the cursor is on a <<<target>>>, update radio targets and
17665 corresponding links in this buffer.
17667 - If the cursor is on a numbered item in a plain list, renumber the
17668 ordered list.
17670 - If the cursor is on a checkbox, toggle it.
17672 - If the cursor is on a code block, evaluate it. The variable
17673 `org-confirm-babel-evaluate' can be used to control prompting
17674 before code block evaluation, by default every code block
17675 evaluation requires confirmation. Code block evaluation can be
17676 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
17677 (interactive "P")
17678 (let ((org-enable-table-editor t))
17679 (cond
17680 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
17681 org-occur-highlights
17682 org-latex-fragment-image-overlays)
17683 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
17684 (org-remove-occur-highlights)
17685 (org-remove-latex-fragment-image-overlays)
17686 (message "Temporary highlights/overlays removed from current buffer"))
17687 ((and (local-variable-p 'org-finish-function (current-buffer))
17688 (fboundp org-finish-function))
17689 (funcall org-finish-function))
17690 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
17691 ((or (looking-at org-property-start-re)
17692 (org-at-property-p))
17693 (call-interactively 'org-property-action))
17694 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
17695 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
17696 (or (org-on-heading-p) (org-at-item-p)))
17697 (call-interactively 'org-update-statistics-cookies))
17698 ((org-on-heading-p) (call-interactively 'org-set-tags))
17699 ((org-at-table.el-p)
17700 (message "Use C-c ' to edit table.el tables"))
17701 ((org-at-table-p)
17702 (org-table-maybe-eval-formula)
17703 (if arg
17704 (call-interactively 'org-table-recalculate)
17705 (org-table-maybe-recalculate-line))
17706 (call-interactively 'org-table-align)
17707 (orgtbl-send-table 'maybe))
17708 ((or (org-footnote-at-reference-p)
17709 (org-footnote-at-definition-p))
17710 (call-interactively 'org-footnote-action))
17711 ((org-at-item-checkbox-p)
17712 ;; Cursor at a checkbox: repair list and update checkboxes. Send
17713 ;; list only if at top item.
17714 (let* ((cbox (match-string 1))
17715 (struct (org-list-struct))
17716 (old-struct (copy-tree struct))
17717 (parents (org-list-parents-alist struct))
17718 (prevs (org-list-prevs-alist struct))
17719 (orderedp (org-entry-get nil "ORDERED"))
17720 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
17721 block-item)
17722 ;; Use a light version of `org-toggle-checkbox' to avoid
17723 ;; computing list structure twice.
17724 (org-list-set-checkbox (point-at-bol) struct
17725 (cond
17726 ((equal arg '(16)) "[-]")
17727 ((equal arg '(4)) nil)
17728 ((equal "[X]" cbox) "[ ]")
17729 (t "[X]")))
17730 (org-list-struct-fix-ind struct parents)
17731 (org-list-struct-fix-bul struct prevs)
17732 (setq block-item
17733 (org-list-struct-fix-box struct parents prevs orderedp))
17734 (when block-item
17735 (message
17736 "Checkboxes were removed due to unchecked box at line %d"
17737 (org-current-line block-item)))
17738 (org-list-struct-apply-struct struct old-struct)
17739 (org-update-checkbox-count-maybe)
17740 (when firstp (org-list-send-list 'maybe))))
17741 ((org-at-item-p)
17742 ;; Cursor at an item: repair list. Do checkbox related actions
17743 ;; only if function was called with an argument. Send list only
17744 ;; if at top item.
17745 (let* ((struct (org-list-struct))
17746 (old-struct (copy-tree struct))
17747 (parents (org-list-parents-alist struct))
17748 (prevs (org-list-prevs-alist struct))
17749 (firstp (= (org-list-get-top-point struct) (point-at-bol))))
17750 (org-list-struct-fix-ind struct parents)
17751 (org-list-struct-fix-bul struct prevs)
17752 (when arg
17753 (org-list-set-checkbox (point-at-bol) struct "[ ]")
17754 (org-list-struct-fix-box struct parents prevs))
17755 (org-list-struct-apply-struct struct old-struct)
17756 (when arg (org-update-checkbox-count-maybe))
17757 (when firstp (org-list-send-list 'maybe))))
17758 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
17759 ;; Dynamic block
17760 (beginning-of-line 1)
17761 (save-excursion (org-update-dblock)))
17762 ((save-excursion
17763 (beginning-of-line 1)
17764 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
17765 (cond
17766 ((equal (match-string 1) "TBLFM")
17767 ;; Recalculate the table before this line
17768 (save-excursion
17769 (beginning-of-line 1)
17770 (skip-chars-backward " \r\n\t")
17771 (if (org-at-table-p)
17772 (org-call-with-arg 'org-table-recalculate (or arg t)))))
17774 (let ((org-inhibit-startup-visibility-stuff t)
17775 (org-startup-align-all-tables nil))
17776 (org-save-outline-visibility 'use-markers (org-mode-restart)))
17777 (message "Local setup has been refreshed"))))
17778 ((org-clock-update-time-maybe))
17779 (t (error "C-c C-c can do nothing useful at this location")))))
17781 (defun org-mode-restart ()
17782 "Restart Org-mode, to scan again for special lines.
17783 Also updates the keyword regular expressions."
17784 (interactive)
17785 (org-mode)
17786 (message "Org-mode restarted"))
17788 (defun org-kill-note-or-show-branches ()
17789 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
17790 (interactive)
17791 (if (not org-finish-function)
17792 (progn
17793 (hide-subtree)
17794 (call-interactively 'show-branches))
17795 (let ((org-note-abort t))
17796 (funcall org-finish-function))))
17798 (defun org-return (&optional indent)
17799 "Goto next table row or insert a newline.
17800 Calls `org-table-next-row' or `newline', depending on context.
17801 See the individual commands for more information."
17802 (interactive)
17803 (cond
17804 ((bobp) (if indent (newline-and-indent) (newline)))
17805 ((org-at-table-p)
17806 (org-table-justify-field-maybe)
17807 (call-interactively 'org-table-next-row))
17808 ;; when `newline-and-indent' is called within a list, make sure
17809 ;; text moved stays inside the item.
17810 ((and (org-in-item-p) indent)
17811 (if (and (org-at-item-p) (>= (point) (match-end 0)))
17812 (progn
17813 (newline)
17814 (org-indent-line-to (length (match-string 0))))
17815 (let ((ind (org-get-indentation)))
17816 (newline)
17817 (if (org-looking-back org-list-end-re)
17818 (org-indent-line-function)
17819 (org-indent-line-to ind)))))
17820 ((and org-return-follows-link
17821 (eq (get-text-property (point) 'face) 'org-link))
17822 (call-interactively 'org-open-at-point))
17823 ((and (org-at-heading-p)
17824 (looking-at
17825 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
17826 (org-show-entry)
17827 (end-of-line 1)
17828 (newline))
17829 (t (if indent (newline-and-indent) (newline)))))
17831 (defun org-return-indent ()
17832 "Goto next table row or insert a newline and indent.
17833 Calls `org-table-next-row' or `newline-and-indent', depending on
17834 context. See the individual commands for more information."
17835 (interactive)
17836 (org-return t))
17838 (defun org-ctrl-c-star ()
17839 "Compute table, or change heading status of lines.
17840 Calls `org-table-recalculate' or `org-toggle-heading',
17841 depending on context."
17842 (interactive)
17843 (cond
17844 ((org-at-table-p)
17845 (call-interactively 'org-table-recalculate))
17847 ;; Convert all lines in region to list items
17848 (call-interactively 'org-toggle-heading))))
17850 (defun org-ctrl-c-minus ()
17851 "Insert separator line in table or modify bullet status of line.
17852 Also turns a plain line or a region of lines into list items.
17853 Calls `org-table-insert-hline', `org-toggle-item', or
17854 `org-cycle-list-bullet', depending on context."
17855 (interactive)
17856 (cond
17857 ((org-at-table-p)
17858 (call-interactively 'org-table-insert-hline))
17859 ((org-region-active-p)
17860 (call-interactively 'org-toggle-item))
17861 ((org-in-item-p)
17862 (call-interactively 'org-cycle-list-bullet))
17864 (call-interactively 'org-toggle-item))))
17866 (defun org-toggle-item (arg)
17867 "Convert headings or normal lines to items, items to normal lines.
17868 If there is no active region, only the current line is considered.
17870 If the first non blank line in the region is an headline, convert
17871 all headlines to items, shifting text accordingly.
17873 If it is an item, convert all items to normal lines.
17875 If it is normal text, change region into an item. With a prefix
17876 argument ARG, change each line in region into an item."
17877 (interactive "P")
17878 (let ((shift-text
17879 (function
17880 ;; Shift text in current section to IND, from point to END.
17881 ;; The function leaves point to END line.
17882 (lambda (ind end)
17883 (let ((min-i 1000) (end (copy-marker end)))
17884 ;; First determine the minimum indentation (MIN-I) of
17885 ;; the text.
17886 (save-excursion
17887 (catch 'exit
17888 (while (< (point) end)
17889 (let ((i (org-get-indentation)))
17890 (cond
17891 ;; Skip blank lines and inline tasks.
17892 ((looking-at "^[ \t]*$"))
17893 ((looking-at "^\\*+ "))
17894 ;; We can't find less than 0 indentation.
17895 ((zerop i) (throw 'exit (setq min-i 0)))
17896 ((< i min-i) (setq min-i i))))
17897 (forward-line))))
17898 ;; Then indent each line so that a line indented to
17899 ;; MIN-I becomes indented to IND. Ignore blank lines
17900 ;; and inline tasks in the process.
17901 (let ((delta (- ind min-i)))
17902 (while (< (point) end)
17903 (unless (or (looking-at "^[ \t]*$")
17904 (looking-at "^\\*+ "))
17905 (org-indent-line-to (+ (org-get-indentation) delta)))
17906 (forward-line)))))))
17907 (skip-blanks
17908 (function
17909 ;; Return beginning of first non-blank line, starting from
17910 ;; line at POS.
17911 (lambda (pos)
17912 (save-excursion
17913 (goto-char pos)
17914 (skip-chars-forward " \r\t\n")
17915 (point-at-bol)))))
17916 beg end)
17917 ;; Determine boundaries of changes.
17918 (if (org-region-active-p)
17919 (setq beg (funcall skip-blanks (region-beginning))
17920 end (copy-marker (region-end)))
17921 (setq beg (funcall skip-blanks (point-at-bol))
17922 end (copy-marker (point-at-eol))))
17923 ;; Depending on the starting line, choose an action on the text
17924 ;; between BEG and END.
17925 (org-with-limited-levels
17926 (save-excursion
17927 (goto-char beg)
17928 (cond
17929 ;; Case 1. Start at an item: de-itemize. Note that it only
17930 ;; happens when a region is active: `org-ctrl-c-minus'
17931 ;; would call `org-cycle-list-bullet' otherwise.
17932 ((org-at-item-p)
17933 (while (< (point) end)
17934 (when (org-at-item-p)
17935 (skip-chars-forward " \t")
17936 (delete-region (point) (match-end 0)))
17937 (forward-line)))
17938 ;; Case 2. Start at an heading: convert to items.
17939 ((org-on-heading-p)
17940 (let* ((bul (org-list-bullet-string "-"))
17941 (bul-len (length bul))
17942 ;; Indentation of the first heading. It should be
17943 ;; relative to the indentation of its parent, if any.
17944 (start-ind (save-excursion
17945 (cond
17946 ((not org-adapt-indentation) 0)
17947 ((not (outline-previous-heading)) 0)
17948 (t (length (match-string 0))))))
17949 ;; Level of first heading. Further headings will be
17950 ;; compared to it to determine hierarchy in the list.
17951 (ref-level (org-reduced-level (org-outline-level))))
17952 (while (< (point) end)
17953 (let* ((level (org-reduced-level (org-outline-level)))
17954 (delta (max 0 (- level ref-level))))
17955 ;; If current headline is less indented than the first
17956 ;; one, set it as reference, in order to preserve
17957 ;; subtrees.
17958 (when (< level ref-level) (setq ref-level level))
17959 (replace-match bul t t)
17960 (org-indent-line-to (+ start-ind (* delta bul-len)))
17961 ;; Ensure all text down to END (or SECTION-END) belongs
17962 ;; to the newly created item.
17963 (let ((section-end (save-excursion
17964 (or (outline-next-heading) (point)))))
17965 (forward-line)
17966 (funcall shift-text
17967 (+ start-ind (* (1+ delta) bul-len))
17968 (min end section-end)))))))
17969 ;; Case 3. Normal line with ARG: turn each non-item line into
17970 ;; an item.
17971 (arg
17972 (while (< (point) end)
17973 (unless (or (org-on-heading-p) (org-at-item-p))
17974 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
17975 (replace-match
17976 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
17977 (forward-line)))
17978 ;; Case 4. Normal line without ARG: make the first line of
17979 ;; region an item, and shift indentation of others
17980 ;; lines to set them as item's body.
17981 (t (let* ((bul (org-list-bullet-string "-"))
17982 (bul-len (length bul))
17983 (ref-ind (org-get-indentation)))
17984 (skip-chars-forward " \t")
17985 (insert bul)
17986 (forward-line)
17987 (while (< (point) end)
17988 ;; Ensure that lines less indented than first one
17989 ;; still get included in item body.
17990 (funcall shift-text
17991 (+ ref-ind bul-len)
17992 (min end (save-excursion (or (outline-next-heading)
17993 (point)))))
17994 (forward-line)))))))))
17996 (defun org-toggle-heading (&optional nstars)
17997 "Convert headings to normal text, or items or text to headings.
17998 If there is no active region, only the current line is considered.
18000 If the first non blank line is an headline, remove the stars from
18001 all headlines in the region.
18003 If it is a plain list item, turn all plain list items into headings.
18005 If it is a normal line, turn each and every normal line (i.e. not
18006 an heading or an item) in the region into a heading.
18008 When converting a line into a heading, the number of stars is chosen
18009 such that the lines become children of the current entry. However,
18010 when a prefix argument is given, its value determines the number of
18011 stars to add."
18012 (interactive "P")
18013 (let ((skip-blanks
18014 (function
18015 ;; Return beginning of first non-blank line, starting from
18016 ;; line at POS.
18017 (lambda (pos)
18018 (save-excursion
18019 (goto-char pos)
18020 (skip-chars-forward " \r\t\n")
18021 (point-at-bol)))))
18022 beg end)
18023 ;; Determine boundaries of changes. If region ends at a bol, do
18024 ;; not consider the last line to be in the region.
18025 (if (org-region-active-p)
18026 (setq beg (funcall skip-blanks (region-beginning))
18027 end (copy-marker (save-excursion
18028 (goto-char (region-end))
18029 (if (bolp) (point) (point-at-eol)))))
18030 (setq beg (funcall skip-blanks (point-at-bol))
18031 end (copy-marker (point-at-eol))))
18032 ;; Ensure inline tasks don't count as headings.
18033 (org-with-limited-levels
18034 (save-excursion
18035 (goto-char beg)
18036 (cond
18037 ;; Case 1. Started at an heading: de-star headings.
18038 ((org-on-heading-p)
18039 (while (< (point) end)
18040 (when (org-on-heading-p t)
18041 (looking-at outline-regexp) (replace-match ""))
18042 (forward-line)))
18043 ;; Case 2. Started at an item: change items into headlines.
18044 ;; One star will be added by `org-list-to-subtree'.
18045 ((org-at-item-p)
18046 (let* ((stars (make-string
18047 (if nstars
18048 ;; subtract the star that will be added again by
18049 ;; `org-list-to-subtree'
18050 (1- (prefix-numeric-value current-prefix-arg))
18051 (or (org-current-level) 0))
18052 ?*))
18053 (add-stars
18054 (cond (nstars "") ; stars from prefix only
18055 ((equal stars "") "") ; before first heading
18056 (org-odd-levels-only "*") ; inside heading, odd
18057 (t "")))) ; inside heading, oddeven
18058 (while (< (point) end)
18059 (when (org-at-item-p)
18060 ;; Pay attention to cases when region ends before list.
18061 (let* ((struct (org-list-struct))
18062 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18063 (save-restriction
18064 (narrow-to-region (point) list-end)
18065 (insert
18066 (org-list-to-subtree
18067 (org-list-parse-list t)
18068 '(:istart (concat stars add-stars (funcall get-stars depth))
18069 :icount (concat stars add-stars (funcall get-stars depth))))))))
18070 (forward-line))))
18071 ;; Case 3. Started at normal text: make every line an heading,
18072 ;; skipping headlines and items.
18073 (t (let* ((stars (make-string
18074 (if nstars
18075 (prefix-numeric-value current-prefix-arg)
18076 (or (org-current-level) 0))
18077 ?*))
18078 (add-stars
18079 (cond (nstars "") ; stars from prefix only
18080 ((equal stars "") "*") ; before first heading
18081 (org-odd-levels-only "**") ; inside heading, odd
18082 (t "*"))) ; inside heading, oddeven
18083 (rpl (concat stars add-stars " ")))
18084 (while (< (point) end)
18085 (when (and (not (org-on-heading-p)) (not (org-at-item-p))
18086 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18087 (replace-match (concat rpl (match-string 2))))
18088 (forward-line)))))))))
18090 (defun org-meta-return (&optional arg)
18091 "Insert a new heading or wrap a region in a table.
18092 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18093 See the individual commands for more information."
18094 (interactive "P")
18095 (cond
18096 ((run-hook-with-args-until-success 'org-metareturn-hook))
18097 ((org-at-table-p)
18098 (call-interactively 'org-table-wrap-region))
18099 (t (call-interactively 'org-insert-heading))))
18101 ;;; Menu entries
18103 ;; Define the Org-mode menus
18104 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18105 '("Tbl"
18106 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18107 ["Next Field" org-cycle (org-at-table-p)]
18108 ["Previous Field" org-shifttab (org-at-table-p)]
18109 ["Next Row" org-return (org-at-table-p)]
18110 "--"
18111 ["Blank Field" org-table-blank-field (org-at-table-p)]
18112 ["Edit Field" org-table-edit-field (org-at-table-p)]
18113 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18114 "--"
18115 ("Column"
18116 ["Move Column Left" org-metaleft (org-at-table-p)]
18117 ["Move Column Right" org-metaright (org-at-table-p)]
18118 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18119 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18120 ("Row"
18121 ["Move Row Up" org-metaup (org-at-table-p)]
18122 ["Move Row Down" org-metadown (org-at-table-p)]
18123 ["Delete Row" org-shiftmetaup (org-at-table-p)]
18124 ["Insert Row" org-shiftmetadown (org-at-table-p)]
18125 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
18126 "--"
18127 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
18128 ("Rectangle"
18129 ["Copy Rectangle" org-copy-special (org-at-table-p)]
18130 ["Cut Rectangle" org-cut-special (org-at-table-p)]
18131 ["Paste Rectangle" org-paste-special (org-at-table-p)]
18132 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
18133 "--"
18134 ("Calculate"
18135 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
18136 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
18137 ["Edit Formulas" org-edit-special (org-at-table-p)]
18138 "--"
18139 ["Recalculate line" org-table-recalculate (org-at-table-p)]
18140 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
18141 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
18142 "--"
18143 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
18144 "--"
18145 ["Sum Column/Rectangle" org-table-sum
18146 (or (org-at-table-p) (org-region-active-p))]
18147 ["Which Column?" org-table-current-column (org-at-table-p)])
18148 ["Debug Formulas"
18149 org-table-toggle-formula-debugger
18150 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
18151 ["Show Col/Row Numbers"
18152 org-table-toggle-coordinate-overlays
18153 :style toggle
18154 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
18155 "--"
18156 ["Create" org-table-create (and (not (org-at-table-p))
18157 org-enable-table-editor)]
18158 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
18159 ["Import from File" org-table-import (not (org-at-table-p))]
18160 ["Export to File" org-table-export (org-at-table-p)]
18161 "--"
18162 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
18164 (easy-menu-define org-org-menu org-mode-map "Org menu"
18165 '("Org"
18166 ("Show/Hide"
18167 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
18168 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
18169 ["Sparse Tree..." org-sparse-tree t]
18170 ["Reveal Context" org-reveal t]
18171 ["Show All" show-all t]
18172 "--"
18173 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
18174 "--"
18175 ["New Heading" org-insert-heading t]
18176 ("Navigate Headings"
18177 ["Up" outline-up-heading t]
18178 ["Next" outline-next-visible-heading t]
18179 ["Previous" outline-previous-visible-heading t]
18180 ["Next Same Level" outline-forward-same-level t]
18181 ["Previous Same Level" outline-backward-same-level t]
18182 "--"
18183 ["Jump" org-goto t])
18184 ("Edit Structure"
18185 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
18186 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
18187 "--"
18188 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
18189 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
18190 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
18191 "--"
18192 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
18193 "--"
18194 ["Promote Heading" org-metaleft (not (org-at-table-p))]
18195 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
18196 ["Demote Heading" org-metaright (not (org-at-table-p))]
18197 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
18198 "--"
18199 ["Sort Region/Children" org-sort (not (org-at-table-p))]
18200 "--"
18201 ["Convert to odd levels" org-convert-to-odd-levels t]
18202 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
18203 ("Editing"
18204 ["Emphasis..." org-emphasize t]
18205 ["Edit Source Example" org-edit-special t]
18206 "--"
18207 ["Footnote new/jump" org-footnote-action t]
18208 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
18209 ("Archive"
18210 ["Archive (default method)" org-archive-subtree-default t]
18211 "--"
18212 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
18213 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
18214 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
18216 "--"
18217 ("Hyperlinks"
18218 ["Store Link (Global)" org-store-link t]
18219 ["Find existing link to here" org-occur-link-in-agenda-files t]
18220 ["Insert Link" org-insert-link t]
18221 ["Follow Link" org-open-at-point t]
18222 "--"
18223 ["Next link" org-next-link t]
18224 ["Previous link" org-previous-link t]
18225 "--"
18226 ["Descriptive Links"
18227 (progn (add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
18228 :style radio
18229 :selected (member '(org-link) buffer-invisibility-spec)]
18230 ["Literal Links"
18231 (progn
18232 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
18233 :style radio
18234 :selected (not (member '(org-link) buffer-invisibility-spec))])
18235 "--"
18236 ("TODO Lists"
18237 ["TODO/DONE/-" org-todo t]
18238 ("Select keyword"
18239 ["Next keyword" org-shiftright (org-on-heading-p)]
18240 ["Previous keyword" org-shiftleft (org-on-heading-p)]
18241 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
18242 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
18243 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
18244 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
18245 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
18246 "--"
18247 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
18248 :selected org-enforce-todo-dependencies :style toggle :active t]
18249 "Settings for tree at point"
18250 ["Do Children sequentially" org-toggle-ordered-property :style radio
18251 :selected (org-entry-get nil "ORDERED")
18252 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18253 ["Do Children parallel" org-toggle-ordered-property :style radio
18254 :selected (not (org-entry-get nil "ORDERED"))
18255 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18256 "--"
18257 ["Set Priority" org-priority t]
18258 ["Priority Up" org-shiftup t]
18259 ["Priority Down" org-shiftdown t]
18260 "--"
18261 ["Get news from all feeds" org-feed-update-all t]
18262 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
18263 ["Customize feeds" (customize-variable 'org-feed-alist) t])
18264 ("TAGS and Properties"
18265 ["Set Tags" org-set-tags-command t]
18266 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
18267 "--"
18268 ["Set property" org-set-property t]
18269 ["Column view of properties" org-columns t]
18270 ["Insert Column View DBlock" org-insert-columns-dblock t])
18271 ("Dates and Scheduling"
18272 ["Timestamp" org-time-stamp t]
18273 ["Timestamp (inactive)" org-time-stamp-inactive t]
18274 ("Change Date"
18275 ["1 Day Later" org-shiftright t]
18276 ["1 Day Earlier" org-shiftleft t]
18277 ["1 ... Later" org-shiftup t]
18278 ["1 ... Earlier" org-shiftdown t])
18279 ["Compute Time Range" org-evaluate-time-range t]
18280 ["Schedule Item" org-schedule t]
18281 ["Deadline" org-deadline t]
18282 "--"
18283 ["Custom time format" org-toggle-time-stamp-overlays
18284 :style radio :selected org-display-custom-times]
18285 "--"
18286 ["Goto Calendar" org-goto-calendar t]
18287 ["Date from Calendar" org-date-from-calendar t]
18288 "--"
18289 ["Start/Restart Timer" org-timer-start t]
18290 ["Pause/Continue Timer" org-timer-pause-or-continue t]
18291 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
18292 ["Insert Timer String" org-timer t]
18293 ["Insert Timer Item" org-timer-item t])
18294 ("Logging work"
18295 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
18296 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
18297 ["Clock out" org-clock-out t]
18298 ["Clock cancel" org-clock-cancel t]
18299 "--"
18300 ["Mark as default task" org-clock-mark-default-task t]
18301 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
18302 ["Goto running clock" org-clock-goto t]
18303 "--"
18304 ["Display times" org-clock-display t]
18305 ["Create clock table" org-clock-report t]
18306 "--"
18307 ["Record DONE time"
18308 (progn (setq org-log-done (not org-log-done))
18309 (message "Switching to %s will %s record a timestamp"
18310 (car org-done-keywords)
18311 (if org-log-done "automatically" "not")))
18312 :style toggle :selected org-log-done])
18313 "--"
18314 ["Agenda Command..." org-agenda t]
18315 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
18316 ("File List for Agenda")
18317 ("Special views current file"
18318 ["TODO Tree" org-show-todo-tree t]
18319 ["Check Deadlines" org-check-deadlines t]
18320 ["Timeline" org-timeline t]
18321 ["Tags/Property tree" org-match-sparse-tree t])
18322 "--"
18323 ["Export/Publish..." org-export t]
18324 ("LaTeX"
18325 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
18326 :selected org-cdlatex-mode]
18327 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
18328 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
18329 ["Modify math symbol" org-cdlatex-math-modify
18330 (org-inside-LaTeX-fragment-p)]
18331 ["Insert citation" org-reftex-citation t]
18332 "--"
18333 ["Template for BEAMER" org-insert-beamer-options-template t])
18334 "--"
18335 ("MobileOrg"
18336 ["Push Files and Views" org-mobile-push t]
18337 ["Get Captured and Flagged" org-mobile-pull t]
18338 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
18339 "--"
18340 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
18341 "--"
18342 ("Documentation"
18343 ["Show Version" org-version t]
18344 ["Info Documentation" org-info t])
18345 ("Customize"
18346 ["Browse Org Group" org-customize t]
18347 "--"
18348 ["Expand This Menu" org-create-customize-menu
18349 (fboundp 'customize-menu-create)])
18350 ["Send bug report" org-submit-bug-report t]
18351 "--"
18352 ("Refresh/Reload"
18353 ["Refresh setup current buffer" org-mode-restart t]
18354 ["Reload Org (after update)" org-reload t]
18355 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
18358 (defun org-info (&optional node)
18359 "Read documentation for Org-mode in the info system.
18360 With optional NODE, go directly to that node."
18361 (interactive)
18362 (info (format "(org)%s" (or node ""))))
18364 ;;;###autoload
18365 (defun org-submit-bug-report ()
18366 "Submit a bug report on Org-mode via mail.
18368 Don't hesitate to report any problems or inaccurate documentation.
18370 If you don't have setup sending mail from (X)Emacs, please copy the
18371 output buffer into your mail program, as it gives us important
18372 information about your Org-mode version and configuration."
18373 (interactive)
18374 (require 'reporter)
18375 (org-load-modules-maybe)
18376 (org-require-autoloaded-modules)
18377 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
18378 (reporter-submit-bug-report
18379 "emacs-orgmode@gnu.org"
18380 (org-version)
18381 (let (list)
18382 (save-window-excursion
18383 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
18384 (delete-other-windows)
18385 (erase-buffer)
18386 (insert "You are about to submit a bug report to the Org-mode mailing list.
18388 We would like to add your full Org-mode and Outline configuration to the
18389 bug report. This greatly simplifies the work of the maintainer and
18390 other experts on the mailing list.
18392 HOWEVER, some variables you have customized may contain private
18393 information. The names of customers, colleagues, or friends, might
18394 appear in the form of file names, tags, todo states, or search strings.
18395 If you answer yes to the prompt, you might want to check and remove
18396 such private information before sending the email.")
18397 (add-text-properties (point-min) (point-max) '(face org-warning))
18398 (when (yes-or-no-p "Include your Org-mode configuration ")
18399 (mapatoms
18400 (lambda (v)
18401 (and (boundp v)
18402 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
18403 (or (and (symbol-value v)
18404 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
18405 (and
18406 (get v 'custom-type) (get v 'standard-value)
18407 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
18408 (push v list)))))
18409 (kill-buffer (get-buffer "*Warn about privacy*"))
18410 list))
18411 nil nil
18412 "Remember to cover the basics, that is, what you expected to happen and
18413 what in fact did happen. You don't know how to make a good report? See
18415 http://orgmode.org/manual/Feedback.html#Feedback
18417 Your bug report will be posted to the Org-mode mailing list.
18418 ------------------------------------------------------------------------")
18419 (save-excursion
18420 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
18421 (replace-match "\\1Bug: \\3 [\\2]")))))
18424 (defun org-install-agenda-files-menu ()
18425 (let ((bl (buffer-list)))
18426 (save-excursion
18427 (while bl
18428 (set-buffer (pop bl))
18429 (if (org-mode-p) (setq bl nil)))
18430 (when (org-mode-p)
18431 (easy-menu-change
18432 '("Org") "File List for Agenda"
18433 (append
18434 (list
18435 ["Edit File List" (org-edit-agenda-file-list) t]
18436 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
18437 ["Remove Current File from List" org-remove-file t]
18438 ["Cycle through agenda files" org-cycle-agenda-files t]
18439 ["Occur in all agenda files" org-occur-in-agenda-files t]
18440 "--")
18441 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
18443 ;;;; Documentation
18445 ;;;###autoload
18446 (defun org-require-autoloaded-modules ()
18447 (interactive)
18448 (mapc 'require
18449 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
18450 org-docbook org-exp org-html org-icalendar
18451 org-id org-latex
18452 org-publish org-remember org-table
18453 org-timer org-xoxo)))
18455 ;;;###autoload
18456 (defun org-reload (&optional uncompiled)
18457 "Reload all org lisp files.
18458 With prefix arg UNCOMPILED, load the uncompiled versions."
18459 (interactive "P")
18460 (require 'find-func)
18461 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
18462 (dir-org (file-name-directory (org-find-library-name "org")))
18463 (dir-org-contrib (ignore-errors
18464 (file-name-directory
18465 (org-find-library-name "org-contribdir"))))
18466 (babel-files
18467 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
18468 (append (list nil "comint" "eval" "exp" "keys"
18469 "lob" "ref" "table" "tangle")
18470 (delq nil
18471 (mapcar
18472 (lambda (lang)
18473 (when (cdr lang) (symbol-name (car lang))))
18474 org-babel-load-languages)))))
18475 (files
18476 (append (directory-files dir-org t file-re)
18477 babel-files
18478 (and dir-org-contrib
18479 (directory-files dir-org-contrib t file-re))))
18480 (remove-re (concat (if (featurep 'xemacs)
18481 "org-colview" "org-colview-xemacs")
18482 "\\'")))
18483 (setq files (mapcar 'file-name-sans-extension files))
18484 (setq files (mapcar
18485 (lambda (x) (if (string-match remove-re x) nil x))
18486 files))
18487 (setq files (delq nil files))
18488 (mapc
18489 (lambda (f)
18490 (when (featurep (intern (file-name-nondirectory f)))
18491 (if (and (not uncompiled)
18492 (file-exists-p (concat f ".elc")))
18493 (load (concat f ".elc") nil nil t)
18494 (load (concat f ".el") nil nil t))))
18495 files))
18496 (org-version))
18498 ;;;###autoload
18499 (defun org-customize ()
18500 "Call the customize function with org as argument."
18501 (interactive)
18502 (org-load-modules-maybe)
18503 (org-require-autoloaded-modules)
18504 (customize-browse 'org))
18506 (defun org-create-customize-menu ()
18507 "Create a full customization menu for Org-mode, insert it into the menu."
18508 (interactive)
18509 (org-load-modules-maybe)
18510 (org-require-autoloaded-modules)
18511 (if (fboundp 'customize-menu-create)
18512 (progn
18513 (easy-menu-change
18514 '("Org") "Customize"
18515 `(["Browse Org group" org-customize t]
18516 "--"
18517 ,(customize-menu-create 'org)
18518 ["Set" Custom-set t]
18519 ["Save" Custom-save t]
18520 ["Reset to Current" Custom-reset-current t]
18521 ["Reset to Saved" Custom-reset-saved t]
18522 ["Reset to Standard Settings" Custom-reset-standard t]))
18523 (message "\"Org\"-menu now contains full customization menu"))
18524 (error "Cannot expand menu (outdated version of cus-edit.el)")))
18526 ;;;; Miscellaneous stuff
18528 ;;; Generally useful functions
18530 (defun org-get-at-bol (property)
18531 "Get text property PROPERTY at beginning of line."
18532 (get-text-property (point-at-bol) property))
18534 (defun org-find-text-property-in-string (prop s)
18535 "Return the first non-nil value of property PROP in string S."
18536 (or (get-text-property 0 prop s)
18537 (get-text-property (or (next-single-property-change 0 prop s) 0)
18538 prop s)))
18540 (defun org-display-warning (message) ;; Copied from Emacs-Muse
18541 "Display the given MESSAGE as a warning."
18542 (if (fboundp 'display-warning)
18543 (display-warning 'org message
18544 (if (featurep 'xemacs) 'warning :warning))
18545 (let ((buf (get-buffer-create "*Org warnings*")))
18546 (with-current-buffer buf
18547 (goto-char (point-max))
18548 (insert "Warning (Org): " message)
18549 (unless (bolp)
18550 (newline)))
18551 (display-buffer buf)
18552 (sit-for 0))))
18554 (defun org-eval (form)
18555 "Eval FORM and return result."
18556 (condition-case error
18557 (eval form)
18558 (error (format "%%![Error: %s]" error))))
18560 (defun org-in-commented-line ()
18561 "Is point in a line starting with `#'?"
18562 (equal (char-after (point-at-bol)) ?#))
18564 (defun org-in-indented-comment-line ()
18565 "Is point in a line starting with `#' after some white space?"
18566 (save-excursion
18567 (save-match-data
18568 (goto-char (point-at-bol))
18569 (looking-at "[ \t]*#"))))
18571 (defun org-in-verbatim-emphasis ()
18572 (save-match-data
18573 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
18575 (defun org-goto-marker-or-bmk (marker &optional bookmark)
18576 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
18577 (if (and marker (marker-buffer marker)
18578 (buffer-live-p (marker-buffer marker)))
18579 (progn
18580 (switch-to-buffer (marker-buffer marker))
18581 (if (or (> marker (point-max)) (< marker (point-min)))
18582 (widen))
18583 (goto-char marker)
18584 (org-show-context 'org-goto))
18585 (if bookmark
18586 (bookmark-jump bookmark)
18587 (error "Cannot find location"))))
18589 (defun org-quote-csv-field (s)
18590 "Quote field for inclusion in CSV material."
18591 (if (string-match "[\",]" s)
18592 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
18595 (defun org-force-self-insert (N)
18596 "Needed to enforce self-insert under remapping."
18597 (interactive "p")
18598 (self-insert-command N))
18600 (defun org-string-width (s)
18601 "Compute width of string, ignoring invisible characters.
18602 This ignores character with invisibility property `org-link', and also
18603 characters with property `org-cwidth', because these will become invisible
18604 upon the next fontification round."
18605 (let (b l)
18606 (when (or (eq t buffer-invisibility-spec)
18607 (assq 'org-link buffer-invisibility-spec))
18608 (while (setq b (text-property-any 0 (length s)
18609 'invisible 'org-link s))
18610 (setq s (concat (substring s 0 b)
18611 (substring s (or (next-single-property-change
18612 b 'invisible s) (length s)))))))
18613 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
18614 (setq s (concat (substring s 0 b)
18615 (substring s (or (next-single-property-change
18616 b 'org-cwidth s) (length s))))))
18617 (setq l (string-width s) b -1)
18618 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
18619 (setq l (- l (get-text-property b 'org-dwidth-n s))))
18622 (defun org-shorten-string (s maxlength)
18623 "Shorten string S so tht it is no longer than MAXLENGTH characters.
18624 If the string is shorter or has length MAXLENGTH, just return the
18625 original string. If it is longer, the functions finds a space in the
18626 string, breaks this string off at that locations and adds three dots
18627 as ellipsis. Including the ellipsis, the string will not be longer
18628 than MAXLENGTH. If finding a good breaking point in the string does
18629 not work, the string is just chopped off in the middle of a word
18630 if necessary."
18631 (if (<= (length s) maxlength)
18633 (let* ((n (max (- maxlength 4) 1))
18634 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
18635 (if (string-match re s)
18636 (concat (match-string 1 s) "...")
18637 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
18639 (defun org-get-indentation (&optional line)
18640 "Get the indentation of the current line, interpreting tabs.
18641 When LINE is given, assume it represents a line and compute its indentation."
18642 (if line
18643 (if (string-match "^ *" (org-remove-tabs line))
18644 (match-end 0))
18645 (save-excursion
18646 (beginning-of-line 1)
18647 (skip-chars-forward " \t")
18648 (current-column))))
18650 (defun org-get-string-indentation (s)
18651 "What indentation has S due to SPACE and TAB at the beginning of the string?"
18652 (let ((n -1) (i 0) (w tab-width) c)
18653 (catch 'exit
18654 (while (< (setq n (1+ n)) (length s))
18655 (setq c (aref s n))
18656 (cond ((= c ?\ ) (setq i (1+ i)))
18657 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
18658 (t (throw 'exit t)))))
18661 (defun org-remove-tabs (s &optional width)
18662 "Replace tabulators in S with spaces.
18663 Assumes that s is a single line, starting in column 0."
18664 (setq width (or width tab-width))
18665 (while (string-match "\t" s)
18666 (setq s (replace-match
18667 (make-string
18668 (- (* width (/ (+ (match-beginning 0) width) width))
18669 (match-beginning 0)) ?\ )
18670 t t s)))
18673 (defun org-fix-indentation (line ind)
18674 "Fix indentation in LINE.
18675 IND is a cons cell with target and minimum indentation.
18676 If the current indentation in LINE is smaller than the minimum,
18677 leave it alone. If it is larger than ind, set it to the target."
18678 (let* ((l (org-remove-tabs line))
18679 (i (org-get-indentation l))
18680 (i1 (car ind)) (i2 (cdr ind)))
18681 (if (>= i i2) (setq l (substring line i2)))
18682 (if (> i1 0)
18683 (concat (make-string i1 ?\ ) l)
18684 l)))
18686 (defun org-remove-indentation (code &optional n)
18687 "Remove the maximum common indentation from the lines in CODE.
18688 N may optionally be the number of spaces to remove."
18689 (with-temp-buffer
18690 (insert code)
18691 (org-do-remove-indentation n)
18692 (buffer-string)))
18694 (defun org-do-remove-indentation (&optional n)
18695 "Remove the maximum common indentation from the buffer."
18696 (untabify (point-min) (point-max))
18697 (let ((min 10000) re)
18698 (if n
18699 (setq min n)
18700 (goto-char (point-min))
18701 (while (re-search-forward "^ *[^ \n]" nil t)
18702 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
18703 (unless (or (= min 0) (= min 10000))
18704 (setq re (format "^ \\{%d\\}" min))
18705 (goto-char (point-min))
18706 (while (re-search-forward re nil t)
18707 (replace-match "")
18708 (end-of-line 1))
18709 min)))
18711 (defun org-fill-template (template alist)
18712 "Find each %key of ALIST in TEMPLATE and replace it."
18713 (let ((case-fold-search nil)
18714 entry key value)
18715 (setq alist (sort (copy-sequence alist)
18716 (lambda (a b) (< (length (car a)) (length (car b))))))
18717 (while (setq entry (pop alist))
18718 (setq template
18719 (replace-regexp-in-string
18720 (concat "%" (regexp-quote (car entry)))
18721 (cdr entry) template t t)))
18722 template))
18724 (defun org-base-buffer (buffer)
18725 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
18726 (if (not buffer)
18727 buffer
18728 (or (buffer-base-buffer buffer)
18729 buffer)))
18731 (defun org-trim (s)
18732 "Remove whitespace at beginning and end of string."
18733 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
18734 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
18737 (defun org-wrap (string &optional width lines)
18738 "Wrap string to either a number of lines, or a width in characters.
18739 If WIDTH is non-nil, the string is wrapped to that width, however many lines
18740 that costs. If there is a word longer than WIDTH, the text is actually
18741 wrapped to the length of that word.
18742 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
18743 many lines, whatever width that takes.
18744 The return value is a list of lines, without newlines at the end."
18745 (let* ((words (org-split-string string "[ \t\n]+"))
18746 (maxword (apply 'max (mapcar 'org-string-width words)))
18747 w ll)
18748 (cond (width
18749 (org-do-wrap words (max maxword width)))
18750 (lines
18751 (setq w maxword)
18752 (setq ll (org-do-wrap words maxword))
18753 (if (<= (length ll) lines)
18755 (setq ll words)
18756 (while (> (length ll) lines)
18757 (setq w (1+ w))
18758 (setq ll (org-do-wrap words w)))
18759 ll))
18760 (t (error "Cannot wrap this")))))
18762 (defun org-do-wrap (words width)
18763 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
18764 (let (lines line)
18765 (while words
18766 (setq line (pop words))
18767 (while (and words (< (+ (length line) (length (car words))) width))
18768 (setq line (concat line " " (pop words))))
18769 (setq lines (push line lines)))
18770 (nreverse lines)))
18772 (defun org-split-string (string &optional separators)
18773 "Splits STRING into substrings at SEPARATORS.
18774 No empty strings are returned if there are matches at the beginning
18775 and end of string."
18776 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
18777 (start 0)
18778 notfirst
18779 (list nil))
18780 (while (and (string-match rexp string
18781 (if (and notfirst
18782 (= start (match-beginning 0))
18783 (< start (length string)))
18784 (1+ start) start))
18785 (< (match-beginning 0) (length string)))
18786 (setq notfirst t)
18787 (or (eq (match-beginning 0) 0)
18788 (and (eq (match-beginning 0) (match-end 0))
18789 (eq (match-beginning 0) start))
18790 (setq list
18791 (cons (substring string start (match-beginning 0))
18792 list)))
18793 (setq start (match-end 0)))
18794 (or (eq start (length string))
18795 (setq list
18796 (cons (substring string start)
18797 list)))
18798 (nreverse list)))
18800 (defun org-quote-vert (s)
18801 "Replace \"|\" with \"\\vert\"."
18802 (while (string-match "|" s)
18803 (setq s (replace-match "\\vert" t t s)))
18806 (defun org-uuidgen-p (s)
18807 "Is S an ID created by UUIDGEN?"
18808 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
18810 (defun org-context ()
18811 "Return a list of contexts of the current cursor position.
18812 If several contexts apply, all are returned.
18813 Each context entry is a list with a symbol naming the context, and
18814 two positions indicating start and end of the context. Possible
18815 contexts are:
18817 :headline anywhere in a headline
18818 :headline-stars on the leading stars in a headline
18819 :todo-keyword on a TODO keyword (including DONE) in a headline
18820 :tags on the TAGS in a headline
18821 :priority on the priority cookie in a headline
18822 :item on the first line of a plain list item
18823 :item-bullet on the bullet/number of a plain list item
18824 :checkbox on the checkbox in a plain list item
18825 :table in an org-mode table
18826 :table-special on a special filed in a table
18827 :table-table in a table.el table
18828 :link on a hyperlink
18829 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
18830 :target on a <<target>>
18831 :radio-target on a <<<radio-target>>>
18832 :latex-fragment on a LaTeX fragment
18833 :latex-preview on a LaTeX fragment with overlayed preview image
18835 This function expects the position to be visible because it uses font-lock
18836 faces as a help to recognize the following contexts: :table-special, :link,
18837 and :keyword."
18838 (let* ((f (get-text-property (point) 'face))
18839 (faces (if (listp f) f (list f)))
18840 (p (point)) clist o)
18841 ;; First the large context
18842 (cond
18843 ((org-on-heading-p t)
18844 (push (list :headline (point-at-bol) (point-at-eol)) clist)
18845 (when (progn
18846 (beginning-of-line 1)
18847 (looking-at org-todo-line-tags-regexp))
18848 (push (org-point-in-group p 1 :headline-stars) clist)
18849 (push (org-point-in-group p 2 :todo-keyword) clist)
18850 (push (org-point-in-group p 4 :tags) clist))
18851 (goto-char p)
18852 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
18853 (if (looking-at "\\[#[A-Z0-9]\\]")
18854 (push (org-point-in-group p 0 :priority) clist)))
18856 ((org-at-item-p)
18857 (push (org-point-in-group p 2 :item-bullet) clist)
18858 (push (list :item (point-at-bol)
18859 (save-excursion (org-end-of-item) (point)))
18860 clist)
18861 (and (org-at-item-checkbox-p)
18862 (push (org-point-in-group p 0 :checkbox) clist)))
18864 ((org-at-table-p)
18865 (push (list :table (org-table-begin) (org-table-end)) clist)
18866 (if (memq 'org-formula faces)
18867 (push (list :table-special
18868 (previous-single-property-change p 'face)
18869 (next-single-property-change p 'face)) clist)))
18870 ((org-at-table-p 'any)
18871 (push (list :table-table) clist)))
18872 (goto-char p)
18874 ;; Now the small context
18875 (cond
18876 ((org-at-timestamp-p)
18877 (push (org-point-in-group p 0 :timestamp) clist))
18878 ((memq 'org-link faces)
18879 (push (list :link
18880 (previous-single-property-change p 'face)
18881 (next-single-property-change p 'face)) clist))
18882 ((memq 'org-special-keyword faces)
18883 (push (list :keyword
18884 (previous-single-property-change p 'face)
18885 (next-single-property-change p 'face)) clist))
18886 ((org-on-target-p)
18887 (push (org-point-in-group p 0 :target) clist)
18888 (goto-char (1- (match-beginning 0)))
18889 (if (looking-at org-radio-target-regexp)
18890 (push (org-point-in-group p 0 :radio-target) clist))
18891 (goto-char p))
18892 ((setq o (car (delq nil
18893 (mapcar
18894 (lambda (x)
18895 (if (memq x org-latex-fragment-image-overlays) x))
18896 (overlays-at (point))))))
18897 (push (list :latex-fragment
18898 (overlay-start o) (overlay-end o)) clist)
18899 (push (list :latex-preview
18900 (overlay-start o) (overlay-end o)) clist))
18901 ((org-inside-LaTeX-fragment-p)
18902 ;; FIXME: positions wrong.
18903 (push (list :latex-fragment (point) (point)) clist)))
18905 (setq clist (nreverse (delq nil clist)))
18906 clist))
18908 ;; FIXME: Compare with at-regexp-p Do we need both?
18909 (defun org-in-regexp (re &optional nlines visually)
18910 "Check if point is inside a match of regexp.
18911 Normally only the current line is checked, but you can include NLINES extra
18912 lines both before and after point into the search.
18913 If VISUALLY is set, require that the cursor is not after the match but
18914 really on, so that the block visually is on the match."
18915 (catch 'exit
18916 (let ((pos (point))
18917 (eol (point-at-eol (+ 1 (or nlines 0))))
18918 (inc (if visually 1 0)))
18919 (save-excursion
18920 (beginning-of-line (- 1 (or nlines 0)))
18921 (while (re-search-forward re eol t)
18922 (if (and (<= (match-beginning 0) pos)
18923 (>= (+ inc (match-end 0)) pos))
18924 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
18926 (defun org-at-regexp-p (regexp)
18927 "Is point inside a match of REGEXP in the current line?"
18928 (catch 'exit
18929 (save-excursion
18930 (let ((pos (point)) (end (point-at-eol)))
18931 (beginning-of-line 1)
18932 (while (re-search-forward regexp end t)
18933 (if (and (<= (match-beginning 0) pos)
18934 (>= (match-end 0) pos))
18935 (throw 'exit t)))
18936 nil))))
18938 (defun org-in-regexps-block-p (start-re end-re &optional bound)
18939 "Return t if the current point is between matches of START-RE and END-RE.
18940 This will also return t if point is on one of the two matches or
18941 in an unfinished block. END-RE can be a string or a form
18942 returning a string.
18944 An optional third argument bounds the search for START-RE. It
18945 defaults to previous heading or `point-min'."
18946 (let ((pos (point))
18947 (limit (or bound (save-excursion (outline-previous-heading)))))
18948 (save-excursion
18949 ;; we're on a block when point is on start-re...
18950 (or (org-at-regexp-p start-re)
18951 ;; ... or start-re can be found above...
18952 (and (re-search-backward start-re limit t)
18953 ;; ... but no end-re between start-re and point.
18954 (not (re-search-forward (eval end-re) pos t)))))))
18956 (defun org-in-block-p (names)
18957 "Is point inside any block whose name belongs to NAMES?
18959 NAMES is a list of strings containing names of blocks."
18960 (save-match-data
18961 (catch 'exit
18962 (let ((case-fold-search t))
18963 (mapc (lambda (name)
18964 (let ((n (regexp-quote name)))
18965 (when (org-in-regexps-block-p
18966 (concat "^[ \t]*#\\+begin_" n)
18967 (concat "^[ \t]*#\\+end_" n))
18968 (throw 'exit t))))
18969 names))
18970 nil)))
18972 (defun org-occur-in-agenda-files (regexp &optional nlines)
18973 "Call `multi-occur' with buffers for all agenda files."
18974 (interactive "sOrg-files matching: \np")
18975 (let* ((files (org-agenda-files))
18976 (tnames (mapcar 'file-truename files))
18977 (extra org-agenda-text-search-extra-files)
18979 (when (eq (car extra) 'agenda-archives)
18980 (setq extra (cdr extra))
18981 (setq files (org-add-archive-files files)))
18982 (while (setq f (pop extra))
18983 (unless (member (file-truename f) tnames)
18984 (add-to-list 'files f 'append)
18985 (add-to-list 'tnames (file-truename f) 'append)))
18986 (multi-occur
18987 (mapcar (lambda (x)
18988 (with-current-buffer
18989 (or (get-file-buffer x) (find-file-noselect x))
18990 (widen)
18991 (current-buffer)))
18992 files)
18993 regexp)))
18995 (if (boundp 'occur-mode-find-occurrence-hook)
18996 ;; Emacs 23
18997 (add-hook 'occur-mode-find-occurrence-hook
18998 (lambda ()
18999 (when (org-mode-p)
19000 (org-reveal))))
19001 ;; Emacs 22
19002 (defadvice occur-mode-goto-occurrence
19003 (after org-occur-reveal activate)
19004 (and (org-mode-p) (org-reveal)))
19005 (defadvice occur-mode-goto-occurrence-other-window
19006 (after org-occur-reveal activate)
19007 (and (org-mode-p) (org-reveal)))
19008 (defadvice occur-mode-display-occurrence
19009 (after org-occur-reveal activate)
19010 (when (org-mode-p)
19011 (let ((pos (occur-mode-find-occurrence)))
19012 (with-current-buffer (marker-buffer pos)
19013 (save-excursion
19014 (goto-char pos)
19015 (org-reveal)))))))
19017 (defun org-occur-link-in-agenda-files ()
19018 "Create a link and search for it in the agendas.
19019 The link is not stored in `org-stored-links', it is just created
19020 for the search purpose."
19021 (interactive)
19022 (let ((link (condition-case nil
19023 (org-store-link nil)
19024 (error "Unable to create a link to here"))))
19025 (org-occur-in-agenda-files (regexp-quote link))))
19027 (defun org-uniquify (list)
19028 "Remove duplicate elements from LIST."
19029 (let (res)
19030 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
19031 res))
19033 (defun org-delete-all (elts list)
19034 "Remove all elements in ELTS from LIST."
19035 (while elts
19036 (setq list (delete (pop elts) list)))
19037 list)
19039 (defun org-count (cl-item cl-seq)
19040 "Count the number of occurrences of ITEM in SEQ.
19041 Taken from `count' in cl-seq.el with all keyword arguments removed."
19042 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
19043 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
19044 (while (< cl-start cl-end)
19045 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
19046 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
19047 (setq cl-start (1+ cl-start)))
19048 cl-count))
19050 (defun org-remove-if (predicate seq)
19051 "Remove everything from SEQ that fulfills PREDICATE."
19052 (let (res e)
19053 (while seq
19054 (setq e (pop seq))
19055 (if (not (funcall predicate e)) (push e res)))
19056 (nreverse res)))
19058 (defun org-remove-if-not (predicate seq)
19059 "Remove everything from SEQ that does not fulfill PREDICATE."
19060 (let (res e)
19061 (while seq
19062 (setq e (pop seq))
19063 (if (funcall predicate e) (push e res)))
19064 (nreverse res)))
19066 (defun org-back-over-empty-lines ()
19067 "Move backwards over whitespace, to the beginning of the first empty line.
19068 Returns the number of empty lines passed."
19069 (let ((pos (point)))
19070 (if (cdr (assoc 'heading org-blank-before-new-entry))
19071 (skip-chars-backward " \t\n\r")
19072 (forward-line -1))
19073 (beginning-of-line 2)
19074 (goto-char (min (point) pos))
19075 (count-lines (point) pos)))
19077 (defun org-skip-whitespace ()
19078 (skip-chars-forward " \t\n\r"))
19080 (defun org-point-in-group (point group &optional context)
19081 "Check if POINT is in match-group GROUP.
19082 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
19083 match. If the match group does not exist or point is not inside it,
19084 return nil."
19085 (and (match-beginning group)
19086 (>= point (match-beginning group))
19087 (<= point (match-end group))
19088 (if context
19089 (list context (match-beginning group) (match-end group))
19090 t)))
19092 (defun org-switch-to-buffer-other-window (&rest args)
19093 "Switch to buffer in a second window on the current frame.
19094 In particular, do not allow pop-up frames.
19095 Returns the newly created buffer."
19096 (let (pop-up-frames special-display-buffer-names special-display-regexps
19097 special-display-function)
19098 (apply 'switch-to-buffer-other-window args)))
19100 (defun org-combine-plists (&rest plists)
19101 "Create a single property list from all plists in PLISTS.
19102 The process starts by copying the first list, and then setting properties
19103 from the other lists. Settings in the last list are the most significant
19104 ones and overrule settings in the other lists."
19105 (let ((rtn (copy-sequence (pop plists)))
19106 p v ls)
19107 (while plists
19108 (setq ls (pop plists))
19109 (while ls
19110 (setq p (pop ls) v (pop ls))
19111 (setq rtn (plist-put rtn p v))))
19112 rtn))
19114 (defun org-move-line-down (arg)
19115 "Move the current line down. With prefix argument, move it past ARG lines."
19116 (interactive "p")
19117 (let ((col (current-column))
19118 beg end pos)
19119 (beginning-of-line 1) (setq beg (point))
19120 (beginning-of-line 2) (setq end (point))
19121 (beginning-of-line (+ 1 arg))
19122 (setq pos (move-marker (make-marker) (point)))
19123 (insert (delete-and-extract-region beg end))
19124 (goto-char pos)
19125 (org-move-to-column col)))
19127 (defun org-move-line-up (arg)
19128 "Move the current line up. With prefix argument, move it past ARG lines."
19129 (interactive "p")
19130 (let ((col (current-column))
19131 beg end pos)
19132 (beginning-of-line 1) (setq beg (point))
19133 (beginning-of-line 2) (setq end (point))
19134 (beginning-of-line (- arg))
19135 (setq pos (move-marker (make-marker) (point)))
19136 (insert (delete-and-extract-region beg end))
19137 (goto-char pos)
19138 (org-move-to-column col)))
19140 (defun org-replace-escapes (string table)
19141 "Replace %-escapes in STRING with values in TABLE.
19142 TABLE is an association list with keys like \"%a\" and string values.
19143 The sequences in STRING may contain normal field width and padding information,
19144 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
19145 so values can contain further %-escapes if they are define later in TABLE."
19146 (let ((tbl (copy-alist table))
19147 (case-fold-search nil)
19148 (pchg 0)
19149 e re rpl)
19150 (while (setq e (pop tbl))
19151 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
19152 (when (and (cdr e) (string-match re (cdr e)))
19153 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
19154 (safe "SREF"))
19155 (add-text-properties 0 3 (list 'sref sref) safe)
19156 (setcdr e (replace-match safe t t (cdr e)))))
19157 (while (string-match re string)
19158 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
19159 (cdr e)))
19160 (setq string (replace-match rpl t t string))))
19161 (while (setq pchg (next-property-change pchg string))
19162 (let ((sref (get-text-property pchg 'sref string)))
19163 (when (and sref (string-match "SREF" string pchg))
19164 (setq string (replace-match sref t t string)))))
19165 string))
19167 (defun org-sublist (list start end)
19168 "Return a section of LIST, from START to END.
19169 Counting starts at 1."
19170 (let (rtn (c start))
19171 (setq list (nthcdr (1- start) list))
19172 (while (and list (<= c end))
19173 (push (pop list) rtn)
19174 (setq c (1+ c)))
19175 (nreverse rtn)))
19177 (defun org-find-base-buffer-visiting (file)
19178 "Like `find-buffer-visiting' but always return the base buffer and
19179 not an indirect buffer."
19180 (let ((buf (or (get-file-buffer file)
19181 (find-buffer-visiting file))))
19182 (if buf
19183 (or (buffer-base-buffer buf) buf)
19184 nil)))
19186 (defun org-image-file-name-regexp (&optional extensions)
19187 "Return regexp matching the file names of images.
19188 If EXTENSIONS is given, only match these."
19189 (if (and (not extensions) (fboundp 'image-file-name-regexp))
19190 (image-file-name-regexp)
19191 (let ((image-file-name-extensions
19192 (or extensions
19193 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
19194 "xbm" "xpm" "pbm" "pgm" "ppm"))))
19195 (concat "\\."
19196 (regexp-opt (nconc (mapcar 'upcase
19197 image-file-name-extensions)
19198 image-file-name-extensions)
19200 "\\'"))))
19202 (defun org-file-image-p (file &optional extensions)
19203 "Return non-nil if FILE is an image."
19204 (save-match-data
19205 (string-match (org-image-file-name-regexp extensions) file)))
19207 (defun org-get-cursor-date ()
19208 "Return the date at cursor in as a time.
19209 This works in the calendar and in the agenda, anywhere else it just
19210 returns the current time."
19211 (let (date day defd)
19212 (cond
19213 ((eq major-mode 'calendar-mode)
19214 (setq date (calendar-cursor-to-date)
19215 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
19216 ((eq major-mode 'org-agenda-mode)
19217 (setq day (get-text-property (point) 'day))
19218 (if day
19219 (setq date (calendar-gregorian-from-absolute day)
19220 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
19221 (nth 2 date))))))
19222 (or defd (current-time))))
19224 (defvar org-agenda-action-marker (make-marker)
19225 "Marker pointing to the entry for the next agenda action.")
19227 (defun org-mark-entry-for-agenda-action ()
19228 "Mark the current entry as target of an agenda action.
19229 Agenda actions are actions executed from the agenda with the key `k',
19230 which make use of the date at the cursor."
19231 (interactive)
19232 (move-marker org-agenda-action-marker
19233 (save-excursion (org-back-to-heading t) (point))
19234 (current-buffer))
19235 (message
19236 "Entry marked for action; press `k' at desired date in agenda or calendar"))
19238 (defun org-mark-subtree ()
19239 "Mark the current subtree.
19240 This puts point at the start of the current subtree, and mark at the end.
19242 If point is in an inline task, mark that task instead."
19243 (interactive)
19244 (let ((inline-task-p
19245 (and (featurep 'org-inlinetask)
19246 (org-inlinetask-in-task-p)))
19247 (beg))
19248 ;; Get beginning of subtree
19249 (cond
19250 (inline-task-p (org-inlinetask-goto-beginning))
19251 ((org-at-heading-p) (beginning-of-line))
19252 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
19253 (setq beg (point))
19254 ;; Get end of it
19255 (if inline-task-p
19256 (org-inlinetask-goto-end)
19257 (org-end-of-subtree))
19258 ;; Mark zone
19259 (push-mark (point) nil t)
19260 (goto-char beg)))
19262 ;;; Paragraph filling stuff.
19263 ;; We want this to be just right, so use the full arsenal.
19265 (defun org-indent-line-function ()
19266 "Indent line depending on context."
19267 (interactive)
19268 (let* ((pos (point))
19269 (itemp (org-at-item-p))
19270 (case-fold-search t)
19271 (org-drawer-regexp (or org-drawer-regexp "\000"))
19272 (inline-task-p (and (featurep 'org-inlinetask)
19273 (org-inlinetask-in-task-p)))
19274 (inline-re (and inline-task-p
19275 (org-inlinetask-outline-regexp)))
19276 column)
19277 (beginning-of-line 1)
19278 (cond
19279 ;; Comments
19280 ((looking-at "# ") (setq column 0))
19281 ;; Headings
19282 ((looking-at "\\*+ ") (setq column 0))
19283 ;; Included files
19284 ((looking-at "#\\+include:") (setq column 0))
19285 ;; Footnote definition
19286 ((looking-at org-footnote-definition-re) (setq column 0))
19287 ;; Literal examples
19288 ((looking-at "[ \t]*:[ \t]")
19289 (setq column (org-get-indentation))) ; do nothing
19290 ;; Lists
19291 ((ignore-errors (goto-char (org-in-item-p)))
19292 (setq column (if itemp
19293 (org-get-indentation)
19294 (org-list-item-body-column (point))))
19295 (goto-char pos))
19296 ;; Drawers
19297 ((and (looking-at "[ \t]*:END:")
19298 (save-excursion (re-search-backward org-drawer-regexp nil t)))
19299 (save-excursion
19300 (goto-char (1- (match-beginning 1)))
19301 (setq column (current-column))))
19302 ;; Special blocks
19303 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
19304 (save-excursion
19305 (re-search-backward
19306 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
19307 (setq column (org-get-indentation (match-string 0))))
19308 ((and (not (looking-at "[ \t]*#\\+begin_"))
19309 (org-in-regexps-block-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
19310 (save-excursion
19311 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
19312 (setq column
19313 (if (equal (downcase (match-string 1)) "src")
19314 ;; src blocks: let `org-edit-src-exit' handle them
19315 (org-get-indentation)
19316 (org-get-indentation (match-string 0)))))
19317 ;; This line has nothing special, look at the previous relevant
19318 ;; line to compute indentation
19320 (beginning-of-line 0)
19321 (while (and (not (bobp))
19322 (not (looking-at org-drawer-regexp))
19323 ;; When point started in an inline task, do not move
19324 ;; above task starting line.
19325 (not (and inline-task-p (looking-at inline-re)))
19326 ;; Skip drawers, blocks, empty lines, verbatim,
19327 ;; comments, tables, footnotes definitions, lists,
19328 ;; inline tasks.
19329 (or (and (looking-at "[ \t]*:END:")
19330 (re-search-backward org-drawer-regexp nil t))
19331 (and (looking-at "[ \t]*#\\+end_")
19332 (re-search-backward "[ \t]*#\\+begin_"nil t))
19333 (looking-at "[ \t]*[\n:#|]")
19334 (looking-at org-footnote-definition-re)
19335 (and (ignore-errors (goto-char (org-in-item-p)))
19336 (goto-char
19337 (org-list-get-top-point (org-list-struct))))
19338 (and (not inline-task-p)
19339 (featurep 'org-inlinetask)
19340 (org-inlinetask-in-task-p)
19341 (or (org-inlinetask-goto-beginning) t))))
19342 (beginning-of-line 0))
19343 (cond
19344 ;; There was an heading above.
19345 ((looking-at "\\*+[ \t]+")
19346 (if (not org-adapt-indentation)
19347 (setq column 0)
19348 (goto-char (match-end 0))
19349 (setq column (current-column))))
19350 ;; A drawer had started and is unfinished
19351 ((looking-at org-drawer-regexp)
19352 (goto-char (1- (match-beginning 1)))
19353 (setq column (current-column)))
19354 ;; Else, nothing noticeable found: get indentation and go on.
19355 (t (setq column (org-get-indentation))))))
19356 ;; Now apply indentation and move cursor accordingly
19357 (goto-char pos)
19358 (if (<= (current-column) (current-indentation))
19359 (org-indent-line-to column)
19360 (save-excursion (org-indent-line-to column)))
19361 ;; Special polishing for properties, see `org-property-format'
19362 (setq column (current-column))
19363 (beginning-of-line 1)
19364 (if (looking-at
19365 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
19366 (replace-match (concat (match-string 1)
19367 (format org-property-format
19368 (match-string 2) (match-string 3)))
19369 t t))
19370 (org-move-to-column column)))
19372 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
19373 "Variable to store copy of `adaptive-fill-regexp'.
19374 Since `adaptive-fill-regexp' is set to never match, we need to
19375 store a backup of its value before entering `org-mode' so that
19376 the functionality can be provided as a fall-back.")
19378 (defun org-set-autofill-regexps ()
19379 (interactive)
19380 ;; In the paragraph separator we include headlines, because filling
19381 ;; text in a line directly attached to a headline would otherwise
19382 ;; fill the headline as well.
19383 (org-set-local 'comment-start-skip "^#+[ \t]*")
19384 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
19385 ;; The paragraph starter includes hand-formatted lists.
19386 (org-set-local
19387 'paragraph-start
19388 (concat
19389 "\f" "\\|"
19390 "[ ]*$" "\\|"
19391 "\\*+ " "\\|"
19392 "[ \t]*#" "\\|"
19393 (org-item-re) "\\|"
19394 "[ \t]*[:|]" "\\|"
19395 "\\$\\$" "\\|"
19396 "\\\\\\(begin\\|end\\|[][]\\)"))
19397 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
19398 ;; But only if the user has not turned off tables or fixed-width regions
19399 (org-set-local
19400 'auto-fill-inhibit-regexp
19401 (concat "\\*+ \\|#\\+"
19402 "\\|[ \t]*" org-keyword-time-regexp
19403 (if (or org-enable-table-editor org-enable-fixed-width-editor)
19404 (concat
19405 "\\|[ \t]*["
19406 (if org-enable-table-editor "|" "")
19407 (if org-enable-fixed-width-editor ":" "")
19408 "]"))))
19409 ;; We use our own fill-paragraph function, to make sure that tables
19410 ;; and fixed-width regions are not wrapped. That function will pass
19411 ;; through to `fill-paragraph' when appropriate.
19412 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
19413 ;; Prevent auto-fill from inserting unwanted new items.
19414 (org-set-local 'fill-nobreak-predicate
19415 (if (memq 'org-fill-item-nobreak-p fill-nobreak-predicate)
19416 fill-nobreak-predicate
19417 (cons 'org-fill-item-nobreak-p fill-nobreak-predicate)))
19418 ;; Adaptive filling: To get full control, first make sure that
19419 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
19420 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
19421 (org-set-local 'org-adaptive-fill-regexp-backup
19422 adaptive-fill-regexp))
19423 (org-set-local 'adaptive-fill-regexp "\000")
19424 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
19425 (org-set-local 'adaptive-fill-function
19426 'org-adaptive-fill-function)
19427 (org-set-local
19428 'align-mode-rules-list
19429 '((org-in-buffer-settings
19430 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
19431 (modes . '(org-mode))))))
19433 (defun org-fill-item-nobreak-p ()
19434 "Non-nil when a line break at point would insert a new item."
19435 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
19437 (defun org-fill-paragraph (&optional justify)
19438 "Re-align a table, pass through to fill-paragraph if no table."
19439 (let ((table-p (org-at-table-p))
19440 (table.el-p (org-at-table.el-p))
19441 (itemp (org-in-item-p)))
19442 (cond ((and (equal (char-after (point-at-bol)) ?*)
19443 (save-excursion (goto-char (point-at-bol))
19444 (looking-at outline-regexp)))
19445 t) ; skip headlines
19446 (table.el-p t) ; skip table.el tables
19447 (table-p (org-table-align) t) ; align Org tables
19448 (itemp ; align text in items
19449 (let* ((struct (save-excursion (goto-char itemp)
19450 (org-list-struct)))
19451 (parents (org-list-parents-alist struct))
19452 (children (org-list-get-children itemp struct parents))
19453 beg end prev next prefix)
19454 ;; Determine in which part of item point is: before
19455 ;; first child, after last child, between two
19456 ;; sub-lists, or simply in item if there's no child.
19457 (cond
19458 ((not children)
19459 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19460 beg itemp
19461 end (org-list-get-item-end itemp struct)))
19462 ((< (point) (setq next (car children)))
19463 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19464 beg itemp
19465 end next))
19466 ((> (point) (setq prev (car (last children))))
19467 (setq beg (org-list-get-item-end prev struct)
19468 end (org-list-get-item-end itemp struct)
19469 prefix (save-excursion
19470 (goto-char beg)
19471 (skip-chars-forward " \t")
19472 (make-string (current-column) ?\ ))))
19473 (t (catch 'exit
19474 (while (setq next (pop children))
19475 (if (> (point) next)
19476 (setq prev next)
19477 (setq beg (org-list-get-item-end prev struct)
19478 end next
19479 prefix (save-excursion
19480 (goto-char beg)
19481 (skip-chars-forward " \t")
19482 (make-string (current-column) ?\ )))
19483 (throw 'exit nil))))))
19484 ;; Use `fill-paragraph' with buffer narrowed to item
19485 ;; without any child, and with our computed PREFIX.
19486 (flet ((fill-context-prefix (from to &optional flr) prefix))
19487 (save-restriction
19488 (narrow-to-region beg end)
19489 (save-excursion (fill-paragraph justify)))) t))
19490 ;; Special case where point is not in a list but is on
19491 ;; a paragraph adjacent to a list: make sure this paragraph
19492 ;; doesn't get merged with the end of the list by narrowing
19493 ;; buffer first.
19494 ((save-excursion (forward-paragraph -1)
19495 (setq itemp (org-in-item-p)))
19496 (let ((struct (save-excursion (goto-char itemp)
19497 (org-list-struct))))
19498 (save-restriction
19499 (narrow-to-region (org-list-get-bottom-point struct)
19500 (save-excursion (forward-paragraph 1)
19501 (point)))
19502 (fill-paragraph justify) t)))
19503 ;; Else simply call `fill-paragraph'.
19504 (t nil))))
19506 ;; For reference, this is the default value of adaptive-fill-regexp
19507 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
19509 (defun org-adaptive-fill-function ()
19510 "Return a fill prefix for org-mode files."
19511 (let (itemp)
19512 (save-excursion
19513 (cond
19514 ;; Comment line
19515 ((looking-at "#[ \t]+")
19516 (match-string-no-properties 0))
19517 ;; Plain list item
19518 ((org-at-item-p)
19519 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
19520 ;; Point is in a list after `backward-paragraph': original
19521 ;; point wasn't in the list, or filling would have been taken
19522 ;; care of by `org-auto-fill-function', but the list and the
19523 ;; real paragraph are not separated by a blank line. Thus, move
19524 ;; point after the list to go back to real paragraph and
19525 ;; determine fill-prefix.
19526 ((setq itemp (org-in-item-p))
19527 (goto-char itemp)
19528 (let* ((struct (org-list-struct))
19529 (bottom (org-list-get-bottom-point struct)))
19530 (goto-char bottom)
19531 (make-string (org-get-indentation) ?\ )))
19532 ;; Other text
19533 ((looking-at org-adaptive-fill-regexp-backup)
19534 (match-string-no-properties 0))))))
19536 (defun org-auto-fill-function ()
19537 "Auto-fill function."
19538 (let (itemp prefix)
19539 ;; When in a list, compute an appropriate fill-prefix and make
19540 ;; sure it will be used by `do-auto-fill'.
19541 (if (setq itemp (org-in-item-p))
19542 (progn
19543 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
19544 (flet ((fill-context-prefix (from to &optional flr) prefix))
19545 (do-auto-fill)))
19546 ;; Else just use `do-auto-fill'.
19547 (do-auto-fill))))
19549 ;;; Other stuff.
19551 (defun org-toggle-fixed-width-section (arg)
19552 "Toggle the fixed-width export.
19553 If there is no active region, the QUOTE keyword at the current headline is
19554 inserted or removed. When present, it causes the text between this headline
19555 and the next to be exported as fixed-width text, and unmodified.
19556 If there is an active region, this command adds or removes a colon as the
19557 first character of this line. If the first character of a line is a colon,
19558 this line is also exported in fixed-width font."
19559 (interactive "P")
19560 (let* ((cc 0)
19561 (regionp (org-region-active-p))
19562 (beg (if regionp (region-beginning) (point)))
19563 (end (if regionp (region-end)))
19564 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
19565 (case-fold-search nil)
19566 (re "[ \t]*\\(: \\)")
19567 off)
19568 (if regionp
19569 (save-excursion
19570 (goto-char beg)
19571 (setq cc (current-column))
19572 (beginning-of-line 1)
19573 (setq off (looking-at re))
19574 (while (> nlines 0)
19575 (setq nlines (1- nlines))
19576 (beginning-of-line 1)
19577 (cond
19578 (arg
19579 (org-move-to-column cc t)
19580 (insert ": \n")
19581 (forward-line -1))
19582 ((and off (looking-at re))
19583 (replace-match "" t t nil 1))
19584 ((not off) (org-move-to-column cc t) (insert ": ")))
19585 (forward-line 1)))
19586 (save-excursion
19587 (org-back-to-heading)
19588 (if (looking-at (concat outline-regexp
19589 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
19590 (replace-match "" t t nil 1)
19591 (if (looking-at outline-regexp)
19592 (progn
19593 (goto-char (match-end 0))
19594 (insert org-quote-string " "))))))))
19596 (defun org-reftex-citation ()
19597 "Use reftex-citation to insert a citation into the buffer.
19598 This looks for a line like
19600 #+BIBLIOGRAPHY: foo plain option:-d
19602 and derives from it that foo.bib is the bibliography file relevant
19603 for this document. It then installs the necessary environment for RefTeX
19604 to work in this buffer and calls `reftex-citation' to insert a citation
19605 into the buffer.
19607 Export of such citations to both LaTeX and HTML is handled by the contributed
19608 package org-exp-bibtex by Taru Karttunen."
19609 (interactive)
19610 (let ((reftex-docstruct-symbol 'rds)
19611 (reftex-cite-format "\\cite{%l}")
19612 rds bib)
19613 (save-excursion
19614 (save-restriction
19615 (widen)
19616 (let ((case-fold-search t)
19617 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
19618 (if (not (save-excursion
19619 (or (re-search-forward re nil t)
19620 (re-search-backward re nil t))))
19621 (error "No bibliography defined in file")
19622 (setq bib (concat (match-string 1) ".bib")
19623 rds (list (list 'bib bib)))))))
19624 (call-interactively 'reftex-citation)))
19626 ;;;; Functions extending outline functionality
19628 (defun org-beginning-of-line (&optional arg)
19629 "Go to the beginning of the current line. If that is invisible, continue
19630 to a visible line beginning. This makes the function of C-a more intuitive.
19631 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
19632 first attempt, and only move to after the tags when the cursor is already
19633 beyond the end of the headline."
19634 (interactive "P")
19635 (let ((pos (point))
19636 (special (if (consp org-special-ctrl-a/e)
19637 (car org-special-ctrl-a/e)
19638 org-special-ctrl-a/e))
19639 refpos)
19640 (if (org-bound-and-true-p line-move-visual)
19641 (beginning-of-visual-line 1)
19642 (beginning-of-line 1))
19643 (if (and arg (fboundp 'move-beginning-of-line))
19644 (call-interactively 'move-beginning-of-line)
19645 (if (bobp)
19647 (backward-char 1)
19648 (if (org-truely-invisible-p)
19649 (while (and (not (bobp)) (org-truely-invisible-p))
19650 (backward-char 1)
19651 (beginning-of-line 1))
19652 (forward-char 1))))
19653 (when special
19654 (cond
19655 ((and (looking-at org-complex-heading-regexp)
19656 (= (char-after (match-end 1)) ?\ ))
19657 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
19658 (point-at-eol)))
19659 (goto-char
19660 (if (eq special t)
19661 (cond ((> pos refpos) refpos)
19662 ((= pos (point)) refpos)
19663 (t (point)))
19664 (cond ((> pos (point)) (point))
19665 ((not (eq last-command this-command)) (point))
19666 (t refpos)))))
19667 ((org-at-item-p)
19668 (goto-char
19669 (if (eq special t)
19670 (cond ((> pos (match-end 0)) (match-end 0))
19671 ((= pos (point)) (match-end 0))
19672 (t (point)))
19673 (cond ((> pos (point)) (point))
19674 ((not (eq last-command this-command)) (point))
19675 (t (match-end 0))))))))
19676 (org-no-warnings
19677 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
19679 (defun org-end-of-line (&optional arg)
19680 "Go to the end of the line.
19681 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
19682 first attempt, and only move to after the tags when the cursor is already
19683 beyond the end of the headline."
19684 (interactive "P")
19685 (let ((special (if (consp org-special-ctrl-a/e)
19686 (cdr org-special-ctrl-a/e)
19687 org-special-ctrl-a/e)))
19688 (if (or (not special)
19689 (not (org-on-heading-p))
19690 arg)
19691 (call-interactively
19692 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
19693 ((fboundp 'move-end-of-line) 'move-end-of-line)
19694 (t 'end-of-line)))
19695 (let ((pos (point)))
19696 (beginning-of-line 1)
19697 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
19698 (if (eq special t)
19699 (if (or (< pos (match-beginning 1))
19700 (= pos (match-end 0)))
19701 (goto-char (match-beginning 1))
19702 (goto-char (match-end 0)))
19703 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
19704 (goto-char (match-end 0))
19705 (goto-char (match-beginning 1))))
19706 (call-interactively (if (fboundp 'move-end-of-line)
19707 'move-end-of-line
19708 'end-of-line)))))
19709 (org-no-warnings
19710 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
19712 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
19713 (define-key org-mode-map "\C-e" 'org-end-of-line)
19715 (defun org-backward-sentence (&optional arg)
19716 "Go to beginning of sentence, or beginning of table field.
19717 This will call `backward-sentence' or `org-table-beginning-of-field',
19718 depending on context."
19719 (interactive "P")
19720 (cond
19721 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
19722 (t (call-interactively 'backward-sentence))))
19724 (defun org-forward-sentence (&optional arg)
19725 "Go to end of sentence, or end of table field.
19726 This will call `forward-sentence' or `org-table-end-of-field',
19727 depending on context."
19728 (interactive "P")
19729 (cond
19730 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
19731 (t (call-interactively 'forward-sentence))))
19733 (define-key org-mode-map "\M-a" 'org-backward-sentence)
19734 (define-key org-mode-map "\M-e" 'org-forward-sentence)
19736 (defun org-kill-line (&optional arg)
19737 "Kill line, to tags or end of line."
19738 (interactive "P")
19739 (cond
19740 ((or (not org-special-ctrl-k)
19741 (bolp)
19742 (not (org-on-heading-p)))
19743 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
19744 org-ctrl-k-protect-subtree)
19745 (if (or (eq org-ctrl-k-protect-subtree 'error)
19746 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
19747 (error "C-k aborted - would kill hidden subtree")))
19748 (call-interactively 'kill-line))
19749 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
19750 (kill-region (point) (match-beginning 1))
19751 (org-set-tags nil t))
19752 (t (kill-region (point) (point-at-eol)))))
19754 (define-key org-mode-map "\C-k" 'org-kill-line)
19756 (defun org-yank (&optional arg)
19757 "Yank. If the kill is a subtree, treat it specially.
19758 This command will look at the current kill and check if is a single
19759 subtree, or a series of subtrees[1]. If it passes the test, and if the
19760 cursor is at the beginning of a line or after the stars of a currently
19761 empty headline, then the yank is handled specially. How exactly depends
19762 on the value of the following variables, both set by default.
19764 org-yank-folded-subtrees
19765 When set, the subtree(s) will be folded after insertion, but only
19766 if doing so would now swallow text after the yanked text.
19768 org-yank-adjusted-subtrees
19769 When set, the subtree will be promoted or demoted in order to
19770 fit into the local outline tree structure, which means that the level
19771 will be adjusted so that it becomes the smaller one of the two
19772 *visible* surrounding headings.
19774 Any prefix to this command will cause `yank' to be called directly with
19775 no special treatment. In particular, a simple \\[universal-argument] prefix \
19776 will just
19777 plainly yank the text as it is.
19779 \[1] The test checks if the first non-white line is a heading
19780 and if there are no other headings with fewer stars."
19781 (interactive "P")
19782 (org-yank-generic 'yank arg))
19784 (defun org-yank-generic (command arg)
19785 "Perform some yank-like command.
19787 This function implements the behavior described in the `org-yank'
19788 documentation. However, it has been generalized to work for any
19789 interactive command with similar behavior."
19791 ;; pretend to be command COMMAND
19792 (setq this-command command)
19794 (if arg
19795 (call-interactively command)
19797 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
19798 (and (org-kill-is-subtree-p)
19799 (or (bolp)
19800 (and (looking-at "[ \t]*$")
19801 (string-match
19802 "\\`\\*+\\'"
19803 (buffer-substring (point-at-bol) (point)))))))
19804 swallowp)
19805 (cond
19806 ((and subtreep org-yank-folded-subtrees)
19807 (let ((beg (point))
19808 end)
19809 (if (and subtreep org-yank-adjusted-subtrees)
19810 (org-paste-subtree nil nil 'for-yank)
19811 (call-interactively command))
19813 (setq end (point))
19814 (goto-char beg)
19815 (when (and (bolp) subtreep
19816 (not (setq swallowp
19817 (org-yank-folding-would-swallow-text beg end))))
19818 (or (looking-at outline-regexp)
19819 (re-search-forward (concat "^" outline-regexp) end t))
19820 (while (and (< (point) end) (looking-at outline-regexp))
19821 (hide-subtree)
19822 (org-cycle-show-empty-lines 'folded)
19823 (condition-case nil
19824 (outline-forward-same-level 1)
19825 (error (goto-char end)))))
19826 (when swallowp
19827 (message
19828 "Inserted text not folded because that would swallow text"))
19830 (goto-char end)
19831 (skip-chars-forward " \t\n\r")
19832 (beginning-of-line 1)
19833 (push-mark beg 'nomsg)))
19834 ((and subtreep org-yank-adjusted-subtrees)
19835 (let ((beg (point-at-bol)))
19836 (org-paste-subtree nil nil 'for-yank)
19837 (push-mark beg 'nomsg)))
19839 (call-interactively command))))))
19841 (defun org-yank-folding-would-swallow-text (beg end)
19842 "Would hide-subtree at BEG swallow any text after END?"
19843 (let (level)
19844 (save-excursion
19845 (goto-char beg)
19846 (when (or (looking-at outline-regexp)
19847 (re-search-forward (concat "^" outline-regexp) end t))
19848 (setq level (org-outline-level)))
19849 (goto-char end)
19850 (skip-chars-forward " \t\r\n\v\f")
19851 (if (or (eobp)
19852 (and (bolp) (looking-at org-outline-regexp)
19853 (<= (org-outline-level) level)))
19854 nil ; Nothing would be swallowed
19855 t)))) ; something would swallow
19857 (define-key org-mode-map "\C-y" 'org-yank)
19859 (defun org-truely-invisible-p ()
19860 "Check if point is at a character currently not visible.
19861 This version does not only check the character property, but also
19862 `visible-mode'."
19863 ;; Early versions of noutline don't have `outline-invisible-p'.
19864 (if (org-bound-and-true-p visible-mode)
19866 (outline-invisible-p)))
19868 (defun org-invisible-p2 ()
19869 "Check if point is at a character currently not visible."
19870 (save-excursion
19871 (if (and (eolp) (not (bobp))) (backward-char 1))
19872 ;; Early versions of noutline don't have `outline-invisible-p'.
19873 (outline-invisible-p)))
19875 (defun org-back-to-heading (&optional invisible-ok)
19876 "Call `outline-back-to-heading', but provide a better error message."
19877 (condition-case nil
19878 (outline-back-to-heading invisible-ok)
19879 (error (error "Before first headline at position %d in buffer %s"
19880 (point) (current-buffer)))))
19882 (defun org-beginning-of-defun ()
19883 "Go to the beginning of the subtree, i.e. back to the heading."
19884 (org-back-to-heading))
19885 (defun org-end-of-defun ()
19886 "Go to the end of the subtree."
19887 (org-end-of-subtree nil t))
19889 (defun org-before-first-heading-p ()
19890 "Before first heading?"
19891 (save-excursion
19892 (end-of-line)
19893 (null (re-search-backward "^\\*+ " nil t))))
19895 (defun org-on-heading-p (&optional ignored)
19896 (outline-on-heading-p t))
19897 (defun org-at-heading-p (&optional ignored)
19898 (outline-on-heading-p t))
19900 (defun org-point-at-end-of-empty-headline ()
19901 "If point is at the end of an empty headline, return t, else nil.
19902 If the heading only contains a TODO keyword, it is still still considered
19903 empty."
19904 (and (looking-at "[ \t]*$")
19905 (save-excursion
19906 (beginning-of-line 1)
19907 (let ((case-fold-search nil))
19908 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
19909 "\\)?[ \t]*$"))))))
19910 (defun org-at-heading-or-item-p ()
19911 (or (org-on-heading-p) (org-at-item-p)))
19913 (defun org-on-target-p ()
19914 (or (org-in-regexp org-radio-target-regexp)
19915 (org-in-regexp org-target-regexp)))
19917 (defun org-up-heading-all (arg)
19918 "Move to the heading line of which the present line is a subheading.
19919 This function considers both visible and invisible heading lines.
19920 With argument, move up ARG levels."
19921 (if (fboundp 'outline-up-heading-all)
19922 (outline-up-heading-all arg) ; emacs 21 version of outline.el
19923 (outline-up-heading arg t))) ; emacs 22 version of outline.el
19925 (defun org-up-heading-safe ()
19926 "Move to the heading line of which the present line is a subheading.
19927 This version will not throw an error. It will return the level of the
19928 headline found, or nil if no higher level is found.
19930 Also, this function will be a lot faster than `outline-up-heading',
19931 because it relies on stars being the outline starters. This can really
19932 make a significant difference in outlines with very many siblings."
19933 (let (start-level re)
19934 (org-back-to-heading t)
19935 (setq start-level (funcall outline-level))
19936 (if (equal start-level 1)
19938 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
19939 (if (re-search-backward re nil t)
19940 (funcall outline-level)))))
19942 (defun org-first-sibling-p ()
19943 "Is this heading the first child of its parents?"
19944 (interactive)
19945 (let ((re (concat "^" outline-regexp))
19946 level l)
19947 (unless (org-at-heading-p t)
19948 (error "Not at a heading"))
19949 (setq level (funcall outline-level))
19950 (save-excursion
19951 (if (not (re-search-backward re nil t))
19953 (setq l (funcall outline-level))
19954 (< l level)))))
19956 (defun org-goto-sibling (&optional previous)
19957 "Goto the next sibling, even if it is invisible.
19958 When PREVIOUS is set, go to the previous sibling instead. Returns t
19959 when a sibling was found. When none is found, return nil and don't
19960 move point."
19961 (let ((fun (if previous 're-search-backward 're-search-forward))
19962 (pos (point))
19963 (re (concat "^" outline-regexp))
19964 level l)
19965 (when (condition-case nil (org-back-to-heading t) (error nil))
19966 (setq level (funcall outline-level))
19967 (catch 'exit
19968 (or previous (forward-char 1))
19969 (while (funcall fun re nil t)
19970 (setq l (funcall outline-level))
19971 (when (< l level) (goto-char pos) (throw 'exit nil))
19972 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
19973 (goto-char pos)
19974 nil))))
19976 (defun org-show-siblings ()
19977 "Show all siblings of the current headline."
19978 (save-excursion
19979 (while (org-goto-sibling) (org-flag-heading nil)))
19980 (save-excursion
19981 (while (org-goto-sibling 'previous)
19982 (org-flag-heading nil))))
19984 (defun org-goto-first-child ()
19985 "Goto the first child, even if it is invisible.
19986 Return t when a child was found. Otherwise don't move point and
19987 return nil."
19988 (let (level (pos (point)) (re (concat "^" outline-regexp)))
19989 (when (condition-case nil (org-back-to-heading t) (error nil))
19990 (setq level (outline-level))
19991 (forward-char 1)
19992 (if (and (re-search-forward re nil t) (> (outline-level) level))
19993 (progn (goto-char (match-beginning 0)) t)
19994 (goto-char pos) nil))))
19996 (defun org-show-hidden-entry ()
19997 "Show an entry where even the heading is hidden."
19998 (save-excursion
19999 (org-show-entry)))
20001 (defun org-flag-heading (flag &optional entry)
20002 "Flag the current heading. FLAG non-nil means make invisible.
20003 When ENTRY is non-nil, show the entire entry."
20004 (save-excursion
20005 (org-back-to-heading t)
20006 ;; Check if we should show the entire entry
20007 (if entry
20008 (progn
20009 (org-show-entry)
20010 (save-excursion
20011 (and (outline-next-heading)
20012 (org-flag-heading nil))))
20013 (outline-flag-region (max (point-min) (1- (point)))
20014 (save-excursion (outline-end-of-heading) (point))
20015 flag))))
20017 (defun org-get-next-sibling ()
20018 "Move to next heading of the same level, and return point.
20019 If there is no such heading, return nil.
20020 This is like outline-next-sibling, but invisible headings are ok."
20021 (let ((level (funcall outline-level)))
20022 (outline-next-heading)
20023 (while (and (not (eobp)) (> (funcall outline-level) level))
20024 (outline-next-heading))
20025 (if (or (eobp) (< (funcall outline-level) level))
20027 (point))))
20029 (defun org-get-last-sibling ()
20030 "Move to previous heading of the same level, and return point.
20031 If there is no such heading, return nil."
20032 (let ((opoint (point))
20033 (level (funcall outline-level)))
20034 (outline-previous-heading)
20035 (when (and (/= (point) opoint) (outline-on-heading-p t))
20036 (while (and (> (funcall outline-level) level)
20037 (not (bobp)))
20038 (outline-previous-heading))
20039 (if (< (funcall outline-level) level)
20041 (point)))))
20043 (defun org-end-of-subtree (&optional invisible-OK to-heading)
20044 ;; This contains an exact copy of the original function, but it uses
20045 ;; `org-back-to-heading', to make it work also in invisible
20046 ;; trees. And is uses an invisible-OK argument.
20047 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
20048 ;; Furthermore, when used inside Org, finding the end of a large subtree
20049 ;; with many children and grandchildren etc, this can be much faster
20050 ;; than the outline version.
20051 (org-back-to-heading invisible-OK)
20052 (let ((first t)
20053 (level (funcall outline-level)))
20054 (if (and (org-mode-p) (< level 1000))
20055 ;; A true heading (not a plain list item), in Org-mode
20056 ;; This means we can easily find the end by looking
20057 ;; only for the right number of stars. Using a regexp to do
20058 ;; this is so much faster than using a Lisp loop.
20059 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
20060 (forward-char 1)
20061 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
20062 ;; something else, do it the slow way
20063 (while (and (not (eobp))
20064 (or first (> (funcall outline-level) level)))
20065 (setq first nil)
20066 (outline-next-heading)))
20067 (unless to-heading
20068 (if (memq (preceding-char) '(?\n ?\^M))
20069 (progn
20070 ;; Go to end of line before heading
20071 (forward-char -1)
20072 (if (memq (preceding-char) '(?\n ?\^M))
20073 ;; leave blank line before heading
20074 (forward-char -1))))))
20075 (point))
20077 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
20078 "Use Org version in org-mode, for dramatic speed-up."
20079 (if (org-mode-p)
20080 (progn
20081 (org-end-of-subtree nil t)
20082 (unless (eobp) (backward-char 1)))
20083 ad-do-it))
20085 (defun org-end-of-meta-data-and-drawers ()
20086 "Jump to the first text after meta data and drawers in the current entry.
20087 This will move over empty lines, lines with planning time stamps,
20088 clocking lines, and drawers."
20089 (org-back-to-heading t)
20090 (let ((end (save-excursion (outline-next-heading) (point)))
20091 (re (concat "\\(" org-drawer-regexp "\\)"
20092 "\\|" "[ \t]*" org-keyword-time-regexp)))
20093 (forward-line 1)
20094 (while (re-search-forward re end t)
20095 (if (not (match-end 1))
20096 ;; empty or planning line
20097 (forward-line 1)
20098 ;; a drawer, find the end
20099 (re-search-forward "^[ \t]*:END:" end 'move)
20100 (forward-line 1)))
20101 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
20102 (point)))
20104 (defun org-forward-same-level (arg &optional invisible-ok)
20105 "Move forward to the arg'th subheading at same level as this one.
20106 Stop at the first and last subheadings of a superior heading.
20107 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
20108 it wil also look at invisible ones."
20109 (interactive "p")
20110 (org-back-to-heading invisible-ok)
20111 (org-on-heading-p)
20112 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20113 (re (format "^\\*\\{1,%d\\} " level))
20115 (forward-char 1)
20116 (while (> arg 0)
20117 (while (and (re-search-forward re nil 'move)
20118 (setq l (- (match-end 0) (match-beginning 0) 1))
20119 (= l level)
20120 (not invisible-ok)
20121 (progn (backward-char 1) (outline-invisible-p)))
20122 (if (< l level) (setq arg 1)))
20123 (setq arg (1- arg)))
20124 (beginning-of-line 1)))
20126 (defun org-backward-same-level (arg &optional invisible-ok)
20127 "Move backward to the arg'th subheading at same level as this one.
20128 Stop at the first and last subheadings of a superior heading."
20129 (interactive "p")
20130 (org-back-to-heading)
20131 (org-on-heading-p)
20132 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20133 (re (format "^\\*\\{1,%d\\} " level))
20135 (while (> arg 0)
20136 (while (and (re-search-backward re nil 'move)
20137 (setq l (- (match-end 0) (match-beginning 0) 1))
20138 (= l level)
20139 (not invisible-ok)
20140 (outline-invisible-p))
20141 (if (< l level) (setq arg 1)))
20142 (setq arg (1- arg)))))
20144 (defun org-show-subtree ()
20145 "Show everything after this heading at deeper levels."
20146 (outline-flag-region
20147 (point)
20148 (save-excursion
20149 (org-end-of-subtree t t))
20150 nil))
20152 (defun org-show-entry ()
20153 "Show the body directly following this heading.
20154 Show the heading too, if it is currently invisible."
20155 (interactive)
20156 (save-excursion
20157 (condition-case nil
20158 (progn
20159 (org-back-to-heading t)
20160 (outline-flag-region
20161 (max (point-min) (1- (point)))
20162 (save-excursion
20163 (if (re-search-forward
20164 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
20165 (match-beginning 1)
20166 (point-max)))
20167 nil)
20168 (org-cycle-hide-drawers 'children))
20169 (error nil))))
20171 (defun org-make-options-regexp (kwds &optional extra)
20172 "Make a regular expression for keyword lines."
20173 (concat
20175 "#?[ \t]*\\+\\("
20176 (mapconcat 'regexp-quote kwds "\\|")
20177 (if extra (concat "\\|" extra))
20178 "\\):[ \t]*"
20179 "\\(.*\\)"))
20181 ;; Make isearch reveal the necessary context
20182 (defun org-isearch-end ()
20183 "Reveal context after isearch exits."
20184 (when isearch-success ; only if search was successful
20185 (if (featurep 'xemacs)
20186 ;; Under XEmacs, the hook is run in the correct place,
20187 ;; we directly show the context.
20188 (org-show-context 'isearch)
20189 ;; In Emacs the hook runs *before* restoring the overlays.
20190 ;; So we have to use a one-time post-command-hook to do this.
20191 ;; (Emacs 22 has a special variable, see function `org-mode')
20192 (unless (and (boundp 'isearch-mode-end-hook-quit)
20193 isearch-mode-end-hook-quit)
20194 ;; Only when the isearch was not quitted.
20195 (org-add-hook 'post-command-hook 'org-isearch-post-command
20196 'append 'local)))))
20198 (defun org-isearch-post-command ()
20199 "Remove self from hook, and show context."
20200 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
20201 (org-show-context 'isearch))
20204 ;;;; Integration with and fixes for other packages
20206 ;;; Imenu support
20208 (defvar org-imenu-markers nil
20209 "All markers currently used by Imenu.")
20210 (make-variable-buffer-local 'org-imenu-markers)
20212 (defun org-imenu-new-marker (&optional pos)
20213 "Return a new marker for use by Imenu, and remember the marker."
20214 (let ((m (make-marker)))
20215 (move-marker m (or pos (point)))
20216 (push m org-imenu-markers)
20219 (defun org-imenu-get-tree ()
20220 "Produce the index for Imenu."
20221 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
20222 (setq org-imenu-markers nil)
20223 (let* ((n org-imenu-depth)
20224 (re (concat "^" outline-regexp))
20225 (subs (make-vector (1+ n) nil))
20226 (last-level 0)
20227 m level head)
20228 (save-excursion
20229 (save-restriction
20230 (widen)
20231 (goto-char (point-max))
20232 (while (re-search-backward re nil t)
20233 (setq level (org-reduced-level (funcall outline-level)))
20234 (when (<= level n)
20235 (looking-at org-complex-heading-regexp)
20236 (setq head (org-link-display-format
20237 (org-match-string-no-properties 4))
20238 m (org-imenu-new-marker))
20239 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
20240 (if (>= level last-level)
20241 (push (cons head m) (aref subs level))
20242 (push (cons head (aref subs (1+ level))) (aref subs level))
20243 (loop for i from (1+ level) to n do (aset subs i nil)))
20244 (setq last-level level)))))
20245 (aref subs 1)))
20247 (eval-after-load "imenu"
20248 '(progn
20249 (add-hook 'imenu-after-jump-hook
20250 (lambda ()
20251 (if (org-mode-p)
20252 (org-show-context 'org-goto))))))
20254 (defun org-link-display-format (link)
20255 "Replace a link with either the description, or the link target
20256 if no description is present"
20257 (save-match-data
20258 (if (string-match org-bracket-link-analytic-regexp link)
20259 (replace-match (if (match-end 5)
20260 (match-string 5 link)
20261 (concat (match-string 1 link)
20262 (match-string 3 link)))
20263 nil t link)
20264 link)))
20266 ;; Speedbar support
20268 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
20269 "Overlay marking the agenda restriction line in speedbar.")
20270 (overlay-put org-speedbar-restriction-lock-overlay
20271 'face 'org-agenda-restriction-lock)
20272 (overlay-put org-speedbar-restriction-lock-overlay
20273 'help-echo "Agendas are currently limited to this item.")
20274 (org-detach-overlay org-speedbar-restriction-lock-overlay)
20276 (defun org-speedbar-set-agenda-restriction ()
20277 "Restrict future agenda commands to the location at point in speedbar.
20278 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
20279 (interactive)
20280 (require 'org-agenda)
20281 (let (p m tp np dir txt)
20282 (cond
20283 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20284 'org-imenu t))
20285 (setq m (get-text-property p 'org-imenu-marker))
20286 (with-current-buffer (marker-buffer m)
20287 (goto-char m)
20288 (org-agenda-set-restriction-lock 'subtree)))
20289 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20290 'speedbar-function 'speedbar-find-file))
20291 (setq tp (previous-single-property-change
20292 (1+ p) 'speedbar-function)
20293 np (next-single-property-change
20294 tp 'speedbar-function)
20295 dir (speedbar-line-directory)
20296 txt (buffer-substring-no-properties (or tp (point-min))
20297 (or np (point-max))))
20298 (with-current-buffer (find-file-noselect
20299 (let ((default-directory dir))
20300 (expand-file-name txt)))
20301 (unless (org-mode-p)
20302 (error "Cannot restrict to non-Org-mode file"))
20303 (org-agenda-set-restriction-lock 'file)))
20304 (t (error "Don't know how to restrict Org-mode's agenda")))
20305 (move-overlay org-speedbar-restriction-lock-overlay
20306 (point-at-bol) (point-at-eol))
20307 (setq current-prefix-arg nil)
20308 (org-agenda-maybe-redo)))
20310 (eval-after-load "speedbar"
20311 '(progn
20312 (speedbar-add-supported-extension ".org")
20313 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
20314 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
20315 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
20316 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
20317 (add-hook 'speedbar-visiting-tag-hook
20318 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
20320 ;;; Fixes and Hacks for problems with other packages
20322 ;; Make flyspell not check words in links, to not mess up our keymap
20323 (defun org-mode-flyspell-verify ()
20324 "Don't let flyspell put overlays at active buttons, or on
20325 {todo,all-time,additional-option-like}-keywords."
20326 (let ((pos (max (1- (point)) (point-min)))
20327 (word (thing-at-point 'word)))
20328 (and (not (get-text-property pos 'keymap))
20329 (not (get-text-property pos 'org-no-flyspell))
20330 (not (member word org-todo-keywords-1))
20331 (not (member word org-all-time-keywords))
20332 (not (member word org-additional-option-like-keywords)))))
20334 (defun org-remove-flyspell-overlays-in (beg end)
20335 "Remove flyspell overlays in region."
20336 (and (org-bound-and-true-p flyspell-mode)
20337 (fboundp 'flyspell-delete-region-overlays)
20338 (flyspell-delete-region-overlays beg end))
20339 (add-text-properties beg end '(org-no-flyspell t)))
20341 ;; Make `bookmark-jump' shows the jump location if it was hidden.
20342 (eval-after-load "bookmark"
20343 '(if (boundp 'bookmark-after-jump-hook)
20344 ;; We can use the hook
20345 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
20346 ;; Hook not available, use advice
20347 (defadvice bookmark-jump (after org-make-visible activate)
20348 "Make the position visible."
20349 (org-bookmark-jump-unhide))))
20351 ;; Make sure saveplace shows the location if it was hidden
20352 (eval-after-load "saveplace"
20353 '(defadvice save-place-find-file-hook (after org-make-visible activate)
20354 "Make the position visible."
20355 (org-bookmark-jump-unhide)))
20357 ;; Make sure ecb shows the location if it was hidden
20358 (eval-after-load "ecb"
20359 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
20360 "Make hierarchy visible when jumping into location from ECB tree buffer."
20361 (if (org-mode-p)
20362 (org-show-context))))
20364 (defun org-bookmark-jump-unhide ()
20365 "Unhide the current position, to show the bookmark location."
20366 (and (org-mode-p)
20367 (or (outline-invisible-p)
20368 (save-excursion (goto-char (max (point-min) (1- (point))))
20369 (outline-invisible-p)))
20370 (org-show-context 'bookmark-jump)))
20372 ;; Make session.el ignore our circular variable
20373 (eval-after-load "session"
20374 '(add-to-list 'session-globals-exclude 'org-mark-ring))
20376 ;;;; Experimental code
20378 (defun org-closed-in-range ()
20379 "Sparse tree of items closed in a certain time range.
20380 Still experimental, may disappear in the future."
20381 (interactive)
20382 ;; Get the time interval from the user.
20383 (let* ((time1 (org-float-time
20384 (org-read-date nil 'to-time nil "Starting date: ")))
20385 (time2 (org-float-time
20386 (org-read-date nil 'to-time nil "End date:")))
20387 ;; callback function
20388 (callback (lambda ()
20389 (let ((time
20390 (org-float-time
20391 (apply 'encode-time
20392 (org-parse-time-string
20393 (match-string 1))))))
20394 ;; check if time in interval
20395 (and (>= time time1) (<= time time2))))))
20396 ;; make tree, check each match with the callback
20397 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
20399 ;;;; Finish up
20401 (provide 'org)
20403 (run-hooks 'org-load-hook)
20405 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
20407 ;;; org.el ends here