Republish org-odt-20111011.tar
[org-mode/org-jambu.git] / lisp / org.el
blobfa071d110a62e36a018adfaf726730c0db9bc698
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
4 ;; Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 7.5
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
79 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
80 (when (fboundp 'defvaralias)
81 (unless (boundp 'calendar-view-holidays-initially-flag)
82 (defvaralias 'calendar-view-holidays-initially-flag
83 'view-calendar-holidays-initially))
84 (unless (boundp 'calendar-view-diary-initially-flag)
85 (defvaralias 'calendar-view-diary-initially-flag
86 'view-diary-entries-initially))
87 (unless (boundp 'diary-fancy-buffer)
88 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
90 (require 'outline) (require 'noutline)
91 ;; Other stuff we need.
92 (require 'time-date)
93 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
94 (require 'easymenu)
95 (require 'overlay)
97 (require 'org-macs)
98 (require 'org-entities)
99 (require 'org-compat)
100 (require 'org-faces)
101 (require 'org-list)
102 (require 'org-pcomplete)
103 (require 'org-src)
104 (require 'org-footnote)
106 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
107 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
108 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
110 ;; babel
111 (require 'ob)
112 (require 'ob-table)
113 (require 'ob-lob)
114 (require 'ob-ref)
115 (require 'ob-tangle)
116 (require 'ob-comint)
117 (require 'ob-keys)
119 ;; load languages based on value of `org-babel-load-languages'
120 (defvar org-babel-load-languages)
121 ;;;###autoload
122 (defun org-babel-do-load-languages (sym value)
123 "Load the languages defined in `org-babel-load-languages'."
124 (set-default sym value)
125 (mapc (lambda (pair)
126 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
127 (if active
128 (progn
129 (require (intern (concat "ob-" lang))))
130 (progn
131 (funcall 'fmakunbound
132 (intern (concat "org-babel-execute:" lang)))
133 (funcall 'fmakunbound
134 (intern (concat "org-babel-expand-body:" lang)))))))
135 org-babel-load-languages))
137 (defcustom org-babel-load-languages '((emacs-lisp . t))
138 "Languages which can be evaluated in Org-mode buffers.
139 This list can be used to load support for any of the languages
140 below, note that each language will depend on a different set of
141 system executables and/or Emacs modes. When a language is
142 \"loaded\", then code blocks in that language can be evaluated
143 with `org-babel-execute-src-block' bound by default to C-c
144 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
145 be set to remove code block evaluation from the C-c C-c
146 keybinding. By default only Emacs Lisp (which has no
147 requirements) is loaded."
148 :group 'org-babel
149 :set 'org-babel-do-load-languages
150 :type '(alist :tag "Babel Languages"
151 :key-type
152 (choice
153 (const :tag "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 "Maxima" maxima)
169 (const :tag "Matlab" matlab)
170 (const :tag "Mscgen" mscgen)
171 (const :tag "Ocaml" ocaml)
172 (const :tag "Octave" octave)
173 (const :tag "Org" org)
174 (const :tag "Perl" perl)
175 (const :tag "PlantUML" plantuml)
176 (const :tag "Python" python)
177 (const :tag "Ruby" ruby)
178 (const :tag "Sass" sass)
179 (const :tag "Scheme" scheme)
180 (const :tag "Screen" screen)
181 (const :tag "Shell Script" sh)
182 (const :tag "Sql" sql)
183 (const :tag "Sqlite" sqlite))
184 :value-type (boolean :tag "Activate" :value t)))
186 ;;;; Customization variables
187 (defcustom org-clone-delete-id nil
188 "Remove ID property of clones of a subtree.
189 When non-nil, clones of a subtree don't inherit the ID property.
190 Otherwise they inherit the ID property with a new unique
191 identifier."
192 :type 'boolean
193 :group 'org-id)
195 ;;; Version
197 (defconst org-version "7.5"
198 "The version number of the file org.el.")
200 (defun org-version (&optional here)
201 "Show the org-mode version in the echo area.
202 With prefix arg HERE, insert it at point."
203 (interactive "P")
204 (let* ((origin default-directory)
205 (version org-version)
206 (git-version)
207 (dir (concat (file-name-directory (locate-library "org")) "../" )))
208 (when (and (file-exists-p (expand-file-name ".git" dir))
209 (executable-find "git"))
210 (unwind-protect
211 (progn
212 (cd dir)
213 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
214 (with-current-buffer "*Shell Command Output*"
215 (goto-char (point-min))
216 (setq git-version (buffer-substring (point) (point-at-eol))))
217 (subst-char-in-string ?- ?. git-version t)
218 (when (string-match "\\S-"
219 (shell-command-to-string
220 "git diff-index --name-only HEAD --"))
221 (setq git-version (concat git-version ".dirty")))
222 (setq version (concat version " (" git-version ")"))))
223 (cd origin)))
224 (setq version (format "Org-mode version %s" version))
225 (if here (insert version))
226 (message version)))
228 ;;; Compatibility constants
230 ;;; The custom variables
232 (defgroup org nil
233 "Outline-based notes management and organizer."
234 :tag "Org"
235 :group 'outlines
236 :group 'calendar)
238 (defcustom org-mode-hook nil
239 "Mode hook for Org-mode, run after the mode was turned on."
240 :group 'org
241 :type 'hook)
243 (defcustom org-load-hook nil
244 "Hook that is run after org.el has been loaded."
245 :group 'org
246 :type 'hook)
248 (defvar org-modules) ; defined below
249 (defvar org-modules-loaded nil
250 "Have the modules been loaded already?")
252 (defun org-load-modules-maybe (&optional force)
253 "Load all extensions listed in `org-modules'."
254 (when (or force (not org-modules-loaded))
255 (mapc (lambda (ext)
256 (condition-case nil (require ext)
257 (error (message "Problems while trying to load feature `%s'" ext))))
258 org-modules)
259 (setq org-modules-loaded t)))
261 (defun org-set-modules (var value)
262 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
263 (set var value)
264 (when (featurep 'org)
265 (org-load-modules-maybe 'force)))
267 (when (org-bound-and-true-p org-modules)
268 (let ((a (member 'org-infojs org-modules)))
269 (and a (setcar a 'org-jsinfo))))
271 (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)
272 "Modules that should always be loaded together with org.el.
273 If a description starts with <C>, the file is not part of Emacs
274 and loading it will require that you have downloaded and properly installed
275 the org-mode distribution.
277 You can also use this system to load external packages (i.e. neither Org
278 core modules, nor modules from the CONTRIB directory). Just add symbols
279 to the end of the list. If the package is called org-xyz.el, then you need
280 to add the symbol `xyz', and the package must have a call to
282 (provide 'org-xyz)"
283 :group 'org
284 :set 'org-set-modules
285 :type
286 '(set :greedy t
287 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
288 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
289 (const :tag " crypt: Encryption of subtrees" org-crypt)
290 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
291 (const :tag " docview: Links to doc-view buffers" org-docview)
292 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
293 (const :tag " id: Global IDs for identifying entries" org-id)
294 (const :tag " info: Links to Info nodes" org-info)
295 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
296 (const :tag " habit: Track your consistency with habits" org-habit)
297 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
298 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
299 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
300 (const :tag " mew Links to Mew folders/messages" org-mew)
301 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
302 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
303 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
304 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
305 (const :tag " vm: Links to VM folders/messages" org-vm)
306 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
307 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
308 (const :tag " mouse: Additional mouse support" org-mouse)
309 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
311 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
312 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
313 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
314 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
315 (const :tag "C collector: Collect properties into tables" org-collector)
316 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
317 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
318 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
319 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
320 (const :tag "C eval: Include command output as text" org-eval)
321 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
322 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
323 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
324 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
325 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
327 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
329 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
330 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
331 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
332 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
333 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
334 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
335 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
336 (const :tag "C mtags: Support for muse-like tags" org-mtags)
337 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
338 (const :tag "C registry: A registry for Org-mode links" org-registry)
339 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
340 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
341 (const :tag "C secretary: Team management with org-mode" org-secretary)
342 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
343 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
344 (const :tag "C track: Keep up with Org-mode development" org-track)
345 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
346 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
347 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
349 (defcustom org-support-shift-select nil
350 "Non-nil means make shift-cursor commands select text when possible.
352 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
353 selecting a region, or enlarge regions started in this way.
354 In Org-mode, in special contexts, these same keys are used for other
355 purposes, important enough to compete with shift selection. Org tries
356 to balance these needs by supporting `shift-select-mode' outside these
357 special contexts, under control of this variable.
359 The default of this variable is nil, to avoid confusing behavior. Shifted
360 cursor keys will then execute Org commands in the following contexts:
361 - on a headline, changing TODO state (left/right) and priority (up/down)
362 - on a time stamp, changing the time
363 - in a plain list item, changing the bullet type
364 - in a property definition line, switching between allowed values
365 - in the BEGIN line of a clock table (changing the time block).
366 Outside these contexts, the commands will throw an error.
368 When this variable is t and the cursor is not in a special context,
369 Org-mode will support shift-selection for making and enlarging regions.
370 To make this more effective, the bullet cycling will no longer happen
371 anywhere in an item line, but only if the cursor is exactly on the bullet.
373 If you set this variable to the symbol `always', then the keys
374 will not be special in headlines, property lines, and item lines, to make
375 shift selection work there as well. If this is what you want, you can
376 use the following alternative commands: `C-c C-t' and `C-c ,' to
377 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
378 TODO sets, `C-c -' to cycle item bullet types, and properties can be
379 edited by hand or in column view.
381 However, when the cursor is on a timestamp, shift-cursor commands
382 will still edit the time stamp - this is just too good to give up.
384 XEmacs user should have this variable set to nil, because shift-select-mode
385 is Emacs 23 only."
386 :group 'org
387 :type '(choice
388 (const :tag "Never" nil)
389 (const :tag "When outside special context" t)
390 (const :tag "Everywhere except timestamps" always)))
392 (defgroup org-startup nil
393 "Options concerning startup of Org-mode."
394 :tag "Org Startup"
395 :group 'org)
397 (defcustom org-startup-folded t
398 "Non-nil means entering Org-mode will switch to OVERVIEW.
399 This can also be configured on a per-file basis by adding one of
400 the following lines anywhere in the buffer:
402 #+STARTUP: fold (or `overview', this is equivalent)
403 #+STARTUP: nofold (or `showall', this is equivalent)
404 #+STARTUP: content
405 #+STARTUP: showeverything"
406 :group 'org-startup
407 :type '(choice
408 (const :tag "nofold: show all" nil)
409 (const :tag "fold: overview" t)
410 (const :tag "content: all headlines" content)
411 (const :tag "show everything, even drawers" showeverything)))
413 (defcustom org-startup-truncated t
414 "Non-nil means entering Org-mode will set `truncate-lines'.
415 This is useful since some lines containing links can be very long and
416 uninteresting. Also tables look terrible when wrapped."
417 :group 'org-startup
418 :type 'boolean)
420 (defcustom org-startup-indented nil
421 "Non-nil means turn on `org-indent-mode' on startup.
422 This can also be configured on a per-file basis by adding one of
423 the following lines anywhere in the buffer:
425 #+STARTUP: indent
426 #+STARTUP: noindent"
427 :group 'org-structure
428 :type '(choice
429 (const :tag "Not" nil)
430 (const :tag "Globally (slow on startup in large files)" t)))
432 (defcustom org-use-sub-superscripts t
433 "Non-nil means interpret \"_\" and \"^\" for export.
434 When this option is turned on, you can use TeX-like syntax for sub- and
435 superscripts. Several characters after \"_\" or \"^\" will be
436 considered as a single item - so grouping with {} is normally not
437 needed. For example, the following things will be parsed as single
438 sub- or superscripts.
440 10^24 or 10^tau several digits will be considered 1 item.
441 10^-12 or 10^-tau a leading sign with digits or a word
442 x^2-y^3 will be read as x^2 - y^3, because items are
443 terminated by almost any nonword/nondigit char.
444 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
446 Still, ambiguity is possible - so when in doubt use {} to enclose the
447 sub/superscript. If you set this variable to the symbol `{}',
448 the braces are *required* in order to trigger interpretations as
449 sub/superscript. This can be helpful in documents that need \"_\"
450 frequently in plain text.
452 Not all export backends support this, but HTML does.
454 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
455 :group 'org-startup
456 :group 'org-export-translation
457 :type '(choice
458 (const :tag "Always interpret" t)
459 (const :tag "Only with braces" {})
460 (const :tag "Never interpret" nil)))
462 (if (fboundp 'defvaralias)
463 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
466 (defcustom org-startup-with-beamer-mode nil
467 "Non-nil means turn on `org-beamer-mode' on startup.
468 This can also be configured on a per-file basis by adding one of
469 the following lines anywhere in the buffer:
471 #+STARTUP: beamer"
472 :group 'org-startup
473 :type 'boolean)
475 (defcustom org-startup-align-all-tables nil
476 "Non-nil means align all tables when visiting a file.
477 This is useful when the column width in tables is forced with <N> cookies
478 in table fields. Such tables will look correct only after the first re-align.
479 This can also be configured on a per-file basis by adding one of
480 the following lines anywhere in the buffer:
481 #+STARTUP: align
482 #+STARTUP: noalign"
483 :group 'org-startup
484 :type 'boolean)
486 (defcustom org-startup-with-inline-images nil
487 "Non-nil means show inline images when loading a new Org file.
488 This can also be configured on a per-file basis by adding one of
489 the following lines anywhere in the buffer:
490 #+STARTUP: inlineimages
491 #+STARTUP: noinlineimages"
492 :group 'org-startup
493 :type 'boolean)
495 (defcustom org-insert-mode-line-in-empty-file nil
496 "Non-nil means insert the first line setting Org-mode in empty files.
497 When the function `org-mode' is called interactively in an empty file, this
498 normally means that the file name does not automatically trigger Org-mode.
499 To ensure that the file will always be in Org-mode in the future, a
500 line enforcing Org-mode will be inserted into the buffer, if this option
501 has been set."
502 :group 'org-startup
503 :type 'boolean)
505 (defcustom org-replace-disputed-keys nil
506 "Non-nil means use alternative key bindings for some keys.
507 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
508 These keys are also used by other packages like shift-selection-mode'
509 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
510 If you want to use Org-mode together with one of these other modes,
511 or more generally if you would like to move some Org-mode commands to
512 other keys, set this variable and configure the keys with the variable
513 `org-disputed-keys'.
515 This option is only relevant at load-time of Org-mode, and must be set
516 *before* org.el is loaded. Changing it requires a restart of Emacs to
517 become effective."
518 :group 'org-startup
519 :type 'boolean)
521 (defcustom org-use-extra-keys nil
522 "Non-nil means use extra key sequence definitions for certain commands.
523 This happens automatically if you run XEmacs or if `window-system'
524 is nil. This variable lets you do the same manually. You must
525 set it before loading org.
527 Example: on Carbon Emacs 22 running graphically, with an external
528 keyboard on a Powerbook, the default way of setting M-left might
529 not work for either Alt or ESC. Setting this variable will make
530 it work for ESC."
531 :group 'org-startup
532 :type 'boolean)
534 (if (fboundp 'defvaralias)
535 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
537 (defcustom org-disputed-keys
538 '(([(shift up)] . [(meta p)])
539 ([(shift down)] . [(meta n)])
540 ([(shift left)] . [(meta -)])
541 ([(shift right)] . [(meta +)])
542 ([(control shift right)] . [(meta shift +)])
543 ([(control shift left)] . [(meta shift -)]))
544 "Keys for which Org-mode and other modes compete.
545 This is an alist, cars are the default keys, second element specifies
546 the alternative to use when `org-replace-disputed-keys' is t.
548 Keys can be specified in any syntax supported by `define-key'.
549 The value of this option takes effect only at Org-mode's startup,
550 therefore you'll have to restart Emacs to apply it after changing."
551 :group 'org-startup
552 :type 'alist)
554 (defun org-key (key)
555 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
556 Or return the original if not disputed.
557 Also apply the translations defined in `org-xemacs-key-equivalents'."
558 (when org-replace-disputed-keys
559 (let* ((nkey (key-description key))
560 (x (org-find-if (lambda (x)
561 (equal (key-description (car x)) nkey))
562 org-disputed-keys)))
563 (setq key (if x (cdr x) key))))
564 (when (featurep 'xemacs)
565 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
566 key)
568 (defun org-find-if (predicate seq)
569 (catch 'exit
570 (while seq
571 (if (funcall predicate (car seq))
572 (throw 'exit (car seq))
573 (pop seq)))))
575 (defun org-defkey (keymap key def)
576 "Define a key, possibly translated, as returned by `org-key'."
577 (define-key keymap (org-key key) def))
579 (defcustom org-ellipsis nil
580 "The ellipsis to use in the Org-mode outline.
581 When nil, just use the standard three dots. When a string, use that instead,
582 When a face, use the standard 3 dots, but with the specified face.
583 The change affects only Org-mode (which will then use its own display table).
584 Changing this requires executing `M-x org-mode' in a buffer to become
585 effective."
586 :group 'org-startup
587 :type '(choice (const :tag "Default" nil)
588 (face :tag "Face" :value org-warning)
589 (string :tag "String" :value "...#")))
591 (defvar org-display-table nil
592 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
594 (defgroup org-keywords nil
595 "Keywords in Org-mode."
596 :tag "Org Keywords"
597 :group 'org)
599 (defcustom org-deadline-string "DEADLINE:"
600 "String to mark deadline entries.
601 A deadline is this string, followed by a time stamp. Should be a word,
602 terminated by a colon. You can insert a schedule keyword and
603 a timestamp with \\[org-deadline].
604 Changes become only effective after restarting Emacs."
605 :group 'org-keywords
606 :type 'string)
608 (defcustom org-scheduled-string "SCHEDULED:"
609 "String to mark scheduled TODO entries.
610 A schedule is this string, followed by a time stamp. Should be a word,
611 terminated by a colon. You can insert a schedule keyword and
612 a timestamp with \\[org-schedule].
613 Changes become only effective after restarting Emacs."
614 :group 'org-keywords
615 :type 'string)
617 (defcustom org-closed-string "CLOSED:"
618 "String used as the prefix for timestamps logging closing a TODO entry."
619 :group 'org-keywords
620 :type 'string)
622 (defcustom org-clock-string "CLOCK:"
623 "String used as prefix for timestamps clocking work hours on an item."
624 :group 'org-keywords
625 :type 'string)
627 (defcustom org-comment-string "COMMENT"
628 "Entries starting with this keyword will never be exported.
629 An entry can be toggled between COMMENT and normal with
630 \\[org-toggle-comment].
631 Changes become only effective after restarting Emacs."
632 :group 'org-keywords
633 :type 'string)
635 (defcustom org-quote-string "QUOTE"
636 "Entries starting with this keyword will be exported in fixed-width font.
637 Quoting applies only to the text in the entry following the headline, and does
638 not extend beyond the next headline, even if that is lower level.
639 An entry can be toggled between QUOTE and normal with
640 \\[org-toggle-fixed-width-section]."
641 :group 'org-keywords
642 :type 'string)
644 (defconst org-repeat-re
645 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
646 "Regular expression for specifying repeated events.
647 After a match, group 1 contains the repeat expression.")
649 (defgroup org-structure nil
650 "Options concerning the general structure of Org-mode files."
651 :tag "Org Structure"
652 :group 'org)
654 (defgroup org-reveal-location nil
655 "Options about how to make context of a location visible."
656 :tag "Org Reveal Location"
657 :group 'org-structure)
659 (defconst org-context-choice
660 '(choice
661 (const :tag "Always" t)
662 (const :tag "Never" nil)
663 (repeat :greedy t :tag "Individual contexts"
664 (cons
665 (choice :tag "Context"
666 (const agenda)
667 (const org-goto)
668 (const occur-tree)
669 (const tags-tree)
670 (const link-search)
671 (const mark-goto)
672 (const bookmark-jump)
673 (const isearch)
674 (const default))
675 (boolean))))
676 "Contexts for the reveal options.")
678 (defcustom org-show-hierarchy-above '((default . t))
679 "Non-nil means show full hierarchy when revealing a location.
680 Org-mode often shows locations in an org-mode file which might have
681 been invisible before. When this is set, the hierarchy of headings
682 above the exposed location is shown.
683 Turning this off for example for sparse trees makes them very compact.
684 Instead of t, this can also be an alist specifying this option for different
685 contexts. Valid contexts are
686 agenda when exposing an entry from the agenda
687 org-goto when using the command `org-goto' on key C-c C-j
688 occur-tree when using the command `org-occur' on key C-c /
689 tags-tree when constructing a sparse tree based on tags matches
690 link-search when exposing search matches associated with a link
691 mark-goto when exposing the jump goal of a mark
692 bookmark-jump when exposing a bookmark location
693 isearch when exiting from an incremental search
694 default default for all contexts not set explicitly"
695 :group 'org-reveal-location
696 :type org-context-choice)
698 (defcustom org-show-following-heading '((default . nil))
699 "Non-nil means show following heading when revealing a location.
700 Org-mode often shows locations in an org-mode file which might have
701 been invisible before. When this is set, the heading following the
702 match is shown.
703 Turning this off for example for sparse trees makes them very compact,
704 but makes it harder to edit the location of the match. In such a case,
705 use the command \\[org-reveal] to show more context.
706 Instead of t, this can also be an alist specifying this option for different
707 contexts. See `org-show-hierarchy-above' for valid contexts."
708 :group 'org-reveal-location
709 :type org-context-choice)
711 (defcustom org-show-siblings '((default . nil) (isearch t))
712 "Non-nil means show all sibling heading when revealing a location.
713 Org-mode often shows locations in an org-mode file which might have
714 been invisible before. When this is set, the sibling of the current entry
715 heading are all made visible. If `org-show-hierarchy-above' is t,
716 the same happens on each level of the hierarchy above the current entry.
718 By default this is on for the isearch context, off for all other contexts.
719 Turning this off for example for sparse trees makes them very compact,
720 but makes it harder to edit the location of the match. In such a case,
721 use the command \\[org-reveal] to show more context.
722 Instead of t, this can also be an alist specifying this option for different
723 contexts. See `org-show-hierarchy-above' for valid contexts."
724 :group 'org-reveal-location
725 :type org-context-choice)
727 (defcustom org-show-entry-below '((default . nil))
728 "Non-nil means show the entry below a headline when revealing a location.
729 Org-mode often shows locations in an org-mode file which might have
730 been invisible before. When this is set, the text below the headline that is
731 exposed is also shown.
733 By default this is off for all contexts.
734 Instead of t, this can also be an alist specifying this option for different
735 contexts. See `org-show-hierarchy-above' for valid contexts."
736 :group 'org-reveal-location
737 :type org-context-choice)
739 (defcustom org-indirect-buffer-display 'other-window
740 "How should indirect tree buffers be displayed?
741 This applies to indirect buffers created with the commands
742 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
743 Valid values are:
744 current-window Display in the current window
745 other-window Just display in another window.
746 dedicated-frame Create one new frame, and re-use it each time.
747 new-frame Make a new frame each time. Note that in this case
748 previously-made indirect buffers are kept, and you need to
749 kill these buffers yourself."
750 :group 'org-structure
751 :group 'org-agenda-windows
752 :type '(choice
753 (const :tag "In current window" current-window)
754 (const :tag "In current frame, other window" other-window)
755 (const :tag "Each time a new frame" new-frame)
756 (const :tag "One dedicated frame" dedicated-frame)))
758 (defcustom org-use-speed-commands nil
759 "Non-nil means activate single letter commands at beginning of a headline.
760 This may also be a function to test for appropriate locations where speed
761 commands should be active."
762 :group 'org-structure
763 :type '(choice
764 (const :tag "Never" nil)
765 (const :tag "At beginning of headline stars" t)
766 (function)))
768 (defcustom org-speed-commands-user nil
769 "Alist of additional speed commands.
770 This list will be checked before `org-speed-commands-default'
771 when the variable `org-use-speed-commands' is non-nil
772 and when the cursor is at the beginning of a headline.
773 The car if each entry is a string with a single letter, which must
774 be assigned to `self-insert-command' in the global map.
775 The cdr is either a command to be called interactively, a function
776 to be called, or a form to be evaluated.
777 An entry that is just a list with a single string will be interpreted
778 as a descriptive headline that will be added when listing the speed
779 commands in the Help buffer using the `?' speed command."
780 :group 'org-structure
781 :type '(repeat :value ("k" . ignore)
782 (choice :value ("k" . ignore)
783 (list :tag "Descriptive Headline" (string :tag "Headline"))
784 (cons :tag "Letter and Command"
785 (string :tag "Command letter")
786 (choice
787 (function)
788 (sexp))))))
790 (defgroup org-cycle nil
791 "Options concerning visibility cycling in Org-mode."
792 :tag "Org Cycle"
793 :group 'org-structure)
795 (defcustom org-cycle-skip-children-state-if-no-children t
796 "Non-nil means skip CHILDREN state in entries that don't have any."
797 :group 'org-cycle
798 :type 'boolean)
800 (defcustom org-cycle-max-level nil
801 "Maximum level which should still be subject to visibility cycling.
802 Levels higher than this will, for cycling, be treated as text, not a headline.
803 When `org-odd-levels-only' is set, a value of N in this variable actually
804 means 2N-1 stars as the limiting headline.
805 When nil, cycle all levels.
806 Note that the limiting level of cycling is also influenced by
807 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
808 `org-inlinetask-min-level' is, cycling will be limited to levels one less
809 than its value."
810 :group 'org-cycle
811 :type '(choice
812 (const :tag "No limit" nil)
813 (integer :tag "Maximum level")))
815 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
816 "Names of drawers. Drawers are not opened by cycling on the headline above.
817 Drawers only open with a TAB on the drawer line itself. A drawer looks like
818 this:
819 :DRAWERNAME:
820 .....
821 :END:
822 The drawer \"PROPERTIES\" is special for capturing properties through
823 the property API.
825 Drawers can be defined on the per-file basis with a line like:
827 #+DRAWERS: HIDDEN STATE PROPERTIES"
828 :group 'org-structure
829 :group 'org-cycle
830 :type '(repeat (string :tag "Drawer Name")))
832 (defcustom org-hide-block-startup nil
833 "Non-nil means entering Org-mode will fold all blocks.
834 This can also be set in on a per-file basis with
836 #+STARTUP: hideblocks
837 #+STARTUP: showblocks"
838 :group 'org-startup
839 :group 'org-cycle
840 :type 'boolean)
842 (defcustom org-cycle-global-at-bob nil
843 "Cycle globally if cursor is at beginning of buffer and not at a headline.
844 This makes it possible to do global cycling without having to use S-TAB or
845 \\[universal-argument] TAB. For this special case to work, the first line \
846 of the buffer
847 must not be a headline - it may be empty or some other text. When used in
848 this way, `org-cycle-hook' is disables temporarily, to make sure the
849 cursor stays at the beginning of the buffer.
850 When this option is nil, don't do anything special at the beginning
851 of the buffer."
852 :group 'org-cycle
853 :type 'boolean)
855 (defcustom org-cycle-level-after-item/entry-creation t
856 "Non-nil means cycle entry level or item indentation in new empty entries.
858 When the cursor is at the end of an empty headline, i.e with only stars
859 and maybe a TODO keyword, TAB will then switch the entry to become a child,
860 and then all possible ancestor states, before returning to the original state.
861 This makes data entry extremely fast: M-RET to create a new headline,
862 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
864 When the cursor is at the end of an empty plain list item, one TAB will
865 make it a subitem, two or more tabs will back up to make this an item
866 higher up in the item hierarchy."
867 :group 'org-cycle
868 :type 'boolean)
870 (defcustom org-cycle-emulate-tab t
871 "Where should `org-cycle' emulate TAB.
872 nil Never
873 white Only in completely white lines
874 whitestart Only at the beginning of lines, before the first non-white char
875 t Everywhere except in headlines
876 exc-hl-bol Everywhere except at the start of a headline
877 If TAB is used in a place where it does not emulate TAB, the current subtree
878 visibility is cycled."
879 :group 'org-cycle
880 :type '(choice (const :tag "Never" nil)
881 (const :tag "Only in completely white lines" white)
882 (const :tag "Before first char in a line" whitestart)
883 (const :tag "Everywhere except in headlines" t)
884 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
887 (defcustom org-cycle-separator-lines 2
888 "Number of empty lines needed to keep an empty line between collapsed trees.
889 If you leave an empty line between the end of a subtree and the following
890 headline, this empty line is hidden when the subtree is folded.
891 Org-mode will leave (exactly) one empty line visible if the number of
892 empty lines is equal or larger to the number given in this variable.
893 So the default 2 means at least 2 empty lines after the end of a subtree
894 are needed to produce free space between a collapsed subtree and the
895 following headline.
897 If the number is negative, and the number of empty lines is at least -N,
898 all empty lines are shown.
900 Special case: when 0, never leave empty lines in collapsed view."
901 :group 'org-cycle
902 :type 'integer)
903 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
905 (defcustom org-pre-cycle-hook nil
906 "Hook that is run before visibility cycling is happening.
907 The function(s) in this hook must accept a single argument which indicates
908 the new state that will be set right after running this hook. The
909 argument is a symbol. Before a global state change, it can have the values
910 `overview', `content', or `all'. Before a local state change, it can have
911 the values `folded', `children', or `subtree'."
912 :group 'org-cycle
913 :type 'hook)
915 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
916 org-cycle-hide-drawers
917 org-cycle-show-empty-lines
918 org-optimize-window-after-visibility-change)
919 "Hook that is run after `org-cycle' has changed the buffer visibility.
920 The function(s) in this hook must accept a single argument which indicates
921 the new state that was set by the most recent `org-cycle' command. The
922 argument is a symbol. After a global state change, it can have the values
923 `overview', `content', or `all'. After a local state change, it can have
924 the values `folded', `children', or `subtree'."
925 :group 'org-cycle
926 :type 'hook)
928 (defgroup org-edit-structure nil
929 "Options concerning structure editing in Org-mode."
930 :tag "Org Edit Structure"
931 :group 'org-structure)
933 (defcustom org-odd-levels-only nil
934 "Non-nil means skip even levels and only use odd levels for the outline.
935 This has the effect that two stars are being added/taken away in
936 promotion/demotion commands. It also influences how levels are
937 handled by the exporters.
938 Changing it requires restart of `font-lock-mode' to become effective
939 for fontification also in regions already fontified.
940 You may also set this on a per-file basis by adding one of the following
941 lines to the buffer:
943 #+STARTUP: odd
944 #+STARTUP: oddeven"
945 :group 'org-edit-structure
946 :group 'org-appearance
947 :type 'boolean)
949 (defcustom org-adapt-indentation t
950 "Non-nil means adapt indentation to outline node level.
952 When this variable is set, Org assumes that you write outlines by
953 indenting text in each node to align with the headline (after the stars).
954 The following issues are influenced by this variable:
956 - When this is set and the *entire* text in an entry is indented, the
957 indentation is increased by one space in a demotion command, and
958 decreased by one in a promotion command. If any line in the entry
959 body starts with text at column 0, indentation is not changed at all.
961 - Property drawers and planning information is inserted indented when
962 this variable s set. When nil, they will not be indented.
964 - TAB indents a line relative to context. The lines below a headline
965 will be indented when this variable is set.
967 Note that this is all about true indentation, by adding and removing
968 space characters. See also `org-indent.el' which does level-dependent
969 indentation in a virtual way, i.e. at display time in Emacs."
970 :group 'org-edit-structure
971 :type 'boolean)
973 (defcustom org-special-ctrl-a/e nil
974 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
976 When t, `C-a' will bring back the cursor to the beginning of the
977 headline text, i.e. after the stars and after a possible TODO keyword.
978 In an item, this will be the position after the bullet.
979 When the cursor is already at that position, another `C-a' will bring
980 it to the beginning of the line.
982 `C-e' will jump to the end of the headline, ignoring the presence of tags
983 in the headline. A second `C-e' will then jump to the true end of the
984 line, after any tags. This also means that, when this variable is
985 non-nil, `C-e' also will never jump beyond the end of the heading of a
986 folded section, i.e. not after the ellipses.
988 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
989 going to the true line boundary first. Only a directly following, identical
990 keypress will bring the cursor to the special positions.
992 This may also be a cons cell where the behavior for `C-a' and `C-e' is
993 set separately."
994 :group 'org-edit-structure
995 :type '(choice
996 (const :tag "off" nil)
997 (const :tag "on: after stars/bullet and before tags first" t)
998 (const :tag "reversed: true line boundary first" reversed)
999 (cons :tag "Set C-a and C-e separately"
1000 (choice :tag "Special C-a"
1001 (const :tag "off" nil)
1002 (const :tag "on: after stars/bullet first" t)
1003 (const :tag "reversed: before stars/bullet first" reversed))
1004 (choice :tag "Special C-e"
1005 (const :tag "off" nil)
1006 (const :tag "on: before tags first" t)
1007 (const :tag "reversed: after tags first" reversed)))))
1008 (if (fboundp 'defvaralias)
1009 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1011 (defcustom org-special-ctrl-k nil
1012 "Non-nil means `C-k' will behave specially in headlines.
1013 When nil, `C-k' will call the default `kill-line' command.
1014 When t, the following will happen while the cursor is in the headline:
1016 - When the cursor is at the beginning of a headline, kill the entire
1017 line and possible the folded subtree below the line.
1018 - When in the middle of the headline text, kill the headline up to the tags.
1019 - When after the headline text, kill the tags."
1020 :group 'org-edit-structure
1021 :type 'boolean)
1023 (defcustom org-ctrl-k-protect-subtree nil
1024 "Non-nil means, do not delete a hidden subtree with C-k.
1025 When set to the symbol `error', simply throw an error when C-k is
1026 used to kill (part-of) a headline that has hidden text behind it.
1027 Any other non-nil value will result in a query to the user, if it is
1028 OK to kill that hidden subtree. When nil, kill without remorse."
1029 :group 'org-edit-structure
1030 :type '(choice
1031 (const :tag "Do not protect hidden subtrees" nil)
1032 (const :tag "Protect hidden subtrees with a security query" t)
1033 (const :tag "Never kill a hidden subtree with C-k" error)))
1035 (defcustom org-yank-folded-subtrees t
1036 "Non-nil means when yanking subtrees, fold them.
1037 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1038 it starts with a heading and all other headings in it are either children
1039 or siblings, then fold all the subtrees. However, do this only if no
1040 text after the yank would be swallowed into a folded tree by this action."
1041 :group 'org-edit-structure
1042 :type 'boolean)
1044 (defcustom org-yank-adjusted-subtrees nil
1045 "Non-nil means when yanking subtrees, adjust the level.
1046 With this setting, `org-paste-subtree' is used to insert the subtree, see
1047 this function for details."
1048 :group 'org-edit-structure
1049 :type 'boolean)
1051 (defcustom org-M-RET-may-split-line '((default . t))
1052 "Non-nil means M-RET will split the line at the cursor position.
1053 When nil, it will go to the end of the line before making a
1054 new line.
1055 You may also set this option in a different way for different
1056 contexts. Valid contexts are:
1058 headline when creating a new headline
1059 item when creating a new item
1060 table in a table field
1061 default the value to be used for all contexts not explicitly
1062 customized"
1063 :group 'org-structure
1064 :group 'org-table
1065 :type '(choice
1066 (const :tag "Always" t)
1067 (const :tag "Never" nil)
1068 (repeat :greedy t :tag "Individual contexts"
1069 (cons
1070 (choice :tag "Context"
1071 (const headline)
1072 (const item)
1073 (const table)
1074 (const default))
1075 (boolean)))))
1078 (defcustom org-insert-heading-respect-content nil
1079 "Non-nil means insert new headings after the current subtree.
1080 When nil, the new heading is created directly after the current line.
1081 The commands \\[org-insert-heading-respect-content] and
1082 \\[org-insert-todo-heading-respect-content] turn this variable on
1083 for the duration of the command."
1084 :group 'org-structure
1085 :type 'boolean)
1087 (defcustom org-blank-before-new-entry '((heading . auto)
1088 (plain-list-item . auto))
1089 "Should `org-insert-heading' leave a blank line before new heading/item?
1090 The value is an alist, with `heading' and `plain-list-item' as car,
1091 and a boolean flag as cdr. The cdr may also be the symbol `auto', and then
1092 Org will look at the surrounding headings/items and try to make an
1093 intelligent decision whether to insert a blank line or not.
1095 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1096 set, the setting here is ignored and no empty line is inserted, to avoid
1097 breaking the list structure."
1098 :group 'org-edit-structure
1099 :type '(list
1100 (cons (const heading)
1101 (choice (const :tag "Never" nil)
1102 (const :tag "Always" t)
1103 (const :tag "Auto" auto)))
1104 (cons (const plain-list-item)
1105 (choice (const :tag "Never" nil)
1106 (const :tag "Always" t)
1107 (const :tag "Auto" auto)))))
1109 (defcustom org-insert-heading-hook nil
1110 "Hook being run after inserting a new heading."
1111 :group 'org-edit-structure
1112 :type 'hook)
1114 (defcustom org-enable-fixed-width-editor t
1115 "Non-nil means lines starting with \":\" are treated as fixed-width.
1116 This currently only means they are never auto-wrapped.
1117 When nil, such lines will be treated like ordinary lines.
1118 See also the QUOTE keyword."
1119 :group 'org-edit-structure
1120 :type 'boolean)
1122 (defcustom org-goto-auto-isearch t
1123 "Non-nil means typing characters in `org-goto' starts incremental search."
1124 :group 'org-edit-structure
1125 :type 'boolean)
1127 (defgroup org-sparse-trees nil
1128 "Options concerning sparse trees in Org-mode."
1129 :tag "Org Sparse Trees"
1130 :group 'org-structure)
1132 (defcustom org-highlight-sparse-tree-matches t
1133 "Non-nil means highlight all matches that define a sparse tree.
1134 The highlights will automatically disappear the next time the buffer is
1135 changed by an edit command."
1136 :group 'org-sparse-trees
1137 :type 'boolean)
1139 (defcustom org-remove-highlights-with-change t
1140 "Non-nil means any change to the buffer will remove temporary highlights.
1141 Such highlights are created by `org-occur' and `org-clock-display'.
1142 When nil, `C-c C-c needs to be used to get rid of the highlights.
1143 The highlights created by `org-preview-latex-fragment' always need
1144 `C-c C-c' to be removed."
1145 :group 'org-sparse-trees
1146 :group 'org-time
1147 :type 'boolean)
1150 (defcustom org-occur-hook '(org-first-headline-recenter)
1151 "Hook that is run after `org-occur' has constructed a sparse tree.
1152 This can be used to recenter the window to show as much of the structure
1153 as possible."
1154 :group 'org-sparse-trees
1155 :type 'hook)
1157 (defgroup org-imenu-and-speedbar nil
1158 "Options concerning imenu and speedbar in Org-mode."
1159 :tag "Org Imenu and Speedbar"
1160 :group 'org-structure)
1162 (defcustom org-imenu-depth 2
1163 "The maximum level for Imenu access to Org-mode headlines.
1164 This also applied for speedbar access."
1165 :group 'org-imenu-and-speedbar
1166 :type 'integer)
1168 (defgroup org-table nil
1169 "Options concerning tables in Org-mode."
1170 :tag "Org Table"
1171 :group 'org)
1173 (defcustom org-enable-table-editor 'optimized
1174 "Non-nil means lines starting with \"|\" are handled by the table editor.
1175 When nil, such lines will be treated like ordinary lines.
1177 When equal to the symbol `optimized', the table editor will be optimized to
1178 do the following:
1179 - Automatic overwrite mode in front of whitespace in table fields.
1180 This makes the structure of the table stay in tact as long as the edited
1181 field does not exceed the column width.
1182 - Minimize the number of realigns. Normally, the table is aligned each time
1183 TAB or RET are pressed to move to another field. With optimization this
1184 happens only if changes to a field might have changed the column width.
1185 Optimization requires replacing the functions `self-insert-command',
1186 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1187 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1188 very good at guessing when a re-align will be necessary, but you can always
1189 force one with \\[org-ctrl-c-ctrl-c].
1191 If you would like to use the optimized version in Org-mode, but the
1192 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1194 This variable can be used to turn on and off the table editor during a session,
1195 but in order to toggle optimization, a restart is required.
1197 See also the variable `org-table-auto-blank-field'."
1198 :group 'org-table
1199 :type '(choice
1200 (const :tag "off" nil)
1201 (const :tag "on" t)
1202 (const :tag "on, optimized" optimized)))
1204 (defcustom org-self-insert-cluster-for-undo t
1205 "Non-nil means cluster self-insert commands for undo when possible.
1206 If this is set, then, like in the Emacs command loop, 20 consecutive
1207 characters will be undone together.
1208 This is configurable, because there is some impact on typing performance."
1209 :group 'org-table
1210 :type 'boolean)
1212 (defcustom org-table-tab-recognizes-table.el t
1213 "Non-nil means TAB will automatically notice a table.el table.
1214 When it sees such a table, it moves point into it and - if necessary -
1215 calls `table-recognize-table'."
1216 :group 'org-table-editing
1217 :type 'boolean)
1219 (defgroup org-link nil
1220 "Options concerning links in Org-mode."
1221 :tag "Org Link"
1222 :group 'org)
1224 (defvar org-link-abbrev-alist-local nil
1225 "Buffer-local version of `org-link-abbrev-alist', which see.
1226 The value of this is taken from the #+LINK lines.")
1227 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1229 (defcustom org-link-abbrev-alist nil
1230 "Alist of link abbreviations.
1231 The car of each element is a string, to be replaced at the start of a link.
1232 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1233 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1235 [[linkkey:tag][description]]
1237 The 'linkkey' must be a word word, starting with a letter, followed
1238 by letters, numbers, '-' or '_'.
1240 If REPLACE is a string, the tag will simply be appended to create the link.
1241 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1242 the placeholder \"%h\" will cause a url-encoded version of the tag to
1243 be inserted at that point (see the function `url-hexify-string').
1245 REPLACE may also be a function that will be called with the tag as the
1246 only argument to create the link, which should be returned as a string.
1248 See the manual for examples."
1249 :group 'org-link
1250 :type '(repeat
1251 (cons
1252 (string :tag "Protocol")
1253 (choice
1254 (string :tag "Format")
1255 (function)))))
1257 (defcustom org-descriptive-links t
1258 "Non-nil means hide link part and only show description of bracket links.
1259 Bracket links are like [[link][description]]. This variable sets the initial
1260 state in new org-mode buffers. The setting can then be toggled on a
1261 per-buffer basis from the Org->Hyperlinks menu."
1262 :group 'org-link
1263 :type 'boolean)
1265 (defcustom org-link-file-path-type 'adaptive
1266 "How the path name in file links should be stored.
1267 Valid values are:
1269 relative Relative to the current directory, i.e. the directory of the file
1270 into which the link is being inserted.
1271 absolute Absolute path, if possible with ~ for home directory.
1272 noabbrev Absolute path, no abbreviation of home directory.
1273 adaptive Use relative path for files in the current directory and sub-
1274 directories of it. For other files, use an absolute path."
1275 :group 'org-link
1276 :type '(choice
1277 (const relative)
1278 (const absolute)
1279 (const noabbrev)
1280 (const adaptive)))
1282 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1283 "Types of links that should be activated in Org-mode files.
1284 This is a list of symbols, each leading to the activation of a certain link
1285 type. In principle, it does not hurt to turn on most link types - there may
1286 be a small gain when turning off unused link types. The types are:
1288 bracket The recommended [[link][description]] or [[link]] links with hiding.
1289 angle Links in angular brackets that may contain whitespace like
1290 <bbdb:Carsten Dominik>.
1291 plain Plain links in normal text, no whitespace, like http://google.com.
1292 radio Text that is matched by a radio target, see manual for details.
1293 tag Tag settings in a headline (link to tag search).
1294 date Time stamps (link to calendar).
1295 footnote Footnote labels.
1297 Changing this variable requires a restart of Emacs to become effective."
1298 :group 'org-link
1299 :type '(set :greedy t
1300 (const :tag "Double bracket links" bracket)
1301 (const :tag "Angular bracket links" angle)
1302 (const :tag "Plain text links" plain)
1303 (const :tag "Radio target matches" radio)
1304 (const :tag "Tags" tag)
1305 (const :tag "Timestamps" date)
1306 (const :tag "Footnotes" footnote)))
1308 (defcustom org-make-link-description-function nil
1309 "Function to use to generate link descriptions from links.
1310 If nil the link location will be used. This function must take
1311 two parameters; the first is the link and the second the
1312 description `org-insert-link' has generated, and should return the
1313 description to use."
1314 :group 'org-link
1315 :type 'function)
1317 (defgroup org-link-store nil
1318 "Options concerning storing links in Org-mode."
1319 :tag "Org Store Link"
1320 :group 'org-link)
1322 (defcustom org-email-link-description-format "Email %c: %.30s"
1323 "Format of the description part of a link to an email or usenet message.
1324 The following %-escapes will be replaced by corresponding information:
1326 %F full \"From\" field
1327 %f name, taken from \"From\" field, address if no name
1328 %T full \"To\" field
1329 %t first name in \"To\" field, address if no name
1330 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1331 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1332 %s subject
1333 %d date
1334 %m message-id.
1336 You may use normal field width specification between the % and the letter.
1337 This is for example useful to limit the length of the subject.
1339 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1340 :group 'org-link-store
1341 :type 'string)
1343 (defcustom org-from-is-user-regexp
1344 (let (r1 r2)
1345 (when (and user-mail-address (not (string= user-mail-address "")))
1346 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1347 (when (and user-full-name (not (string= user-full-name "")))
1348 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1349 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1350 "Regexp matched against the \"From:\" header of an email or usenet message.
1351 It should match if the message is from the user him/herself."
1352 :group 'org-link-store
1353 :type 'regexp)
1355 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1356 "Non-nil means storing a link to an Org file will use entry IDs.
1358 Note that before this variable is even considered, org-id must be loaded,
1359 so please customize `org-modules' and turn it on.
1361 The variable can have the following values:
1363 t Create an ID if needed to make a link to the current entry.
1365 create-if-interactive
1366 If `org-store-link' is called directly (interactively, as a user
1367 command), do create an ID to support the link. But when doing the
1368 job for remember, only use the ID if it already exists. The
1369 purpose of this setting is to avoid proliferation of unwanted
1370 IDs, just because you happen to be in an Org file when you
1371 call `org-remember' that automatically and preemptively
1372 creates a link. If you do want to get an ID link in a remember
1373 template to an entry not having an ID, create it first by
1374 explicitly creating a link to it, using `C-c C-l' first.
1376 create-if-interactive-and-no-custom-id
1377 Like create-if-interactive, but do not create an ID if there is
1378 a CUSTOM_ID property defined in the entry. This is the default.
1380 use-existing
1381 Use existing ID, do not create one.
1383 nil Never use an ID to make a link, instead link using a text search for
1384 the headline text."
1385 :group 'org-link-store
1386 :type '(choice
1387 (const :tag "Create ID to make link" t)
1388 (const :tag "Create if storing link interactively"
1389 create-if-interactive)
1390 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1391 create-if-interactive-and-no-custom-id)
1392 (const :tag "Only use existing" use-existing)
1393 (const :tag "Do not use ID to create link" nil)))
1395 (defcustom org-context-in-file-links t
1396 "Non-nil means file links from `org-store-link' contain context.
1397 A search string will be added to the file name with :: as separator and
1398 used to find the context when the link is activated by the command
1399 `org-open-at-point'. When this option is t, the entire active region
1400 will be placed in the search string of the file link. If set to a
1401 positive integer, only the first n lines of context will be stored.
1403 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1404 negates this setting for the duration of the command."
1405 :group 'org-link-store
1406 :type '(choice boolean integer))
1408 (defcustom org-keep-stored-link-after-insertion nil
1409 "Non-nil means keep link in list for entire session.
1411 The command `org-store-link' adds a link pointing to the current
1412 location to an internal list. These links accumulate during a session.
1413 The command `org-insert-link' can be used to insert links into any
1414 Org-mode file (offering completion for all stored links). When this
1415 option is nil, every link which has been inserted once using \\[org-insert-link]
1416 will be removed from the list, to make completing the unused links
1417 more efficient."
1418 :group 'org-link-store
1419 :type 'boolean)
1421 (defgroup org-link-follow nil
1422 "Options concerning following links in Org-mode."
1423 :tag "Org Follow Link"
1424 :group 'org-link)
1426 (defcustom org-link-translation-function nil
1427 "Function to translate links with different syntax to Org syntax.
1428 This can be used to translate links created for example by the Planner
1429 or emacs-wiki packages to Org syntax.
1430 The function must accept two parameters, a TYPE containing the link
1431 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1432 which is everything after the link protocol. It should return a cons
1433 with possibly modified values of type and path.
1434 Org contains a function for this, so if you set this variable to
1435 `org-translate-link-from-planner', you should be able follow many
1436 links created by planner."
1437 :group 'org-link-follow
1438 :type 'function)
1440 (defcustom org-follow-link-hook nil
1441 "Hook that is run after a link has been followed."
1442 :group 'org-link-follow
1443 :type 'hook)
1445 (defcustom org-tab-follows-link nil
1446 "Non-nil means on links TAB will follow the link.
1447 Needs to be set before org.el is loaded.
1448 This really should not be used, it does not make sense, and the
1449 implementation is bad."
1450 :group 'org-link-follow
1451 :type 'boolean)
1453 (defcustom org-return-follows-link nil
1454 "Non-nil means on links RET will follow the link."
1455 :group 'org-link-follow
1456 :type 'boolean)
1458 (defcustom org-mouse-1-follows-link
1459 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1460 "Non-nil means mouse-1 on a link will follow the link.
1461 A longer mouse click will still set point. Does not work on XEmacs.
1462 Needs to be set before org.el is loaded."
1463 :group 'org-link-follow
1464 :type 'boolean)
1466 (defcustom org-mark-ring-length 4
1467 "Number of different positions to be recorded in the ring.
1468 Changing this requires a restart of Emacs to work correctly."
1469 :group 'org-link-follow
1470 :type 'integer)
1472 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1473 "Non-nil means internal links in Org files must exactly match a headline.
1474 When nil, the link search tries to match a phrase with all words
1475 in the search text."
1476 :group 'org-link-follow
1477 :type '(choice
1478 (const :tag "Use fuzy text search" nil)
1479 (const :tag "Match only exact headline" t)
1480 (const :tag "Match extact headline or query to create it"
1481 query-to-create)))
1483 (defcustom org-link-frame-setup
1484 '((vm . vm-visit-folder-other-frame)
1485 (gnus . org-gnus-no-new-news)
1486 (file . find-file-other-window)
1487 (wl . wl-other-frame))
1488 "Setup the frame configuration for following links.
1489 When following a link with Emacs, it may often be useful to display
1490 this link in another window or frame. This variable can be used to
1491 set this up for the different types of links.
1492 For VM, use any of
1493 `vm-visit-folder'
1494 `vm-visit-folder-other-window'
1495 `vm-visit-folder-other-frame'
1496 For Gnus, use any of
1497 `gnus'
1498 `gnus-other-frame'
1499 `org-gnus-no-new-news'
1500 For FILE, use any of
1501 `find-file'
1502 `find-file-other-window'
1503 `find-file-other-frame'
1504 For Wanderlust use any of
1505 `wl'
1506 `wl-other-frame'
1507 For the calendar, use the variable `calendar-setup'.
1508 For BBDB, it is currently only possible to display the matches in
1509 another window."
1510 :group 'org-link-follow
1511 :type '(list
1512 (cons (const vm)
1513 (choice
1514 (const vm-visit-folder)
1515 (const vm-visit-folder-other-window)
1516 (const vm-visit-folder-other-frame)))
1517 (cons (const gnus)
1518 (choice
1519 (const gnus)
1520 (const gnus-other-frame)
1521 (const org-gnus-no-new-news)))
1522 (cons (const file)
1523 (choice
1524 (const find-file)
1525 (const find-file-other-window)
1526 (const find-file-other-frame)))
1527 (cons (const wl)
1528 (choice
1529 (const wl)
1530 (const wl-other-frame)))))
1532 (defcustom org-display-internal-link-with-indirect-buffer nil
1533 "Non-nil means use indirect buffer to display infile links.
1534 Activating internal links (from one location in a file to another location
1535 in the same file) normally just jumps to the location. When the link is
1536 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1537 is displayed in
1538 another window. When this option is set, the other window actually displays
1539 an indirect buffer clone of the current buffer, to avoid any visibility
1540 changes to the current buffer."
1541 :group 'org-link-follow
1542 :type 'boolean)
1544 (defcustom org-open-non-existing-files nil
1545 "Non-nil means `org-open-file' will open non-existing files.
1546 When nil, an error will be generated.
1547 This variable applies only to external applications because they
1548 might choke on non-existing files. If the link is to a file that
1549 will be opened in Emacs, the variable is ignored."
1550 :group 'org-link-follow
1551 :type 'boolean)
1553 (defcustom org-open-directory-means-index-dot-org nil
1554 "Non-nil means a link to a directory really means to index.org.
1555 When nil, following a directory link will run dired or open a finder/explorer
1556 window on that directory."
1557 :group 'org-link-follow
1558 :type 'boolean)
1560 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1561 "Function and arguments to call for following mailto links.
1562 This is a list with the first element being a Lisp function, and the
1563 remaining elements being arguments to the function. In string arguments,
1564 %a will be replaced by the address, and %s will be replaced by the subject
1565 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1566 :group 'org-link-follow
1567 :type '(choice
1568 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1569 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1570 (const :tag "message-mail" (message-mail "%a" "%s"))
1571 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1573 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1574 "Non-nil means ask for confirmation before executing shell links.
1575 Shell links can be dangerous: just think about a link
1577 [[shell:rm -rf ~/*][Google Search]]
1579 This link would show up in your Org-mode document as \"Google Search\",
1580 but really it would remove your entire home directory.
1581 Therefore we advise against setting this variable to nil.
1582 Just change it to `y-or-n-p' if you want to confirm with a
1583 single keystroke rather than having to type \"yes\"."
1584 :group 'org-link-follow
1585 :type '(choice
1586 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1587 (const :tag "with y-or-n (faster)" y-or-n-p)
1588 (const :tag "no confirmation (dangerous)" nil)))
1589 (put 'org-confirm-shell-link-function
1590 'safe-local-variable
1591 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1593 (defcustom org-confirm-shell-link-not-regexp ""
1594 "A regexp to skip confirmation for shell links."
1595 :group 'org-link-follow
1596 :type 'regexp)
1598 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1599 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1600 Elisp links can be dangerous: just think about a link
1602 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1604 This link would show up in your Org-mode document as \"Google Search\",
1605 but really it would remove your entire home directory.
1606 Therefore we advise against setting this variable to nil.
1607 Just change it to `y-or-n-p' if you want to confirm with a
1608 single keystroke rather than having to type \"yes\"."
1609 :group 'org-link-follow
1610 :type '(choice
1611 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1612 (const :tag "with y-or-n (faster)" y-or-n-p)
1613 (const :tag "no confirmation (dangerous)" nil)))
1614 (put 'org-confirm-shell-link-function
1615 'safe-local-variable
1616 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1618 (defcustom org-confirm-elisp-link-not-regexp ""
1619 "A regexp to skip confirmation for Elisp links."
1620 :group 'org-link-follow
1621 :type 'regexp)
1623 (defconst org-file-apps-defaults-gnu
1624 '((remote . emacs)
1625 (system . mailcap)
1626 (t . mailcap))
1627 "Default file applications on a UNIX or GNU/Linux system.
1628 See `org-file-apps'.")
1630 (defconst org-file-apps-defaults-macosx
1631 '((remote . emacs)
1632 (t . "open %s")
1633 (system . "open %s")
1634 ("ps.gz" . "gv %s")
1635 ("eps.gz" . "gv %s")
1636 ("dvi" . "xdvi %s")
1637 ("fig" . "xfig %s"))
1638 "Default file applications on a MacOS X system.
1639 The system \"open\" is known as a default, but we use X11 applications
1640 for some files for which the OS does not have a good default.
1641 See `org-file-apps'.")
1643 (defconst org-file-apps-defaults-windowsnt
1644 (list
1645 '(remote . emacs)
1646 (cons t
1647 (list (if (featurep 'xemacs)
1648 'mswindows-shell-execute
1649 'w32-shell-execute)
1650 "open" 'file))
1651 (cons 'system
1652 (list (if (featurep 'xemacs)
1653 'mswindows-shell-execute
1654 'w32-shell-execute)
1655 "open" 'file)))
1656 "Default file applications on a Windows NT system.
1657 The system \"open\" is used for most files.
1658 See `org-file-apps'.")
1660 (defcustom org-file-apps
1662 (auto-mode . emacs)
1663 ("\\.mm\\'" . default)
1664 ("\\.x?html?\\'" . default)
1665 ("\\.pdf\\'" . default)
1667 "External applications for opening `file:path' items in a document.
1668 Org-mode uses system defaults for different file types, but
1669 you can use this variable to set the application for a given file
1670 extension. The entries in this list are cons cells where the car identifies
1671 files and the cdr the corresponding command. Possible values for the
1672 file identifier are
1673 \"string\" A string as a file identifier can be interpreted in different
1674 ways, depending on its contents:
1676 - Alphanumeric characters only:
1677 Match links with this file extension.
1678 Example: (\"pdf\" . \"evince %s\")
1679 to open PDFs with evince.
1681 - Regular expression: Match links where the
1682 filename matches the regexp. If you want to
1683 use groups here, use shy groups.
1685 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1686 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1687 to open *.html and *.xhtml with firefox.
1689 - Regular expression which contains (non-shy) groups:
1690 Match links where the whole link, including \"::\", and
1691 anything after that, matches the regexp.
1692 In a custom command string, %1, %2, etc. are replaced with
1693 the parts of the link that were matched by the groups.
1694 For backwards compatibility, if a command string is given
1695 that does not use any of the group matches, this case is
1696 handled identically to the second one (i.e. match against
1697 file name only).
1698 In a custom lisp form, you can access the group matches with
1699 (match-string n link).
1701 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1702 to open [[file:document.pdf::5]] with evince at page 5.
1704 `directory' Matches a directory
1705 `remote' Matches a remote file, accessible through tramp or efs.
1706 Remote files most likely should be visited through Emacs
1707 because external applications cannot handle such paths.
1708 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1709 so all files Emacs knows how to handle. Using this with
1710 command `emacs' will open most files in Emacs. Beware that this
1711 will also open html files inside Emacs, unless you add
1712 (\"html\" . default) to the list as well.
1713 t Default for files not matched by any of the other options.
1714 `system' The system command to open files, like `open' on Windows
1715 and Mac OS X, and mailcap under GNU/Linux. This is the command
1716 that will be selected if you call `C-c C-o' with a double
1717 \\[universal-argument] \\[universal-argument] prefix.
1719 Possible values for the command are:
1720 `emacs' The file will be visited by the current Emacs process.
1721 `default' Use the default application for this file type, which is the
1722 association for t in the list, most likely in the system-specific
1723 part.
1724 This can be used to overrule an unwanted setting in the
1725 system-specific variable.
1726 `system' Use the system command for opening files, like \"open\".
1727 This command is specified by the entry whose car is `system'.
1728 Most likely, the system-specific version of this variable
1729 does define this command, but you can overrule/replace it
1730 here.
1731 string A command to be executed by a shell; %s will be replaced
1732 by the path to the file.
1733 sexp A Lisp form which will be evaluated. The file path will
1734 be available in the Lisp variable `file'.
1735 For more examples, see the system specific constants
1736 `org-file-apps-defaults-macosx'
1737 `org-file-apps-defaults-windowsnt'
1738 `org-file-apps-defaults-gnu'."
1739 :group 'org-link-follow
1740 :type '(repeat
1741 (cons (choice :value ""
1742 (string :tag "Extension")
1743 (const :tag "System command to open files" system)
1744 (const :tag "Default for unrecognized files" t)
1745 (const :tag "Remote file" remote)
1746 (const :tag "Links to a directory" directory)
1747 (const :tag "Any files that have Emacs modes"
1748 auto-mode))
1749 (choice :value ""
1750 (const :tag "Visit with Emacs" emacs)
1751 (const :tag "Use default" default)
1752 (const :tag "Use the system command" system)
1753 (string :tag "Command")
1754 (sexp :tag "Lisp form")))))
1758 (defgroup org-refile nil
1759 "Options concerning refiling entries in Org-mode."
1760 :tag "Org Refile"
1761 :group 'org)
1763 (defcustom org-directory "~/org"
1764 "Directory with org files.
1765 This is just a default location to look for Org files. There is no need
1766 at all to put your files into this directory. It is only used in the
1767 following situations:
1769 1. When a remember template specifies a target file that is not an
1770 absolute path. The path will then be interpreted relative to
1771 `org-directory'
1772 2. When a remember note is filed away in an interactive way (when exiting the
1773 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1774 with `org-directory' as the default path."
1775 :group 'org-refile
1776 :group 'org-remember
1777 :type 'directory)
1779 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1780 "Default target for storing notes.
1781 Used as a fall back file for org-remember.el and org-capture.el, for
1782 templates that do not specify a target file."
1783 :group 'org-refile
1784 :group 'org-remember
1785 :type '(choice
1786 (const :tag "Default from remember-data-file" nil)
1787 file))
1789 (defcustom org-goto-interface 'outline
1790 "The default interface to be used for `org-goto'.
1791 Allowed values are:
1792 outline The interface shows an outline of the relevant file
1793 and the correct heading is found by moving through
1794 the outline or by searching with incremental search.
1795 outline-path-completion Headlines in the current buffer are offered via
1796 completion. This is the interface also used by
1797 the refile command."
1798 :group 'org-refile
1799 :type '(choice
1800 (const :tag "Outline" outline)
1801 (const :tag "Outline-path-completion" outline-path-completion)))
1803 (defcustom org-goto-max-level 5
1804 "Maximum target level when running `org-goto' with refile interface."
1805 :group 'org-refile
1806 :type 'integer)
1808 (defcustom org-reverse-note-order nil
1809 "Non-nil means store new notes at the beginning of a file or entry.
1810 When nil, new notes will be filed to the end of a file or entry.
1811 This can also be a list with cons cells of regular expressions that
1812 are matched against file names, and values."
1813 :group 'org-remember
1814 :group 'org-refile
1815 :type '(choice
1816 (const :tag "Reverse always" t)
1817 (const :tag "Reverse never" nil)
1818 (repeat :tag "By file name regexp"
1819 (cons regexp boolean))))
1821 (defcustom org-log-refile nil
1822 "Information to record when a task is refiled.
1824 Possible values are:
1826 nil Don't add anything
1827 time Add a time stamp to the task
1828 note Prompt for a note and add it with template `org-log-note-headings'
1830 This option can also be set with on a per-file-basis with
1832 #+STARTUP: nologrefile
1833 #+STARTUP: logrefile
1834 #+STARTUP: lognoterefile
1836 You can have local logging settings for a subtree by setting the LOGGING
1837 property to one or more of these keywords.
1839 When bulk-refiling from the agenda, the value `note' is forbidden and
1840 will temporarily be changed to `time'."
1841 :group 'org-refile
1842 :group 'org-progress
1843 :type '(choice
1844 (const :tag "No logging" nil)
1845 (const :tag "Record timestamp" time)
1846 (const :tag "Record timestamp with note." note)))
1848 (defcustom org-refile-targets nil
1849 "Targets for refiling entries with \\[org-refile].
1850 This is list of cons cells. Each cell contains:
1851 - a specification of the files to be considered, either a list of files,
1852 or a symbol whose function or variable value will be used to retrieve
1853 a file name or a list of file names. If you use `org-agenda-files' for
1854 that, all agenda files will be scanned for targets. Nil means consider
1855 headings in the current buffer.
1856 - A specification of how to find candidate refile targets. This may be
1857 any of:
1858 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1859 This tag has to be present in all target headlines, inheritance will
1860 not be considered.
1861 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1862 todo keyword.
1863 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1864 headlines that are refiling targets.
1865 - a cons cell (:level . N). Any headline of level N is considered a target.
1866 Note that, when `org-odd-levels-only' is set, level corresponds to
1867 order in hierarchy, not to the number of stars.
1868 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1869 Note that, when `org-odd-levels-only' is set, level corresponds to
1870 order in hierarchy, not to the number of stars.
1872 You can set the variable `org-refile-target-verify-function' to a function
1873 to verify each headline found by the simple criteria above.
1875 When this variable is nil, all top-level headlines in the current buffer
1876 are used, equivalent to the value `((nil . (:level . 1))'."
1877 :group 'org-refile
1878 :type '(repeat
1879 (cons
1880 (choice :value org-agenda-files
1881 (const :tag "All agenda files" org-agenda-files)
1882 (const :tag "Current buffer" nil)
1883 (function) (variable) (file))
1884 (choice :tag "Identify target headline by"
1885 (cons :tag "Specific tag" (const :value :tag) (string))
1886 (cons :tag "TODO keyword" (const :value :todo) (string))
1887 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1888 (cons :tag "Level number" (const :value :level) (integer))
1889 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1891 (defcustom org-refile-target-verify-function nil
1892 "Function to verify if the headline at point should be a refile target.
1893 The function will be called without arguments, with point at the
1894 beginning of the headline. It should return t and leave point
1895 where it is if the headline is a valid target for refiling.
1897 If the target should not be selected, the function must return nil.
1898 In addition to this, it may move point to a place from where the search
1899 should be continued. For example, the function may decide that the entire
1900 subtree of the current entry should be excluded and move point to the end
1901 of the subtree."
1902 :group 'org-refile
1903 :type 'function)
1905 (defcustom org-refile-use-cache nil
1906 "Non-nil means cache refile targets to speed up the process.
1907 The cache for a particular file will be updated automatically when
1908 the buffer has been killed, or when any of the marker used for flagging
1909 refile targets no longer points at a live buffer.
1910 If you have added new entries to a buffer that might themselves be targets,
1911 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1912 find that easier, `C-u C-u C-u C-c C-w'."
1913 :group 'org-refile
1914 :type 'boolean)
1916 (defcustom org-refile-use-outline-path nil
1917 "Non-nil means provide refile targets as paths.
1918 So a level 3 headline will be available as level1/level2/level3.
1920 When the value is `file', also include the file name (without directory)
1921 into the path. In this case, you can also stop the completion after
1922 the file name, to get entries inserted as top level in the file.
1924 When `full-file-path', include the full file path."
1925 :group 'org-refile
1926 :type '(choice
1927 (const :tag "Not" nil)
1928 (const :tag "Yes" t)
1929 (const :tag "Start with file name" file)
1930 (const :tag "Start with full file path" full-file-path)))
1932 (defcustom org-outline-path-complete-in-steps t
1933 "Non-nil means complete the outline path in hierarchical steps.
1934 When Org-mode uses the refile interface to select an outline path
1935 \(see variable `org-refile-use-outline-path'), the completion of
1936 the path can be done is a single go, or if can be done in steps down
1937 the headline hierarchy. Going in steps is probably the best if you
1938 do not use a special completion package like `ido' or `icicles'.
1939 However, when using these packages, going in one step can be very
1940 fast, while still showing the whole path to the entry."
1941 :group 'org-refile
1942 :type 'boolean)
1944 (defcustom org-refile-allow-creating-parent-nodes nil
1945 "Non-nil means allow to create new nodes as refile targets.
1946 New nodes are then created by adding \"/new node name\" to the completion
1947 of an existing node. When the value of this variable is `confirm',
1948 new node creation must be confirmed by the user (recommended)
1949 When nil, the completion must match an existing entry.
1951 Note that, if the new heading is not seen by the criteria
1952 listed in `org-refile-targets', multiple instances of the same
1953 heading would be created by trying again to file under the new
1954 heading."
1955 :group 'org-refile
1956 :type '(choice
1957 (const :tag "Never" nil)
1958 (const :tag "Always" t)
1959 (const :tag "Prompt for confirmation" confirm)))
1961 (defgroup org-todo nil
1962 "Options concerning TODO items in Org-mode."
1963 :tag "Org TODO"
1964 :group 'org)
1966 (defgroup org-progress nil
1967 "Options concerning Progress logging in Org-mode."
1968 :tag "Org Progress"
1969 :group 'org-time)
1971 (defvar org-todo-interpretation-widgets
1973 (:tag "Sequence (cycling hits every state)" sequence)
1974 (:tag "Type (cycling directly to DONE)" type))
1975 "The available interpretation symbols for customizing `org-todo-keywords'.
1976 Interested libraries should add to this list.")
1978 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1979 "List of TODO entry keyword sequences and their interpretation.
1980 \\<org-mode-map>This is a list of sequences.
1982 Each sequence starts with a symbol, either `sequence' or `type',
1983 indicating if the keywords should be interpreted as a sequence of
1984 action steps, or as different types of TODO items. The first
1985 keywords are states requiring action - these states will select a headline
1986 for inclusion into the global TODO list Org-mode produces. If one of
1987 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
1988 signify that no further action is necessary. If \"|\" is not found,
1989 the last keyword is treated as the only DONE state of the sequence.
1991 The command \\[org-todo] cycles an entry through these states, and one
1992 additional state where no keyword is present. For details about this
1993 cycling, see the manual.
1995 TODO keywords and interpretation can also be set on a per-file basis with
1996 the special #+SEQ_TODO and #+TYP_TODO lines.
1998 Each keyword can optionally specify a character for fast state selection
1999 \(in combination with the variable `org-use-fast-todo-selection')
2000 and specifiers for state change logging, using the same syntax
2001 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
2002 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2003 indicates to record a time stamp each time this state is selected.
2005 Each keyword may also specify if a timestamp or a note should be
2006 recorded when entering or leaving the state, by adding additional
2007 characters in the parenthesis after the keyword. This looks like this:
2008 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2009 record only the time of the state change. With X and Y being either
2010 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2011 Y when leaving the state if and only if the *target* state does not
2012 define X. You may omit any of the fast-selection key or X or /Y,
2013 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2015 For backward compatibility, this variable may also be just a list
2016 of keywords - in this case the interpretation (sequence or type) will be
2017 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2018 :group 'org-todo
2019 :group 'org-keywords
2020 :type '(choice
2021 (repeat :tag "Old syntax, just keywords"
2022 (string :tag "Keyword"))
2023 (repeat :tag "New syntax"
2024 (cons
2025 (choice
2026 :tag "Interpretation"
2027 ;;Quick and dirty way to see
2028 ;;`org-todo-interpretations'. This takes the
2029 ;;place of item arguments
2030 :convert-widget
2031 (lambda (widget)
2032 (widget-put widget
2033 :args (mapcar
2034 #'(lambda (x)
2035 (widget-convert
2036 (cons 'const x)))
2037 org-todo-interpretation-widgets))
2038 widget))
2039 (repeat
2040 (string :tag "Keyword"))))))
2042 (defvar org-todo-keywords-1 nil
2043 "All TODO and DONE keywords active in a buffer.")
2044 (make-variable-buffer-local 'org-todo-keywords-1)
2045 (defvar org-todo-keywords-for-agenda nil)
2046 (defvar org-done-keywords-for-agenda nil)
2047 (defvar org-drawers-for-agenda nil)
2048 (defvar org-todo-keyword-alist-for-agenda nil)
2049 (defvar org-tag-alist-for-agenda nil)
2050 (defvar org-agenda-contributing-files nil)
2051 (defvar org-not-done-keywords nil)
2052 (make-variable-buffer-local 'org-not-done-keywords)
2053 (defvar org-done-keywords nil)
2054 (make-variable-buffer-local 'org-done-keywords)
2055 (defvar org-todo-heads nil)
2056 (make-variable-buffer-local 'org-todo-heads)
2057 (defvar org-todo-sets nil)
2058 (make-variable-buffer-local 'org-todo-sets)
2059 (defvar org-todo-log-states nil)
2060 (make-variable-buffer-local 'org-todo-log-states)
2061 (defvar org-todo-kwd-alist nil)
2062 (make-variable-buffer-local 'org-todo-kwd-alist)
2063 (defvar org-todo-key-alist nil)
2064 (make-variable-buffer-local 'org-todo-key-alist)
2065 (defvar org-todo-key-trigger nil)
2066 (make-variable-buffer-local 'org-todo-key-trigger)
2068 (defcustom org-todo-interpretation 'sequence
2069 "Controls how TODO keywords are interpreted.
2070 This variable is in principle obsolete and is only used for
2071 backward compatibility, if the interpretation of todo keywords is
2072 not given already in `org-todo-keywords'. See that variable for
2073 more information."
2074 :group 'org-todo
2075 :group 'org-keywords
2076 :type '(choice (const sequence)
2077 (const type)))
2079 (defcustom org-use-fast-todo-selection t
2080 "Non-nil means use the fast todo selection scheme with C-c C-t.
2081 This variable describes if and under what circumstances the cycling
2082 mechanism for TODO keywords will be replaced by a single-key, direct
2083 selection scheme.
2085 When nil, fast selection is never used.
2087 When the symbol `prefix', it will be used when `org-todo' is called with
2088 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
2089 in an agenda buffer.
2091 When t, fast selection is used by default. In this case, the prefix
2092 argument forces cycling instead.
2094 In all cases, the special interface is only used if access keys have actually
2095 been assigned by the user, i.e. if keywords in the configuration are followed
2096 by a letter in parenthesis, like TODO(t)."
2097 :group 'org-todo
2098 :type '(choice
2099 (const :tag "Never" nil)
2100 (const :tag "By default" t)
2101 (const :tag "Only with C-u C-c C-t" prefix)))
2103 (defcustom org-provide-todo-statistics t
2104 "Non-nil means update todo statistics after insert and toggle.
2105 ALL-HEADLINES means update todo statistics by including headlines
2106 with no TODO keyword as well, counting them as not done.
2107 A list of TODO keywords means the same, but skip keywords that are
2108 not in this list.
2110 When this is set, todo statistics is updated in the parent of the
2111 current entry each time a todo state is changed."
2112 :group 'org-todo
2113 :type '(choice
2114 (const :tag "Yes, only for TODO entries" t)
2115 (const :tag "Yes, including all entries" 'all-headlines)
2116 (repeat :tag "Yes, for TODOs in this list"
2117 (string :tag "TODO keyword"))
2118 (other :tag "No TODO statistics" nil)))
2120 (defcustom org-hierarchical-todo-statistics t
2121 "Non-nil means TODO statistics covers just direct children.
2122 When nil, all entries in the subtree are considered.
2123 This has only an effect if `org-provide-todo-statistics' is set.
2124 To set this to nil for only a single subtree, use a COOKIE_DATA
2125 property and include the word \"recursive\" into the value."
2126 :group 'org-todo
2127 :type 'boolean)
2129 (defcustom org-after-todo-state-change-hook nil
2130 "Hook which is run after the state of a TODO item was changed.
2131 The new state (a string with a TODO keyword, or nil) is available in the
2132 Lisp variable `state'."
2133 :group 'org-todo
2134 :type 'hook)
2136 (defvar org-blocker-hook nil
2137 "Hook for functions that are allowed to block a state change.
2139 Each function gets as its single argument a property list, see
2140 `org-trigger-hook' for more information about this list.
2142 If any of the functions in this hook returns nil, the state change
2143 is blocked.")
2145 (defvar org-trigger-hook nil
2146 "Hook for functions that are triggered by a state change.
2148 Each function gets as its single argument a property list with at least
2149 the following elements:
2151 (:type type-of-change :position pos-at-entry-start
2152 :from old-state :to new-state)
2154 Depending on the type, more properties may be present.
2156 This mechanism is currently implemented for:
2158 TODO state changes
2159 ------------------
2160 :type todo-state-change
2161 :from previous state (keyword as a string), or nil, or a symbol
2162 'todo' or 'done', to indicate the general type of state.
2163 :to new state, like in :from")
2165 (defcustom org-enforce-todo-dependencies nil
2166 "Non-nil means undone TODO entries will block switching the parent to DONE.
2167 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2168 be blocked if any prior sibling is not yet done.
2169 Finally, if the parent is blocked because of ordered siblings of its own,
2170 the child will also be blocked.
2171 This variable needs to be set before org.el is loaded, and you need to
2172 restart Emacs after a change to make the change effective. The only way
2173 to change is while Emacs is running is through the customize interface."
2174 :set (lambda (var val)
2175 (set var val)
2176 (if val
2177 (add-hook 'org-blocker-hook
2178 'org-block-todo-from-children-or-siblings-or-parent)
2179 (remove-hook 'org-blocker-hook
2180 'org-block-todo-from-children-or-siblings-or-parent)))
2181 :group 'org-todo
2182 :type 'boolean)
2184 (defcustom org-enforce-todo-checkbox-dependencies nil
2185 "Non-nil means unchecked boxes will block switching the parent to DONE.
2186 When this is nil, checkboxes have no influence on switching TODO states.
2187 When non-nil, you first need to check off all check boxes before the TODO
2188 entry can be switched to DONE.
2189 This variable needs to be set before org.el is loaded, and you need to
2190 restart Emacs after a change to make the change effective. The only way
2191 to change is while Emacs is running is through the customize interface."
2192 :set (lambda (var val)
2193 (set var val)
2194 (if val
2195 (add-hook 'org-blocker-hook
2196 'org-block-todo-from-checkboxes)
2197 (remove-hook 'org-blocker-hook
2198 'org-block-todo-from-checkboxes)))
2199 :group 'org-todo
2200 :type 'boolean)
2202 (defcustom org-treat-insert-todo-heading-as-state-change nil
2203 "Non-nil means inserting a TODO heading is treated as state change.
2204 So when the command \\[org-insert-todo-heading] is used, state change
2205 logging will apply if appropriate. When nil, the new TODO item will
2206 be inserted directly, and no logging will take place."
2207 :group 'org-todo
2208 :type 'boolean)
2210 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2211 "Non-nil means switching TODO states with S-cursor counts as state change.
2212 This is the default behavior. However, setting this to nil allows a
2213 convenient way to select a TODO state and bypass any logging associated
2214 with that."
2215 :group 'org-todo
2216 :type 'boolean)
2218 (defcustom org-todo-state-tags-triggers nil
2219 "Tag changes that should be triggered by TODO state changes.
2220 This is a list. Each entry is
2222 (state-change (tag . flag) .......)
2224 State-change can be a string with a state, and empty string to indicate the
2225 state that has no TODO keyword, or it can be one of the symbols `todo'
2226 or `done', meaning any not-done or done state, respectively."
2227 :group 'org-todo
2228 :group 'org-tags
2229 :type '(repeat
2230 (cons (choice :tag "When changing to"
2231 (const :tag "Not-done state" todo)
2232 (const :tag "Done state" done)
2233 (string :tag "State"))
2234 (repeat
2235 (cons :tag "Tag action"
2236 (string :tag "Tag")
2237 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2239 (defcustom org-log-done nil
2240 "Information to record when a task moves to the DONE state.
2242 Possible values are:
2244 nil Don't add anything, just change the keyword
2245 time Add a time stamp to the task
2246 note Prompt for a note and add it with template `org-log-note-headings'
2248 This option can also be set with on a per-file-basis with
2250 #+STARTUP: nologdone
2251 #+STARTUP: logdone
2252 #+STARTUP: lognotedone
2254 You can have local logging settings for a subtree by setting the LOGGING
2255 property to one or more of these keywords."
2256 :group 'org-todo
2257 :group 'org-progress
2258 :type '(choice
2259 (const :tag "No logging" nil)
2260 (const :tag "Record CLOSED timestamp" time)
2261 (const :tag "Record CLOSED timestamp with note." note)))
2263 ;; Normalize old uses of org-log-done.
2264 (cond
2265 ((eq org-log-done t) (setq org-log-done 'time))
2266 ((and (listp org-log-done) (memq 'done org-log-done))
2267 (setq org-log-done 'note)))
2269 (defcustom org-log-reschedule nil
2270 "Information to record when the scheduling date of a tasks is modified.
2272 Possible values are:
2274 nil Don't add anything, just change the date
2275 time Add a time stamp to the task
2276 note Prompt for a note and add it with template `org-log-note-headings'
2278 This option can also be set with on a per-file-basis with
2280 #+STARTUP: nologreschedule
2281 #+STARTUP: logreschedule
2282 #+STARTUP: lognotereschedule"
2283 :group 'org-todo
2284 :group 'org-progress
2285 :type '(choice
2286 (const :tag "No logging" nil)
2287 (const :tag "Record timestamp" time)
2288 (const :tag "Record timestamp with note." note)))
2290 (defcustom org-log-redeadline nil
2291 "Information to record when the deadline date of a tasks is modified.
2293 Possible values are:
2295 nil Don't add anything, just change the date
2296 time Add a time stamp to the task
2297 note Prompt for a note and add it with template `org-log-note-headings'
2299 This option can also be set with on a per-file-basis with
2301 #+STARTUP: nologredeadline
2302 #+STARTUP: logredeadline
2303 #+STARTUP: lognoteredeadline
2305 You can have local logging settings for a subtree by setting the LOGGING
2306 property to one or more of these keywords."
2307 :group 'org-todo
2308 :group 'org-progress
2309 :type '(choice
2310 (const :tag "No logging" nil)
2311 (const :tag "Record timestamp" time)
2312 (const :tag "Record timestamp with note." note)))
2314 (defcustom org-log-note-clock-out nil
2315 "Non-nil means record a note when clocking out of an item.
2316 This can also be configured on a per-file basis by adding one of
2317 the following lines anywhere in the buffer:
2319 #+STARTUP: lognoteclock-out
2320 #+STARTUP: nolognoteclock-out"
2321 :group 'org-todo
2322 :group 'org-progress
2323 :type 'boolean)
2325 (defcustom org-log-done-with-time t
2326 "Non-nil means the CLOSED time stamp will contain date and time.
2327 When nil, only the date will be recorded."
2328 :group 'org-progress
2329 :type 'boolean)
2331 (defcustom org-log-note-headings
2332 '((done . "CLOSING NOTE %t")
2333 (state . "State %-12s from %-12S %t")
2334 (note . "Note taken on %t")
2335 (reschedule . "Rescheduled from %S on %t")
2336 (delschedule . "Not scheduled, was %S on %t")
2337 (redeadline . "New deadline from %S on %t")
2338 (deldeadline . "Removed deadline, was %S on %t")
2339 (refile . "Refiled on %t")
2340 (clock-out . ""))
2341 "Headings for notes added to entries.
2342 The value is an alist, with the car being a symbol indicating the note
2343 context, and the cdr is the heading to be used. The heading may also be the
2344 empty string.
2345 %t in the heading will be replaced by a time stamp.
2346 %T will be an active time stamp instead the default inactive one
2347 %s will be replaced by the new TODO state, in double quotes.
2348 %S will be replaced by the old TODO state, in double quotes.
2349 %u will be replaced by the user name.
2350 %U will be replaced by the full user name.
2352 In fact, it is not a good idea to change the `state' entry, because
2353 agenda log mode depends on the format of these entries."
2354 :group 'org-todo
2355 :group 'org-progress
2356 :type '(list :greedy t
2357 (cons (const :tag "Heading when closing an item" done) string)
2358 (cons (const :tag
2359 "Heading when changing todo state (todo sequence only)"
2360 state) string)
2361 (cons (const :tag "Heading when just taking a note" note) string)
2362 (cons (const :tag "Heading when clocking out" clock-out) string)
2363 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2364 (cons (const :tag "Heading when rescheduling" reschedule) string)
2365 (cons (const :tag "Heading when changing deadline" redeadline) string)
2366 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2367 (cons (const :tag "Heading when refiling" refile) string)))
2369 (unless (assq 'note org-log-note-headings)
2370 (push '(note . "%t") org-log-note-headings))
2372 (defcustom org-log-into-drawer nil
2373 "Non-nil means insert state change notes and time stamps into a drawer.
2374 When nil, state changes notes will be inserted after the headline and
2375 any scheduling and clock lines, but not inside a drawer.
2377 The value of this variable should be the name of the drawer to use.
2378 LOGBOOK is proposed as the default drawer for this purpose, you can
2379 also set this to a string to define the drawer of your choice.
2381 A value of t is also allowed, representing \"LOGBOOK\".
2383 If this variable is set, `org-log-state-notes-insert-after-drawers'
2384 will be ignored.
2386 You can set the property LOG_INTO_DRAWER to overrule this setting for
2387 a subtree."
2388 :group 'org-todo
2389 :group 'org-progress
2390 :type '(choice
2391 (const :tag "Not into a drawer" nil)
2392 (const :tag "LOGBOOK" t)
2393 (string :tag "Other")))
2395 (if (fboundp 'defvaralias)
2396 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2398 (defun org-log-into-drawer ()
2399 "Return the value of `org-log-into-drawer', but let properties overrule.
2400 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2401 used instead of the default value."
2402 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2403 (cond
2404 ((or (not p) (equal p "nil")) org-log-into-drawer)
2405 ((equal p "t") "LOGBOOK")
2406 (t p))))
2408 (defcustom org-log-state-notes-insert-after-drawers nil
2409 "Non-nil means insert state change notes after any drawers in entry.
2410 Only the drawers that *immediately* follow the headline and the
2411 deadline/scheduled line are skipped.
2412 When nil, insert notes right after the heading and perhaps the line
2413 with deadline/scheduling if present.
2415 This variable will have no effect if `org-log-into-drawer' is
2416 set."
2417 :group 'org-todo
2418 :group 'org-progress
2419 :type 'boolean)
2421 (defcustom org-log-states-order-reversed t
2422 "Non-nil means the latest state note will be directly after heading.
2423 When nil, the state change notes will be ordered according to time."
2424 :group 'org-todo
2425 :group 'org-progress
2426 :type 'boolean)
2428 (defcustom org-todo-repeat-to-state nil
2429 "The TODO state to which a repeater should return the repeating task.
2430 By default this is the first task in a TODO sequence, or the previous state
2431 in a TODO_TYP set. But you can specify another task here.
2432 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2433 :group 'org-todo
2434 :type '(choice (const :tag "Head of sequence" nil)
2435 (string :tag "Specific state")))
2437 (defcustom org-log-repeat 'time
2438 "Non-nil means record moving through the DONE state when triggering repeat.
2439 An auto-repeating task is immediately switched back to TODO when
2440 marked DONE. If you are not logging state changes (by adding \"@\"
2441 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2442 record a closing note, there will be no record of the task moving
2443 through DONE. This variable forces taking a note anyway.
2445 nil Don't force a record
2446 time Record a time stamp
2447 note Record a note
2449 This option can also be set with on a per-file-basis with
2451 #+STARTUP: logrepeat
2452 #+STARTUP: lognoterepeat
2453 #+STARTUP: nologrepeat
2455 You can have local logging settings for a subtree by setting the LOGGING
2456 property to one or more of these keywords."
2457 :group 'org-todo
2458 :group 'org-progress
2459 :type '(choice
2460 (const :tag "Don't force a record" nil)
2461 (const :tag "Force recording the DONE state" time)
2462 (const :tag "Force recording a note with the DONE state" note)))
2465 (defgroup org-priorities nil
2466 "Priorities in Org-mode."
2467 :tag "Org Priorities"
2468 :group 'org-todo)
2470 (defcustom org-enable-priority-commands t
2471 "Non-nil means priority commands are active.
2472 When nil, these commands will be disabled, so that you never accidentally
2473 set a priority."
2474 :group 'org-priorities
2475 :type 'boolean)
2477 (defcustom org-highest-priority ?A
2478 "The highest priority of TODO items. A character like ?A, ?B etc.
2479 Must have a smaller ASCII number than `org-lowest-priority'."
2480 :group 'org-priorities
2481 :type 'character)
2483 (defcustom org-lowest-priority ?C
2484 "The lowest priority of TODO items. A character like ?A, ?B etc.
2485 Must have a larger ASCII number than `org-highest-priority'."
2486 :group 'org-priorities
2487 :type 'character)
2489 (defcustom org-default-priority ?B
2490 "The default priority of TODO items.
2491 This is the priority an item gets if no explicit priority is given.
2492 When starting to cycle on an empty priority the first step in the cycle
2493 depends on `org-priority-start-cycle-with-default'. The resulting first
2494 step priority must not exceed the range from `org-highest-priority' to
2495 `org-lowest-priority' which means that `org-default-priority' has to be
2496 in this range exclusive or inclusive the range boundaries. Else the
2497 first step refuses to set the default and the second will fall back
2498 to (depending on the command used) the highest or lowest priority."
2499 :group 'org-priorities
2500 :type 'character)
2502 (defcustom org-priority-start-cycle-with-default t
2503 "Non-nil means start with default priority when starting to cycle.
2504 When this is nil, the first step in the cycle will be (depending on the
2505 command used) one higher or lower than the default priority.
2506 See also `org-default-priority'."
2507 :group 'org-priorities
2508 :type 'boolean)
2510 (defcustom org-get-priority-function nil
2511 "Function to extract the priority from a string.
2512 The string is normally the headline. If this is nil Org computes the
2513 priority from the priority cookie like [#A] in the headline. It returns
2514 an integer, increasing by 1000 for each priority level.
2515 The user can set a different function here, which should take a string
2516 as an argument and return the numeric priority."
2517 :group 'org-priorities
2518 :type 'function)
2520 (defgroup org-time nil
2521 "Options concerning time stamps and deadlines in Org-mode."
2522 :tag "Org Time"
2523 :group 'org)
2525 (defcustom org-insert-labeled-timestamps-at-point nil
2526 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2527 When nil, these labeled time stamps are forces into the second line of an
2528 entry, just after the headline. When scheduling from the global TODO list,
2529 the time stamp will always be forced into the second line."
2530 :group 'org-time
2531 :type 'boolean)
2533 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2534 "Formats for `format-time-string' which are used for time stamps.
2535 It is not recommended to change this constant.")
2537 (defcustom org-time-stamp-rounding-minutes '(0 5)
2538 "Number of minutes to round time stamps to.
2539 These are two values, the first applies when first creating a time stamp.
2540 The second applies when changing it with the commands `S-up' and `S-down'.
2541 When changing the time stamp, this means that it will change in steps
2542 of N minutes, as given by the second value.
2544 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2545 numbers should be factors of 60, so for example 5, 10, 15.
2547 When this is larger than 1, you can still force an exact time stamp by using
2548 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2549 and by using a prefix arg to `S-up/down' to specify the exact number
2550 of minutes to shift."
2551 :group 'org-time
2552 :get #'(lambda (var) ; Make sure both elements are there
2553 (if (integerp (default-value var))
2554 (list (default-value var) 5)
2555 (default-value var)))
2556 :type '(list
2557 (integer :tag "when inserting times")
2558 (integer :tag "when modifying times")))
2560 ;; Normalize old customizations of this variable.
2561 (when (integerp org-time-stamp-rounding-minutes)
2562 (setq org-time-stamp-rounding-minutes
2563 (list org-time-stamp-rounding-minutes
2564 org-time-stamp-rounding-minutes)))
2566 (defcustom org-display-custom-times nil
2567 "Non-nil means overlay custom formats over all time stamps.
2568 The formats are defined through the variable `org-time-stamp-custom-formats'.
2569 To turn this on on a per-file basis, insert anywhere in the file:
2570 #+STARTUP: customtime"
2571 :group 'org-time
2572 :set 'set-default
2573 :type 'sexp)
2574 (make-variable-buffer-local 'org-display-custom-times)
2576 (defcustom org-time-stamp-custom-formats
2577 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2578 "Custom formats for time stamps. See `format-time-string' for the syntax.
2579 These are overlayed over the default ISO format if the variable
2580 `org-display-custom-times' is set. Time like %H:%M should be at the
2581 end of the second format. The custom formats are also honored by export
2582 commands, if custom time display is turned on at the time of export."
2583 :group 'org-time
2584 :type 'sexp)
2586 (defun org-time-stamp-format (&optional long inactive)
2587 "Get the right format for a time string."
2588 (let ((f (if long (cdr org-time-stamp-formats)
2589 (car org-time-stamp-formats))))
2590 (if inactive
2591 (concat "[" (substring f 1 -1) "]")
2592 f)))
2594 (defcustom org-time-clocksum-format "%d:%02d"
2595 "The format string used when creating CLOCKSUM lines.
2596 This is also used when org-mode generates a time duration."
2597 :group 'org-time
2598 :type 'string)
2600 (defcustom org-time-clocksum-use-fractional nil
2601 "If non-nil, \\[org-clock-display] uses fractional times.
2602 org-mode generates a time duration."
2603 :group 'org-time
2604 :type 'boolean)
2606 (defcustom org-time-clocksum-fractional-format "%.2f"
2607 "The format string used when creating CLOCKSUM lines, or when
2608 org-mode generates a time duration."
2609 :group 'org-time
2610 :type 'string)
2612 (defcustom org-deadline-warning-days 14
2613 "No. of days before expiration during which a deadline becomes active.
2614 This variable governs the display in sparse trees and in the agenda.
2615 When 0 or negative, it means use this number (the absolute value of it)
2616 even if a deadline has a different individual lead time specified.
2618 Custom commands can set this variable in the options section."
2619 :group 'org-time
2620 :group 'org-agenda-daily/weekly
2621 :type 'integer)
2623 (defcustom org-read-date-prefer-future t
2624 "Non-nil means assume future for incomplete date input from user.
2625 This affects the following situations:
2626 1. The user gives a month but not a year.
2627 For example, if it is April and you enter \"feb 2\", this will be read
2628 as Feb 2, *next* year. \"May 5\", however, will be this year.
2629 2. The user gives a day, but no month.
2630 For example, if today is the 15th, and you enter \"3\", Org-mode will
2631 read this as the third of *next* month. However, if you enter \"17\",
2632 it will be considered as *this* month.
2634 If you set this variable to the symbol `time', then also the following
2635 will work:
2637 3. If the user gives a time, but no day. If the time is before now,
2638 to will be interpreted as tomorrow.
2640 Currently none of this works for ISO week specifications.
2642 When this option is nil, the current day, month and year will always be
2643 used as defaults.
2645 See also `org-agenda-jump-prefer-future'."
2646 :group 'org-time
2647 :type '(choice
2648 (const :tag "Never" nil)
2649 (const :tag "Check month and day" t)
2650 (const :tag "Check month, day, and time" time)))
2652 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2653 "Should the agenda jump command prefer the future for incomplete dates?
2654 The default is to do the same as configured in `org-read-date-prefer-future'.
2655 But you can also set a deviating value here.
2656 This may t or nil, or the symbol `org-read-date-prefer-future'."
2657 :group 'org-agenda
2658 :group 'org-time
2659 :type '(choice
2660 (const :tag "Use org-read-date-prefer-future"
2661 org-read-date-prefer-future)
2662 (const :tag "Never" nil)
2663 (const :tag "Always" t)))
2665 (defcustom org-read-date-force-compatible-dates t
2666 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2668 Depending on the system Emacs is running on, certain dates cannot
2669 be represented with the type used internally to represent time.
2670 Dates between 1970-1-1 and 2038-1-1 can always be represented
2671 correctly. Some systems allow for earlier dates, some for later,
2672 some for both. One way to find out it to insert any date into an
2673 Org buffer, putting the cursor on the year and hitting S-up and
2674 S-down to test the range.
2676 When this variable is set to t, the date/time prompt will not let
2677 you specify dates outside the 1970-2037 range, so it is certain that
2678 these dates will work in whatever version of Emacs you are
2679 running, and also that you can move a file from one Emacs implementation
2680 to another. WHenever Org is forcing the year for you, it will display
2681 a message and beep.
2683 When this variable is nil, Org will check if the date is
2684 representable in the specific Emacs implementation you are using.
2685 If not, it will force a year, usually the current year, and beep
2686 to remind you. Currently this setting is not recommended because
2687 the likelihood that you will open your Org files in an Emacs that
2688 has limited date range is not negligible.
2690 A workaround for this problem is to use diary sexp dates for time
2691 stamps outside of this range."
2692 :group 'org-time
2693 :type 'boolean)
2695 (defcustom org-read-date-display-live t
2696 "Non-nil means display current interpretation of date prompt live.
2697 This display will be in an overlay, in the minibuffer."
2698 :group 'org-time
2699 :type 'boolean)
2701 (defcustom org-read-date-popup-calendar t
2702 "Non-nil means pop up a calendar when prompting for a date.
2703 In the calendar, the date can be selected with mouse-1. However, the
2704 minibuffer will also be active, and you can simply enter the date as well.
2705 When nil, only the minibuffer will be available."
2706 :group 'org-time
2707 :type 'boolean)
2708 (if (fboundp 'defvaralias)
2709 (defvaralias 'org-popup-calendar-for-date-prompt
2710 'org-read-date-popup-calendar))
2712 (defcustom org-read-date-minibuffer-setup-hook nil
2713 "Hook to be used to set up keys for the date/time interface.
2714 Add key definitions to `minibuffer-local-map', which will be a temporary
2715 copy."
2716 :group 'org-time
2717 :type 'hook)
2719 (defcustom org-extend-today-until 0
2720 "The hour when your day really ends. Must be an integer.
2721 This has influence for the following applications:
2722 - When switching the agenda to \"today\". It it is still earlier than
2723 the time given here, the day recognized as TODAY is actually yesterday.
2724 - When a date is read from the user and it is still before the time given
2725 here, the current date and time will be assumed to be yesterday, 23:59.
2726 Also, timestamps inserted in remember templates follow this rule.
2728 IMPORTANT: This is a feature whose implementation is and likely will
2729 remain incomplete. Really, it is only here because past midnight seems to
2730 be the favorite working time of John Wiegley :-)"
2731 :group 'org-time
2732 :type 'integer)
2734 (defcustom org-edit-timestamp-down-means-later nil
2735 "Non-nil means S-down will increase the time in a time stamp.
2736 When nil, S-up will increase."
2737 :group 'org-time
2738 :type 'boolean)
2740 (defcustom org-calendar-follow-timestamp-change t
2741 "Non-nil means make the calendar window follow timestamp changes.
2742 When a timestamp is modified and the calendar window is visible, it will be
2743 moved to the new date."
2744 :group 'org-time
2745 :type 'boolean)
2747 (defgroup org-tags nil
2748 "Options concerning tags in Org-mode."
2749 :tag "Org Tags"
2750 :group 'org)
2752 (defcustom org-tag-alist nil
2753 "List of tags allowed in Org-mode files.
2754 When this list is nil, Org-mode will base TAG input on what is already in the
2755 buffer.
2756 The value of this variable is an alist, the car of each entry must be a
2757 keyword as a string, the cdr may be a character that is used to select
2758 that tag through the fast-tag-selection interface.
2759 See the manual for details."
2760 :group 'org-tags
2761 :type '(repeat
2762 (choice
2763 (cons (string :tag "Tag name")
2764 (character :tag "Access char"))
2765 (list :tag "Start radio group"
2766 (const :startgroup)
2767 (option (string :tag "Group description")))
2768 (list :tag "End radio group"
2769 (const :endgroup)
2770 (option (string :tag "Group description")))
2771 (const :tag "New line" (:newline)))))
2773 (defcustom org-tag-persistent-alist nil
2774 "List of tags that will always appear in all Org-mode files.
2775 This is in addition to any in buffer settings or customizations
2776 of `org-tag-alist'.
2777 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2778 The value of this variable is an alist, the car of each entry must be a
2779 keyword as a string, the cdr may be a character that is used to select
2780 that tag through the fast-tag-selection interface.
2781 See the manual for details.
2782 To disable these tags on a per-file basis, insert anywhere in the file:
2783 #+STARTUP: noptag"
2784 :group 'org-tags
2785 :type '(repeat
2786 (choice
2787 (cons (string :tag "Tag name")
2788 (character :tag "Access char"))
2789 (const :tag "Start radio group" (:startgroup))
2790 (const :tag "End radio group" (:endgroup))
2791 (const :tag "New line" (:newline)))))
2793 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2794 "If non-nil, always offer completion for all tags of all agenda files.
2795 Instead of customizing this variable directly, you might want to
2796 set it locally for capture buffers, because there no list of
2797 tags in that file can be created dynamically (there are none).
2799 (add-hook 'org-capture-mode-hook
2800 (lambda ()
2801 (set (make-local-variable
2802 'org-complete-tags-always-offer-all-agenda-tags)
2803 t)))"
2804 :group 'org-tags
2805 :type 'boolean)
2807 (defvar org-file-tags nil
2808 "List of tags that can be inherited by all entries in the file.
2809 The tags will be inherited if the variable `org-use-tag-inheritance'
2810 says they should be.
2811 This variable is populated from #+FILETAGS lines.")
2813 (defcustom org-use-fast-tag-selection 'auto
2814 "Non-nil means use fast tag selection scheme.
2815 This is a special interface to select and deselect tags with single keys.
2816 When nil, fast selection is never used.
2817 When the symbol `auto', fast selection is used if and only if selection
2818 characters for tags have been configured, either through the variable
2819 `org-tag-alist' or through a #+TAGS line in the buffer.
2820 When t, fast selection is always used and selection keys are assigned
2821 automatically if necessary."
2822 :group 'org-tags
2823 :type '(choice
2824 (const :tag "Always" t)
2825 (const :tag "Never" nil)
2826 (const :tag "When selection characters are configured" 'auto)))
2828 (defcustom org-fast-tag-selection-single-key nil
2829 "Non-nil means fast tag selection exits after first change.
2830 When nil, you have to press RET to exit it.
2831 During fast tag selection, you can toggle this flag with `C-c'.
2832 This variable can also have the value `expert'. In this case, the window
2833 displaying the tags menu is not even shown, until you press C-c again."
2834 :group 'org-tags
2835 :type '(choice
2836 (const :tag "No" nil)
2837 (const :tag "Yes" t)
2838 (const :tag "Expert" expert)))
2840 (defvar org-fast-tag-selection-include-todo nil
2841 "Non-nil means fast tags selection interface will also offer TODO states.
2842 This is an undocumented feature, you should not rely on it.")
2844 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2845 "The column to which tags should be indented in a headline.
2846 If this number is positive, it specifies the column. If it is negative,
2847 it means that the tags should be flushright to that column. For example,
2848 -80 works well for a normal 80 character screen."
2849 :group 'org-tags
2850 :type 'integer)
2852 (defcustom org-auto-align-tags t
2853 "Non-nil keeps tags aligned when modifying headlines.
2854 Some operations (i.e. demoting) change the length of a headline and
2855 therefore shift the tags around. With this option turned on, after
2856 each such operation the tags are again aligned to `org-tags-column'."
2857 :group 'org-tags
2858 :type 'boolean)
2860 (defcustom org-use-tag-inheritance t
2861 "Non-nil means tags in levels apply also for sublevels.
2862 When nil, only the tags directly given in a specific line apply there.
2863 This may also be a list of tags that should be inherited, or a regexp that
2864 matches tags that should be inherited. Additional control is possible
2865 with the variable `org-tags-exclude-from-inheritance' which gives an
2866 explicit list of tags to be excluded from inheritance., even if the value of
2867 `org-use-tag-inheritance' would select it for inheritance.
2869 If this option is t, a match early-on in a tree can lead to a large
2870 number of matches in the subtree when constructing the agenda or creating
2871 a sparse tree. If you only want to see the first match in a tree during
2872 a search, check out the variable `org-tags-match-list-sublevels'."
2873 :group 'org-tags
2874 :type '(choice
2875 (const :tag "Not" nil)
2876 (const :tag "Always" t)
2877 (repeat :tag "Specific tags" (string :tag "Tag"))
2878 (regexp :tag "Tags matched by regexp")))
2880 (defcustom org-tags-exclude-from-inheritance nil
2881 "List of tags that should never be inherited.
2882 This is a way to exclude a few tags from inheritance. For way to do
2883 the opposite, to actively allow inheritance for selected tags,
2884 see the variable `org-use-tag-inheritance'."
2885 :group 'org-tags
2886 :type '(repeat (string :tag "Tag")))
2888 (defun org-tag-inherit-p (tag)
2889 "Check if TAG is one that should be inherited."
2890 (cond
2891 ((member tag org-tags-exclude-from-inheritance) nil)
2892 ((eq org-use-tag-inheritance t) t)
2893 ((not org-use-tag-inheritance) nil)
2894 ((stringp org-use-tag-inheritance)
2895 (string-match org-use-tag-inheritance tag))
2896 ((listp org-use-tag-inheritance)
2897 (member tag org-use-tag-inheritance))
2898 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2900 (defcustom org-tags-match-list-sublevels t
2901 "Non-nil means list also sublevels of headlines matching a search.
2902 This variable applies to tags/property searches, and also to stuck
2903 projects because this search is based on a tags match as well.
2905 When set to the symbol `indented', sublevels are indented with
2906 leading dots.
2908 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2909 the sublevels of a headline matching a tag search often also match
2910 the same search. Listing all of them can create very long lists.
2911 Setting this variable to nil causes subtrees of a match to be skipped.
2913 This variable is semi-obsolete and probably should always be true. It
2914 is better to limit inheritance to certain tags using the variables
2915 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2916 :group 'org-tags
2917 :type '(choice
2918 (const :tag "No, don't list them" nil)
2919 (const :tag "Yes, do list them" t)
2920 (const :tag "List them, indented with leading dots" indented)))
2922 (defcustom org-tags-sort-function nil
2923 "When set, tags are sorted using this function as a comparator."
2924 :group 'org-tags
2925 :type '(choice
2926 (const :tag "No sorting" nil)
2927 (const :tag "Alphabetical" string<)
2928 (const :tag "Reverse alphabetical" string>)
2929 (function :tag "Custom function" nil)))
2931 (defvar org-tags-history nil
2932 "History of minibuffer reads for tags.")
2933 (defvar org-last-tags-completion-table nil
2934 "The last used completion table for tags.")
2935 (defvar org-after-tags-change-hook nil
2936 "Hook that is run after the tags in a line have changed.")
2938 (defgroup org-properties nil
2939 "Options concerning properties in Org-mode."
2940 :tag "Org Properties"
2941 :group 'org)
2943 (defcustom org-property-format "%-10s %s"
2944 "How property key/value pairs should be formatted by `indent-line'.
2945 When `indent-line' hits a property definition, it will format the line
2946 according to this format, mainly to make sure that the values are
2947 lined-up with respect to each other."
2948 :group 'org-properties
2949 :type 'string)
2951 (defcustom org-use-property-inheritance nil
2952 "Non-nil means properties apply also for sublevels.
2954 This setting is chiefly used during property searches. Turning it on can
2955 cause significant overhead when doing a search, which is why it is not
2956 on by default.
2958 When nil, only the properties directly given in the current entry count.
2959 When t, every property is inherited. The value may also be a list of
2960 properties that should have inheritance, or a regular expression matching
2961 properties that should be inherited.
2963 However, note that some special properties use inheritance under special
2964 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2965 and the properties ending in \"_ALL\" when they are used as descriptor
2966 for valid values of a property.
2968 Note for programmers:
2969 When querying an entry with `org-entry-get', you can control if inheritance
2970 should be used. By default, `org-entry-get' looks only at the local
2971 properties. You can request inheritance by setting the inherit argument
2972 to t (to force inheritance) or to `selective' (to respect the setting
2973 in this variable)."
2974 :group 'org-properties
2975 :type '(choice
2976 (const :tag "Not" nil)
2977 (const :tag "Always" t)
2978 (repeat :tag "Specific properties" (string :tag "Property"))
2979 (regexp :tag "Properties matched by regexp")))
2981 (defun org-property-inherit-p (property)
2982 "Check if PROPERTY is one that should be inherited."
2983 (cond
2984 ((eq org-use-property-inheritance t) t)
2985 ((not org-use-property-inheritance) nil)
2986 ((stringp org-use-property-inheritance)
2987 (string-match org-use-property-inheritance property))
2988 ((listp org-use-property-inheritance)
2989 (member property org-use-property-inheritance))
2990 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2992 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2993 "The default column format, if no other format has been defined.
2994 This variable can be set on the per-file basis by inserting a line
2996 #+COLUMNS: %25ITEM ....."
2997 :group 'org-properties
2998 :type 'string)
3000 (defcustom org-columns-ellipses ".."
3001 "The ellipses to be used when a field in column view is truncated.
3002 When this is the empty string, as many characters as possible are shown,
3003 but then there will be no visual indication that the field has been truncated.
3004 When this is a string of length N, the last N characters of a truncated
3005 field are replaced by this string. If the column is narrower than the
3006 ellipses string, only part of the ellipses string will be shown."
3007 :group 'org-properties
3008 :type 'string)
3010 (defcustom org-columns-modify-value-for-display-function nil
3011 "Function that modifies values for display in column view.
3012 For example, it can be used to cut out a certain part from a time stamp.
3013 The function must take 2 arguments:
3015 column-title The title of the column (*not* the property name)
3016 value The value that should be modified.
3018 The function should return the value that should be displayed,
3019 or nil if the normal value should be used."
3020 :group 'org-properties
3021 :type 'function)
3023 (defcustom org-effort-property "Effort"
3024 "The property that is being used to keep track of effort estimates.
3025 Effort estimates given in this property need to have the format H:MM."
3026 :group 'org-properties
3027 :group 'org-progress
3028 :type '(string :tag "Property"))
3030 (defconst org-global-properties-fixed
3031 '(("VISIBILITY_ALL" . "folded children content all")
3032 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3033 "List of property/value pairs that can be inherited by any entry.
3035 These are fixed values, for the preset properties. The user variable
3036 that can be used to add to this list is `org-global-properties'.
3038 The entries in this list are cons cells where the car is a property
3039 name and cdr is a string with the value. If the value represents
3040 multiple items like an \"_ALL\" property, separate the items by
3041 spaces.")
3043 (defcustom org-global-properties nil
3044 "List of property/value pairs that can be inherited by any entry.
3046 This list will be combined with the constant `org-global-properties-fixed'.
3048 The entries in this list are cons cells where the car is a property
3049 name and cdr is a string with the value.
3051 You can set buffer-local values for the same purpose in the variable
3052 `org-file-properties' this by adding lines like
3054 #+PROPERTY: NAME VALUE"
3055 :group 'org-properties
3056 :type '(repeat
3057 (cons (string :tag "Property")
3058 (string :tag "Value"))))
3060 (defvar org-file-properties nil
3061 "List of property/value pairs that can be inherited by any entry.
3062 Valid for the current buffer.
3063 This variable is populated from #+PROPERTY lines.")
3064 (make-variable-buffer-local 'org-file-properties)
3066 (defgroup org-agenda nil
3067 "Options concerning agenda views in Org-mode."
3068 :tag "Org Agenda"
3069 :group 'org)
3071 (defvar org-category nil
3072 "Variable used by org files to set a category for agenda display.
3073 Such files should use a file variable to set it, for example
3075 # -*- mode: org; org-category: \"ELisp\"
3077 or contain a special line
3079 #+CATEGORY: ELisp
3081 If the file does not specify a category, then file's base name
3082 is used instead.")
3083 (make-variable-buffer-local 'org-category)
3084 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3086 (defcustom org-agenda-files nil
3087 "The files to be used for agenda display.
3088 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3089 \\[org-remove-file]. You can also use customize to edit the list.
3091 If an entry is a directory, all files in that directory that are matched by
3092 `org-agenda-file-regexp' will be part of the file list.
3094 If the value of the variable is not a list but a single file name, then
3095 the list of agenda files is actually stored and maintained in that file, one
3096 agenda file per line. In this file paths can be given relative to
3097 `org-directory'. Tilde expansion and environment variable substitution
3098 are also made."
3099 :group 'org-agenda
3100 :type '(choice
3101 (repeat :tag "List of files and directories" file)
3102 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3104 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3105 "Regular expression to match files for `org-agenda-files'.
3106 If any element in the list in that variable contains a directory instead
3107 of a normal file, all files in that directory that are matched by this
3108 regular expression will be included."
3109 :group 'org-agenda
3110 :type 'regexp)
3112 (defcustom org-agenda-text-search-extra-files nil
3113 "List of extra files to be searched by text search commands.
3114 These files will be search in addition to the agenda files by the
3115 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3116 Note that these files will only be searched for text search commands,
3117 not for the other agenda views like todo lists, tag searches or the weekly
3118 agenda. This variable is intended to list notes and possibly archive files
3119 that should also be searched by these two commands.
3120 In fact, if the first element in the list is the symbol `agenda-archives',
3121 than all archive files of all agenda files will be added to the search
3122 scope."
3123 :group 'org-agenda
3124 :type '(set :greedy t
3125 (const :tag "Agenda Archives" agenda-archives)
3126 (repeat :inline t (file))))
3128 (if (fboundp 'defvaralias)
3129 (defvaralias 'org-agenda-multi-occur-extra-files
3130 'org-agenda-text-search-extra-files))
3132 (defcustom org-agenda-skip-unavailable-files nil
3133 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3134 A nil value means to remove them, after a query, from the list."
3135 :group 'org-agenda
3136 :type 'boolean)
3138 (defcustom org-calendar-to-agenda-key [?c]
3139 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3140 The command `org-calendar-goto-agenda' will be bound to this key. The
3141 default is the character `c' because then `c' can be used to switch back and
3142 forth between agenda and calendar."
3143 :group 'org-agenda
3144 :type 'sexp)
3146 (defcustom org-calendar-agenda-action-key [?k]
3147 "The key to be installed in `calendar-mode-map' for agenda-action.
3148 The command `org-agenda-action' will be bound to this key. The
3149 default is the character `k' because we use the same key in the agenda."
3150 :group 'org-agenda
3151 :type 'sexp)
3153 (defcustom org-calendar-insert-diary-entry-key [?i]
3154 "The key to be installed in `calendar-mode-map' for adding diary entries.
3155 This option is irrelevant until `org-agenda-diary-file' has been configured
3156 to point to an Org-mode file. When that is the case, the command
3157 `org-agenda-diary-entry' will be bound to the key given here, by default
3158 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3159 if you want to continue doing this, you need to change this to a different
3160 key."
3161 :group 'org-agenda
3162 :type 'sexp)
3164 (defcustom org-agenda-diary-file 'diary-file
3165 "File to which to add new entries with the `i' key in agenda and calendar.
3166 When this is the symbol `diary-file', the functionality in the Emacs
3167 calendar will be used to add entries to the `diary-file'. But when this
3168 points to a file, `org-agenda-diary-entry' will be used instead."
3169 :group 'org-agenda
3170 :type '(choice
3171 (const :tag "The standard Emacs diary file" diary-file)
3172 (file :tag "Special Org file diary entries")))
3174 (eval-after-load "calendar"
3175 '(progn
3176 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3177 'org-calendar-goto-agenda)
3178 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3179 'org-agenda-action)
3180 (add-hook 'calendar-mode-hook
3181 (lambda ()
3182 (unless (eq org-agenda-diary-file 'diary-file)
3183 (define-key calendar-mode-map
3184 org-calendar-insert-diary-entry-key
3185 'org-agenda-diary-entry))))))
3187 (defgroup org-latex nil
3188 "Options for embedding LaTeX code into Org-mode."
3189 :tag "Org LaTeX"
3190 :group 'org)
3192 (defcustom org-format-latex-options
3193 '(:foreground default :background default :scale 1.0
3194 :html-foreground "Black" :html-background "Transparent"
3195 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3196 "Options for creating images from LaTeX fragments.
3197 This is a property list with the following properties:
3198 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3199 `default' means use the foreground of the default face.
3200 :background the background color, or \"Transparent\".
3201 `default' means use the background of the default face.
3202 :scale a scaling factor for the size of the images, to get more pixels
3203 :html-foreground, :html-background, :html-scale
3204 the same numbers for HTML export.
3205 :matchers a list indicating which matchers should be used to
3206 find LaTeX fragments. Valid members of this list are:
3207 \"begin\" find environments
3208 \"$1\" find single characters surrounded by $.$
3209 \"$\" find math expressions surrounded by $...$
3210 \"$$\" find math expressions surrounded by $$....$$
3211 \"\\(\" find math expressions surrounded by \\(...\\)
3212 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3213 :group 'org-latex
3214 :type 'plist)
3216 (defcustom org-format-latex-signal-error t
3217 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3218 When nil, just push out a message."
3219 :group 'org-latex
3220 :type 'boolean)
3222 (defcustom org-format-latex-header "\\documentclass{article}
3223 \\usepackage[usenames]{color}
3224 \\usepackage{amsmath}
3225 \\usepackage[mathscr]{eucal}
3226 \\pagestyle{empty} % do not remove
3227 \[PACKAGES]
3228 \[DEFAULT-PACKAGES]
3229 % The settings below are copied from fullpage.sty
3230 \\setlength{\\textwidth}{\\paperwidth}
3231 \\addtolength{\\textwidth}{-3cm}
3232 \\setlength{\\oddsidemargin}{1.5cm}
3233 \\addtolength{\\oddsidemargin}{-2.54cm}
3234 \\setlength{\\evensidemargin}{\\oddsidemargin}
3235 \\setlength{\\textheight}{\\paperheight}
3236 \\addtolength{\\textheight}{-\\headheight}
3237 \\addtolength{\\textheight}{-\\headsep}
3238 \\addtolength{\\textheight}{-\\footskip}
3239 \\addtolength{\\textheight}{-3cm}
3240 \\setlength{\\topmargin}{1.5cm}
3241 \\addtolength{\\topmargin}{-2.54cm}"
3242 "The document header used for processing LaTeX fragments.
3243 It is imperative that this header make sure that no page number
3244 appears on the page. The package defined in the variables
3245 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3246 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3247 will be appended."
3248 :group 'org-latex
3249 :type 'string)
3251 (defvar org-format-latex-header-extra nil)
3253 (defun org-set-packages-alist (var val)
3254 "Set the packages alist and make sure it has 3 elements per entry."
3255 (set var (mapcar (lambda (x)
3256 (if (and (consp x) (= (length x) 2))
3257 (list (car x) (nth 1 x) t)
3259 val)))
3261 (defun org-get-packages-alist (var)
3263 "Get the packages alist and make sure it has 3 elements per entry."
3264 (mapcar (lambda (x)
3265 (if (and (consp x) (= (length x) 2))
3266 (list (car x) (nth 1 x) t)
3268 (default-value var)))
3270 ;; The following variables are defined here because is it also used
3271 ;; when formatting latex fragments. Originally it was part of the
3272 ;; LaTeX exporter, which is why the name includes "export".
3273 (defcustom org-export-latex-default-packages-alist
3274 '(("AUTO" "inputenc" t)
3275 ("T1" "fontenc" t)
3276 ("" "fixltx2e" nil)
3277 ("" "graphicx" t)
3278 ("" "longtable" nil)
3279 ("" "float" nil)
3280 ("" "wrapfig" nil)
3281 ("" "soul" t)
3282 ("" "textcomp" t)
3283 ("" "marvosym" t)
3284 ("" "wasysym" t)
3285 ("" "latexsym" t)
3286 ("" "amssymb" t)
3287 ("" "hyperref" nil)
3288 "\\tolerance=1000"
3290 "Alist of default packages to be inserted in the header.
3291 Change this only if one of the packages here causes an incompatibility
3292 with another package you are using.
3293 The packages in this list are needed by one part or another of Org-mode
3294 to function properly.
3296 - inputenc, fontenc: for basic font and character selection
3297 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3298 for interpreting the entities in `org-entities'. You can skip some of these
3299 packages if you don't use any of the symbols in it.
3300 - graphicx: for including images
3301 - float, wrapfig: for figure placement
3302 - longtable: for long tables
3303 - hyperref: for cross references
3305 Therefore you should not modify this variable unless you know what you
3306 are doing. The one reason to change it anyway is that you might be loading
3307 some other package that conflicts with one of the default packages.
3308 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3309 If SNIPPET-FLAG is t, the package also needs to be included when
3310 compiling LaTeX snippets into images for inclusion into HTML."
3311 :group 'org-export-latex
3312 :set 'org-set-packages-alist
3313 :get 'org-get-packages-alist
3314 :type '(repeat
3315 (choice
3316 (list :tag "options/package pair"
3317 (string :tag "options")
3318 (string :tag "package")
3319 (boolean :tag "Snippet"))
3320 (string :tag "A line of LaTeX"))))
3322 (defcustom org-export-latex-packages-alist nil
3323 "Alist of packages to be inserted in every LaTeX header.
3324 These will be inserted after `org-export-latex-default-packages-alist'.
3325 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3326 SNIPPET-FLAG, when t, indicates that this package is also needed when
3327 turning LaTeX snippets into images for inclusion into HTML.
3328 Make sure that you only list packages here which:
3329 - you want in every file
3330 - do not conflict with the default packages in
3331 `org-export-latex-default-packages-alist'
3332 - do not conflict with the setup in `org-format-latex-header'."
3333 :group 'org-export-latex
3334 :set 'org-set-packages-alist
3335 :get 'org-get-packages-alist
3336 :type '(repeat
3337 (choice
3338 (list :tag "options/package pair"
3339 (string :tag "options")
3340 (string :tag "package")
3341 (boolean :tag "Snippet"))
3342 (string :tag "A line of LaTeX"))))
3345 (defgroup org-appearance nil
3346 "Settings for Org-mode appearance."
3347 :tag "Org Appearance"
3348 :group 'org)
3350 (defcustom org-level-color-stars-only nil
3351 "Non-nil means fontify only the stars in each headline.
3352 When nil, the entire headline is fontified.
3353 Changing it requires restart of `font-lock-mode' to become effective
3354 also in regions already fontified."
3355 :group 'org-appearance
3356 :type 'boolean)
3358 (defcustom org-hide-leading-stars nil
3359 "Non-nil means hide the first N-1 stars in a headline.
3360 This works by using the face `org-hide' for these stars. This
3361 face is white for a light background, and black for a dark
3362 background. You may have to customize the face `org-hide' to
3363 make this work.
3364 Changing it requires restart of `font-lock-mode' to become effective
3365 also in regions already fontified.
3366 You may also set this on a per-file basis by adding one of the following
3367 lines to the buffer:
3369 #+STARTUP: hidestars
3370 #+STARTUP: showstars"
3371 :group 'org-appearance
3372 :type 'boolean)
3374 (defcustom org-hidden-keywords nil
3375 "List of symbols corresponding to keywords to be hidden the org buffer.
3376 For example, a value '(title) for this list will make the document's title
3377 appear in the buffer without the initial #+TITLE: keyword."
3378 :group 'org-appearance
3379 :type '(set (const :tag "#+AUTHOR" author)
3380 (const :tag "#+DATE" date)
3381 (const :tag "#+EMAIL" email)
3382 (const :tag "#+TITLE" title)))
3384 (defcustom org-fontify-done-headline nil
3385 "Non-nil means change the face of a headline if it is marked DONE.
3386 Normally, only the TODO/DONE keyword indicates the state of a headline.
3387 When this is non-nil, the headline after the keyword is set to the
3388 `org-headline-done' as an additional indication."
3389 :group 'org-appearance
3390 :type 'boolean)
3392 (defcustom org-fontify-emphasized-text t
3393 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3394 Changing this variable requires a restart of Emacs to take effect."
3395 :group 'org-appearance
3396 :type 'boolean)
3398 (defcustom org-fontify-whole-heading-line nil
3399 "Non-nil means fontify the whole line for headings.
3400 This is useful when setting a background color for the
3401 org-level-* faces."
3402 :group 'org-appearance
3403 :type 'boolean)
3405 (defcustom org-highlight-latex-fragments-and-specials nil
3406 "Non-nil means fontify what is treated specially by the exporters."
3407 :group 'org-appearance
3408 :type 'boolean)
3410 (defcustom org-hide-emphasis-markers nil
3411 "Non-nil mean font-lock should hide the emphasis marker characters."
3412 :group 'org-appearance
3413 :type 'boolean)
3415 (defcustom org-pretty-entities nil
3416 "Non-nil means show entities as UTF8 characters.
3417 When nil, the \\name form remains in the buffer."
3418 :group 'org-appearance
3419 :type 'boolean)
3421 (defcustom org-pretty-entities-include-sub-superscripts t
3422 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3423 :group 'org-appearance
3424 :type 'boolean)
3426 (defvar org-emph-re nil
3427 "Regular expression for matching emphasis.
3428 After a match, the match groups contain these elements:
3429 0 The match of the full regular expression, including the characters
3430 before and after the proper match
3431 1 The character before the proper match, or empty at beginning of line
3432 2 The proper match, including the leading and trailing markers
3433 3 The leading marker like * or /, indicating the type of highlighting
3434 4 The text between the emphasis markers, not including the markers
3435 5 The character after the match, empty at the end of a line")
3436 (defvar org-verbatim-re nil
3437 "Regular expression for matching verbatim text.")
3438 (defvar org-emphasis-regexp-components) ; defined just below
3439 (defvar org-emphasis-alist) ; defined just below
3440 (defun org-set-emph-re (var val)
3441 "Set variable and compute the emphasis regular expression."
3442 (set var val)
3443 (when (and (boundp 'org-emphasis-alist)
3444 (boundp 'org-emphasis-regexp-components)
3445 org-emphasis-alist org-emphasis-regexp-components)
3446 (let* ((e org-emphasis-regexp-components)
3447 (pre (car e))
3448 (post (nth 1 e))
3449 (border (nth 2 e))
3450 (body (nth 3 e))
3451 (nl (nth 4 e))
3452 (body1 (concat body "*?"))
3453 (markers (mapconcat 'car org-emphasis-alist ""))
3454 (vmarkers (mapconcat
3455 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3456 org-emphasis-alist "")))
3457 ;; make sure special characters appear at the right position in the class
3458 (if (string-match "\\^" markers)
3459 (setq markers (concat (replace-match "" t t markers) "^")))
3460 (if (string-match "-" markers)
3461 (setq markers (concat (replace-match "" t t markers) "-")))
3462 (if (string-match "\\^" vmarkers)
3463 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3464 (if (string-match "-" vmarkers)
3465 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3466 (if (> nl 0)
3467 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3468 (int-to-string nl) "\\}")))
3469 ;; Make the regexp
3470 (setq org-emph-re
3471 (concat "\\([" pre "]\\|^\\)"
3472 "\\("
3473 "\\([" markers "]\\)"
3474 "\\("
3475 "[^" border "]\\|"
3476 "[^" border "]"
3477 body1
3478 "[^" border "]"
3479 "\\)"
3480 "\\3\\)"
3481 "\\([" post "]\\|$\\)"))
3482 (setq org-verbatim-re
3483 (concat "\\([" pre "]\\|^\\)"
3484 "\\("
3485 "\\([" vmarkers "]\\)"
3486 "\\("
3487 "[^" border "]\\|"
3488 "[^" border "]"
3489 body1
3490 "[^" border "]"
3491 "\\)"
3492 "\\3\\)"
3493 "\\([" post "]\\|$\\)")))))
3495 (defcustom org-emphasis-regexp-components
3496 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3497 "Components used to build the regular expression for emphasis.
3498 This is a list with five entries. Terminology: In an emphasis string
3499 like \" *strong word* \", we call the initial space PREMATCH, the final
3500 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3501 and \"trong wor\" is the body. The different components in this variable
3502 specify what is allowed/forbidden in each part:
3504 pre Chars allowed as prematch. Beginning of line will be allowed too.
3505 post Chars allowed as postmatch. End of line will be allowed too.
3506 border The chars *forbidden* as border characters.
3507 body-regexp A regexp like \".\" to match a body character. Don't use
3508 non-shy groups here, and don't allow newline here.
3509 newline The maximum number of newlines allowed in an emphasis exp.
3511 Use customize to modify this, or restart Emacs after changing it."
3512 :group 'org-appearance
3513 :set 'org-set-emph-re
3514 :type '(list
3515 (sexp :tag "Allowed chars in pre ")
3516 (sexp :tag "Allowed chars in post ")
3517 (sexp :tag "Forbidden chars in border ")
3518 (sexp :tag "Regexp for body ")
3519 (integer :tag "number of newlines allowed")
3520 (option (boolean :tag "Please ignore this button"))))
3522 (defcustom org-emphasis-alist
3523 `(("*" bold "<b>" "</b>")
3524 ("/" italic "<i>" "</i>")
3525 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3526 ("=" org-code "<code>" "</code>" verbatim)
3527 ("~" org-verbatim "<code>" "</code>" verbatim)
3528 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3529 "<del>" "</del>")
3531 "Special syntax for emphasized text.
3532 Text starting and ending with a special character will be emphasized, for
3533 example *bold*, _underlined_ and /italic/. This variable sets the marker
3534 characters, the face to be used by font-lock for highlighting in Org-mode
3535 Emacs buffers, and the HTML tags to be used for this.
3536 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3537 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3538 Use customize to modify this, or restart Emacs after changing it."
3539 :group 'org-appearance
3540 :set 'org-set-emph-re
3541 :type '(repeat
3542 (list
3543 (string :tag "Marker character")
3544 (choice
3545 (face :tag "Font-lock-face")
3546 (plist :tag "Face property list"))
3547 (string :tag "HTML start tag")
3548 (string :tag "HTML end tag")
3549 (option (const verbatim)))))
3551 (defvar org-protecting-blocks
3552 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3553 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3554 This is needed for font-lock setup.")
3556 ;;; Miscellaneous options
3558 (defgroup org-completion nil
3559 "Completion in Org-mode."
3560 :tag "Org Completion"
3561 :group 'org)
3563 (defcustom org-completion-use-ido nil
3564 "Non-nil means use ido completion wherever possible.
3565 Note that `ido-mode' must be active for this variable to be relevant.
3566 If you decide to turn this variable on, you might well want to turn off
3567 `org-outline-path-complete-in-steps'.
3568 See also `org-completion-use-iswitchb'."
3569 :group 'org-completion
3570 :type 'boolean)
3572 (defcustom org-completion-use-iswitchb nil
3573 "Non-nil means use iswitchb completion wherever possible.
3574 Note that `iswitchb-mode' must be active for this variable to be relevant.
3575 If you decide to turn this variable on, you might well want to turn off
3576 `org-outline-path-complete-in-steps'.
3577 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3578 :group 'org-completion
3579 :type 'boolean)
3581 (defcustom org-completion-fallback-command 'hippie-expand
3582 "The expansion command called by \\[pcomplete] in normal context.
3583 Normal means, no org-mode-specific context."
3584 :group 'org-completion
3585 :type 'function)
3587 ;;; Functions and variables from their packages
3588 ;; Declared here to avoid compiler warnings
3590 ;; XEmacs only
3591 (defvar outline-mode-menu-heading)
3592 (defvar outline-mode-menu-show)
3593 (defvar outline-mode-menu-hide)
3594 (defvar zmacs-regions) ; XEmacs regions
3596 ;; Emacs only
3597 (defvar mark-active)
3599 ;; Various packages
3600 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3601 (declare-function calendar-forward-day "cal-move" (arg))
3602 (declare-function calendar-goto-date "cal-move" (date))
3603 (declare-function calendar-goto-today "cal-move" ())
3604 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3605 (defvar calc-embedded-close-formula)
3606 (defvar calc-embedded-open-formula)
3607 (declare-function cdlatex-tab "ext:cdlatex" ())
3608 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3609 (defvar font-lock-unfontify-region-function)
3610 (declare-function iswitchb-read-buffer "iswitchb"
3611 (prompt &optional default require-match start matches-set))
3612 (defvar iswitchb-temp-buflist)
3613 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3614 (defvar org-agenda-tags-todo-honor-ignore-options)
3615 (declare-function org-agenda-skip "org-agenda" ())
3616 (declare-function
3617 org-format-agenda-item "org-agenda"
3618 (extra txt &optional category tags dotime noprefix remove-re habitp))
3619 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3620 (declare-function org-agenda-change-all-lines "org-agenda"
3621 (newhead hdmarker &optional fixface just-this))
3622 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3623 (declare-function org-agenda-maybe-redo "org-agenda" ())
3624 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3625 (beg end))
3626 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3627 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3628 "org-agenda" (&optional end))
3629 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3630 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3631 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3632 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3633 (declare-function org-indent-mode "org-indent" (&optional arg))
3634 (declare-function parse-time-string "parse-time" (string))
3635 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3636 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3637 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3638 (defvar remember-data-file)
3639 (defvar texmathp-why)
3640 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3641 (declare-function table--at-cell-p "table" (position &optional object at-column))
3643 (defvar w3m-current-url)
3644 (defvar w3m-current-title)
3646 (defvar org-latex-regexps)
3648 ;;; Autoload and prepare some org modules
3650 ;; Some table stuff that needs to be defined here, because it is used
3651 ;; by the functions setting up org-mode or checking for table context.
3653 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3654 "Detect an org-type or table-type table.")
3655 (defconst org-table-line-regexp "^[ \t]*|"
3656 "Detect an org-type table line.")
3657 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3658 "Detect an org-type table line.")
3659 (defconst org-table-hline-regexp "^[ \t]*|-"
3660 "Detect an org-type table hline.")
3661 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3662 "Detect a table-type table hline.")
3663 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3664 "Detect the first line outside a table when searching from within it.
3665 This works for both table types.")
3667 ;; Autoload the functions in org-table.el that are needed by functions here.
3669 (eval-and-compile
3670 (org-autoload "org-table"
3671 '(org-table-align org-table-begin org-table-blank-field
3672 org-table-convert org-table-convert-region org-table-copy-down
3673 org-table-copy-region org-table-create
3674 org-table-create-or-convert-from-region
3675 org-table-create-with-table.el org-table-current-dline
3676 org-table-cut-region org-table-delete-column org-table-edit-field
3677 org-table-edit-formulas org-table-end org-table-eval-formula
3678 org-table-export org-table-field-info
3679 org-table-get-stored-formulas org-table-goto-column
3680 org-table-hline-and-move org-table-import org-table-insert-column
3681 org-table-insert-hline org-table-insert-row org-table-iterate
3682 org-table-justify-field-maybe org-table-kill-row
3683 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3684 org-table-move-column org-table-move-column-left
3685 org-table-move-column-right org-table-move-row
3686 org-table-move-row-down org-table-move-row-up
3687 org-table-next-field org-table-next-row org-table-paste-rectangle
3688 org-table-previous-field org-table-recalculate
3689 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3690 org-table-toggle-coordinate-overlays
3691 org-table-toggle-formula-debugger org-table-wrap-region
3692 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3693 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3694 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3696 (defun org-at-table-p (&optional table-type)
3697 "Return t if the cursor is inside an org-type table.
3698 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3699 (if org-enable-table-editor
3700 (save-excursion
3701 (beginning-of-line 1)
3702 (looking-at (if table-type org-table-any-line-regexp
3703 org-table-line-regexp)))
3704 nil))
3705 (defsubst org-table-p () (org-at-table-p))
3707 (defun org-at-table.el-p ()
3708 "Return t if and only if we are at a table.el table."
3709 (and (org-at-table-p 'any)
3710 (save-excursion
3711 (goto-char (org-table-begin 'any))
3712 (looking-at org-table1-hline-regexp))))
3713 (defun org-table-recognize-table.el ()
3714 "If there is a table.el table nearby, recognize it and move into it."
3715 (if org-table-tab-recognizes-table.el
3716 (if (org-at-table.el-p)
3717 (progn
3718 (beginning-of-line 1)
3719 (if (looking-at org-table-dataline-regexp)
3721 (if (looking-at org-table1-hline-regexp)
3722 (progn
3723 (beginning-of-line 2)
3724 (if (looking-at org-table-any-border-regexp)
3725 (beginning-of-line -1)))))
3726 (if (re-search-forward "|" (org-table-end t) t)
3727 (progn
3728 (require 'table)
3729 (if (table--at-cell-p (point))
3731 (message "recognizing table.el table...")
3732 (table-recognize-table)
3733 (message "recognizing table.el table...done")))
3734 (error "This should not happen"))
3736 nil)
3737 nil))
3739 (defun org-at-table-hline-p ()
3740 "Return t if the cursor is inside a hline in a table."
3741 (if org-enable-table-editor
3742 (save-excursion
3743 (beginning-of-line 1)
3744 (looking-at org-table-hline-regexp))
3745 nil))
3747 (defvar org-table-clean-did-remove-column nil)
3749 (defun org-table-map-tables (function &optional quietly)
3750 "Apply FUNCTION to the start of all tables in the buffer."
3751 (save-excursion
3752 (save-restriction
3753 (widen)
3754 (goto-char (point-min))
3755 (while (re-search-forward org-table-any-line-regexp nil t)
3756 (unless quietly
3757 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3758 (beginning-of-line 1)
3759 (when (looking-at org-table-line-regexp)
3760 (save-excursion (funcall function))
3761 (or (looking-at org-table-line-regexp)
3762 (forward-char 1)))
3763 (re-search-forward org-table-any-border-regexp nil 1))))
3764 (unless quietly (message "Mapping tables: done")))
3766 ;; Declare and autoload functions from org-exp.el & Co
3768 (declare-function org-default-export-plist "org-exp")
3769 (declare-function org-infile-export-plist "org-exp")
3770 (declare-function org-get-current-options "org-exp")
3771 (eval-and-compile
3772 (org-autoload "org-exp"
3773 '(org-export org-export-visible
3774 org-insert-export-options-template
3775 org-table-clean-before-export))
3776 (org-autoload "org-ascii"
3777 '(org-export-as-ascii org-export-ascii-preprocess
3778 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3779 org-export-region-as-ascii))
3780 (org-autoload "org-latex"
3781 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3782 org-replace-region-by-latex org-export-region-as-latex
3783 org-export-as-latex org-export-as-pdf
3784 org-export-as-pdf-and-open))
3785 (org-autoload "org-html"
3786 '(org-export-as-html-and-open
3787 org-export-as-html-batch org-export-as-html-to-buffer
3788 org-replace-region-by-html org-export-region-as-html
3789 org-export-as-html))
3790 (org-autoload "org-docbook"
3791 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3792 org-replace-region-by-docbook org-export-region-as-docbook
3793 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3794 org-export-as-docbook))
3795 (org-autoload "org-icalendar"
3796 '(org-export-icalendar-this-file
3797 org-export-icalendar-all-agenda-files
3798 org-export-icalendar-combine-agenda-files))
3799 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3800 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3802 ;; Declare and autoload functions from org-agenda.el
3804 (eval-and-compile
3805 (org-autoload "org-agenda"
3806 '(org-agenda org-agenda-list org-search-view
3807 org-todo-list org-tags-view org-agenda-list-stuck-projects
3808 org-diary org-agenda-to-appt
3809 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3811 ;; Autoload org-remember
3813 (eval-and-compile
3814 (org-autoload "org-remember"
3815 '(org-remember-insinuate org-remember-annotation
3816 org-remember-apply-template org-remember org-remember-handler)))
3818 (eval-and-compile
3819 (org-autoload "org-capture"
3820 '(org-capture org-capture-insert-template-here
3821 org-capture-import-remember-templates)))
3823 ;; Autoload org-clock.el
3825 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3826 (beg end))
3827 (declare-function org-clock-update-mode-line "org-clock" ())
3828 (declare-function org-resolve-clocks "org-clock"
3829 (&optional also-non-dangling-p prompt last-valid))
3830 (defvar org-clock-start-time)
3831 (defvar org-clock-marker (make-marker)
3832 "Marker recording the last clock-in.")
3833 (defvar org-clock-hd-marker (make-marker)
3834 "Marker recording the last clock-in, but the headline position.")
3835 (defvar org-clock-heading ""
3836 "The heading of the current clock entry.")
3837 (defun org-clock-is-active ()
3838 "Return non-nil if clock is currently running.
3839 The return value is actually the clock marker."
3840 (marker-buffer org-clock-marker))
3842 (eval-and-compile
3843 (org-autoload
3844 "org-clock"
3845 '(org-clock-in org-clock-out org-clock-cancel
3846 org-clock-goto org-clock-sum org-clock-display
3847 org-clock-remove-overlays org-clock-report
3848 org-clocktable-shift org-dblock-write:clocktable
3849 org-get-clocktable org-resolve-clocks)))
3851 (defun org-clock-update-time-maybe ()
3852 "If this is a CLOCK line, update it and return t.
3853 Otherwise, return nil."
3854 (interactive)
3855 (save-excursion
3856 (beginning-of-line 1)
3857 (skip-chars-forward " \t")
3858 (when (looking-at org-clock-string)
3859 (let ((re (concat "[ \t]*" org-clock-string
3860 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3861 "\\([ \t]*=>.*\\)?\\)?"))
3862 ts te h m s neg)
3863 (cond
3864 ((not (looking-at re))
3865 nil)
3866 ((not (match-end 2))
3867 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3868 (> org-clock-marker (point))
3869 (<= org-clock-marker (point-at-eol)))
3870 ;; The clock is running here
3871 (setq org-clock-start-time
3872 (apply 'encode-time
3873 (org-parse-time-string (match-string 1))))
3874 (org-clock-update-mode-line)))
3876 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3877 (end-of-line 1)
3878 (setq ts (match-string 1)
3879 te (match-string 3))
3880 (setq s (- (org-float-time
3881 (apply 'encode-time (org-parse-time-string te)))
3882 (org-float-time
3883 (apply 'encode-time (org-parse-time-string ts))))
3884 neg (< s 0)
3885 s (abs s)
3886 h (floor (/ s 3600))
3887 s (- s (* 3600 h))
3888 m (floor (/ s 60))
3889 s (- s (* 60 s)))
3890 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3891 t))))))
3893 (defun org-check-running-clock ()
3894 "Check if the current buffer contains the running clock.
3895 If yes, offer to stop it and to save the buffer with the changes."
3896 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3897 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3898 (buffer-name))))
3899 (org-clock-out)
3900 (when (y-or-n-p "Save changed buffer?")
3901 (save-buffer))))
3903 (defun org-clocktable-try-shift (dir n)
3904 "Check if this line starts a clock table, if yes, shift the time block."
3905 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
3906 (org-clocktable-shift dir n)))
3908 ;; Autoload org-timer.el
3910 (eval-and-compile
3911 (org-autoload
3912 "org-timer"
3913 '(org-timer-start org-timer org-timer-item
3914 org-timer-change-times-in-region
3915 org-timer-set-timer
3916 org-timer-reset-timers
3917 org-timer-show-remaining-time)))
3919 ;; Autoload org-feed.el
3921 (eval-and-compile
3922 (org-autoload
3923 "org-feed"
3924 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3927 ;; Autoload org-indent.el
3929 ;; Define the variable already here, to make sure we have it.
3930 (defvar org-indent-mode nil
3931 "Non-nil if Org-Indent mode is enabled.
3932 Use the command `org-indent-mode' to change this variable.")
3934 (eval-and-compile
3935 (org-autoload
3936 "org-indent"
3937 '(org-indent-mode)))
3939 ;; Autoload org-mobile.el
3941 (eval-and-compile
3942 (org-autoload
3943 "org-mobile"
3944 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3946 ;; Autoload archiving code
3947 ;; The stuff that is needed for cycling and tags has to be defined here.
3949 (defgroup org-archive nil
3950 "Options concerning archiving in Org-mode."
3951 :tag "Org Archive"
3952 :group 'org-structure)
3954 (defcustom org-archive-location "%s_archive::"
3955 "The location where subtrees should be archived.
3957 The value of this variable is a string, consisting of two parts,
3958 separated by a double-colon. The first part is a filename and
3959 the second part is a headline.
3961 When the filename is omitted, archiving happens in the same file.
3962 %s in the filename will be replaced by the current file
3963 name (without the directory part). Archiving to a different file
3964 is useful to keep archived entries from contributing to the
3965 Org-mode Agenda.
3967 The archived entries will be filed as subtrees of the specified
3968 headline. When the headline is omitted, the subtrees are simply
3969 filed away at the end of the file, as top-level entries. Also in
3970 the heading you can use %s to represent the file name, this can be
3971 useful when using the same archive for a number of different files.
3973 Here are a few examples:
3974 \"%s_archive::\"
3975 If the current file is Projects.org, archive in file
3976 Projects.org_archive, as top-level trees. This is the default.
3978 \"::* Archived Tasks\"
3979 Archive in the current file, under the top-level headline
3980 \"* Archived Tasks\".
3982 \"~/org/archive.org::\"
3983 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3985 \"~/org/archive.org::From %s\"
3986 Archive in file ~/org/archive.org (absolute path), under headlines
3987 \"From FILENAME\" where file name is the current file name.
3989 \"basement::** Finished Tasks\"
3990 Archive in file ./basement (relative path), as level 3 trees
3991 below the level 2 heading \"** Finished Tasks\".
3993 You may set this option on a per-file basis by adding to the buffer a
3994 line like
3996 #+ARCHIVE: basement::** Finished Tasks
3998 You may also define it locally for a subtree by setting an ARCHIVE property
3999 in the entry. If such a property is found in an entry, or anywhere up
4000 the hierarchy, it will be used."
4001 :group 'org-archive
4002 :type 'string)
4004 (defcustom org-archive-tag "ARCHIVE"
4005 "The tag that marks a subtree as archived.
4006 An archived subtree does not open during visibility cycling, and does
4007 not contribute to the agenda listings.
4008 After changing this, font-lock must be restarted in the relevant buffers to
4009 get the proper fontification."
4010 :group 'org-archive
4011 :group 'org-keywords
4012 :type 'string)
4014 (defcustom org-agenda-skip-archived-trees t
4015 "Non-nil means the agenda will skip any items located in archived trees.
4016 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4017 variable is no longer recommended, you should leave it at the value t.
4018 Instead, use the key `v' to cycle the archives-mode in the agenda."
4019 :group 'org-archive
4020 :group 'org-agenda-skip
4021 :type 'boolean)
4023 (defcustom org-columns-skip-archived-trees t
4024 "Non-nil means ignore archived trees when creating column view."
4025 :group 'org-archive
4026 :group 'org-properties
4027 :type 'boolean)
4029 (defcustom org-cycle-open-archived-trees nil
4030 "Non-nil means `org-cycle' will open archived trees.
4031 An archived tree is a tree marked with the tag ARCHIVE.
4032 When nil, archived trees will stay folded. You can still open them with
4033 normal outline commands like `show-all', but not with the cycling commands."
4034 :group 'org-archive
4035 :group 'org-cycle
4036 :type 'boolean)
4038 (defcustom org-sparse-tree-open-archived-trees nil
4039 "Non-nil means sparse tree construction shows matches in archived trees.
4040 When nil, matches in these trees are highlighted, but the trees are kept in
4041 collapsed state."
4042 :group 'org-archive
4043 :group 'org-sparse-trees
4044 :type 'boolean)
4046 (defun org-cycle-hide-archived-subtrees (state)
4047 "Re-hide all archived subtrees after a visibility state change."
4048 (when (and (not org-cycle-open-archived-trees)
4049 (not (memq state '(overview folded))))
4050 (save-excursion
4051 (let* ((globalp (memq state '(contents all)))
4052 (beg (if globalp (point-min) (point)))
4053 (end (if globalp (point-max) (org-end-of-subtree t))))
4054 (org-hide-archived-subtrees beg end)
4055 (goto-char beg)
4056 (if (looking-at (concat ".*:" org-archive-tag ":"))
4057 (message "%s" (substitute-command-keys
4058 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4060 (defun org-force-cycle-archived ()
4061 "Cycle subtree even if it is archived."
4062 (interactive)
4063 (setq this-command 'org-cycle)
4064 (let ((org-cycle-open-archived-trees t))
4065 (call-interactively 'org-cycle)))
4067 (defun org-hide-archived-subtrees (beg end)
4068 "Re-hide all archived subtrees after a visibility state change."
4069 (save-excursion
4070 (let* ((re (concat ":" org-archive-tag ":")))
4071 (goto-char beg)
4072 (while (re-search-forward re end t)
4073 (when (org-on-heading-p)
4074 (org-flag-subtree t)
4075 (org-end-of-subtree t))))))
4077 (defun org-flag-subtree (flag)
4078 (save-excursion
4079 (org-back-to-heading t)
4080 (outline-end-of-heading)
4081 (outline-flag-region (point)
4082 (progn (org-end-of-subtree t) (point))
4083 flag)))
4085 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4087 (eval-and-compile
4088 (org-autoload "org-archive"
4089 '(org-add-archive-files org-archive-subtree
4090 org-archive-to-archive-sibling org-toggle-archive-tag
4091 org-archive-subtree-default
4092 org-archive-subtree-default-with-confirmation)))
4094 ;; Autoload Column View Code
4096 (declare-function org-columns-number-to-string "org-colview")
4097 (declare-function org-columns-get-format-and-top-level "org-colview")
4098 (declare-function org-columns-compute "org-colview")
4100 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4101 '(org-columns-number-to-string org-columns-get-format-and-top-level
4102 org-columns-compute org-agenda-columns org-columns-remove-overlays
4103 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4105 ;; Autoload ID code
4107 (declare-function org-id-store-link "org-id")
4108 (declare-function org-id-locations-load "org-id")
4109 (declare-function org-id-locations-save "org-id")
4110 (defvar org-id-track-globally)
4111 (org-autoload "org-id"
4112 '(org-id-get-create org-id-new org-id-copy org-id-get
4113 org-id-get-with-outline-path-completion
4114 org-id-get-with-outline-drilling org-id-store-link
4115 org-id-goto org-id-find org-id-store-link))
4117 ;; Autoload Plotting Code
4119 (org-autoload "org-plot"
4120 '(org-plot/gnuplot))
4122 ;;; Variables for pre-computed regular expressions, all buffer local
4124 (defvar org-drawer-regexp nil
4125 "Matches first line of a hidden block.")
4126 (make-variable-buffer-local 'org-drawer-regexp)
4127 (defvar org-todo-regexp nil
4128 "Matches any of the TODO state keywords.")
4129 (make-variable-buffer-local 'org-todo-regexp)
4130 (defvar org-not-done-regexp nil
4131 "Matches any of the TODO state keywords except the last one.")
4132 (make-variable-buffer-local 'org-not-done-regexp)
4133 (defvar org-not-done-heading-regexp nil
4134 "Matches a TODO headline that is not done.")
4135 (make-variable-buffer-local 'org-not-done-regexp)
4136 (defvar org-todo-line-regexp nil
4137 "Matches a headline and puts TODO state into group 2 if present.")
4138 (make-variable-buffer-local 'org-todo-line-regexp)
4139 (defvar org-complex-heading-regexp nil
4140 "Matches a headline and puts everything into groups:
4141 group 1: the stars
4142 group 2: The todo keyword, maybe
4143 group 3: Priority cookie
4144 group 4: True headline
4145 group 5: Tags")
4146 (make-variable-buffer-local 'org-complex-heading-regexp)
4147 (defvar org-complex-heading-regexp-format nil
4148 "Printf format to make regexp to match an exact headline.
4149 This regexp will match the headline of any node which hase the exact
4150 headline text that is put into the format, but may have any TODO state,
4151 priority and tags.")
4152 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4153 (defvar org-todo-line-tags-regexp nil
4154 "Matches a headline and puts TODO state into group 2 if present.
4155 Also put tags into group 4 if tags are present.")
4156 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4157 (defvar org-nl-done-regexp nil
4158 "Matches newline followed by a headline with the DONE keyword.")
4159 (make-variable-buffer-local 'org-nl-done-regexp)
4160 (defvar org-looking-at-done-regexp nil
4161 "Matches the DONE keyword a point.")
4162 (make-variable-buffer-local 'org-looking-at-done-regexp)
4163 (defvar org-ds-keyword-length 12
4164 "Maximum length of the Deadline and SCHEDULED keywords.")
4165 (make-variable-buffer-local 'org-ds-keyword-length)
4166 (defvar org-deadline-regexp nil
4167 "Matches the DEADLINE keyword.")
4168 (make-variable-buffer-local 'org-deadline-regexp)
4169 (defvar org-deadline-time-regexp nil
4170 "Matches the DEADLINE keyword together with a time stamp.")
4171 (make-variable-buffer-local 'org-deadline-time-regexp)
4172 (defvar org-deadline-line-regexp nil
4173 "Matches the DEADLINE keyword and the rest of the line.")
4174 (make-variable-buffer-local 'org-deadline-line-regexp)
4175 (defvar org-scheduled-regexp nil
4176 "Matches the SCHEDULED keyword.")
4177 (make-variable-buffer-local 'org-scheduled-regexp)
4178 (defvar org-scheduled-time-regexp nil
4179 "Matches the SCHEDULED keyword together with a time stamp.")
4180 (make-variable-buffer-local 'org-scheduled-time-regexp)
4181 (defvar org-closed-time-regexp nil
4182 "Matches the CLOSED keyword together with a time stamp.")
4183 (make-variable-buffer-local 'org-closed-time-regexp)
4185 (defvar org-keyword-time-regexp nil
4186 "Matches any of the 4 keywords, together with the time stamp.")
4187 (make-variable-buffer-local 'org-keyword-time-regexp)
4188 (defvar org-keyword-time-not-clock-regexp nil
4189 "Matches any of the 3 keywords, together with the time stamp.")
4190 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4191 (defvar org-maybe-keyword-time-regexp nil
4192 "Matches a timestamp, possibly preceded by a keyword.")
4193 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4194 (defvar org-planning-or-clock-line-re nil
4195 "Matches a line with planning or clock info.")
4196 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4197 (defvar org-all-time-keywords nil
4198 "List of time keywords.")
4199 (make-variable-buffer-local 'org-all-time-keywords)
4201 (defconst org-plain-time-of-day-regexp
4202 (concat
4203 "\\(\\<[012]?[0-9]"
4204 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4205 "\\(--?"
4206 "\\(\\<[012]?[0-9]"
4207 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4208 "\\)?")
4209 "Regular expression to match a plain time or time range.
4210 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4211 groups carry important information:
4212 0 the full match
4213 1 the first time, range or not
4214 8 the second time, if it is a range.")
4216 (defconst org-plain-time-extension-regexp
4217 (concat
4218 "\\(\\<[012]?[0-9]"
4219 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4220 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4221 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4222 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4223 groups carry important information:
4224 0 the full match
4225 7 hours of duration
4226 9 minutes of duration")
4228 (defconst org-stamp-time-of-day-regexp
4229 (concat
4230 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4231 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4232 "\\(--?"
4233 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4234 "Regular expression to match a timestamp time or time range.
4235 After a match, the following groups carry important information:
4236 0 the full match
4237 1 date plus weekday, for back referencing to make sure both times are on the same day
4238 2 the first time, range or not
4239 4 the second time, if it is a range.")
4241 (defconst org-startup-options
4242 '(("fold" org-startup-folded t)
4243 ("overview" org-startup-folded t)
4244 ("nofold" org-startup-folded nil)
4245 ("showall" org-startup-folded nil)
4246 ("showeverything" org-startup-folded showeverything)
4247 ("content" org-startup-folded content)
4248 ("indent" org-startup-indented t)
4249 ("noindent" org-startup-indented nil)
4250 ("hidestars" org-hide-leading-stars t)
4251 ("showstars" org-hide-leading-stars nil)
4252 ("odd" org-odd-levels-only t)
4253 ("oddeven" org-odd-levels-only nil)
4254 ("align" org-startup-align-all-tables t)
4255 ("noalign" org-startup-align-all-tables nil)
4256 ("inlineimages" org-startup-with-inline-images t)
4257 ("noinlineimages" org-startup-with-inline-images nil)
4258 ("customtime" org-display-custom-times t)
4259 ("logdone" org-log-done time)
4260 ("lognotedone" org-log-done note)
4261 ("nologdone" org-log-done nil)
4262 ("lognoteclock-out" org-log-note-clock-out t)
4263 ("nolognoteclock-out" org-log-note-clock-out nil)
4264 ("logrepeat" org-log-repeat state)
4265 ("lognoterepeat" org-log-repeat note)
4266 ("nologrepeat" org-log-repeat nil)
4267 ("logreschedule" org-log-reschedule time)
4268 ("lognotereschedule" org-log-reschedule note)
4269 ("nologreschedule" org-log-reschedule nil)
4270 ("logredeadline" org-log-redeadline time)
4271 ("lognoteredeadline" org-log-redeadline note)
4272 ("nologredeadline" org-log-redeadline nil)
4273 ("logrefile" org-log-refile time)
4274 ("lognoterefile" org-log-refile note)
4275 ("nologrefile" org-log-refile nil)
4276 ("fninline" org-footnote-define-inline t)
4277 ("nofninline" org-footnote-define-inline nil)
4278 ("fnlocal" org-footnote-section nil)
4279 ("fnauto" org-footnote-auto-label t)
4280 ("fnprompt" org-footnote-auto-label nil)
4281 ("fnconfirm" org-footnote-auto-label confirm)
4282 ("fnplain" org-footnote-auto-label plain)
4283 ("fnadjust" org-footnote-auto-adjust t)
4284 ("nofnadjust" org-footnote-auto-adjust nil)
4285 ("constcgs" constants-unit-system cgs)
4286 ("constSI" constants-unit-system SI)
4287 ("noptag" org-tag-persistent-alist nil)
4288 ("hideblocks" org-hide-block-startup t)
4289 ("nohideblocks" org-hide-block-startup nil)
4290 ("beamer" org-startup-with-beamer-mode t)
4291 ("entitiespretty" org-pretty-entities t)
4292 ("entitiesplain" org-pretty-entities nil))
4293 "Variable associated with STARTUP options for org-mode.
4294 Each element is a list of three items: The startup options as written
4295 in the #+STARTUP line, the corresponding variable, and the value to
4296 set this variable to if the option is found. An optional forth element PUSH
4297 means to push this value onto the list in the variable.")
4299 (defun org-set-regexps-and-options ()
4300 "Precompute regular expressions for current buffer."
4301 (when (org-mode-p)
4302 (org-set-local 'org-todo-kwd-alist nil)
4303 (org-set-local 'org-todo-key-alist nil)
4304 (org-set-local 'org-todo-key-trigger nil)
4305 (org-set-local 'org-todo-keywords-1 nil)
4306 (org-set-local 'org-done-keywords nil)
4307 (org-set-local 'org-todo-heads nil)
4308 (org-set-local 'org-todo-sets nil)
4309 (org-set-local 'org-todo-log-states nil)
4310 (org-set-local 'org-file-properties nil)
4311 (org-set-local 'org-file-tags nil)
4312 (let ((re (org-make-options-regexp
4313 '("CATEGORY" "TODO" "COLUMNS"
4314 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4315 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4316 "OPTIONS")
4317 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4318 (splitre "[ \t]+")
4319 (scripts org-use-sub-superscripts)
4320 kwds kws0 kwsa key log value cat arch tags const links hw dws
4321 tail sep kws1 prio props ftags drawers beamer-p
4322 ext-setup-or-nil setup-contents (start 0))
4323 (save-excursion
4324 (save-restriction
4325 (widen)
4326 (goto-char (point-min))
4327 (while (or (and ext-setup-or-nil
4328 (string-match re ext-setup-or-nil start)
4329 (setq start (match-end 0)))
4330 (and (setq ext-setup-or-nil nil start 0)
4331 (re-search-forward re nil t)))
4332 (setq key (upcase (match-string 1 ext-setup-or-nil))
4333 value (org-match-string-no-properties 2 ext-setup-or-nil))
4334 (if (stringp value) (setq value (org-trim value)))
4335 (cond
4336 ((equal key "CATEGORY")
4337 (setq cat value))
4338 ((member key '("SEQ_TODO" "TODO"))
4339 (push (cons 'sequence (org-split-string value splitre)) kwds))
4340 ((equal key "TYP_TODO")
4341 (push (cons 'type (org-split-string value splitre)) kwds))
4342 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4343 ;; general TODO-like setup
4344 (push (cons (intern (downcase (match-string 1 key)))
4345 (org-split-string value splitre)) kwds))
4346 ((equal key "TAGS")
4347 (setq tags (append tags (if tags '("\\n") nil)
4348 (org-split-string value splitre))))
4349 ((equal key "COLUMNS")
4350 (org-set-local 'org-columns-default-format value))
4351 ((equal key "LINK")
4352 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4353 (push (cons (match-string 1 value)
4354 (org-trim (match-string 2 value)))
4355 links)))
4356 ((equal key "PRIORITIES")
4357 (setq prio (org-split-string value " +")))
4358 ((equal key "PROPERTY")
4359 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4360 (push (cons (match-string 1 value) (match-string 2 value))
4361 props)))
4362 ((equal key "FILETAGS")
4363 (when (string-match "\\S-" value)
4364 (setq ftags
4365 (append
4366 ftags
4367 (apply 'append
4368 (mapcar (lambda (x) (org-split-string x ":"))
4369 (org-split-string value)))))))
4370 ((equal key "DRAWERS")
4371 (setq drawers (org-split-string value splitre)))
4372 ((equal key "CONSTANTS")
4373 (setq const (append const (org-split-string value splitre))))
4374 ((equal key "STARTUP")
4375 (let ((opts (org-split-string value splitre))
4376 l var val)
4377 (while (setq l (pop opts))
4378 (when (setq l (assoc l org-startup-options))
4379 (setq var (nth 1 l) val (nth 2 l))
4380 (if (not (nth 3 l))
4381 (set (make-local-variable var) val)
4382 (if (not (listp (symbol-value var)))
4383 (set (make-local-variable var) nil))
4384 (set (make-local-variable var) (symbol-value var))
4385 (add-to-list var val))))))
4386 ((equal key "ARCHIVE")
4387 (setq arch value)
4388 (remove-text-properties 0 (length arch)
4389 '(face t fontified t) arch))
4390 ((equal key "LATEX_CLASS")
4391 (setq beamer-p (equal value "beamer")))
4392 ((equal key "OPTIONS")
4393 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4394 (setq scripts (read (match-string 2 value)))))
4395 ((equal key "SETUPFILE")
4396 (setq setup-contents (org-file-contents
4397 (expand-file-name
4398 (org-remove-double-quotes value))
4399 'noerror))
4400 (if (not ext-setup-or-nil)
4401 (setq ext-setup-or-nil setup-contents start 0)
4402 (setq ext-setup-or-nil
4403 (concat (substring ext-setup-or-nil 0 start)
4404 "\n" setup-contents "\n"
4405 (substring ext-setup-or-nil start)))))
4406 ))))
4407 (org-set-local 'org-use-sub-superscripts scripts)
4408 (when cat
4409 (org-set-local 'org-category (intern cat))
4410 (push (cons "CATEGORY" cat) props))
4411 (when prio
4412 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4413 (setq prio (mapcar 'string-to-char prio))
4414 (org-set-local 'org-highest-priority (nth 0 prio))
4415 (org-set-local 'org-lowest-priority (nth 1 prio))
4416 (org-set-local 'org-default-priority (nth 2 prio)))
4417 (and props (org-set-local 'org-file-properties (nreverse props)))
4418 (and ftags (org-set-local 'org-file-tags
4419 (mapcar 'org-add-prop-inherited ftags)))
4420 (and drawers (org-set-local 'org-drawers drawers))
4421 (and arch (org-set-local 'org-archive-location arch))
4422 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4423 ;; Process the TODO keywords
4424 (unless kwds
4425 ;; Use the global values as if they had been given locally.
4426 (setq kwds (default-value 'org-todo-keywords))
4427 (if (stringp (car kwds))
4428 (setq kwds (list (cons org-todo-interpretation
4429 (default-value 'org-todo-keywords)))))
4430 (setq kwds (reverse kwds)))
4431 (setq kwds (nreverse kwds))
4432 (let (inter kws kw)
4433 (while (setq kws (pop kwds))
4434 (let ((kws (or
4435 (run-hook-with-args-until-success
4436 'org-todo-setup-filter-hook kws)
4437 kws)))
4438 (setq inter (pop kws) sep (member "|" kws)
4439 kws0 (delete "|" (copy-sequence kws))
4440 kwsa nil
4441 kws1 (mapcar
4442 (lambda (x)
4443 ;; 1 2
4444 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4445 (progn
4446 (setq kw (match-string 1 x)
4447 key (and (match-end 2) (match-string 2 x))
4448 log (org-extract-log-state-settings x))
4449 (push (cons kw (and key (string-to-char key))) kwsa)
4450 (and log (push log org-todo-log-states))
4452 (error "Invalid TODO keyword %s" x)))
4453 kws0)
4454 kwsa (if kwsa (append '((:startgroup))
4455 (nreverse kwsa)
4456 '((:endgroup))))
4457 hw (car kws1)
4458 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4459 tail (list inter hw (car dws) (org-last dws))))
4460 (add-to-list 'org-todo-heads hw 'append)
4461 (push kws1 org-todo-sets)
4462 (setq org-done-keywords (append org-done-keywords dws nil))
4463 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4464 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4465 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4466 (setq org-todo-sets (nreverse org-todo-sets)
4467 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4468 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4469 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4470 ;; Process the constants
4471 (when const
4472 (let (e cst)
4473 (while (setq e (pop const))
4474 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4475 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4476 (setq org-table-formula-constants-local cst)))
4478 ;; Process the tags.
4479 (when tags
4480 (let (e tgs)
4481 (while (setq e (pop tags))
4482 (cond
4483 ((equal e "{") (push '(:startgroup) tgs))
4484 ((equal e "}") (push '(:endgroup) tgs))
4485 ((equal e "\\n") (push '(:newline) tgs))
4486 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4487 (push (cons (match-string 1 e)
4488 (string-to-char (match-string 2 e)))
4489 tgs))
4490 (t (push (list e) tgs))))
4491 (org-set-local 'org-tag-alist nil)
4492 (while (setq e (pop tgs))
4493 (or (and (stringp (car e))
4494 (assoc (car e) org-tag-alist))
4495 (push e org-tag-alist)))))
4497 ;; Compute the regular expressions and other local variables
4498 (if (not org-done-keywords)
4499 (setq org-done-keywords (and org-todo-keywords-1
4500 (list (org-last org-todo-keywords-1)))))
4501 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4502 (length org-scheduled-string)
4503 (length org-clock-string)
4504 (length org-closed-string)))
4505 org-drawer-regexp
4506 (concat "^[ \t]*:\\("
4507 (mapconcat 'regexp-quote org-drawers "\\|")
4508 "\\):[ \t]*$")
4509 org-not-done-keywords
4510 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4511 org-todo-regexp
4512 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4513 "\\|") "\\)\\>")
4514 org-not-done-regexp
4515 (concat "\\<\\("
4516 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4517 "\\)\\>")
4518 org-not-done-heading-regexp
4519 (concat "^\\(\\*+\\)[ \t]+\\("
4520 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4521 "\\)\\>")
4522 org-todo-line-regexp
4523 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4524 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4525 "\\)\\>\\)?[ \t]*\\(.*\\)")
4526 org-complex-heading-regexp
4527 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4528 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4529 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4530 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
4531 org-complex-heading-regexp-format
4532 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4533 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4534 "\\)\\>\\)?"
4535 "\\(?:[ \t]*\\(\\[#.\\]\\)\\)?"
4536 "\\(?:[ \t]*\\(?:\\[[0-9%%/]+\\]\\)\\)?" ;; stats cookie
4537 "[ \t]*\\(%s\\)"
4538 "\\(?:[ \t]*\\(?:\\[[0-9%%/]+\\]\\)\\)?" ;; stats cookie
4539 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?[ \t]*$")
4540 org-nl-done-regexp
4541 (concat "\n\\*+[ \t]+"
4542 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4543 "\\)" "\\>")
4544 org-todo-line-tags-regexp
4545 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4546 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4547 (org-re
4548 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@#%]+:[ \t]*\\)?$\\)"))
4549 org-looking-at-done-regexp
4550 (concat "^" "\\(?:"
4551 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4552 "\\>")
4553 org-deadline-regexp (concat "\\<" org-deadline-string)
4554 org-deadline-time-regexp
4555 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4556 org-deadline-line-regexp
4557 (concat "\\<\\(" org-deadline-string "\\).*")
4558 org-scheduled-regexp
4559 (concat "\\<" org-scheduled-string)
4560 org-scheduled-time-regexp
4561 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4562 org-closed-time-regexp
4563 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4564 org-keyword-time-regexp
4565 (concat "\\<\\(" org-scheduled-string
4566 "\\|" org-deadline-string
4567 "\\|" org-closed-string
4568 "\\|" org-clock-string "\\)"
4569 " *[[<]\\([^]>]+\\)[]>]")
4570 org-keyword-time-not-clock-regexp
4571 (concat "\\<\\(" org-scheduled-string
4572 "\\|" org-deadline-string
4573 "\\|" org-closed-string
4574 "\\)"
4575 " *[[<]\\([^]>]+\\)[]>]")
4576 org-maybe-keyword-time-regexp
4577 (concat "\\(\\<\\(" org-scheduled-string
4578 "\\|" org-deadline-string
4579 "\\|" org-closed-string
4580 "\\|" org-clock-string "\\)\\)?"
4581 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4582 org-planning-or-clock-line-re
4583 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4584 "\\|" org-deadline-string
4585 "\\|" org-closed-string "\\|" org-clock-string
4586 "\\)\\>\\)")
4587 org-all-time-keywords
4588 (mapcar (lambda (w) (substring w 0 -1))
4589 (list org-scheduled-string org-deadline-string
4590 org-clock-string org-closed-string))
4592 (org-compute-latex-and-specials-regexp)
4593 (org-set-font-lock-defaults))))
4595 (defun org-file-contents (file &optional noerror)
4596 "Return the contents of FILE, as a string."
4597 (if (or (not file)
4598 (not (file-readable-p file)))
4599 (if noerror
4600 (progn
4601 (message "Cannot read file \"%s\"" file)
4602 (ding) (sit-for 2)
4604 (error "Cannot read file \"%s\"" file))
4605 (with-temp-buffer
4606 (insert-file-contents file)
4607 (buffer-string))))
4609 (defun org-extract-log-state-settings (x)
4610 "Extract the log state setting from a TODO keyword string.
4611 This will extract info from a string like \"WAIT(w@/!)\"."
4612 (let (kw key log1 log2)
4613 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4614 (setq kw (match-string 1 x)
4615 key (and (match-end 2) (match-string 2 x))
4616 log1 (and (match-end 3) (match-string 3 x))
4617 log2 (and (match-end 4) (match-string 4 x)))
4618 (and (or log1 log2)
4619 (list kw
4620 (and log1 (if (equal log1 "!") 'time 'note))
4621 (and log2 (if (equal log2 "!") 'time 'note)))))))
4623 (defun org-remove-keyword-keys (list)
4624 "Remove a pair of parenthesis at the end of each string in LIST."
4625 (mapcar (lambda (x)
4626 (if (string-match "(.*)$" x)
4627 (substring x 0 (match-beginning 0))
4629 list))
4631 (defun org-assign-fast-keys (alist)
4632 "Assign fast keys to a keyword-key alist.
4633 Respect keys that are already there."
4634 (let (new e (alt ?0))
4635 (while (setq e (pop alist))
4636 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4637 (cdr e)) ;; Key already assigned.
4638 (push e new)
4639 (let ((clist (string-to-list (downcase (car e))))
4640 (used (append new alist)))
4641 (when (= (car clist) ?@)
4642 (pop clist))
4643 (while (and clist (rassoc (car clist) used))
4644 (pop clist))
4645 (unless clist
4646 (while (rassoc alt used)
4647 (incf alt)))
4648 (push (cons (car e) (or (car clist) alt)) new))))
4649 (nreverse new)))
4651 ;;; Some variables used in various places
4653 (defvar org-window-configuration nil
4654 "Used in various places to store a window configuration.")
4655 (defvar org-selected-window nil
4656 "Used in various places to store a window configuration.")
4657 (defvar org-finish-function nil
4658 "Function to be called when `C-c C-c' is used.
4659 This is for getting out of special buffers like remember.")
4662 ;; FIXME: Occasionally check by commenting these, to make sure
4663 ;; no other functions uses these, forgetting to let-bind them.
4664 (defvar entry)
4665 (defvar last-state)
4666 (defvar date)
4668 ;; Defined somewhere in this file, but used before definition.
4669 (defvar org-entities) ;; defined in org-entities.el
4670 (defvar org-struct-menu)
4671 (defvar org-org-menu)
4672 (defvar org-tbl-menu)
4674 ;;;; Define the Org-mode
4676 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4677 (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"))
4680 ;; We use a before-change function to check if a table might need
4681 ;; an update.
4682 (defvar org-table-may-need-update t
4683 "Indicates that a table might need an update.
4684 This variable is set by `org-before-change-function'.
4685 `org-table-align' sets it back to nil.")
4686 (defun org-before-change-function (beg end)
4687 "Every change indicates that a table might need an update."
4688 (setq org-table-may-need-update t))
4689 (defvar org-mode-map)
4690 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4691 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4692 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4693 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4694 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4695 (defvar org-table-buffer-is-an nil)
4696 (defconst org-outline-regexp "\\*+ ")
4698 ;;;###autoload
4699 (define-derived-mode org-mode outline-mode "Org"
4700 "Outline-based notes management and organizer, alias
4701 \"Carsten's outline-mode for keeping track of everything.\"
4703 Org-mode develops organizational tasks around a NOTES file which
4704 contains information about projects as plain text. Org-mode is
4705 implemented on top of outline-mode, which is ideal to keep the content
4706 of large files well structured. It supports ToDo items, deadlines and
4707 time stamps, which magically appear in the diary listing of the Emacs
4708 calendar. Tables are easily created with a built-in table editor.
4709 Plain text URL-like links connect to websites, emails (VM), Usenet
4710 messages (Gnus), BBDB entries, and any files related to the project.
4711 For printing and sharing of notes, an Org-mode file (or a part of it)
4712 can be exported as a structured ASCII or HTML file.
4714 The following commands are available:
4716 \\{org-mode-map}"
4718 ;; Get rid of Outline menus, they are not needed
4719 ;; Need to do this here because define-derived-mode sets up
4720 ;; the keymap so late. Still, it is a waste to call this each time
4721 ;; we switch another buffer into org-mode.
4722 (if (featurep 'xemacs)
4723 (when (boundp 'outline-mode-menu-heading)
4724 ;; Assume this is Greg's port, it uses easymenu
4725 (easy-menu-remove outline-mode-menu-heading)
4726 (easy-menu-remove outline-mode-menu-show)
4727 (easy-menu-remove outline-mode-menu-hide))
4728 (define-key org-mode-map [menu-bar headings] 'undefined)
4729 (define-key org-mode-map [menu-bar hide] 'undefined)
4730 (define-key org-mode-map [menu-bar show] 'undefined))
4732 (org-load-modules-maybe)
4733 (easy-menu-add org-org-menu)
4734 (easy-menu-add org-tbl-menu)
4735 (org-install-agenda-files-menu)
4736 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
4737 (add-to-invisibility-spec '(org-cwidth))
4738 (add-to-invisibility-spec '(org-hide-block . t))
4739 (when (featurep 'xemacs)
4740 (org-set-local 'line-move-ignore-invisible t))
4741 (org-set-local 'outline-regexp org-outline-regexp)
4742 (org-set-local 'outline-level 'org-outline-level)
4743 (when (and org-ellipsis
4744 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4745 (fboundp 'make-glyph-code))
4746 (unless org-display-table
4747 (setq org-display-table (make-display-table)))
4748 (set-display-table-slot
4749 org-display-table 4
4750 (vconcat (mapcar
4751 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4752 org-ellipsis)))
4753 (if (stringp org-ellipsis) org-ellipsis "..."))))
4754 (setq buffer-display-table org-display-table))
4755 (org-set-regexps-and-options)
4756 (when (and org-tag-faces (not org-tags-special-faces-re))
4757 ;; tag faces set outside customize.... force initialization.
4758 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4759 ;; Calc embedded
4760 (org-set-local 'calc-embedded-open-mode "# ")
4761 (modify-syntax-entry ?@ "w")
4762 (if org-startup-truncated (setq truncate-lines t))
4763 (org-set-local 'font-lock-unfontify-region-function
4764 'org-unfontify-region)
4765 ;; Activate before-change-function
4766 (org-set-local 'org-table-may-need-update t)
4767 (org-add-hook 'before-change-functions 'org-before-change-function nil
4768 'local)
4769 ;; Check for running clock before killing a buffer
4770 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4771 ;; Paragraphs and auto-filling
4772 (org-set-autofill-regexps)
4773 (setq indent-line-function 'org-indent-line-function)
4774 (org-update-radio-target-regexp)
4775 ;; Beginning/end of defun
4776 (org-set-local 'beginning-of-defun-function 'org-beginning-of-defun)
4777 (org-set-local 'end-of-defun-function 'org-end-of-defun)
4778 ;; Next error for sparse trees
4779 (org-set-local 'next-error-function 'org-occur-next-match)
4780 ;; Make sure dependence stuff works reliably, even for users who set it
4781 ;; too late :-(
4782 (if org-enforce-todo-dependencies
4783 (add-hook 'org-blocker-hook
4784 'org-block-todo-from-children-or-siblings-or-parent)
4785 (remove-hook 'org-blocker-hook
4786 'org-block-todo-from-children-or-siblings-or-parent))
4787 (if org-enforce-todo-checkbox-dependencies
4788 (add-hook 'org-blocker-hook
4789 'org-block-todo-from-checkboxes)
4790 (remove-hook 'org-blocker-hook
4791 'org-block-todo-from-checkboxes))
4793 ;; Comment characters
4794 (org-set-local 'comment-start "#")
4795 (org-set-local 'comment-padding " ")
4797 ;; Align options lines
4798 (org-set-local
4799 'align-mode-rules-list
4800 '((org-in-buffer-settings
4801 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4802 (modes . '(org-mode)))))
4804 ;; Imenu
4805 (org-set-local 'imenu-create-index-function
4806 'org-imenu-get-tree)
4808 ;; Make isearch reveal context
4809 (if (or (featurep 'xemacs)
4810 (not (boundp 'outline-isearch-open-invisible-function)))
4811 ;; Emacs 21 and XEmacs make use of the hook
4812 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4813 ;; Emacs 22 deals with this through a special variable
4814 (org-set-local 'outline-isearch-open-invisible-function
4815 (lambda (&rest ignore) (org-show-context 'isearch))))
4817 ;; Turn on org-beamer-mode?
4818 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4820 ;; Setup the pcomplete hooks
4821 (set (make-local-variable 'pcomplete-command-completion-function)
4822 'org-pcomplete-initial)
4823 (set (make-local-variable 'pcomplete-command-name-function)
4824 'org-command-at-point)
4825 (set (make-local-variable 'pcomplete-default-completion-function)
4826 'ignore)
4827 (set (make-local-variable 'pcomplete-parse-arguments-function)
4828 'org-parse-arguments)
4829 (set (make-local-variable 'pcomplete-termination-string) "")
4831 ;; If empty file that did not turn on org-mode automatically, make it to.
4832 (if (and org-insert-mode-line-in-empty-file
4833 (org-called-interactively-p 'any)
4834 (= (point-min) (point-max)))
4835 (insert "# -*- mode: org -*-\n\n"))
4836 (unless org-inhibit-startup
4837 (when org-startup-align-all-tables
4838 (let ((bmp (buffer-modified-p)))
4839 (org-table-map-tables 'org-table-align 'quietly)
4840 (set-buffer-modified-p bmp)))
4841 (when org-startup-with-inline-images
4842 (org-display-inline-images))
4843 (when org-startup-indented
4844 (require 'org-indent)
4845 (org-indent-mode 1))
4846 (unless org-inhibit-startup-visibility-stuff
4847 (org-set-startup-visibility))))
4849 (when (fboundp 'abbrev-table-put)
4850 (abbrev-table-put org-mode-abbrev-table
4851 :parents (list text-mode-abbrev-table)))
4853 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4855 (defun org-current-time ()
4856 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4857 (if (> (car org-time-stamp-rounding-minutes) 1)
4858 (let ((r (car org-time-stamp-rounding-minutes))
4859 (time (decode-time)))
4860 (apply 'encode-time
4861 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4862 (nthcdr 2 time))))
4863 (current-time)))
4865 (defun org-today ()
4866 "Return today date, considering `org-extend-today-until'."
4867 (time-to-days
4868 (time-subtract (current-time)
4869 (list 0 (* 3600 org-extend-today-until) 0))))
4871 ;;;; Font-Lock stuff, including the activators
4873 (defvar org-mouse-map (make-sparse-keymap))
4874 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
4875 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
4876 (when org-mouse-1-follows-link
4877 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4878 (when org-tab-follows-link
4879 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4880 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4882 (require 'font-lock)
4884 (defconst org-non-link-chars "]\t\n\r<>")
4885 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4886 "shell" "elisp" "doi" "message"))
4887 (defvar org-link-types-re nil
4888 "Matches a link that has a url-like prefix like \"http:\"")
4889 (defvar org-link-re-with-space nil
4890 "Matches a link with spaces, optional angular brackets around it.")
4891 (defvar org-link-re-with-space2 nil
4892 "Matches a link with spaces, optional angular brackets around it.")
4893 (defvar org-link-re-with-space3 nil
4894 "Matches a link with spaces, only for internal part in bracket links.")
4895 (defvar org-angle-link-re nil
4896 "Matches link with angular brackets, spaces are allowed.")
4897 (defvar org-plain-link-re nil
4898 "Matches plain link, without spaces.")
4899 (defvar org-bracket-link-regexp nil
4900 "Matches a link in double brackets.")
4901 (defvar org-bracket-link-analytic-regexp nil
4902 "Regular expression used to analyze links.
4903 Here is what the match groups contain after a match:
4904 1: http:
4905 2: http
4906 3: path
4907 4: [desc]
4908 5: desc")
4909 (defvar org-bracket-link-analytic-regexp++ nil
4910 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
4911 (defvar org-any-link-re nil
4912 "Regular expression matching any link.")
4914 (defcustom org-match-sexp-depth 3
4915 "Number of stacked braces for sub/superscript matching.
4916 This has to be set before loading org.el to be effective."
4917 :group 'org-export-translation ; ??????????????????????????/
4918 :type 'integer)
4920 (defun org-create-multibrace-regexp (left right n)
4921 "Create a regular expression which will match a balanced sexp.
4922 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
4923 as single character strings.
4924 The regexp returned will match the entire expression including the
4925 delimiters. It will also define a single group which contains the
4926 match except for the outermost delimiters. The maximum depth of
4927 stacked delimiters is N. Escaping delimiters is not possible."
4928 (let* ((nothing (concat "[^" left right "]*?"))
4929 (or "\\|")
4930 (re nothing)
4931 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
4932 (while (> n 1)
4933 (setq n (1- n)
4934 re (concat re or next)
4935 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
4936 (concat left "\\(" re "\\)" right)))
4938 (defvar org-match-substring-regexp
4939 (concat
4940 "\\([^\\]\\)\\([_^]\\)\\("
4941 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
4942 "\\|"
4943 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
4944 "\\|"
4945 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
4946 "The regular expression matching a sub- or superscript.")
4948 (defvar org-match-substring-with-braces-regexp
4949 (concat
4950 "\\([^\\]\\)\\([_^]\\)\\("
4951 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
4952 "\\)")
4953 "The regular expression matching a sub- or superscript, forcing braces.")
4955 (defun org-make-link-regexps ()
4956 "Update the link regular expressions.
4957 This should be called after the variable `org-link-types' has changed."
4958 (setq org-link-types-re
4959 (concat
4960 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
4961 org-link-re-with-space
4962 (concat
4963 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4964 "\\([^" org-non-link-chars " ]"
4965 "[^" org-non-link-chars "]*"
4966 "[^" org-non-link-chars " ]\\)>?")
4967 org-link-re-with-space2
4968 (concat
4969 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4970 "\\([^" org-non-link-chars " ]"
4971 "[^\t\n\r]*"
4972 "[^" org-non-link-chars " ]\\)>?")
4973 org-link-re-with-space3
4974 (concat
4975 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4976 "\\([^" org-non-link-chars " ]"
4977 "[^\t\n\r]*\\)")
4978 org-angle-link-re
4979 (concat
4980 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4981 "\\([^" org-non-link-chars " ]"
4982 "[^" org-non-link-chars "]*"
4983 "\\)>")
4984 org-plain-link-re
4985 (concat
4986 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4987 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4988 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4989 org-bracket-link-regexp
4990 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4991 org-bracket-link-analytic-regexp
4992 (concat
4993 "\\[\\["
4994 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
4995 "\\([^]]+\\)"
4996 "\\]"
4997 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4998 "\\]")
4999 org-bracket-link-analytic-regexp++
5000 (concat
5001 "\\[\\["
5002 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5003 "\\([^]]+\\)"
5004 "\\]"
5005 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5006 "\\]")
5007 org-any-link-re
5008 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5009 org-angle-link-re "\\)\\|\\("
5010 org-plain-link-re "\\)")))
5012 (org-make-link-regexps)
5014 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5015 "Regular expression for fast time stamp matching.")
5016 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?\\)[]>]"
5017 "Regular expression for fast time stamp matching.")
5018 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5019 "Regular expression matching time strings for analysis.
5020 This one does not require the space after the date, so it can be used
5021 on a string that terminates immediately after the date.")
5022 (defconst org-ts-regexp1 "\\(\\([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 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5025 "Regular expression matching time stamps, with groups.")
5026 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5027 "Regular expression matching time stamps (also [..]), with groups.")
5028 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5029 "Regular expression matching a time stamp range.")
5030 (defconst org-tr-regexp-both
5031 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5032 "Regular expression matching a time stamp range.")
5033 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5034 org-ts-regexp "\\)?")
5035 "Regular expression matching a time stamp or time stamp range.")
5036 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5037 org-ts-regexp-both "\\)?")
5038 "Regular expression matching a time stamp or time stamp range.
5039 The time stamps may be either active or inactive.")
5041 (defvar org-emph-face nil)
5043 (defun org-do-emphasis-faces (limit)
5044 "Run through the buffer and add overlays to links."
5045 (let (rtn a)
5046 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5047 (if (not (= (char-after (match-beginning 3))
5048 (char-after (match-beginning 4))))
5049 (progn
5050 (setq rtn t)
5051 (setq a (assoc (match-string 3) org-emphasis-alist))
5052 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5053 'face
5054 (nth 1 a))
5055 (and (nth 4 a)
5056 (org-remove-flyspell-overlays-in
5057 (match-beginning 0) (match-end 0)))
5058 (add-text-properties (match-beginning 2) (match-end 2)
5059 '(font-lock-multiline t org-emphasis t))
5060 (when org-hide-emphasis-markers
5061 (add-text-properties (match-end 4) (match-beginning 5)
5062 '(invisible org-link))
5063 (add-text-properties (match-beginning 3) (match-end 3)
5064 '(invisible org-link)))))
5065 (backward-char 1))
5066 rtn))
5068 (defun org-emphasize (&optional char)
5069 "Insert or change an emphasis, i.e. a font like bold or italic.
5070 If there is an active region, change that region to a new emphasis.
5071 If there is no region, just insert the marker characters and position
5072 the cursor between them.
5073 CHAR should be either the marker character, or the first character of the
5074 HTML tag associated with that emphasis. If CHAR is a space, the means
5075 to remove the emphasis of the selected region.
5076 If char is not given (for example in an interactive call) it
5077 will be prompted for."
5078 (interactive)
5079 (let ((eal org-emphasis-alist) e det
5080 (erc org-emphasis-regexp-components)
5081 (prompt "")
5082 (string "") beg end move tag c s)
5083 (if (org-region-active-p)
5084 (setq beg (region-beginning) end (region-end)
5085 string (buffer-substring beg end))
5086 (setq move t))
5088 (while (setq e (pop eal))
5089 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5090 c (aref tag 0))
5091 (push (cons c (string-to-char (car e))) det)
5092 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5093 (substring tag 1)))))
5094 (setq det (nreverse det))
5095 (unless char
5096 (message "%s" (concat "Emphasis marker or tag:" prompt))
5097 (setq char (read-char-exclusive)))
5098 (setq char (or (cdr (assoc char det)) char))
5099 (if (equal char ?\ )
5100 (setq s "" move nil)
5101 (unless (assoc (char-to-string char) org-emphasis-alist)
5102 (error "No such emphasis marker: \"%c\"" char))
5103 (setq s (char-to-string char)))
5104 (while (and (> (length string) 1)
5105 (equal (substring string 0 1) (substring string -1))
5106 (assoc (substring string 0 1) org-emphasis-alist))
5107 (setq string (substring string 1 -1)))
5108 (setq string (concat s string s))
5109 (if beg (delete-region beg end))
5110 (unless (or (bolp)
5111 (string-match (concat "[" (nth 0 erc) "\n]")
5112 (char-to-string (char-before (point)))))
5113 (insert " "))
5114 (unless (or (eobp)
5115 (string-match (concat "[" (nth 1 erc) "\n]")
5116 (char-to-string (char-after (point)))))
5117 (insert " ") (backward-char 1))
5118 (insert string)
5119 (and move (backward-char 1))))
5121 (defconst org-nonsticky-props
5122 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5124 (defsubst org-rear-nonsticky-at (pos)
5125 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5127 (defun org-activate-plain-links (limit)
5128 "Run through the buffer and add overlays to links."
5129 (catch 'exit
5130 (let (f)
5131 (if (re-search-forward org-plain-link-re limit t)
5132 (progn
5133 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5134 (setq f (get-text-property (match-beginning 0) 'face))
5135 (if (or (eq f 'org-tag)
5136 (and (listp f) (memq 'org-tag f)))
5138 (add-text-properties (match-beginning 0) (match-end 0)
5139 (list 'mouse-face 'highlight
5140 'face 'org-link
5141 'keymap org-mouse-map))
5142 (org-rear-nonsticky-at (match-end 0)))
5143 t)))))
5145 (defun org-activate-code (limit)
5146 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
5147 (progn
5148 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5149 (remove-text-properties (match-beginning 0) (match-end 0)
5150 '(display t invisible t intangible t))
5151 t)))
5153 (defcustom org-src-fontify-natively nil
5154 "When non-nil, fontify code in code blocks."
5155 :type 'boolean
5156 :group 'org-appearance
5157 :group 'org-babel)
5159 (defun org-fontify-meta-lines-and-blocks (limit)
5160 (condition-case nil
5161 (org-fontify-meta-lines-and-blocks-1 limit)
5162 (error (message "org-mode fontification error"))))
5164 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5165 "Fontify #+ lines and blocks, in the correct ways."
5166 (let ((case-fold-search t))
5167 (if (re-search-forward
5168 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5169 limit t)
5170 (let ((beg (match-beginning 0))
5171 (block-start (match-end 0))
5172 (block-end nil)
5173 (lang (match-string 7))
5174 (beg1 (line-beginning-position 2))
5175 (dc1 (downcase (match-string 2)))
5176 (dc3 (downcase (match-string 3)))
5177 end end1 quoting block-type ovl)
5178 (cond
5179 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
5180 ;; a single line of backend-specific content
5181 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5182 (remove-text-properties (match-beginning 0) (match-end 0)
5183 '(display t invisible t intangible t))
5184 (add-text-properties (match-beginning 1) (match-end 3)
5185 '(font-lock-fontified t face org-meta-line))
5186 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5187 '(font-lock-fontified t face org-block))
5188 ; for backend-specific code
5190 ((and (match-end 4) (equal dc3 "begin"))
5191 ;; Truly a block
5192 (setq block-type (downcase (match-string 5))
5193 quoting (member block-type org-protecting-blocks))
5194 (when (re-search-forward
5195 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5196 nil t) ;; on purpose, we look further than LIMIT
5197 (setq end (match-end 0) end1 (1- (match-beginning 0)))
5198 (setq block-end (match-beginning 0))
5199 (when quoting
5200 (remove-text-properties beg end
5201 '(display t invisible t intangible t)))
5202 (add-text-properties
5203 beg end
5204 '(font-lock-fontified t font-lock-multiline t))
5205 (add-text-properties beg beg1 '(face org-meta-line))
5206 (add-text-properties end1 (+ end 1) '(face org-meta-line))
5207 ; for end_src
5208 (cond
5209 ((and lang org-src-fontify-natively)
5210 (org-src-font-lock-fontify-block lang block-start block-end)
5211 ;; remove old background overlays
5212 (mapc (lambda (ov)
5213 (if (eq (overlay-get ov 'face) 'org-block-background)
5214 (delete-overlay ov)))
5215 (overlays-at (/ (+ beg1 block-end) 2)))
5216 ;; add a background overlay
5217 (setq ovl (make-overlay beg1 block-end))
5218 (overlay-put ovl 'face 'org-block-background)
5219 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5220 (quoting
5221 (add-text-properties beg1 (+ end1 1) '(face org-block)))
5222 ; end of source block
5223 ((not org-fontify-quote-and-verse-blocks))
5224 ((string= block-type "quote")
5225 (add-text-properties beg1 (1+ end1) '(face org-quote)))
5226 ((string= block-type "verse")
5227 (add-text-properties beg1 (1+ end1) '(face org-verse))))
5228 (add-text-properties beg beg1 '(face org-block-begin-line))
5229 (add-text-properties (1+ end) (1+ end1) '(face org-block-end-line))
5231 ((member dc1 '("title:" "author:" "email:" "date:"))
5232 (add-text-properties
5233 beg (match-end 3)
5234 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5235 '(font-lock-fontified t invisible t)
5236 '(font-lock-fontified t face org-document-info-keyword)))
5237 (add-text-properties
5238 (match-beginning 6) (match-end 6)
5239 (if (string-equal dc1 "title:")
5240 '(font-lock-fontified t face org-document-title)
5241 '(font-lock-fontified t face org-document-info))))
5242 ((not (member (char-after beg) '(?\ ?\t)))
5243 ;; just any other in-buffer setting, but not indented
5244 (add-text-properties
5245 beg (1+ (match-end 0))
5246 '(font-lock-fontified t face org-meta-line))
5248 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
5249 "orgtbl:" "tblfm:" "tblname:" "result:"
5250 "results:" "source:" "srcname:" "call:"))
5251 (and (match-end 4) (equal dc3 "attr")))
5252 (add-text-properties
5253 beg (match-end 0)
5254 '(font-lock-fontified t face org-meta-line))
5256 ((member dc3 '(" " ""))
5257 (add-text-properties
5258 beg (match-end 0)
5259 '(font-lock-fontified t face font-lock-comment-face)))
5260 (t nil))))))
5262 (defun org-activate-angle-links (limit)
5263 "Run through the buffer and add overlays to links."
5264 (if (re-search-forward org-angle-link-re limit t)
5265 (progn
5266 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5267 (add-text-properties (match-beginning 0) (match-end 0)
5268 (list 'mouse-face 'highlight
5269 'keymap org-mouse-map))
5270 (org-rear-nonsticky-at (match-end 0))
5271 t)))
5273 (defun org-activate-footnote-links (limit)
5274 "Run through the buffer and add overlays to links."
5275 (let ((fn (org-footnote-next-reference-or-definition limit)))
5276 (when fn
5277 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5278 (org-remove-flyspell-overlays-in beg end)
5279 (add-text-properties beg end
5280 (list 'mouse-face 'highlight
5281 'keymap org-mouse-map
5282 'help-echo
5283 (if (= (point-at-bol) beg)
5284 "Footnote definition"
5285 "Footnote reference")))
5286 (save-excursion
5287 (goto-char beg)
5288 (looking-at (regexp-quote (buffer-substring beg end))))))))
5290 (defun org-activate-bracket-links (limit)
5291 "Run through the buffer and add overlays to bracketed links."
5292 (if (re-search-forward org-bracket-link-regexp limit t)
5293 (let* ((help (concat "LINK: "
5294 (org-match-string-no-properties 1)))
5295 ;; FIXME: above we should remove the escapes.
5296 ;; but that requires another match, protecting match data,
5297 ;; a lot of overhead for font-lock.
5298 (ip (org-maybe-intangible
5299 (list 'invisible 'org-link
5300 'keymap org-mouse-map 'mouse-face 'highlight
5301 'font-lock-multiline t 'help-echo help)))
5302 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5303 'font-lock-multiline t 'help-echo help)))
5304 ;; We need to remove the invisible property here. Table narrowing
5305 ;; may have made some of this invisible.
5306 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5307 (remove-text-properties (match-beginning 0) (match-end 0)
5308 '(invisible nil))
5309 (if (match-end 3)
5310 (progn
5311 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5312 (org-rear-nonsticky-at (match-beginning 3))
5313 (add-text-properties (match-beginning 3) (match-end 3) vp)
5314 (org-rear-nonsticky-at (match-end 3))
5315 (add-text-properties (match-end 3) (match-end 0) ip)
5316 (org-rear-nonsticky-at (match-end 0)))
5317 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5318 (org-rear-nonsticky-at (match-beginning 1))
5319 (add-text-properties (match-beginning 1) (match-end 1) vp)
5320 (org-rear-nonsticky-at (match-end 1))
5321 (add-text-properties (match-end 1) (match-end 0) ip)
5322 (org-rear-nonsticky-at (match-end 0)))
5323 t)))
5325 (defun org-activate-dates (limit)
5326 "Run through the buffer and add overlays to dates."
5327 (if (re-search-forward org-tsr-regexp-both limit t)
5328 (progn
5329 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5330 (add-text-properties (match-beginning 0) (match-end 0)
5331 (list 'mouse-face 'highlight
5332 'keymap org-mouse-map))
5333 (org-rear-nonsticky-at (match-end 0))
5334 (when org-display-custom-times
5335 (if (match-end 3)
5336 (org-display-custom-time (match-beginning 3) (match-end 3)))
5337 (org-display-custom-time (match-beginning 1) (match-end 1)))
5338 t)))
5340 (defvar org-target-link-regexp nil
5341 "Regular expression matching radio targets in plain text.")
5342 (make-variable-buffer-local 'org-target-link-regexp)
5343 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5344 "Regular expression matching a link target.")
5345 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5346 "Regular expression matching a radio target.")
5347 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5348 "Regular expression matching any target.")
5350 (defun org-activate-target-links (limit)
5351 "Run through the buffer and add overlays to target matches."
5352 (when org-target-link-regexp
5353 (let ((case-fold-search t))
5354 (if (re-search-forward org-target-link-regexp limit t)
5355 (progn
5356 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5357 (add-text-properties (match-beginning 0) (match-end 0)
5358 (list 'mouse-face 'highlight
5359 'keymap org-mouse-map
5360 'help-echo "Radio target link"
5361 'org-linked-text t))
5362 (org-rear-nonsticky-at (match-end 0))
5363 t)))))
5365 (defun org-update-radio-target-regexp ()
5366 "Find all radio targets in this file and update the regular expression."
5367 (interactive)
5368 (when (memq 'radio org-activate-links)
5369 (setq org-target-link-regexp
5370 (org-make-target-link-regexp (org-all-targets 'radio)))
5371 (org-restart-font-lock)))
5373 (defun org-hide-wide-columns (limit)
5374 (let (s e)
5375 (setq s (text-property-any (point) (or limit (point-max))
5376 'org-cwidth t))
5377 (when s
5378 (setq e (next-single-property-change s 'org-cwidth))
5379 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5380 (goto-char e)
5381 t)))
5383 (defvar org-latex-and-specials-regexp nil
5384 "Regular expression for highlighting export special stuff.")
5385 (defvar org-match-substring-regexp)
5386 (defvar org-match-substring-with-braces-regexp)
5388 ;; This should be with the exporter code, but we also use if for font-locking
5389 (defconst org-export-html-special-string-regexps
5390 '(("\\\\-" . "&shy;")
5391 ("---\\([^-]\\)" . "&mdash;\\1")
5392 ("--\\([^-]\\)" . "&ndash;\\1")
5393 ("\\.\\.\\." . "&hellip;"))
5394 "Regular expressions for special string conversion.")
5397 (defun org-compute-latex-and-specials-regexp ()
5398 "Compute regular expression for stuff treated specially by exporters."
5399 (if (not org-highlight-latex-fragments-and-specials)
5400 (org-set-local 'org-latex-and-specials-regexp nil)
5401 (require 'org-exp)
5402 (let*
5403 ((matchers (plist-get org-format-latex-options :matchers))
5404 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5405 org-latex-regexps)))
5406 (org-export-allow-BIND nil)
5407 (options (org-combine-plists (org-default-export-plist)
5408 (org-infile-export-plist)))
5409 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5410 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5411 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5412 (org-export-html-expand (plist-get options :expand-quoted-html))
5413 (org-export-with-special-strings (plist-get options :special-strings))
5414 (re-sub
5415 (cond
5416 ((equal org-export-with-sub-superscripts '{})
5417 (list org-match-substring-with-braces-regexp))
5418 (org-export-with-sub-superscripts
5419 (list org-match-substring-regexp))
5420 (t nil)))
5421 (re-latex
5422 (if org-export-with-LaTeX-fragments
5423 (mapcar (lambda (x) (nth 1 x)) latexs)))
5424 (re-macros
5425 (if org-export-with-TeX-macros
5426 (list (concat "\\\\"
5427 (regexp-opt
5428 (append
5430 (delq nil
5431 (mapcar 'car-safe
5432 (append org-entities-user
5433 org-entities)))
5434 (if (boundp 'org-latex-entities)
5435 (mapcar (lambda (x)
5436 (or (car-safe x) x))
5437 org-latex-entities)
5438 nil))
5439 'words))) ; FIXME
5441 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5442 (re-special (if org-export-with-special-strings
5443 (mapcar (lambda (x) (car x))
5444 org-export-html-special-string-regexps)))
5445 (re-rest
5446 (delq nil
5447 (list
5448 (if org-export-html-expand "@<[^>\n]+>")
5449 ))))
5450 (org-set-local
5451 'org-latex-and-specials-regexp
5452 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5453 re-rest) "\\|")))))
5455 (defun org-do-latex-and-special-faces (limit)
5456 "Run through the buffer and add overlays to links."
5457 (when org-latex-and-specials-regexp
5458 (let (rtn d)
5459 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5460 limit t))
5461 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5462 'face))
5463 '(org-code org-verbatim underline)))
5464 (progn
5465 (setq rtn t
5466 d (cond ((member (char-after (1+ (match-beginning 0)))
5467 '(?_ ?^)) 1)
5468 (t 0)))
5469 (font-lock-prepend-text-property
5470 (+ d (match-beginning 0)) (match-end 0)
5471 'face 'org-latex-and-export-specials)
5472 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5473 '(font-lock-multiline t)))))
5474 rtn)))
5476 (defun org-restart-font-lock ()
5477 "Restart `font-lock-mode', to force refontification."
5478 (when (and (boundp 'font-lock-mode) font-lock-mode)
5479 (font-lock-mode -1)
5480 (font-lock-mode 1)))
5482 (defun org-all-targets (&optional radio)
5483 "Return a list of all targets in this file.
5484 With optional argument RADIO, only find radio targets."
5485 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5486 rtn)
5487 (save-excursion
5488 (goto-char (point-min))
5489 (while (re-search-forward re nil t)
5490 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5491 rtn)))
5493 (defun org-make-target-link-regexp (targets)
5494 "Make regular expression matching all strings in TARGETS.
5495 The regular expression finds the targets also if there is a line break
5496 between words."
5497 (and targets
5498 (concat
5499 "\\<\\("
5500 (mapconcat
5501 (lambda (x)
5502 (setq x (regexp-quote x))
5503 (while (string-match " +" x)
5504 (setq x (replace-match "\\s-+" t t x)))
5506 targets
5507 "\\|")
5508 "\\)\\>")))
5510 (defun org-activate-tags (limit)
5511 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5512 (progn
5513 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5514 (add-text-properties (match-beginning 1) (match-end 1)
5515 (list 'mouse-face 'highlight
5516 'keymap org-mouse-map))
5517 (org-rear-nonsticky-at (match-end 1))
5518 t)))
5520 (defun org-outline-level ()
5521 "Compute the outline level of the heading at point.
5522 This function assumes that the cursor is at the beginning of a line matched
5523 by `outline-regexp'. Otherwise it returns garbage.
5524 If this is called at a normal headline, the level is the number of stars.
5525 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5526 (save-excursion
5527 (looking-at outline-regexp)
5528 (1- (- (match-end 0) (match-beginning 0)))))
5530 (defvar org-font-lock-keywords nil)
5532 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5533 "Regular expression matching a property line.")
5535 (defvar org-font-lock-hook nil
5536 "Functions to be called for special font lock stuff.")
5538 (defvar org-font-lock-set-keywords-hook nil
5539 "Functions that can manipulate `org-font-lock-extra-keywords'.
5540 This is calles after `org-font-lock-extra-keywords' is defined, but before
5541 it is installed to be used by font lock. This can be useful if something
5542 needs to be inserted at a specific position in the font-lock sequence.")
5544 (defun org-font-lock-hook (limit)
5545 (run-hook-with-args 'org-font-lock-hook limit))
5547 (defun org-set-font-lock-defaults ()
5548 (let* ((em org-fontify-emphasized-text)
5549 (lk org-activate-links)
5550 (org-font-lock-extra-keywords
5551 (list
5552 ;; Call the hook
5553 '(org-font-lock-hook)
5554 ;; Headlines
5555 `(,(if org-fontify-whole-heading-line
5556 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5557 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5558 (1 (org-get-level-face 1))
5559 (2 (org-get-level-face 2))
5560 (3 (org-get-level-face 3)))
5561 ;; Table lines
5562 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5563 (1 'org-table t))
5564 ;; Table internals
5565 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5566 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5567 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5568 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5569 ;; Drawers
5570 (list org-drawer-regexp '(0 'org-special-keyword t))
5571 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5572 ;; Properties
5573 (list org-property-re
5574 '(1 'org-special-keyword t)
5575 '(3 'org-property-value t))
5576 ;; Links
5577 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5578 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5579 (if (memq 'plain lk) '(org-activate-plain-links))
5580 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5581 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5582 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5583 (if (memq 'footnote lk) '(org-activate-footnote-links
5584 (0 'org-footnote t)))
5585 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5586 '(org-hide-wide-columns (0 nil append))
5587 ;; TODO lines
5588 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
5589 '(1 (org-get-todo-face 1) t))
5590 ;; DONE
5591 (if org-fontify-done-headline
5592 (list (concat "^[*]+ +\\<\\("
5593 (mapconcat 'regexp-quote org-done-keywords "\\|")
5594 "\\)\\(.*\\)")
5595 '(2 'org-headline-done t))
5596 nil)
5597 ;; Priorities
5598 '(org-font-lock-add-priority-faces)
5599 ;; Tags
5600 '(org-font-lock-add-tag-faces)
5601 ;; Special keywords
5602 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5603 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5604 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5605 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5606 ;; Emphasis
5607 (if em
5608 (if (featurep 'xemacs)
5609 '(org-do-emphasis-faces (0 nil append))
5610 '(org-do-emphasis-faces)))
5611 ;; Checkboxes
5612 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5613 1 'org-checkbox prepend)
5614 (if (cdr (assq 'checkbox org-list-automatic-rules))
5615 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5616 (0 (org-get-checkbox-statistics-face) t)))
5617 ;; Description list items
5618 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5619 1 'bold prepend)
5620 ;; ARCHIVEd headings
5621 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5622 '(1 'org-archived prepend))
5623 ;; Specials
5624 '(org-do-latex-and-special-faces)
5625 '(org-fontify-entities)
5626 '(org-raise-scripts)
5627 ;; Code
5628 '(org-activate-code (1 'org-code t))
5629 ;; COMMENT
5630 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5631 "\\|" org-quote-string "\\)\\>")
5632 '(1 'org-special-keyword t))
5633 '("^#.*" (0 'font-lock-comment-face t))
5634 ;; Blocks and meta lines
5635 '(org-fontify-meta-lines-and-blocks)
5637 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5638 (run-hooks 'org-font-lock-set-keywords-hook)
5639 ;; Now set the full font-lock-keywords
5640 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5641 (org-set-local 'font-lock-defaults
5642 '(org-font-lock-keywords t nil nil backward-paragraph))
5643 (kill-local-variable 'font-lock-keywords) nil))
5645 (defun org-toggle-pretty-entities ()
5646 "Toggle the composition display of entities as UTF8 characters."
5647 (interactive)
5648 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5649 (org-restart-font-lock)
5650 (if org-pretty-entities
5651 (message "Entities are displayed as UTF8 characers")
5652 (save-restriction
5653 (widen)
5654 (org-decompose-region (point-min) (point-max))
5655 (message "Entities are displayed plain"))))
5657 (defun org-fontify-entities (limit)
5658 "Find an entity to fontify."
5659 (let (ee)
5660 (when org-pretty-entities
5661 (catch 'match
5662 (while (re-search-forward
5663 "\\\\\\([a-zA-Z][a-zA-Z0-9]*\\)\\($\\|[^[:alnum:]\n]\\)"
5664 limit t)
5665 (if (and (not (org-in-indented-comment-line))
5666 (setq ee (org-entity-get (match-string 1)))
5667 (= (length (nth 6 ee)) 1))
5668 (progn
5669 (add-text-properties
5670 (match-beginning 0) (match-end 1)
5671 (list 'font-lock-fontified t))
5672 (compose-region (match-beginning 0) (match-end 1)
5673 (nth 6 ee) nil)
5674 (backward-char 1)
5675 (throw 'match t))))
5676 nil))))
5678 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5679 "Fontify string S like in Org-mode."
5680 (with-temp-buffer
5681 (insert s)
5682 (let ((org-odd-levels-only odd-levels))
5683 (org-mode)
5684 (font-lock-fontify-buffer)
5685 (buffer-string))))
5687 (defvar org-m nil)
5688 (defvar org-l nil)
5689 (defvar org-f nil)
5690 (defun org-get-level-face (n)
5691 "Get the right face for match N in font-lock matching of headlines."
5692 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5693 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5694 (if org-cycle-level-faces
5695 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5696 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
5697 (cond
5698 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5699 ((eq n 2) org-f)
5700 (t (if org-level-color-stars-only nil org-f))))
5703 (defun org-get-todo-face (kwd)
5704 "Get the right face for a TODO keyword KWD.
5705 If KWD is a number, get the corresponding match group."
5706 (if (numberp kwd) (setq kwd (match-string kwd)))
5707 (or (org-face-from-face-or-color
5708 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5709 (and (member kwd org-done-keywords) 'org-done)
5710 'org-todo))
5712 (defun org-face-from-face-or-color (context inherit face-or-color)
5713 "Create a face list that inherits INHERIT, but sets the foreground color.
5714 When FACE-OR-COLOR is not a string, just return it."
5715 (if (stringp face-or-color)
5716 (list :inherit inherit
5717 (cdr (assoc context org-faces-easy-properties))
5718 face-or-color)
5719 face-or-color))
5721 (defun org-font-lock-add-tag-faces (limit)
5722 "Add the special tag faces."
5723 (when (and org-tag-faces org-tags-special-faces-re)
5724 (while (re-search-forward org-tags-special-faces-re limit t)
5725 (add-text-properties (match-beginning 1) (match-end 1)
5726 (list 'face (org-get-tag-face 1)
5727 'font-lock-fontified t))
5728 (backward-char 1))))
5730 (defun org-font-lock-add-priority-faces (limit)
5731 "Add the special priority faces."
5732 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5733 (add-text-properties
5734 (match-beginning 0) (match-end 0)
5735 (list 'face (or (org-face-from-face-or-color
5736 'priority 'org-special-keyword
5737 (cdr (assoc (char-after (match-beginning 1))
5738 org-priority-faces)))
5739 'org-special-keyword)
5740 'font-lock-fontified t))))
5742 (defun org-get-tag-face (kwd)
5743 "Get the right face for a TODO keyword KWD.
5744 If KWD is a number, get the corresponding match group."
5745 (if (numberp kwd) (setq kwd (match-string kwd)))
5746 (or (org-face-from-face-or-color
5747 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5748 'org-tag))
5750 (defun org-unfontify-region (beg end &optional maybe_loudly)
5751 "Remove fontification and activation overlays from links."
5752 (font-lock-default-unfontify-region beg end)
5753 (let* ((buffer-undo-list t)
5754 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5755 (inhibit-modification-hooks t)
5756 deactivate-mark buffer-file-name buffer-file-truename)
5757 (org-decompose-region beg end)
5758 (remove-text-properties
5759 beg end
5760 (if org-indent-mode
5761 ;; also remove line-prefix and wrap-prefix properties
5762 '(mouse-face t keymap t org-linked-text t
5763 invisible t intangible t
5764 line-prefix t wrap-prefix t
5765 org-no-flyspell t org-emphasis t)
5766 '(mouse-face t keymap t org-linked-text t
5767 invisible t intangible t
5768 org-no-flyspell t org-emphasis t)))
5769 (org-remove-font-lock-display-properties beg end)))
5771 (defconst org-script-display '(((raise -0.3) (height 0.7))
5772 ((raise 0.3) (height 0.7))
5773 ((raise -0.5))
5774 ((raise 0.5)))
5775 "Display properties for showing superscripts and subscripts.")
5777 (defun org-remove-font-lock-display-properties (beg end)
5778 "Remove specific display properties that have been added by font lock.
5779 The will remove the raise properties that are used to show superscripts
5780 and subscripts."
5781 (let (next prop)
5782 (while (< beg end)
5783 (setq next (next-single-property-change beg 'display nil end)
5784 prop (get-text-property beg 'display))
5785 (if (member prop org-script-display)
5786 (put-text-property beg next 'display nil))
5787 (setq beg next))))
5789 (defun org-raise-scripts (limit)
5790 "Add raise properties to sub/superscripts."
5791 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
5792 (if (re-search-forward
5793 (if (eq org-use-sub-superscripts t)
5794 org-match-substring-regexp
5795 org-match-substring-with-braces-regexp)
5796 limit t)
5797 (let* ((pos (point)) table-p comment-p
5798 (mpos (match-beginning 3))
5799 (emph-p (get-text-property mpos 'org-emphasis))
5800 (link-p (get-text-property mpos 'mouse-face))
5801 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
5802 (goto-char (point-at-bol))
5803 (setq table-p (org-looking-at-p org-table-dataline-regexp)
5804 comment-p (org-looking-at-p "[ \t]*#"))
5805 (goto-char pos)
5806 ;; FIXME: Should we go back one character here, for a_b^c
5807 ;; (goto-char (1- pos)) ;????????????????????
5808 (if (or comment-p emph-p link-p keyw-p)
5810 (put-text-property (match-beginning 3) (match-end 0)
5811 'display
5812 (if (equal (char-after (match-beginning 2)) ?^)
5813 (nth (if table-p 3 1) org-script-display)
5814 (nth (if table-p 2 0) org-script-display)))
5815 (add-text-properties (match-beginning 2) (match-end 2)
5816 (list 'invisible t
5817 'org-dwidth t 'org-dwidth-n 1))
5818 (if (and (eq (char-after (match-beginning 3)) ?{)
5819 (eq (char-before (match-end 3)) ?}))
5820 (progn
5821 (add-text-properties
5822 (match-beginning 3) (1+ (match-beginning 3))
5823 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
5824 (add-text-properties
5825 (1- (match-end 3)) (match-end 3)
5826 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
5827 t)))))
5829 ;;;; Visibility cycling, including org-goto and indirect buffer
5831 ;;; Cycling
5833 (defvar org-cycle-global-status nil)
5834 (make-variable-buffer-local 'org-cycle-global-status)
5835 (defvar org-cycle-subtree-status nil)
5836 (make-variable-buffer-local 'org-cycle-subtree-status)
5838 ;;;###autoload
5840 (defvar org-inlinetask-min-level)
5842 (defun org-cycle (&optional arg)
5843 "TAB-action and visibility cycling for Org-mode.
5845 This is the command invoked in Org-mode by the TAB key. Its main purpose
5846 is outline visibility cycling, but it also invokes other actions
5847 in special contexts.
5849 - When this function is called with a prefix argument, rotate the entire
5850 buffer through 3 states (global cycling)
5851 1. OVERVIEW: Show only top-level headlines.
5852 2. CONTENTS: Show all headlines of all levels, but no body text.
5853 3. SHOW ALL: Show everything.
5854 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5855 determined by the variable `org-startup-folded', and by any VISIBILITY
5856 properties in the buffer.
5857 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5858 including any drawers.
5860 - When inside a table, re-align the table and move to the next field.
5862 - When point is at the beginning of a headline, rotate the subtree started
5863 by this line through 3 different states (local cycling)
5864 1. FOLDED: Only the main headline is shown.
5865 2. CHILDREN: The main headline and the direct children are shown.
5866 From this state, you can move to one of the children
5867 and zoom in further.
5868 3. SUBTREE: Show the entire subtree, including body text.
5869 If there is no subtree, switch directly from CHILDREN to FOLDED.
5871 - When point is at the beginning of an empty headline and the variable
5872 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5873 of the headline by demoting and promoting it to likely levels. This
5874 speeds up creation document structure by pressing TAB once or several
5875 times right after creating a new headline.
5877 - When there is a numeric prefix, go up to a heading with level ARG, do
5878 a `show-subtree' and return to the previous cursor position. If ARG
5879 is negative, go up that many levels.
5881 - When point is not at the beginning of a headline, execute the global
5882 binding for TAB, which is re-indenting the line. See the option
5883 `org-cycle-emulate-tab' for details.
5885 - Special case: if point is at the beginning of the buffer and there is
5886 no headline in line 1, this function will act as if called with prefix arg
5887 (C-u TAB, same as S-TAB) also when called without prefix arg.
5888 But only if also the variable `org-cycle-global-at-bob' is t."
5889 (interactive "P")
5890 (org-load-modules-maybe)
5891 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5892 (and org-cycle-level-after-item/entry-creation
5893 (or (org-cycle-level)
5894 (org-cycle-item-indentation))))
5895 (let* ((limit-level
5896 (or org-cycle-max-level
5897 (and (boundp 'org-inlinetask-min-level)
5898 org-inlinetask-min-level
5899 (1- org-inlinetask-min-level))))
5900 (nstars (and limit-level
5901 (if org-odd-levels-only
5902 (and limit-level (1- (* limit-level 2)))
5903 limit-level)))
5904 (outline-regexp
5905 (if (not (org-mode-p))
5906 outline-regexp
5907 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
5908 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
5909 (not (looking-at outline-regexp))))
5910 (org-cycle-hook
5911 (if bob-special
5912 (delq 'org-optimize-window-after-visibility-change
5913 (copy-sequence org-cycle-hook))
5914 org-cycle-hook))
5915 (pos (point)))
5917 (if (or bob-special (equal arg '(4)))
5918 ;; special case: use global cycling
5919 (setq arg t))
5921 (cond
5923 ((equal arg '(16))
5924 (setq last-command 'dummy)
5925 (org-set-startup-visibility)
5926 (message "Startup visibility, plus VISIBILITY properties"))
5928 ((equal arg '(64))
5929 (show-all)
5930 (message "Entire buffer visible, including drawers"))
5932 ;; Table: enter it or move to the next field.
5933 ((org-at-table-p 'any)
5934 (if (org-at-table.el-p)
5935 (message "Use C-c ' to edit table.el tables")
5936 (if arg (org-table-edit-field t)
5937 (org-table-justify-field-maybe)
5938 (call-interactively 'org-table-next-field))))
5940 ((run-hook-with-args-until-success
5941 'org-tab-after-check-for-table-hook))
5943 ;; Global cycling: delegate to `org-cycle-internal-global'.
5944 ((eq arg t) (org-cycle-internal-global))
5946 ;; Drawers: delegate to `org-flag-drawer'.
5947 ((and org-drawers org-drawer-regexp
5948 (save-excursion
5949 (beginning-of-line 1)
5950 (looking-at org-drawer-regexp)))
5951 (org-flag-drawer ; toggle block visibility
5952 (not (get-char-property (match-end 0) 'invisible))))
5954 ;; Show-subtree, ARG levels up from here.
5955 ((integerp arg)
5956 (save-excursion
5957 (org-back-to-heading)
5958 (outline-up-heading (if (< arg 0) (- arg)
5959 (- (funcall outline-level) arg)))
5960 (org-show-subtree)))
5962 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
5963 ((and (featurep 'org-inlinetask)
5964 (org-inlinetask-at-task-p)
5965 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5966 (org-inlinetask-toggle-visibility))
5968 ;; At an item/headline: delegate to `org-cycle-internal-local'.
5969 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
5970 (save-excursion (beginning-of-line 1)
5971 (looking-at outline-regexp)))
5972 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5973 (org-cycle-internal-local))
5975 ;; From there: TAB emulation and template completion.
5976 (buffer-read-only (org-back-to-heading))
5978 ((run-hook-with-args-until-success
5979 'org-tab-after-check-for-cycling-hook))
5981 ((org-try-structure-completion))
5983 ((org-try-cdlatex-tab))
5985 ((run-hook-with-args-until-success
5986 'org-tab-before-tab-emulation-hook))
5988 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5989 (or (not (bolp))
5990 (not (looking-at outline-regexp))))
5991 (call-interactively (global-key-binding "\t")))
5993 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5994 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5995 (or (and (eq org-cycle-emulate-tab 'white)
5996 (= (match-end 0) (point-at-eol)))
5997 (and (eq org-cycle-emulate-tab 'whitestart)
5998 (>= (match-end 0) pos))))
6000 (eq org-cycle-emulate-tab t))
6001 (call-interactively (global-key-binding "\t")))
6003 (t (save-excursion
6004 (org-back-to-heading)
6005 (org-cycle)))))))
6007 (defun org-cycle-internal-global ()
6008 "Do the global cycling action."
6009 (cond
6010 ((and (eq last-command this-command)
6011 (eq org-cycle-global-status 'overview))
6012 ;; We just created the overview - now do table of contents
6013 ;; This can be slow in very large buffers, so indicate action
6014 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6015 (message "CONTENTS...")
6016 (org-content)
6017 (message "CONTENTS...done")
6018 (setq org-cycle-global-status 'contents)
6019 (run-hook-with-args 'org-cycle-hook 'contents))
6021 ((and (eq last-command this-command)
6022 (eq org-cycle-global-status 'contents))
6023 ;; We just showed the table of contents - now show everything
6024 (run-hook-with-args 'org-pre-cycle-hook 'all)
6025 (show-all)
6026 (message "SHOW ALL")
6027 (setq org-cycle-global-status 'all)
6028 (run-hook-with-args 'org-cycle-hook 'all))
6031 ;; Default action: go to overview
6032 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6033 (org-overview)
6034 (message "OVERVIEW")
6035 (setq org-cycle-global-status 'overview)
6036 (run-hook-with-args 'org-cycle-hook 'overview))))
6038 (defun org-cycle-internal-local ()
6039 "Do the local cycling action."
6040 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6041 ;; First, determine end of headline (EOH), end of subtree or item
6042 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6043 (save-excursion
6044 (if (org-at-item-p)
6045 (progn
6046 (beginning-of-line)
6047 (setq struct (org-list-struct))
6048 (setq eoh (point-at-eol))
6049 (setq eos (org-list-get-item-end-before-blank (point) struct))
6050 (setq has-children (org-list-has-child-p (point) struct)))
6051 (org-back-to-heading)
6052 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6053 (setq eos (save-excursion
6054 (org-end-of-subtree t)
6055 (unless (eobp)
6056 (skip-chars-forward " \t\n"))
6057 (if (eobp) (point) (1- (point)))))
6058 (setq has-children
6059 (or (save-excursion
6060 (let ((level (funcall outline-level)))
6061 (outline-next-heading)
6062 (and (org-at-heading-p t)
6063 (> (funcall outline-level) level))))
6064 (save-excursion
6065 (org-list-search-forward (org-item-beginning-re) eos t)))))
6066 ;; Determine end invisible part of buffer (EOL)
6067 (beginning-of-line 2)
6068 ;; XEmacs doesn't have `next-single-char-property-change'
6069 (if (featurep 'xemacs)
6070 (while (and (not (eobp)) ;; this is like `next-line'
6071 (get-char-property (1- (point)) 'invisible))
6072 (beginning-of-line 2))
6073 (while (and (not (eobp)) ;; this is like `next-line'
6074 (get-char-property (1- (point)) 'invisible))
6075 (goto-char (next-single-char-property-change (point) 'invisible))
6076 (and (eolp) (beginning-of-line 2))))
6077 (setq eol (point)))
6078 ;; Find out what to do next and set `this-command'
6079 (cond
6080 ((= eos eoh)
6081 ;; Nothing is hidden behind this heading
6082 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6083 (message "EMPTY ENTRY")
6084 (setq org-cycle-subtree-status nil)
6085 (save-excursion
6086 (goto-char eos)
6087 (outline-next-heading)
6088 (if (outline-invisible-p) (org-flag-heading nil))))
6089 ((and (or (>= eol eos)
6090 (not (string-match "\\S-" (buffer-substring eol eos))))
6091 (or has-children
6092 (not (setq children-skipped
6093 org-cycle-skip-children-state-if-no-children))))
6094 ;; Entire subtree is hidden in one line: children view
6095 (run-hook-with-args 'org-pre-cycle-hook 'children)
6096 (if (org-at-item-p)
6097 (org-list-set-item-visibility (point-at-bol) struct 'children)
6098 (org-show-entry)
6099 (show-children)
6100 ;; Fold every list in subtree to top-level items.
6101 (when (eq org-cycle-include-plain-lists 'integrate)
6102 (save-excursion
6103 (org-back-to-heading)
6104 (while (org-list-search-forward (org-item-beginning-re) eos t)
6105 (beginning-of-line 1)
6106 (let* ((struct (org-list-struct))
6107 (prevs (org-list-prevs-alist struct))
6108 (end (org-list-get-bottom-point struct)))
6109 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6110 (org-list-get-all-items (point) struct prevs))
6111 (goto-char end))))))
6112 (message "CHILDREN")
6113 (save-excursion
6114 (goto-char eos)
6115 (outline-next-heading)
6116 (if (outline-invisible-p) (org-flag-heading nil)))
6117 (setq org-cycle-subtree-status 'children)
6118 (run-hook-with-args 'org-cycle-hook 'children))
6119 ((or children-skipped
6120 (and (eq last-command this-command)
6121 (eq org-cycle-subtree-status 'children)))
6122 ;; We just showed the children, or no children are there,
6123 ;; now show everything.
6124 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6125 (outline-flag-region eoh eos nil)
6126 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6127 (setq org-cycle-subtree-status 'subtree)
6128 (run-hook-with-args 'org-cycle-hook 'subtree))
6130 ;; Default action: hide the subtree.
6131 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6132 (outline-flag-region eoh eos t)
6133 (message "FOLDED")
6134 (setq org-cycle-subtree-status 'folded)
6135 (run-hook-with-args 'org-cycle-hook 'folded)))))
6137 ;;;###autoload
6138 (defun org-global-cycle (&optional arg)
6139 "Cycle the global visibility. For details see `org-cycle'.
6140 With \\[universal-argument] prefix arg, switch to startup visibility.
6141 With a numeric prefix, show all headlines up to that level."
6142 (interactive "P")
6143 (let ((org-cycle-include-plain-lists
6144 (if (org-mode-p) org-cycle-include-plain-lists nil)))
6145 (cond
6146 ((integerp arg)
6147 (show-all)
6148 (hide-sublevels arg)
6149 (setq org-cycle-global-status 'contents))
6150 ((equal arg '(4))
6151 (org-set-startup-visibility)
6152 (message "Startup visibility, plus VISIBILITY properties."))
6154 (org-cycle '(4))))))
6156 (defun org-set-startup-visibility ()
6157 "Set the visibility required by startup options and properties."
6158 (cond
6159 ((eq org-startup-folded t)
6160 (org-cycle '(4)))
6161 ((eq org-startup-folded 'content)
6162 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6163 (org-cycle '(4)) (org-cycle '(4)))))
6164 (unless (eq org-startup-folded 'showeverything)
6165 (if org-hide-block-startup (org-hide-block-all))
6166 (org-set-visibility-according-to-property 'no-cleanup)
6167 (org-cycle-hide-archived-subtrees 'all)
6168 (org-cycle-hide-drawers 'all)
6169 (org-cycle-show-empty-lines t)))
6171 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6172 "Switch subtree visibilities according to :VISIBILITY: property."
6173 (interactive)
6174 (let (org-show-entry-below state)
6175 (save-excursion
6176 (goto-char (point-min))
6177 (while (re-search-forward
6178 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6179 nil t)
6180 (setq state (match-string 1))
6181 (save-excursion
6182 (org-back-to-heading t)
6183 (hide-subtree)
6184 (org-reveal)
6185 (cond
6186 ((equal state '("fold" "folded"))
6187 (hide-subtree))
6188 ((equal state "children")
6189 (org-show-hidden-entry)
6190 (show-children))
6191 ((equal state "content")
6192 (save-excursion
6193 (save-restriction
6194 (org-narrow-to-subtree)
6195 (org-content))))
6196 ((member state '("all" "showall"))
6197 (show-subtree)))))
6198 (unless no-cleanup
6199 (org-cycle-hide-archived-subtrees 'all)
6200 (org-cycle-hide-drawers 'all)
6201 (org-cycle-show-empty-lines 'all)))))
6203 (defun org-overview ()
6204 "Switch to overview mode, showing only top-level headlines.
6205 Really, this shows all headlines with level equal or greater than the level
6206 of the first headline in the buffer. This is important, because if the
6207 first headline is not level one, then (hide-sublevels 1) gives confusing
6208 results."
6209 (interactive)
6210 (let ((level (save-excursion
6211 (goto-char (point-min))
6212 (if (re-search-forward (concat "^" outline-regexp) nil t)
6213 (progn
6214 (goto-char (match-beginning 0))
6215 (funcall outline-level))))))
6216 (and level (hide-sublevels level))))
6218 (defun org-content (&optional arg)
6219 "Show all headlines in the buffer, like a table of contents.
6220 With numerical argument N, show content up to level N."
6221 (interactive "P")
6222 (save-excursion
6223 ;; Visit all headings and show their offspring
6224 (and (integerp arg) (org-overview))
6225 (goto-char (point-max))
6226 (catch 'exit
6227 (while (and (progn (condition-case nil
6228 (outline-previous-visible-heading 1)
6229 (error (goto-char (point-min))))
6231 (looking-at outline-regexp))
6232 (if (integerp arg)
6233 (show-children (1- arg))
6234 (show-branches))
6235 (if (bobp) (throw 'exit nil))))))
6238 (defun org-optimize-window-after-visibility-change (state)
6239 "Adjust the window after a change in outline visibility.
6240 This function is the default value of the hook `org-cycle-hook'."
6241 (when (get-buffer-window (current-buffer))
6242 (cond
6243 ((eq state 'content) nil)
6244 ((eq state 'all) nil)
6245 ((eq state 'folded) nil)
6246 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6247 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6249 (defun org-remove-empty-overlays-at (pos)
6250 "Remove outline overlays that do not contain non-white stuff."
6251 (mapc
6252 (lambda (o)
6253 (and (eq 'outline (overlay-get o 'invisible))
6254 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6255 (overlay-end o))))
6256 (delete-overlay o)))
6257 (overlays-at pos)))
6259 (defun org-clean-visibility-after-subtree-move ()
6260 "Fix visibility issues after moving a subtree."
6261 ;; First, find a reasonable region to look at:
6262 ;; Start two siblings above, end three below
6263 (let* ((beg (save-excursion
6264 (and (org-get-last-sibling)
6265 (org-get-last-sibling))
6266 (point)))
6267 (end (save-excursion
6268 (and (org-get-next-sibling)
6269 (org-get-next-sibling)
6270 (org-get-next-sibling))
6271 (if (org-at-heading-p)
6272 (point-at-eol)
6273 (point))))
6274 (level (looking-at "\\*+"))
6275 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6276 (save-excursion
6277 (save-restriction
6278 (narrow-to-region beg end)
6279 (when re
6280 ;; Properly fold already folded siblings
6281 (goto-char (point-min))
6282 (while (re-search-forward re nil t)
6283 (if (and (not (outline-invisible-p))
6284 (save-excursion
6285 (goto-char (point-at-eol)) (outline-invisible-p)))
6286 (hide-entry))))
6287 (org-cycle-show-empty-lines 'overview)
6288 (org-cycle-hide-drawers 'overview)))))
6290 (defun org-cycle-show-empty-lines (state)
6291 "Show empty lines above all visible headlines.
6292 The region to be covered depends on STATE when called through
6293 `org-cycle-hook'. Lisp program can use t for STATE to get the
6294 entire buffer covered. Note that an empty line is only shown if there
6295 are at least `org-cycle-separator-lines' empty lines before the headline."
6296 (when (not (= org-cycle-separator-lines 0))
6297 (save-excursion
6298 (let* ((n (abs org-cycle-separator-lines))
6299 (re (cond
6300 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6301 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6302 (t (let ((ns (number-to-string (- n 2))))
6303 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6304 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6305 beg end b e)
6306 (cond
6307 ((memq state '(overview contents t))
6308 (setq beg (point-min) end (point-max)))
6309 ((memq state '(children folded))
6310 (setq beg (point) end (progn (org-end-of-subtree t t)
6311 (beginning-of-line 2)
6312 (point)))))
6313 (when beg
6314 (goto-char beg)
6315 (while (re-search-forward re end t)
6316 (unless (get-char-property (match-end 1) 'invisible)
6317 (setq e (match-end 1))
6318 (if (< org-cycle-separator-lines 0)
6319 (setq b (save-excursion
6320 (goto-char (match-beginning 0))
6321 (org-back-over-empty-lines)
6322 (if (save-excursion
6323 (goto-char (max (point-min) (1- (point))))
6324 (org-on-heading-p))
6325 (1- (point))
6326 (point))))
6327 (setq b (match-beginning 1)))
6328 (outline-flag-region b e nil)))))))
6329 ;; Never hide empty lines at the end of the file.
6330 (save-excursion
6331 (goto-char (point-max))
6332 (outline-previous-heading)
6333 (outline-end-of-heading)
6334 (if (and (looking-at "[ \t\n]+")
6335 (= (match-end 0) (point-max)))
6336 (outline-flag-region (point) (match-end 0) nil))))
6338 (defun org-show-empty-lines-in-parent ()
6339 "Move to the parent and re-show empty lines before visible headlines."
6340 (save-excursion
6341 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6342 (org-cycle-show-empty-lines context))))
6344 (defun org-files-list ()
6345 "Return `org-agenda-files' list, plus all open org-mode files.
6346 This is useful for operations that need to scan all of a user's
6347 open and agenda-wise Org files."
6348 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6349 (dolist (buf (buffer-list))
6350 (with-current-buffer buf
6351 (if (and (org-mode-p) (buffer-file-name))
6352 (let ((file (expand-file-name (buffer-file-name))))
6353 (unless (member file files)
6354 (push file files))))))
6355 files))
6357 (defsubst org-entry-beginning-position ()
6358 "Return the beginning position of the current entry."
6359 (save-excursion (outline-back-to-heading t) (point)))
6361 (defsubst org-entry-end-position ()
6362 "Return the end position of the current entry."
6363 (save-excursion (outline-next-heading) (point)))
6365 (defun org-cycle-hide-drawers (state)
6366 "Re-hide all drawers after a visibility state change."
6367 (when (and (org-mode-p)
6368 (not (memq state '(overview folded contents))))
6369 (save-excursion
6370 (let* ((globalp (memq state '(contents all)))
6371 (beg (if globalp (point-min) (point)))
6372 (end (if globalp (point-max)
6373 (if (eq state 'children)
6374 (save-excursion (outline-next-heading) (point))
6375 (org-end-of-subtree t)))))
6376 (goto-char beg)
6377 (while (re-search-forward org-drawer-regexp end t)
6378 (org-flag-drawer t))))))
6380 (defun org-flag-drawer (flag)
6381 (save-excursion
6382 (beginning-of-line 1)
6383 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6384 (let ((b (match-end 0))
6385 (outline-regexp org-outline-regexp))
6386 (if (re-search-forward
6387 "^[ \t]*:END:"
6388 (save-excursion (outline-next-heading) (point)) t)
6389 (outline-flag-region b (point-at-eol) flag)
6390 (error ":END: line missing at position %s" b))))))
6392 (defun org-subtree-end-visible-p ()
6393 "Is the end of the current subtree visible?"
6394 (pos-visible-in-window-p
6395 (save-excursion (org-end-of-subtree t) (point))))
6397 (defun org-first-headline-recenter (&optional N)
6398 "Move cursor to the first headline and recenter the headline.
6399 Optional argument N means put the headline into the Nth line of the window."
6400 (goto-char (point-min))
6401 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
6402 (beginning-of-line)
6403 (recenter (prefix-numeric-value N))))
6405 ;;; Saving and restoring visibility
6407 (defun org-outline-overlay-data (&optional use-markers)
6408 "Return a list of the locations of all outline overlays.
6409 These are overlays with the `invisible' property value `outline'.
6410 The return value is a list of cons cells, with start and stop
6411 positions for each overlay.
6412 If USE-MARKERS is set, return the positions as markers."
6413 (let (beg end)
6414 (save-excursion
6415 (save-restriction
6416 (widen)
6417 (delq nil
6418 (mapcar (lambda (o)
6419 (when (eq (overlay-get o 'invisible) 'outline)
6420 (setq beg (overlay-start o)
6421 end (overlay-end o))
6422 (and beg end (> end beg)
6423 (if use-markers
6424 (cons (move-marker (make-marker) beg)
6425 (move-marker (make-marker) end))
6426 (cons beg end)))))
6427 (overlays-in (point-min) (point-max))))))))
6429 (defun org-set-outline-overlay-data (data)
6430 "Create visibility overlays for all positions in DATA.
6431 DATA should have been made by `org-outline-overlay-data'."
6432 (let (o)
6433 (save-excursion
6434 (save-restriction
6435 (widen)
6436 (show-all)
6437 (mapc (lambda (c)
6438 (setq o (make-overlay (car c) (cdr c)))
6439 (overlay-put o 'invisible 'outline))
6440 data)))))
6442 ;;; Folding of blocks
6444 (defconst org-block-regexp
6445 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
6446 "Regular expression for hiding blocks.")
6448 (defvar org-hide-block-overlays nil
6449 "Overlays hiding blocks.")
6450 (make-variable-buffer-local 'org-hide-block-overlays)
6452 (defun org-block-map (function &optional start end)
6453 "Call FUNCTION at the head of all source blocks in the current buffer.
6454 Optional arguments START and END can be used to limit the range."
6455 (let ((start (or start (point-min)))
6456 (end (or end (point-max))))
6457 (save-excursion
6458 (goto-char start)
6459 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6460 (save-excursion
6461 (save-match-data
6462 (goto-char (match-beginning 0))
6463 (funcall function)))))))
6465 (defun org-hide-block-toggle-all ()
6466 "Toggle the visibility of all blocks in the current buffer."
6467 (org-block-map #'org-hide-block-toggle))
6469 (defun org-hide-block-all ()
6470 "Fold all blocks in the current buffer."
6471 (interactive)
6472 (org-show-block-all)
6473 (org-block-map #'org-hide-block-toggle-maybe))
6475 (defun org-show-block-all ()
6476 "Unfold all blocks in the current buffer."
6477 (interactive)
6478 (mapc 'delete-overlay org-hide-block-overlays)
6479 (setq org-hide-block-overlays nil))
6481 (defun org-hide-block-toggle-maybe ()
6482 "Toggle visibility of block at point."
6483 (interactive)
6484 (let ((case-fold-search t))
6485 (if (save-excursion
6486 (beginning-of-line 1)
6487 (looking-at org-block-regexp))
6488 (progn (org-hide-block-toggle)
6489 t) ;; to signal that we took action
6490 nil))) ;; to signal that we did not
6492 (defun org-hide-block-toggle (&optional force)
6493 "Toggle the visibility of the current block."
6494 (interactive)
6495 (save-excursion
6496 (beginning-of-line)
6497 (if (re-search-forward org-block-regexp nil t)
6498 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6499 (end (match-end 0)) ;; end of entire body
6501 (if (memq t (mapcar (lambda (overlay)
6502 (eq (overlay-get overlay 'invisible)
6503 'org-hide-block))
6504 (overlays-at start)))
6505 (if (or (not force) (eq force 'off))
6506 (mapc (lambda (ov)
6507 (when (member ov org-hide-block-overlays)
6508 (setq org-hide-block-overlays
6509 (delq ov org-hide-block-overlays)))
6510 (when (eq (overlay-get ov 'invisible)
6511 'org-hide-block)
6512 (delete-overlay ov)))
6513 (overlays-at start)))
6514 (setq ov (make-overlay start end))
6515 (overlay-put ov 'invisible 'org-hide-block)
6516 ;; make the block accessible to isearch
6517 (overlay-put
6518 ov 'isearch-open-invisible
6519 (lambda (ov)
6520 (when (member ov org-hide-block-overlays)
6521 (setq org-hide-block-overlays
6522 (delq ov org-hide-block-overlays)))
6523 (when (eq (overlay-get ov 'invisible)
6524 'org-hide-block)
6525 (delete-overlay ov))))
6526 (push ov org-hide-block-overlays)))
6527 (error "Not looking at a source block"))))
6529 ;; org-tab-after-check-for-cycling-hook
6530 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6531 ;; Remove overlays when changing major mode
6532 (add-hook 'org-mode-hook
6533 (lambda () (org-add-hook 'change-major-mode-hook
6534 'org-show-block-all 'append 'local)))
6536 ;;; Org-goto
6538 (defvar org-goto-window-configuration nil)
6539 (defvar org-goto-marker nil)
6540 (defvar org-goto-map
6541 (let ((map (make-sparse-keymap)))
6542 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6543 (while (setq cmd (pop cmds))
6544 (substitute-key-definition cmd cmd map global-map)))
6545 (suppress-keymap map)
6546 (org-defkey map "\C-m" 'org-goto-ret)
6547 (org-defkey map [(return)] 'org-goto-ret)
6548 (org-defkey map [(left)] 'org-goto-left)
6549 (org-defkey map [(right)] 'org-goto-right)
6550 (org-defkey map [(control ?g)] 'org-goto-quit)
6551 (org-defkey map "\C-i" 'org-cycle)
6552 (org-defkey map [(tab)] 'org-cycle)
6553 (org-defkey map [(down)] 'outline-next-visible-heading)
6554 (org-defkey map [(up)] 'outline-previous-visible-heading)
6555 (if org-goto-auto-isearch
6556 (if (fboundp 'define-key-after)
6557 (define-key-after map [t] 'org-goto-local-auto-isearch)
6558 nil)
6559 (org-defkey map "q" 'org-goto-quit)
6560 (org-defkey map "n" 'outline-next-visible-heading)
6561 (org-defkey map "p" 'outline-previous-visible-heading)
6562 (org-defkey map "f" 'outline-forward-same-level)
6563 (org-defkey map "b" 'outline-backward-same-level)
6564 (org-defkey map "u" 'outline-up-heading))
6565 (org-defkey map "/" 'org-occur)
6566 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6567 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6568 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6569 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6570 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6571 map))
6573 (defconst org-goto-help
6574 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6575 RET=jump to location [Q]uit and return to previous location
6576 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6578 (defvar org-goto-start-pos) ; dynamically scoped parameter
6580 ;; FIXME: Docstring does not mention both interfaces
6581 (defun org-goto (&optional alternative-interface)
6582 "Look up a different location in the current file, keeping current visibility.
6584 When you want look-up or go to a different location in a document, the
6585 fastest way is often to fold the entire buffer and then dive into the tree.
6586 This method has the disadvantage, that the previous location will be folded,
6587 which may not be what you want.
6589 This command works around this by showing a copy of the current buffer
6590 in an indirect buffer, in overview mode. You can dive into the tree in
6591 that copy, use org-occur and incremental search to find a location.
6592 When pressing RET or `Q', the command returns to the original buffer in
6593 which the visibility is still unchanged. After RET is will also jump to
6594 the location selected in the indirect buffer and expose the headline
6595 hierarchy above."
6596 (interactive "P")
6597 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6598 (org-refile-use-outline-path t)
6599 (org-refile-target-verify-function nil)
6600 (interface
6601 (if (not alternative-interface)
6602 org-goto-interface
6603 (if (eq org-goto-interface 'outline)
6604 'outline-path-completion
6605 'outline)))
6606 (org-goto-start-pos (point))
6607 (selected-point
6608 (if (eq interface 'outline)
6609 (car (org-get-location (current-buffer) org-goto-help))
6610 (let ((pa (org-refile-get-location "Goto")))
6611 (org-refile-check-position pa)
6612 (nth 3 pa)))))
6613 (if selected-point
6614 (progn
6615 (org-mark-ring-push org-goto-start-pos)
6616 (goto-char selected-point)
6617 (if (or (outline-invisible-p) (org-invisible-p2))
6618 (org-show-context 'org-goto)))
6619 (message "Quit"))))
6621 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6622 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6623 (defvar org-goto-local-auto-isearch-map) ; defined below
6625 (defun org-get-location (buf help)
6626 "Let the user select a location in the Org-mode buffer BUF.
6627 This function uses a recursive edit. It returns the selected position
6628 or nil."
6629 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6630 (isearch-hide-immediately nil)
6631 (isearch-search-fun-function
6632 (lambda () 'org-goto-local-search-headings))
6633 (org-goto-selected-point org-goto-exit-command)
6634 (pop-up-frames nil)
6635 (special-display-buffer-names nil)
6636 (special-display-regexps nil)
6637 (special-display-function nil))
6638 (save-excursion
6639 (save-window-excursion
6640 (delete-other-windows)
6641 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6642 (switch-to-buffer
6643 (condition-case nil
6644 (make-indirect-buffer (current-buffer) "*org-goto*")
6645 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6646 (with-output-to-temp-buffer "*Help*"
6647 (princ help))
6648 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6649 (setq buffer-read-only nil)
6650 (let ((org-startup-truncated t)
6651 (org-startup-folded nil)
6652 (org-startup-align-all-tables nil))
6653 (org-mode)
6654 (org-overview))
6655 (setq buffer-read-only t)
6656 (if (and (boundp 'org-goto-start-pos)
6657 (integer-or-marker-p org-goto-start-pos))
6658 (let ((org-show-hierarchy-above t)
6659 (org-show-siblings t)
6660 (org-show-following-heading t))
6661 (goto-char org-goto-start-pos)
6662 (and (outline-invisible-p) (org-show-context)))
6663 (goto-char (point-min)))
6664 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6665 (message "Select location and press RET")
6666 (use-local-map org-goto-map)
6667 (recursive-edit)
6669 (kill-buffer "*org-goto*")
6670 (cons org-goto-selected-point org-goto-exit-command)))
6672 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6673 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6674 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6675 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6677 (defun org-goto-local-search-headings (string bound noerror)
6678 "Search and make sure that any matches are in headlines."
6679 (catch 'return
6680 (while (if isearch-forward
6681 (search-forward string bound noerror)
6682 (search-backward string bound noerror))
6683 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6684 (and (member :headline context)
6685 (not (member :tags context))))
6686 (throw 'return (point))))))
6688 (defun org-goto-local-auto-isearch ()
6689 "Start isearch."
6690 (interactive)
6691 (goto-char (point-min))
6692 (let ((keys (this-command-keys)))
6693 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6694 (isearch-mode t)
6695 (isearch-process-search-char (string-to-char keys)))))
6697 (defun org-goto-ret (&optional arg)
6698 "Finish `org-goto' by going to the new location."
6699 (interactive "P")
6700 (setq org-goto-selected-point (point)
6701 org-goto-exit-command 'return)
6702 (throw 'exit nil))
6704 (defun org-goto-left ()
6705 "Finish `org-goto' by going to the new location."
6706 (interactive)
6707 (if (org-on-heading-p)
6708 (progn
6709 (beginning-of-line 1)
6710 (setq org-goto-selected-point (point)
6711 org-goto-exit-command 'left)
6712 (throw 'exit nil))
6713 (error "Not on a heading")))
6715 (defun org-goto-right ()
6716 "Finish `org-goto' by going to the new location."
6717 (interactive)
6718 (if (org-on-heading-p)
6719 (progn
6720 (setq org-goto-selected-point (point)
6721 org-goto-exit-command 'right)
6722 (throw 'exit nil))
6723 (error "Not on a heading")))
6725 (defun org-goto-quit ()
6726 "Finish `org-goto' without cursor motion."
6727 (interactive)
6728 (setq org-goto-selected-point nil)
6729 (setq org-goto-exit-command 'quit)
6730 (throw 'exit nil))
6732 ;;; Indirect buffer display of subtrees
6734 (defvar org-indirect-dedicated-frame nil
6735 "This is the frame being used for indirect tree display.")
6736 (defvar org-last-indirect-buffer nil)
6738 (defun org-tree-to-indirect-buffer (&optional arg)
6739 "Create indirect buffer and narrow it to current subtree.
6740 With numerical prefix ARG, go up to this level and then take that tree.
6741 If ARG is negative, go up that many levels.
6742 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6743 indirect buffer previously made with this command, to avoid proliferation of
6744 indirect buffers. However, when you call the command with a \
6745 \\[universal-argument] prefix, or
6746 when `org-indirect-buffer-display' is `new-frame', the last buffer
6747 is kept so that you can work with several indirect buffers at the same time.
6748 If `org-indirect-buffer-display' is `dedicated-frame', the \
6749 \\[universal-argument] prefix also
6750 requests that a new frame be made for the new buffer, so that the dedicated
6751 frame is not changed."
6752 (interactive "P")
6753 (let ((cbuf (current-buffer))
6754 (cwin (selected-window))
6755 (pos (point))
6756 beg end level heading ibuf)
6757 (save-excursion
6758 (org-back-to-heading t)
6759 (when (numberp arg)
6760 (setq level (org-outline-level))
6761 (if (< arg 0) (setq arg (+ level arg)))
6762 (while (> (setq level (org-outline-level)) arg)
6763 (outline-up-heading 1 t)))
6764 (setq beg (point)
6765 heading (org-get-heading))
6766 (org-end-of-subtree t t)
6767 (if (org-on-heading-p) (backward-char 1))
6768 (setq end (point)))
6769 (if (and (buffer-live-p org-last-indirect-buffer)
6770 (not (eq org-indirect-buffer-display 'new-frame))
6771 (not arg))
6772 (kill-buffer org-last-indirect-buffer))
6773 (setq ibuf (org-get-indirect-buffer cbuf)
6774 org-last-indirect-buffer ibuf)
6775 (cond
6776 ((or (eq org-indirect-buffer-display 'new-frame)
6777 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6778 (select-frame (make-frame))
6779 (delete-other-windows)
6780 (switch-to-buffer ibuf)
6781 (org-set-frame-title heading))
6782 ((eq org-indirect-buffer-display 'dedicated-frame)
6783 (raise-frame
6784 (select-frame (or (and org-indirect-dedicated-frame
6785 (frame-live-p org-indirect-dedicated-frame)
6786 org-indirect-dedicated-frame)
6787 (setq org-indirect-dedicated-frame (make-frame)))))
6788 (delete-other-windows)
6789 (switch-to-buffer ibuf)
6790 (org-set-frame-title (concat "Indirect: " heading)))
6791 ((eq org-indirect-buffer-display 'current-window)
6792 (switch-to-buffer ibuf))
6793 ((eq org-indirect-buffer-display 'other-window)
6794 (pop-to-buffer ibuf))
6795 (t (error "Invalid value")))
6796 (if (featurep 'xemacs)
6797 (save-excursion (org-mode) (turn-on-font-lock)))
6798 (narrow-to-region beg end)
6799 (show-all)
6800 (goto-char pos)
6801 (and (window-live-p cwin) (select-window cwin))))
6803 (defun org-get-indirect-buffer (&optional buffer)
6804 (setq buffer (or buffer (current-buffer)))
6805 (let ((n 1) (base (buffer-name buffer)) bname)
6806 (while (buffer-live-p
6807 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6808 (setq n (1+ n)))
6809 (condition-case nil
6810 (make-indirect-buffer buffer bname 'clone)
6811 (error (make-indirect-buffer buffer bname)))))
6813 (defun org-set-frame-title (title)
6814 "Set the title of the current frame to the string TITLE."
6815 ;; FIXME: how to name a single frame in XEmacs???
6816 (unless (featurep 'xemacs)
6817 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6819 ;;;; Structure editing
6821 ;;; Inserting headlines
6823 (defun org-previous-line-empty-p ()
6824 (save-excursion
6825 (and (not (bobp))
6826 (or (beginning-of-line 0) t)
6827 (save-match-data
6828 (looking-at "[ \t]*$")))))
6830 (defun org-insert-heading (&optional force-heading invisible-ok)
6831 "Insert a new heading or item with same depth at point.
6832 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6833 If point is at the beginning of a headline, insert a sibling before the
6834 current headline. If point is not at the beginning, split the line,
6835 create the new headline with the text in the current line after point
6836 \(but see also the variable `org-M-RET-may-split-line').
6838 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6839 This is important for non-interactive uses of the command."
6840 (interactive "P")
6841 (if (or (= (buffer-size) 0)
6842 (and (not (save-excursion
6843 (and (ignore-errors (org-back-to-heading invisible-ok))
6844 (org-on-heading-p))))
6845 (not (org-in-item-p))))
6846 (progn
6847 (insert "\n* ")
6848 (run-hooks 'org-insert-heading-hook))
6849 (when (or force-heading (not (org-insert-item)))
6850 (let* ((empty-line-p nil)
6851 (level nil)
6852 (on-heading (org-on-heading-p))
6853 (head (save-excursion
6854 (condition-case nil
6855 (progn
6856 (org-back-to-heading invisible-ok)
6857 (when (and (not on-heading)
6858 (featurep 'org-inlinetask)
6859 (integerp org-inlinetask-min-level)
6860 (>= (length (match-string 0))
6861 org-inlinetask-min-level))
6862 ;; Find a heading level before the inline task
6863 (while (and (setq level (org-up-heading-safe))
6864 (>= level org-inlinetask-min-level)))
6865 (if (org-on-heading-p)
6866 (org-back-to-heading invisible-ok)
6867 (error "This should not happen")))
6868 (setq empty-line-p (org-previous-line-empty-p))
6869 (match-string 0))
6870 (error "*"))))
6871 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6872 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6873 pos hide-previous previous-pos)
6874 (cond
6875 ((and (org-on-heading-p) (bolp)
6876 (or (bobp)
6877 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
6878 ;; insert before the current line
6879 (open-line (if blank 2 1)))
6880 ((and (bolp)
6881 (not org-insert-heading-respect-content)
6882 (or (bobp)
6883 (save-excursion
6884 (backward-char 1) (not (outline-invisible-p)))))
6885 ;; insert right here
6886 nil)
6888 ;; somewhere in the line
6889 (save-excursion
6890 (setq previous-pos (point-at-bol))
6891 (end-of-line)
6892 (setq hide-previous (outline-invisible-p)))
6893 (and org-insert-heading-respect-content (org-show-subtree))
6894 (let ((split
6895 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6896 (save-excursion
6897 (let ((p (point)))
6898 (goto-char (point-at-bol))
6899 (and (looking-at org-complex-heading-regexp)
6900 (> p (match-beginning 4)))))))
6901 tags pos)
6902 (cond
6903 (org-insert-heading-respect-content
6904 (org-end-of-subtree nil t)
6905 (when (featurep 'org-inlinetask)
6906 (while (and (not (eobp))
6907 (looking-at "\\(\\*+\\)[ \t]+")
6908 (>= (length (match-string 1))
6909 org-inlinetask-min-level))
6910 (org-end-of-subtree nil t)))
6911 (or (bolp) (newline))
6912 (or (org-previous-line-empty-p)
6913 (and blank (newline)))
6914 (open-line 1))
6915 ((org-on-heading-p)
6916 (when hide-previous
6917 (show-children)
6918 (org-show-entry))
6919 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
6920 (setq tags (and (match-end 2) (match-string 2)))
6921 (and (match-end 1)
6922 (delete-region (match-beginning 1) (match-end 1)))
6923 (setq pos (point-at-bol))
6924 (or split (end-of-line 1))
6925 (delete-horizontal-space)
6926 (if (string-match "\\`\\*+\\'"
6927 (buffer-substring (point-at-bol) (point)))
6928 (insert " "))
6929 (newline (if blank 2 1))
6930 (when tags
6931 (save-excursion
6932 (goto-char pos)
6933 (end-of-line 1)
6934 (insert " " tags)
6935 (org-set-tags nil 'align))))
6937 (or split (end-of-line 1))
6938 (newline (if blank 2 1)))))))
6939 (insert head) (just-one-space)
6940 (setq pos (point))
6941 (end-of-line 1)
6942 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6943 (when (and org-insert-heading-respect-content hide-previous)
6944 (save-excursion
6945 (goto-char previous-pos)
6946 (hide-subtree)))
6947 (run-hooks 'org-insert-heading-hook)))))
6949 (defun org-get-heading (&optional no-tags)
6950 "Return the heading of the current entry, without the stars."
6951 (save-excursion
6952 (org-back-to-heading t)
6953 (if (looking-at
6954 (if no-tags
6955 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@#%]+:[ \t]*\\)?$")
6956 "\\*+[ \t]+\\([^\r\n]*\\)"))
6957 (match-string 1) "")))
6959 (defun org-heading-components ()
6960 "Return the components of the current heading.
6961 This is a list with the following elements:
6962 - the level as an integer
6963 - the reduced level, different if `org-odd-levels-only' is set.
6964 - the TODO keyword, or nil
6965 - the priority character, like ?A, or nil if no priority is given
6966 - the headline text itself, or the tags string if no headline text
6967 - the tags string, or nil."
6968 (save-excursion
6969 (org-back-to-heading t)
6970 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6971 (list (length (match-string 1))
6972 (org-reduced-level (length (match-string 1)))
6973 (org-match-string-no-properties 2)
6974 (and (match-end 3) (aref (match-string 3) 2))
6975 (org-match-string-no-properties 4)
6976 (org-match-string-no-properties 5)))))
6978 (defun org-get-entry ()
6979 "Get the entry text, after heading, entire subtree."
6980 (save-excursion
6981 (org-back-to-heading t)
6982 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6984 (defun org-insert-heading-after-current ()
6985 "Insert a new heading with same level as current, after current subtree."
6986 (interactive)
6987 (org-back-to-heading)
6988 (org-insert-heading)
6989 (org-move-subtree-down)
6990 (end-of-line 1))
6992 (defun org-insert-heading-respect-content ()
6993 (interactive)
6994 (let ((org-insert-heading-respect-content t))
6995 (org-insert-heading t)))
6997 (defun org-insert-todo-heading-respect-content (&optional force-state)
6998 (interactive "P")
6999 (let ((org-insert-heading-respect-content t))
7000 (org-insert-todo-heading force-state t)))
7002 (defun org-insert-todo-heading (arg &optional force-heading)
7003 "Insert a new heading with the same level and TODO state as current heading.
7004 If the heading has no TODO state, or if the state is DONE, use the first
7005 state (TODO by default). Also with prefix arg, force first state."
7006 (interactive "P")
7007 (when (or force-heading (not (org-insert-item 'checkbox)))
7008 (org-insert-heading force-heading)
7009 (save-excursion
7010 (org-back-to-heading)
7011 (outline-previous-heading)
7012 (looking-at org-todo-line-regexp))
7013 (let*
7014 ((new-mark-x
7015 (if (or arg
7016 (not (match-beginning 2))
7017 (member (match-string 2) org-done-keywords))
7018 (car org-todo-keywords-1)
7019 (match-string 2)))
7020 (new-mark
7022 (run-hook-with-args-until-success
7023 'org-todo-get-default-hook new-mark-x nil)
7024 new-mark-x)))
7025 (beginning-of-line 1)
7026 (and (looking-at "\\*+ ") (goto-char (match-end 0))
7027 (if org-treat-insert-todo-heading-as-state-change
7028 (org-todo new-mark)
7029 (insert new-mark " "))))
7030 (when org-provide-todo-statistics
7031 (org-update-parent-todo-statistics))))
7033 (defun org-insert-subheading (arg)
7034 "Insert a new subheading and demote it.
7035 Works for outline headings and for plain lists alike."
7036 (interactive "P")
7037 (org-insert-heading arg)
7038 (cond
7039 ((org-on-heading-p) (org-do-demote))
7040 ((org-at-item-p) (org-indent-item))))
7042 (defun org-insert-todo-subheading (arg)
7043 "Insert a new subheading with TODO keyword or checkbox and demote it.
7044 Works for outline headings and for plain lists alike."
7045 (interactive "P")
7046 (org-insert-todo-heading arg)
7047 (cond
7048 ((org-on-heading-p) (org-do-demote))
7049 ((org-at-item-p) (org-indent-item))))
7051 ;;; Promotion and Demotion
7053 (defvar org-after-demote-entry-hook nil
7054 "Hook run after an entry has been demoted.
7055 The cursor will be at the beginning of the entry.
7056 When a subtree is being demoted, the hook will be called for each node.")
7058 (defvar org-after-promote-entry-hook nil
7059 "Hook run after an entry has been promoted.
7060 The cursor will be at the beginning of the entry.
7061 When a subtree is being promoted, the hook will be called for each node.")
7063 (defun org-promote-subtree ()
7064 "Promote the entire subtree.
7065 See also `org-promote'."
7066 (interactive)
7067 (save-excursion
7068 (org-with-limited-levels (org-map-tree 'org-promote)))
7069 (org-fix-position-after-promote))
7071 (defun org-demote-subtree ()
7072 "Demote the entire subtree. See `org-demote'.
7073 See also `org-promote'."
7074 (interactive)
7075 (save-excursion
7076 (org-with-limited-levels (org-map-tree 'org-demote)))
7077 (org-fix-position-after-promote))
7080 (defun org-do-promote ()
7081 "Promote the current heading higher up the tree.
7082 If the region is active in `transient-mark-mode', promote all headings
7083 in the region."
7084 (interactive)
7085 (save-excursion
7086 (if (org-region-active-p)
7087 (org-map-region 'org-promote (region-beginning) (region-end))
7088 (org-promote)))
7089 (org-fix-position-after-promote))
7091 (defun org-do-demote ()
7092 "Demote the current heading lower down the tree.
7093 If the region is active in `transient-mark-mode', demote all headings
7094 in the region."
7095 (interactive)
7096 (save-excursion
7097 (if (org-region-active-p)
7098 (org-map-region 'org-demote (region-beginning) (region-end))
7099 (org-demote)))
7100 (org-fix-position-after-promote))
7102 (defun org-fix-position-after-promote ()
7103 "Make sure that after pro/demotion cursor position is right."
7104 (let ((pos (point)))
7105 (when (save-excursion
7106 (beginning-of-line 1)
7107 (looking-at org-todo-line-regexp)
7108 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7109 (cond ((eobp) (insert " "))
7110 ((eolp) (insert " "))
7111 ((equal (char-after) ?\ ) (forward-char 1))))))
7113 (defun org-current-level ()
7114 "Return the level of the current entry, or nil if before the first headline.
7115 The level is the number of stars at the beginning of the headline."
7116 (save-excursion
7117 (org-with-limited-levels
7118 (ignore-errors
7119 (org-back-to-heading t)
7120 (funcall outline-level)))))
7122 (defun org-get-previous-line-level ()
7123 "Return the outline depth of the last headline before the current line.
7124 Returns 0 for the first headline in the buffer, and nil if before the
7125 first headline."
7126 (let ((current-level (org-current-level))
7127 (prev-level (when (> (line-number-at-pos) 1)
7128 (save-excursion
7129 (beginning-of-line 0)
7130 (org-current-level)))))
7131 (cond ((null current-level) nil) ; Before first headline
7132 ((null prev-level) 0) ; At first headline
7133 (prev-level))))
7135 (defun org-reduced-level (l)
7136 "Compute the effective level of a heading.
7137 This takes into account the setting of `org-odd-levels-only'."
7138 (cond
7139 ((zerop l) 0)
7140 (org-odd-levels-only (1+ (floor (/ l 2))))
7141 (t l)))
7143 (defun org-level-increment ()
7144 "Return the number of stars that will be added or removed at a
7145 time to headlines when structure editing, based on the value of
7146 `org-odd-levels-only'."
7147 (if org-odd-levels-only 2 1))
7149 (defun org-get-valid-level (level &optional change)
7150 "Rectify a level change under the influence of `org-odd-levels-only'
7151 LEVEL is a current level, CHANGE is by how much the level should be
7152 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7153 even level numbers will become the next higher odd number."
7154 (if org-odd-levels-only
7155 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7156 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7157 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7158 (max 1 (+ level (or change 0)))))
7160 (if (boundp 'define-obsolete-function-alias)
7161 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7162 (define-obsolete-function-alias 'org-get-legal-level
7163 'org-get-valid-level)
7164 (define-obsolete-function-alias 'org-get-legal-level
7165 'org-get-valid-level "23.1")))
7167 (defun org-promote ()
7168 "Promote the current heading higher up the tree.
7169 If the region is active in `transient-mark-mode', promote all headings
7170 in the region."
7171 (org-back-to-heading t)
7172 (let* ((level (save-match-data (funcall outline-level)))
7173 (after-change-functions (remove 'flyspell-after-change-function
7174 after-change-functions))
7175 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7176 (diff (abs (- level (length up-head) -1))))
7177 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
7178 (replace-match up-head nil t)
7179 ;; Fixup tag positioning
7180 (and org-auto-align-tags (org-set-tags nil t))
7181 (if org-adapt-indentation (org-fixup-indentation (- diff)))
7182 (run-hooks 'org-after-promote-entry-hook)))
7184 (defun org-demote ()
7185 "Demote the current heading lower down the tree.
7186 If the region is active in `transient-mark-mode', demote all headings
7187 in the region."
7188 (org-back-to-heading t)
7189 (let* ((level (save-match-data (funcall outline-level)))
7190 (after-change-functions (remove 'flyspell-after-change-function
7191 after-change-functions))
7192 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7193 (diff (abs (- level (length down-head) -1))))
7194 (replace-match down-head nil t)
7195 ;; Fixup tag positioning
7196 (and org-auto-align-tags (org-set-tags nil t))
7197 (if org-adapt-indentation (org-fixup-indentation diff))
7198 (run-hooks 'org-after-demote-entry-hook)))
7200 (defun org-cycle-level ()
7201 "Cycle the level of an empty headline through possible states.
7202 This goes first to child, then to parent, level, then up the hierarchy.
7203 After top level, it switches back to sibling level."
7204 (interactive)
7205 (let ((org-adapt-indentation nil))
7206 (when (org-point-at-end-of-empty-headline)
7207 (setq this-command 'org-cycle-level) ; Only needed for caching
7208 (let ((cur-level (org-current-level))
7209 (prev-level (org-get-previous-line-level)))
7210 (cond
7211 ;; If first headline in file, promote to top-level.
7212 ((= prev-level 0)
7213 (loop repeat (/ (- cur-level 1) (org-level-increment))
7214 do (org-do-promote)))
7215 ;; If same level as prev, demote one.
7216 ((= prev-level cur-level)
7217 (org-do-demote))
7218 ;; If parent is top-level, promote to top level if not already.
7219 ((= prev-level 1)
7220 (loop repeat (/ (- cur-level 1) (org-level-increment))
7221 do (org-do-promote)))
7222 ;; If top-level, return to prev-level.
7223 ((= cur-level 1)
7224 (loop repeat (/ (- prev-level 1) (org-level-increment))
7225 do (org-do-demote)))
7226 ;; If less than prev-level, promote one.
7227 ((< cur-level prev-level)
7228 (org-do-promote))
7229 ;; If deeper than prev-level, promote until higher than
7230 ;; prev-level.
7231 ((> cur-level prev-level)
7232 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7233 do (org-do-promote))))
7234 t))))
7236 (defun org-map-tree (fun)
7237 "Call FUN for every heading underneath the current one."
7238 (org-back-to-heading)
7239 (let ((level (funcall outline-level)))
7240 (save-excursion
7241 (funcall fun)
7242 (while (and (progn
7243 (outline-next-heading)
7244 (> (funcall outline-level) level))
7245 (not (eobp)))
7246 (funcall fun)))))
7248 (defun org-map-region (fun beg end)
7249 "Call FUN for every heading between BEG and END."
7250 (let ((org-ignore-region t))
7251 (save-excursion
7252 (setq end (copy-marker end))
7253 (goto-char beg)
7254 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
7255 (< (point) end))
7256 (funcall fun))
7257 (while (and (progn
7258 (outline-next-heading)
7259 (< (point) end))
7260 (not (eobp)))
7261 (funcall fun)))))
7263 (defun org-fixup-indentation (diff)
7264 "Change the indentation in the current entry by DIFF.
7265 However, if any line in the current entry has no indentation, or if it
7266 would end up with no indentation after the change, nothing at all is done."
7267 (save-excursion
7268 (let ((end (save-excursion (outline-next-heading)
7269 (point-marker)))
7270 (prohibit (if (> diff 0)
7271 "^\\S-"
7272 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7273 col)
7274 (unless (save-excursion (end-of-line 1)
7275 (re-search-forward prohibit end t))
7276 (while (and (< (point) end)
7277 (re-search-forward "^[ \t]+" end t))
7278 (goto-char (match-end 0))
7279 (setq col (current-column))
7280 (if (< diff 0) (replace-match ""))
7281 (org-indent-to-column (+ diff col))))
7282 (move-marker end nil))))
7284 (defun org-convert-to-odd-levels ()
7285 "Convert an org-mode file with all levels allowed to one with odd levels.
7286 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7287 level 5 etc."
7288 (interactive)
7289 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7290 (let ((outline-regexp org-outline-regexp)
7291 (outline-level 'org-outline-level)
7292 (org-odd-levels-only nil) n)
7293 (save-excursion
7294 (goto-char (point-min))
7295 (while (re-search-forward "^\\*\\*+ " nil t)
7296 (setq n (- (length (match-string 0)) 2))
7297 (while (>= (setq n (1- n)) 0)
7298 (org-demote))
7299 (end-of-line 1))))))
7301 (defun org-convert-to-oddeven-levels ()
7302 "Convert an org-mode file with only odd levels to one with odd/even levels.
7303 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7304 file contains a section with an even level, conversion would
7305 destroy the structure of the file. An error is signaled in this
7306 case."
7307 (interactive)
7308 (goto-char (point-min))
7309 ;; First check if there are no even levels
7310 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7311 (org-show-context t)
7312 (error "Not all levels are odd in this file. Conversion not possible"))
7313 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7314 (let ((outline-regexp org-outline-regexp)
7315 (outline-level 'org-outline-level)
7316 (org-odd-levels-only nil) n)
7317 (save-excursion
7318 (goto-char (point-min))
7319 (while (re-search-forward "^\\*\\*+ " nil t)
7320 (setq n (/ (1- (length (match-string 0))) 2))
7321 (while (>= (setq n (1- n)) 0)
7322 (org-promote))
7323 (end-of-line 1))))))
7325 (defun org-tr-level (n)
7326 "Make N odd if required."
7327 (if org-odd-levels-only (1+ (/ n 2)) n))
7329 ;;; Vertical tree motion, cutting and pasting of subtrees
7331 (defun org-move-subtree-up (&optional arg)
7332 "Move the current subtree up past ARG headlines of the same level."
7333 (interactive "p")
7334 (org-move-subtree-down (- (prefix-numeric-value arg))))
7336 (defun org-move-subtree-down (&optional arg)
7337 "Move the current subtree down past ARG headlines of the same level."
7338 (interactive "p")
7339 (setq arg (prefix-numeric-value arg))
7340 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7341 'org-get-last-sibling))
7342 (ins-point (make-marker))
7343 (cnt (abs arg))
7344 (col (current-column))
7345 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7346 ;; Select the tree
7347 (org-back-to-heading)
7348 (setq beg0 (point))
7349 (save-excursion
7350 (setq ne-beg (org-back-over-empty-lines))
7351 (setq beg (point)))
7352 (save-match-data
7353 (save-excursion (outline-end-of-heading)
7354 (setq folded (outline-invisible-p)))
7355 (outline-end-of-subtree))
7356 (outline-next-heading)
7357 (setq ne-end (org-back-over-empty-lines))
7358 (setq end (point))
7359 (goto-char beg0)
7360 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7361 ;; include less whitespace
7362 (save-excursion
7363 (goto-char beg)
7364 (forward-line (- ne-beg ne-end))
7365 (setq beg (point))))
7366 ;; Find insertion point, with error handling
7367 (while (> cnt 0)
7368 (or (and (funcall movfunc) (looking-at outline-regexp))
7369 (progn (goto-char beg0)
7370 (error "Cannot move past superior level or buffer limit")))
7371 (setq cnt (1- cnt)))
7372 (if (> arg 0)
7373 ;; Moving forward - still need to move over subtree
7374 (progn (org-end-of-subtree t t)
7375 (save-excursion
7376 (org-back-over-empty-lines)
7377 (or (bolp) (newline)))))
7378 (setq ne-ins (org-back-over-empty-lines))
7379 (move-marker ins-point (point))
7380 (setq txt (buffer-substring beg end))
7381 (org-save-markers-in-region beg end)
7382 (delete-region beg end)
7383 (org-remove-empty-overlays-at beg)
7384 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7385 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7386 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7387 (let ((bbb (point)))
7388 (insert-before-markers txt)
7389 (org-reinstall-markers-in-region bbb)
7390 (move-marker ins-point bbb))
7391 (or (bolp) (insert "\n"))
7392 (setq ins-end (point))
7393 (goto-char ins-point)
7394 (org-skip-whitespace)
7395 (when (and (< arg 0)
7396 (org-first-sibling-p)
7397 (> ne-ins ne-beg))
7398 ;; Move whitespace back to beginning
7399 (save-excursion
7400 (goto-char ins-end)
7401 (let ((kill-whole-line t))
7402 (kill-line (- ne-ins ne-beg)) (point)))
7403 (insert (make-string (- ne-ins ne-beg) ?\n)))
7404 (move-marker ins-point nil)
7405 (if folded
7406 (hide-subtree)
7407 (org-show-entry)
7408 (show-children)
7409 (org-cycle-hide-drawers 'children))
7410 (org-clean-visibility-after-subtree-move)
7411 ;; move back to the initial column we were at
7412 (move-to-column col)))
7414 (defvar org-subtree-clip ""
7415 "Clipboard for cut and paste of subtrees.
7416 This is actually only a copy of the kill, because we use the normal kill
7417 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7419 (defvar org-subtree-clip-folded nil
7420 "Was the last copied subtree folded?
7421 This is used to fold the tree back after pasting.")
7423 (defun org-cut-subtree (&optional n)
7424 "Cut the current subtree into the clipboard.
7425 With prefix arg N, cut this many sequential subtrees.
7426 This is a short-hand for marking the subtree and then cutting it."
7427 (interactive "p")
7428 (org-copy-subtree n 'cut))
7430 (defun org-copy-subtree (&optional n cut force-store-markers)
7431 "Cut the current subtree into the clipboard.
7432 With prefix arg N, cut this many sequential subtrees.
7433 This is a short-hand for marking the subtree and then copying it.
7434 If CUT is non-nil, actually cut the subtree.
7435 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7436 of some markers in the region, even if CUT is non-nil. This is
7437 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7438 (interactive "p")
7439 (let (beg end folded (beg0 (point)))
7440 (if (org-called-interactively-p 'any)
7441 (org-back-to-heading nil) ; take what looks like a subtree
7442 (org-back-to-heading t)) ; take what is really there
7443 (org-back-over-empty-lines)
7444 (setq beg (point))
7445 (skip-chars-forward " \t\r\n")
7446 (save-match-data
7447 (save-excursion (outline-end-of-heading)
7448 (setq folded (outline-invisible-p)))
7449 (condition-case nil
7450 (org-forward-same-level (1- n) t)
7451 (error nil))
7452 (org-end-of-subtree t t))
7453 (org-back-over-empty-lines)
7454 (setq end (point))
7455 (goto-char beg0)
7456 (when (> end beg)
7457 (setq org-subtree-clip-folded folded)
7458 (when (or cut force-store-markers)
7459 (org-save-markers-in-region beg end))
7460 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7461 (setq org-subtree-clip (current-kill 0))
7462 (message "%s: Subtree(s) with %d characters"
7463 (if cut "Cut" "Copied")
7464 (length org-subtree-clip)))))
7466 (defun org-paste-subtree (&optional level tree for-yank)
7467 "Paste the clipboard as a subtree, with modification of headline level.
7468 The entire subtree is promoted or demoted in order to match a new headline
7469 level.
7471 If the cursor is at the beginning of a headline, the same level as
7472 that headline is used to paste the tree
7474 If not, the new level is derived from the *visible* headings
7475 before and after the insertion point, and taken to be the inferior headline
7476 level of the two. So if the previous visible heading is level 3 and the
7477 next is level 4 (or vice versa), level 4 will be used for insertion.
7478 This makes sure that the subtree remains an independent subtree and does
7479 not swallow low level entries.
7481 You can also force a different level, either by using a numeric prefix
7482 argument, or by inserting the heading marker by hand. For example, if the
7483 cursor is after \"*****\", then the tree will be shifted to level 5.
7485 If optional TREE is given, use this text instead of the kill ring.
7487 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7488 move back over whitespace before inserting, and move point to the end of
7489 the inserted text when done."
7490 (interactive "P")
7491 (setq tree (or tree (and kill-ring (current-kill 0))))
7492 (unless (org-kill-is-subtree-p tree)
7493 (error "%s"
7494 (substitute-command-keys
7495 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7496 (let* ((visp (not (outline-invisible-p)))
7497 (txt tree)
7498 (^re (concat "^\\(" outline-regexp "\\)"))
7499 (re (concat "\\(" outline-regexp "\\)"))
7500 (^re_ (concat "\\(\\*+\\)[ \t]*"))
7502 (old-level (if (string-match ^re txt)
7503 (- (match-end 0) (match-beginning 0) 1)
7504 -1))
7505 (force-level (cond (level (prefix-numeric-value level))
7506 ((and (looking-at "[ \t]*$")
7507 (string-match
7508 ^re_ (buffer-substring
7509 (point-at-bol) (point))))
7510 (- (match-end 1) (match-beginning 1)))
7511 ((and (bolp)
7512 (looking-at org-outline-regexp))
7513 (- (match-end 0) (point) 1))
7514 (t nil)))
7515 (previous-level (save-excursion
7516 (condition-case nil
7517 (progn
7518 (outline-previous-visible-heading 1)
7519 (if (looking-at re)
7520 (- (match-end 0) (match-beginning 0) 1)
7522 (error 1))))
7523 (next-level (save-excursion
7524 (condition-case nil
7525 (progn
7526 (or (looking-at outline-regexp)
7527 (outline-next-visible-heading 1))
7528 (if (looking-at re)
7529 (- (match-end 0) (match-beginning 0) 1)
7531 (error 1))))
7532 (new-level (or force-level (max previous-level next-level)))
7533 (shift (if (or (= old-level -1)
7534 (= new-level -1)
7535 (= old-level new-level))
7537 (- new-level old-level)))
7538 (delta (if (> shift 0) -1 1))
7539 (func (if (> shift 0) 'org-demote 'org-promote))
7540 (org-odd-levels-only nil)
7541 beg end newend)
7542 ;; Remove the forced level indicator
7543 (if force-level
7544 (delete-region (point-at-bol) (point)))
7545 ;; Paste
7546 (beginning-of-line 1)
7547 (unless for-yank (org-back-over-empty-lines))
7548 (setq beg (point))
7549 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7550 (insert-before-markers txt)
7551 (unless (string-match "\n\\'" txt) (insert "\n"))
7552 (setq newend (point))
7553 (org-reinstall-markers-in-region beg)
7554 (setq end (point))
7555 (goto-char beg)
7556 (skip-chars-forward " \t\n\r")
7557 (setq beg (point))
7558 (if (and (outline-invisible-p) visp)
7559 (save-excursion (outline-show-heading)))
7560 ;; Shift if necessary
7561 (unless (= shift 0)
7562 (save-restriction
7563 (narrow-to-region beg end)
7564 (while (not (= shift 0))
7565 (org-map-region func (point-min) (point-max))
7566 (setq shift (+ delta shift)))
7567 (goto-char (point-min))
7568 (setq newend (point-max))))
7569 (when (or (org-called-interactively-p 'interactive) for-yank)
7570 (message "Clipboard pasted as level %d subtree" new-level))
7571 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7572 kill-ring
7573 (eq org-subtree-clip (current-kill 0))
7574 org-subtree-clip-folded)
7575 ;; The tree was folded before it was killed/copied
7576 (hide-subtree))
7577 (and for-yank (goto-char newend))))
7579 (defun org-kill-is-subtree-p (&optional txt)
7580 "Check if the current kill is an outline subtree, or a set of trees.
7581 Returns nil if kill does not start with a headline, or if the first
7582 headline level is not the largest headline level in the tree.
7583 So this will actually accept several entries of equal levels as well,
7584 which is OK for `org-paste-subtree'.
7585 If optional TXT is given, check this string instead of the current kill."
7586 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7587 (start-level (and kill
7588 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
7589 org-outline-regexp "\\)")
7590 kill)
7591 (- (match-end 2) (match-beginning 2) 1)))
7592 (re (concat "^" org-outline-regexp))
7593 (start (1+ (or (match-beginning 2) -1))))
7594 (if (not start-level)
7595 (progn
7596 nil) ;; does not even start with a heading
7597 (catch 'exit
7598 (while (setq start (string-match re kill (1+ start)))
7599 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7600 (throw 'exit nil)))
7601 t))))
7603 (defvar org-markers-to-move nil
7604 "Markers that should be moved with a cut-and-paste operation.
7605 Those markers are stored together with their positions relative to
7606 the start of the region.")
7608 (defun org-save-markers-in-region (beg end)
7609 "Check markers in region.
7610 If these markers are between BEG and END, record their position relative
7611 to BEG, so that after moving the block of text, we can put the markers back
7612 into place.
7613 This function gets called just before an entry or tree gets cut from the
7614 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7615 called immediately, to move the markers with the entries."
7616 (setq org-markers-to-move nil)
7617 (when (featurep 'org-clock)
7618 (org-clock-save-markers-for-cut-and-paste beg end))
7619 (when (featurep 'org-agenda)
7620 (org-agenda-save-markers-for-cut-and-paste beg end)))
7622 (defun org-check-and-save-marker (marker beg end)
7623 "Check if MARKER is between BEG and END.
7624 If yes, remember the marker and the distance to BEG."
7625 (when (and (marker-buffer marker)
7626 (equal (marker-buffer marker) (current-buffer)))
7627 (if (and (>= marker beg) (< marker end))
7628 (push (cons marker (- marker beg)) org-markers-to-move))))
7630 (defun org-reinstall-markers-in-region (beg)
7631 "Move all remembered markers to their position relative to BEG."
7632 (mapc (lambda (x)
7633 (move-marker (car x) (+ beg (cdr x))))
7634 org-markers-to-move)
7635 (setq org-markers-to-move nil))
7637 (defun org-narrow-to-subtree ()
7638 "Narrow buffer to the current subtree."
7639 (interactive)
7640 (save-excursion
7641 (save-match-data
7642 (org-with-limited-levels
7643 (narrow-to-region
7644 (progn (org-back-to-heading t) (point))
7645 (progn (org-end-of-subtree t t)
7646 (if (and (org-on-heading-p) (not (eobp))) (backward-char 1))
7647 (point)))))))
7649 (defun org-narrow-to-block ()
7650 "Narrow buffer to the current block."
7651 (interactive)
7652 (let ((bstart "^[ \t]*#\\+begin")
7653 (bend "[ \t]*#\\+end")
7654 (case-fold-search t) ;; allow #+BEGIN
7655 b_start b_end)
7656 (if (org-in-regexps-block-p bstart bend)
7657 (progn
7658 (save-excursion (re-search-backward bstart nil t)
7659 (setq b_start (match-beginning 0)))
7660 (save-excursion (re-search-forward bend nil t)
7661 (setq b_end (match-end 0)))
7662 (narrow-to-region b_start b_end))
7663 (error "Not in a block"))))
7665 (eval-when-compile
7666 (defvar org-property-drawer-re))
7668 (defvar org-property-start-re) ;; defined below
7669 (defun org-clone-subtree-with-time-shift (n &optional shift)
7670 "Clone the task (subtree) at point N times.
7671 The clones will be inserted as siblings.
7673 In interactive use, the user will be prompted for the number of
7674 clones to be produced, and for a time SHIFT, which may be a
7675 repeater as used in time stamps, for example `+3d'.
7677 When a valid repeater is given and the entry contains any time
7678 stamps, the clones will become a sequence in time, with time
7679 stamps in the subtree shifted for each clone produced. If SHIFT
7680 is nil or the empty string, time stamps will be left alone. The
7681 ID property of the original subtree is removed.
7683 If the original subtree did contain time stamps with a repeater,
7684 the following will happen:
7685 - the repeater will be removed in each clone
7686 - an additional clone will be produced, with the current, unshifted
7687 date(s) in the entry.
7688 - the original entry will be placed *after* all the clones, with
7689 repeater intact.
7690 - the start days in the repeater in the original entry will be shifted
7691 to past the last clone.
7692 I this way you can spell out a number of instances of a repeating task,
7693 and still retain the repeater to cover future instances of the task."
7694 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7695 (let (beg end template task idprop
7696 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7697 (if (not (and (integerp n) (> n 0)))
7698 (error "Invalid number of replications %s" n))
7699 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7700 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7701 shift)))
7702 (error "Invalid shift specification %s" shift))
7703 (when doshift
7704 (setq shift-n (string-to-number (match-string 1 shift))
7705 shift-what (cdr (assoc (match-string 2 shift)
7706 '(("d" . day) ("w" . week)
7707 ("m" . month) ("y" . year))))))
7708 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7709 (setq nmin 1 nmax n)
7710 (org-back-to-heading t)
7711 (setq beg (point))
7712 (setq idprop (org-entry-get nil "ID"))
7713 (org-end-of-subtree t t)
7714 (or (bolp) (insert "\n"))
7715 (setq end (point))
7716 (setq template (buffer-substring beg end))
7717 (when (and doshift
7718 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7719 (delete-region beg end)
7720 (setq end beg)
7721 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7722 (goto-char end)
7723 (loop for n from nmin to nmax do
7724 ;; prepare clone
7725 (with-temp-buffer
7726 (insert template)
7727 (org-mode)
7728 (goto-char (point-min))
7729 (and idprop (if org-clone-delete-id
7730 (org-entry-delete nil "ID")
7731 (org-id-get-create t)))
7732 (while (re-search-forward org-property-start-re nil t)
7733 (org-remove-empty-drawer-at "PROPERTIES" (point)))
7734 (goto-char (point-min))
7735 (when doshift
7736 (while (re-search-forward org-ts-regexp-both nil t)
7737 (org-timestamp-change (* n shift-n) shift-what))
7738 (unless (= n n-no-remove)
7739 (goto-char (point-min))
7740 (while (re-search-forward org-ts-regexp nil t)
7741 (save-excursion
7742 (goto-char (match-beginning 0))
7743 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7744 (delete-region (match-beginning 1) (match-end 1)))))))
7745 (setq task (buffer-string)))
7746 (insert task))
7747 (goto-char beg)))
7749 ;;; Outline Sorting
7751 (defun org-sort (with-case)
7752 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
7753 Optional argument WITH-CASE means sort case-sensitively.
7754 With a double prefix argument, also remove duplicate entries."
7755 (interactive "P")
7756 (cond
7757 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
7758 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
7760 (org-call-with-arg 'org-sort-entries with-case))))
7762 (defun org-sort-remove-invisible (s)
7763 (remove-text-properties 0 (length s) org-rm-props s)
7764 (while (string-match org-bracket-link-regexp s)
7765 (setq s (replace-match (if (match-end 2)
7766 (match-string 3 s)
7767 (match-string 1 s)) t t s)))
7770 (defvar org-priority-regexp) ; defined later in the file
7772 (defvar org-after-sorting-entries-or-items-hook nil
7773 "Hook that is run after a bunch of entries or items have been sorted.
7774 When children are sorted, the cursor is in the parent line when this
7775 hook gets called. When a region or a plain list is sorted, the cursor
7776 will be in the first entry of the sorted region/list.")
7778 (defun org-sort-entries
7779 (&optional with-case sorting-type getkey-func compare-func property)
7780 "Sort entries on a certain level of an outline tree.
7781 If there is an active region, the entries in the region are sorted.
7782 Else, if the cursor is before the first entry, sort the top-level items.
7783 Else, the children of the entry at point are sorted.
7785 Sorting can be alphabetically, numerically, by date/time as given by
7786 a time stamp, by a property or by priority.
7788 The command prompts for the sorting type unless it has been given to the
7789 function through the SORTING-TYPE argument, which needs to be a character,
7790 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7791 precise meaning of each character:
7793 n Numerically, by converting the beginning of the entry/item to a number.
7794 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7795 t By date/time, either the first active time stamp in the entry, or, if
7796 none exist, by the first inactive one.
7797 s By the scheduled date/time.
7798 d By deadline date/time.
7799 c By creation time, which is assumed to be the first inactive time stamp
7800 at the beginning of a line.
7801 p By priority according to the cookie.
7802 r By the value of a property.
7804 Capital letters will reverse the sort order.
7806 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7807 called with point at the beginning of the record. It must return either
7808 a string or a number that should serve as the sorting key for that record.
7810 Comparing entries ignores case by default. However, with an optional argument
7811 WITH-CASE, the sorting considers case as well."
7812 (interactive "P")
7813 (let ((case-func (if with-case 'identity 'downcase))
7814 start beg end stars re re2
7815 txt what tmp)
7816 ;; Find beginning and end of region to sort
7817 (cond
7818 ((org-region-active-p)
7819 ;; we will sort the region
7820 (setq end (region-end)
7821 what "region")
7822 (goto-char (region-beginning))
7823 (if (not (org-on-heading-p)) (outline-next-heading))
7824 (setq start (point)))
7825 ((or (org-on-heading-p)
7826 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7827 ;; we will sort the children of the current headline
7828 (org-back-to-heading)
7829 (setq start (point)
7830 end (progn (org-end-of-subtree t t)
7831 (or (bolp) (insert "\n"))
7832 (org-back-over-empty-lines)
7833 (point))
7834 what "children")
7835 (goto-char start)
7836 (show-subtree)
7837 (outline-next-heading))
7839 ;; we will sort the top-level entries in this file
7840 (goto-char (point-min))
7841 (or (org-on-heading-p) (outline-next-heading))
7842 (setq start (point))
7843 (goto-char (point-max))
7844 (beginning-of-line 1)
7845 (when (looking-at ".*?\\S-")
7846 ;; File ends in a non-white line
7847 (end-of-line 1)
7848 (insert "\n"))
7849 (setq end (point-max))
7850 (setq what "top-level")
7851 (goto-char start)
7852 (show-all)))
7854 (setq beg (point))
7855 (if (>= beg end) (error "Nothing to sort"))
7857 (looking-at "\\(\\*+\\)")
7858 (setq stars (match-string 1)
7859 re (concat "^" (regexp-quote stars) " +")
7860 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
7861 txt (buffer-substring beg end))
7862 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7863 (if (and (not (equal stars "*")) (string-match re2 txt))
7864 (error "Region to sort contains a level above the first entry"))
7866 (unless sorting-type
7867 (message
7868 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7869 [t]ime [s]cheduled [d]eadline [c]reated
7870 A/N/T/S/D/C/P/O/F means reversed:"
7871 what)
7872 (setq sorting-type (read-char-exclusive))
7874 (and (= (downcase sorting-type) ?f)
7875 (setq getkey-func
7876 (org-icompleting-read "Sort using function: "
7877 obarray 'fboundp t nil nil))
7878 (setq getkey-func (intern getkey-func)))
7880 (and (= (downcase sorting-type) ?r)
7881 (setq property
7882 (org-icompleting-read "Property: "
7883 (mapcar 'list (org-buffer-property-keys t))
7884 nil t))))
7886 (message "Sorting entries...")
7888 (save-restriction
7889 (narrow-to-region start end)
7890 (let ((dcst (downcase sorting-type))
7891 (case-fold-search nil)
7892 (now (current-time)))
7893 (sort-subr
7894 (/= dcst sorting-type)
7895 ;; This function moves to the beginning character of the "record" to
7896 ;; be sorted.
7897 (lambda nil
7898 (if (re-search-forward re nil t)
7899 (goto-char (match-beginning 0))
7900 (goto-char (point-max))))
7901 ;; This function moves to the last character of the "record" being
7902 ;; sorted.
7903 (lambda nil
7904 (save-match-data
7905 (condition-case nil
7906 (outline-forward-same-level 1)
7907 (error
7908 (goto-char (point-max))))))
7909 ;; This function returns the value that gets sorted against.
7910 (lambda nil
7911 (cond
7912 ((= dcst ?n)
7913 (if (looking-at org-complex-heading-regexp)
7914 (string-to-number (match-string 4))
7915 nil))
7916 ((= dcst ?a)
7917 (if (looking-at org-complex-heading-regexp)
7918 (funcall case-func (match-string 4))
7919 nil))
7920 ((= dcst ?t)
7921 (let ((end (save-excursion (outline-next-heading) (point))))
7922 (if (or (re-search-forward org-ts-regexp end t)
7923 (re-search-forward org-ts-regexp-both end t))
7924 (org-time-string-to-seconds (match-string 0))
7925 (org-float-time now))))
7926 ((= dcst ?c)
7927 (let ((end (save-excursion (outline-next-heading) (point))))
7928 (if (re-search-forward
7929 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7930 end t)
7931 (org-time-string-to-seconds (match-string 0))
7932 (org-float-time now))))
7933 ((= dcst ?s)
7934 (let ((end (save-excursion (outline-next-heading) (point))))
7935 (if (re-search-forward org-scheduled-time-regexp end t)
7936 (org-time-string-to-seconds (match-string 1))
7937 (org-float-time now))))
7938 ((= dcst ?d)
7939 (let ((end (save-excursion (outline-next-heading) (point))))
7940 (if (re-search-forward org-deadline-time-regexp end t)
7941 (org-time-string-to-seconds (match-string 1))
7942 (org-float-time now))))
7943 ((= dcst ?p)
7944 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7945 (string-to-char (match-string 2))
7946 org-default-priority))
7947 ((= dcst ?r)
7948 (or (org-entry-get nil property) ""))
7949 ((= dcst ?o)
7950 (if (looking-at org-complex-heading-regexp)
7951 (- 9999 (length (member (match-string 2)
7952 org-todo-keywords-1)))))
7953 ((= dcst ?f)
7954 (if getkey-func
7955 (progn
7956 (setq tmp (funcall getkey-func))
7957 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7958 tmp)
7959 (error "Invalid key function `%s'" getkey-func)))
7960 (t (error "Invalid sorting type `%c'" sorting-type))))
7962 (cond
7963 ((= dcst ?a) 'string<)
7964 ((= dcst ?f) compare-func)
7965 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7966 (t nil)))))
7967 (run-hooks 'org-after-sorting-entries-or-items-hook)
7968 (message "Sorting entries...done")))
7970 (defun org-do-sort (table what &optional with-case sorting-type)
7971 "Sort TABLE of WHAT according to SORTING-TYPE.
7972 The user will be prompted for the SORTING-TYPE if the call to this
7973 function does not specify it. WHAT is only for the prompt, to indicate
7974 what is being sorted. The sorting key will be extracted from
7975 the car of the elements of the table.
7976 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7977 (unless sorting-type
7978 (message
7979 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7980 what)
7981 (setq sorting-type (read-char-exclusive)))
7982 (let ((dcst (downcase sorting-type))
7983 extractfun comparefun)
7984 ;; Define the appropriate functions
7985 (cond
7986 ((= dcst ?n)
7987 (setq extractfun 'string-to-number
7988 comparefun (if (= dcst sorting-type) '< '>)))
7989 ((= dcst ?a)
7990 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7991 (lambda(x) (downcase (org-sort-remove-invisible x))))
7992 comparefun (if (= dcst sorting-type)
7993 'string<
7994 (lambda (a b) (and (not (string< a b))
7995 (not (string= a b)))))))
7996 ((= dcst ?t)
7997 (setq extractfun
7998 (lambda (x)
7999 (if (or (string-match org-ts-regexp x)
8000 (string-match org-ts-regexp-both x))
8001 (org-float-time
8002 (org-time-string-to-time (match-string 0 x)))
8004 comparefun (if (= dcst sorting-type) '< '>)))
8005 (t (error "Invalid sorting type `%c'" sorting-type)))
8007 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8008 table)
8009 (lambda (a b) (funcall comparefun (car a) (car b))))))
8012 ;;; The orgstruct minor mode
8014 ;; Define a minor mode which can be used in other modes in order to
8015 ;; integrate the org-mode structure editing commands.
8017 ;; This is really a hack, because the org-mode structure commands use
8018 ;; keys which normally belong to the major mode. Here is how it
8019 ;; works: The minor mode defines all the keys necessary to operate the
8020 ;; structure commands, but wraps the commands into a function which
8021 ;; tests if the cursor is currently at a headline or a plain list
8022 ;; item. If that is the case, the structure command is used,
8023 ;; temporarily setting many Org-mode variables like regular
8024 ;; expressions for filling etc. However, when any of those keys is
8025 ;; used at a different location, function uses `key-binding' to look
8026 ;; up if the key has an associated command in another currently active
8027 ;; keymap (minor modes, major mode, global), and executes that
8028 ;; command. There might be problems if any of the keys is otherwise
8029 ;; used as a prefix key.
8031 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8032 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8033 ;; addresses this by checking explicitly for both bindings.
8035 (defvar orgstruct-mode-map (make-sparse-keymap)
8036 "Keymap for the minor `orgstruct-mode'.")
8038 (defvar org-local-vars nil
8039 "List of local variables, for use by `orgstruct-mode'.")
8041 ;;;###autoload
8042 (define-minor-mode orgstruct-mode
8043 "Toggle the minor mode `orgstruct-mode'.
8044 This mode is for using Org-mode structure commands in other
8045 modes. The following keys behave as if Org-mode were active, if
8046 the cursor is on a headline, or on a plain list item (both as
8047 defined by Org-mode).
8049 M-up Move entry/item up
8050 M-down Move entry/item down
8051 M-left Promote
8052 M-right Demote
8053 M-S-up Move entry/item up
8054 M-S-down Move entry/item down
8055 M-S-left Promote subtree
8056 M-S-right Demote subtree
8057 M-q Fill paragraph and items like in Org-mode
8058 C-c ^ Sort entries
8059 C-c - Cycle list bullet
8060 TAB Cycle item visibility
8061 M-RET Insert new heading/item
8062 S-M-RET Insert new TODO heading / Checkbox item
8063 C-c C-c Set tags / toggle checkbox"
8064 nil " OrgStruct" nil
8065 (org-load-modules-maybe)
8066 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8068 ;;;###autoload
8069 (defun turn-on-orgstruct ()
8070 "Unconditionally turn on `orgstruct-mode'."
8071 (orgstruct-mode 1))
8073 (defun orgstruct++-mode (&optional arg)
8074 "Toggle `orgstruct-mode', the enhanced version of it.
8075 In addition to setting orgstruct-mode, this also exports all indentation
8076 and autofilling variables from org-mode into the buffer. It will also
8077 recognize item context in multiline items.
8078 Note that turning off orgstruct-mode will *not* remove the
8079 indentation/paragraph settings. This can only be done by refreshing the
8080 major mode, for example with \\[normal-mode]."
8081 (interactive "P")
8082 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8083 (if (< arg 1)
8084 (orgstruct-mode -1)
8085 (orgstruct-mode 1)
8086 (let (var val)
8087 (mapc
8088 (lambda (x)
8089 (when (string-match
8090 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8091 (symbol-name (car x)))
8092 (setq var (car x) val (nth 1 x))
8093 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8094 org-local-vars)
8095 (org-set-local 'orgstruct-is-++ t))))
8097 (defvar orgstruct-is-++ nil
8098 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8099 (make-variable-buffer-local 'orgstruct-is-++)
8101 ;;;###autoload
8102 (defun turn-on-orgstruct++ ()
8103 "Unconditionally turn on `orgstruct++-mode'."
8104 (orgstruct++-mode 1))
8106 (defun orgstruct-error ()
8107 "Error when there is no default binding for a structure key."
8108 (interactive)
8109 (error "This key has no function outside structure elements"))
8111 (defun orgstruct-setup ()
8112 "Setup orgstruct keymaps."
8113 (let ((nfunc 0)
8114 (bindings
8115 (list
8116 '([(meta up)] org-metaup)
8117 '([(meta down)] org-metadown)
8118 '([(meta left)] org-metaleft)
8119 '([(meta right)] org-metaright)
8120 '([(meta shift up)] org-shiftmetaup)
8121 '([(meta shift down)] org-shiftmetadown)
8122 '([(meta shift left)] org-shiftmetaleft)
8123 '([(meta shift right)] org-shiftmetaright)
8124 '([?\e (up)] org-metaup)
8125 '([?\e (down)] org-metadown)
8126 '([?\e (left)] org-metaleft)
8127 '([?\e (right)] org-metaright)
8128 '([?\e (shift up)] org-shiftmetaup)
8129 '([?\e (shift down)] org-shiftmetadown)
8130 '([?\e (shift left)] org-shiftmetaleft)
8131 '([?\e (shift right)] org-shiftmetaright)
8132 '([(shift up)] org-shiftup)
8133 '([(shift down)] org-shiftdown)
8134 '([(shift left)] org-shiftleft)
8135 '([(shift right)] org-shiftright)
8136 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8137 '("\M-q" fill-paragraph)
8138 '("\C-c^" org-sort)
8139 '("\C-c-" org-cycle-list-bullet)))
8140 elt key fun cmd)
8141 (while (setq elt (pop bindings))
8142 (setq nfunc (1+ nfunc))
8143 (setq key (org-key (car elt))
8144 fun (nth 1 elt)
8145 cmd (orgstruct-make-binding fun nfunc key))
8146 (org-defkey orgstruct-mode-map key cmd))
8148 ;; Special treatment needed for TAB and RET
8149 (org-defkey orgstruct-mode-map [(tab)]
8150 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8151 (org-defkey orgstruct-mode-map "\C-i"
8152 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8154 (org-defkey orgstruct-mode-map "\M-\C-m"
8155 (orgstruct-make-binding 'org-insert-heading 105
8156 "\M-\C-m" [(meta return)]))
8157 (org-defkey orgstruct-mode-map [(meta return)]
8158 (orgstruct-make-binding 'org-insert-heading 106
8159 [(meta return)] "\M-\C-m"))
8161 (org-defkey orgstruct-mode-map [(shift meta return)]
8162 (orgstruct-make-binding 'org-insert-todo-heading 107
8163 [(meta return)] "\M-\C-m"))
8165 (org-defkey orgstruct-mode-map "\e\C-m"
8166 (orgstruct-make-binding 'org-insert-heading 108
8167 "\e\C-m" [?\e (return)]))
8168 (org-defkey orgstruct-mode-map [?\e (return)]
8169 (orgstruct-make-binding 'org-insert-heading 109
8170 [?\e (return)] "\e\C-m"))
8171 (org-defkey orgstruct-mode-map [?\e (shift return)]
8172 (orgstruct-make-binding 'org-insert-todo-heading 110
8173 [?\e (return)] "\e\C-m"))
8175 (unless org-local-vars
8176 (setq org-local-vars (org-get-local-variables)))
8180 (defun orgstruct-make-binding (fun n &rest keys)
8181 "Create a function for binding in the structure minor mode.
8182 FUN is the command to call inside a table. N is used to create a unique
8183 command name. KEYS are keys that should be checked in for a command
8184 to execute outside of tables."
8185 (eval
8186 (list 'defun
8187 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8188 '(arg)
8189 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8190 "Outside of structure, run the binding of `"
8191 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8192 "'.")
8193 '(interactive "p")
8194 (list 'if
8195 `(org-context-p 'headline 'item
8196 (and orgstruct-is-++
8197 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8198 'item-body))
8199 (list 'org-run-like-in-org-mode (list 'quote fun))
8200 (list 'let '(orgstruct-mode)
8201 (list 'call-interactively
8202 (append '(or)
8203 (mapcar (lambda (k)
8204 (list 'key-binding k))
8205 keys)
8206 '('orgstruct-error))))))))
8208 (defun org-context-p (&rest contexts)
8209 "Check if local context is any of CONTEXTS.
8210 Possible values in the list of contexts are `table', `headline', and `item'."
8211 (let ((pos (point)))
8212 (goto-char (point-at-bol))
8213 (prog1 (or (and (memq 'table contexts)
8214 (looking-at "[ \t]*|"))
8215 (and (memq 'headline contexts)
8216 ;;????????? (looking-at "\\*+"))
8217 (looking-at outline-regexp))
8218 (and (memq 'item contexts)
8219 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8220 (and (memq 'item-body contexts)
8221 (org-in-item-p)))
8222 (goto-char pos))))
8224 (defun org-get-local-variables ()
8225 "Return a list of all local variables in an org-mode buffer."
8226 (let (varlist)
8227 (with-current-buffer (get-buffer-create "*Org tmp*")
8228 (erase-buffer)
8229 (org-mode)
8230 (setq varlist (buffer-local-variables)))
8231 (kill-buffer "*Org tmp*")
8232 (delq nil
8233 (mapcar
8234 (lambda (x)
8235 (setq x
8236 (if (symbolp x)
8237 (list x)
8238 (list (car x) (list 'quote (cdr x)))))
8239 (if (string-match
8240 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8241 (symbol-name (car x)))
8242 x nil))
8243 varlist))))
8245 (defun org-clone-local-variables (from-buffer &optional regexp)
8246 "Clone local variables from FROM-BUFFER.
8247 Optional argument REGEXP selects variables to clone."
8248 (mapc
8249 (lambda (pair)
8250 (and (symbolp (car pair))
8251 (or (null regexp)
8252 (string-match regexp (symbol-name (car pair))))
8253 (set (make-local-variable (car pair))
8254 (cdr pair))))
8255 (buffer-local-variables from-buffer)))
8257 ;;;###autoload
8258 (defun org-run-like-in-org-mode (cmd)
8259 "Run a command, pretending that the current buffer is in Org-mode.
8260 This will temporarily bind local variables that are typically bound in
8261 Org-mode to the values they have in Org-mode, and then interactively
8262 call CMD."
8263 (org-load-modules-maybe)
8264 (unless org-local-vars
8265 (setq org-local-vars (org-get-local-variables)))
8266 (eval (list 'let org-local-vars
8267 (list 'call-interactively (list 'quote cmd)))))
8269 ;;;; Archiving
8271 (defun org-get-category (&optional pos force-refresh)
8272 "Get the category applying to position POS."
8273 (if force-refresh (org-refresh-category-properties))
8274 (let ((pos (or pos (point))))
8275 (or (get-text-property pos 'org-category)
8276 (progn (org-refresh-category-properties)
8277 (get-text-property pos 'org-category)))))
8279 (defun org-refresh-category-properties ()
8280 "Refresh category text properties in the buffer."
8281 (let ((def-cat (cond
8282 ((null org-category)
8283 (if buffer-file-name
8284 (file-name-sans-extension
8285 (file-name-nondirectory buffer-file-name))
8286 "???"))
8287 ((symbolp org-category) (symbol-name org-category))
8288 (t org-category)))
8289 beg end cat pos optionp)
8290 (org-unmodified
8291 (save-excursion
8292 (save-restriction
8293 (widen)
8294 (goto-char (point-min))
8295 (put-text-property (point) (point-max) 'org-category def-cat)
8296 (while (re-search-forward
8297 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8298 (setq pos (match-end 0)
8299 optionp (equal (char-after (match-beginning 0)) ?#)
8300 cat (org-trim (match-string 2)))
8301 (if optionp
8302 (setq beg (point-at-bol) end (point-max))
8303 (org-back-to-heading t)
8304 (setq beg (point) end (org-end-of-subtree t t)))
8305 (put-text-property beg end 'org-category cat)
8306 (goto-char pos)))))))
8309 ;;;; Link Stuff
8311 ;;; Link abbreviations
8313 (defun org-link-expand-abbrev (link)
8314 "Apply replacements as defined in `org-link-abbrev-alist."
8315 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8316 (let* ((key (match-string 1 link))
8317 (as (or (assoc key org-link-abbrev-alist-local)
8318 (assoc key org-link-abbrev-alist)))
8319 (tag (and (match-end 2) (match-string 3 link)))
8320 rpl)
8321 (if (not as)
8322 link
8323 (setq rpl (cdr as))
8324 (cond
8325 ((symbolp rpl) (funcall rpl tag))
8326 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8327 ((string-match "%h" rpl)
8328 (replace-match (url-hexify-string (or tag "")) t t rpl))
8329 (t (concat rpl tag)))))
8330 link))
8332 ;;; Storing and inserting links
8334 (defvar org-insert-link-history nil
8335 "Minibuffer history for links inserted with `org-insert-link'.")
8337 (defvar org-stored-links nil
8338 "Contains the links stored with `org-store-link'.")
8340 (defvar org-store-link-plist nil
8341 "Plist with info about the most recently link created with `org-store-link'.")
8343 (defvar org-link-protocols nil
8344 "Link protocols added to Org-mode using `org-add-link-type'.")
8346 (defvar org-store-link-functions nil
8347 "List of functions that are called to create and store a link.
8348 Each function will be called in turn until one returns a non-nil
8349 value. Each function should check if it is responsible for creating
8350 this link (for example by looking at the major mode).
8351 If not, it must exit and return nil.
8352 If yes, it should return a non-nil value after a calling
8353 `org-store-link-props' with a list of properties and values.
8354 Special properties are:
8356 :type The link prefix, like \"http\". This must be given.
8357 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8358 This is obligatory as well.
8359 :description Optional default description for the second pair
8360 of brackets in an Org-mode link. The user can still change
8361 this when inserting this link into an Org-mode buffer.
8363 In addition to these, any additional properties can be specified
8364 and then used in remember templates.")
8366 (defun org-add-link-type (type &optional follow export)
8367 "Add TYPE to the list of `org-link-types'.
8368 Re-compute all regular expressions depending on `org-link-types'
8370 FOLLOW and EXPORT are two functions.
8372 FOLLOW should take the link path as the single argument and do whatever
8373 is necessary to follow the link, for example find a file or display
8374 a mail message.
8376 EXPORT should format the link path for export to one of the export formats.
8377 It should be a function accepting three arguments:
8379 path the path of the link, the text after the prefix (like \"http:\")
8380 desc the description of the link, if any, or a description added by
8381 org-export-normalize-links if there is none
8382 format the export format, a symbol like `html' or `latex' or `ascii'..
8384 The function may use the FORMAT information to return different values
8385 depending on the format. The return value will be put literally into
8386 the exported file. If the return value is nil, this means Org should
8387 do what it normally does with links which do not have EXPORT defined.
8389 Org-mode has a built-in default for exporting links. If you are happy with
8390 this default, there is no need to define an export function for the link
8391 type. For a simple example of an export function, see `org-bbdb.el'."
8392 (add-to-list 'org-link-types type t)
8393 (org-make-link-regexps)
8394 (if (assoc type org-link-protocols)
8395 (setcdr (assoc type org-link-protocols) (list follow export))
8396 (push (list type follow export) org-link-protocols)))
8398 (defvar org-agenda-buffer-name)
8400 ;;;###autoload
8401 (defun org-store-link (arg)
8402 "\\<org-mode-map>Store an org-link to the current location.
8403 This link is added to `org-stored-links' and can later be inserted
8404 into an org-buffer with \\[org-insert-link].
8406 For some link types, a prefix arg is interpreted:
8407 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8408 For file links, arg negates `org-context-in-file-links'."
8409 (interactive "P")
8410 (org-load-modules-maybe)
8411 (setq org-store-link-plist nil) ; reset
8412 (org-with-limited-levels
8413 (let (link cpltxt desc description search txt custom-id agenda-link)
8414 (cond
8416 ((run-hook-with-args-until-success 'org-store-link-functions)
8417 (setq link (plist-get org-store-link-plist :link)
8418 desc (or (plist-get org-store-link-plist :description) link)))
8420 ((equal (buffer-name) "*Org Edit Src Example*")
8421 (let (label gc)
8422 (while (or (not label)
8423 (save-excursion
8424 (save-restriction
8425 (widen)
8426 (goto-char (point-min))
8427 (re-search-forward
8428 (regexp-quote (format org-coderef-label-format label))
8429 nil t))))
8430 (when label (message "Label exists already") (sit-for 2))
8431 (setq label (read-string "Code line label: " label)))
8432 (end-of-line 1)
8433 (setq link (format org-coderef-label-format label))
8434 (setq gc (- 79 (length link)))
8435 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8436 (insert link)
8437 (setq link (concat "(" label ")") desc nil)))
8439 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8440 ;; We are in the agenda, link to referenced location
8441 (let ((m (or (get-text-property (point) 'org-hd-marker)
8442 (get-text-property (point) 'org-marker))))
8443 (when m
8444 (org-with-point-at m
8445 (setq agenda-link
8446 (if (org-called-interactively-p 'any)
8447 (call-interactively 'org-store-link)
8448 (org-store-link nil)))))))
8450 ((eq major-mode 'calendar-mode)
8451 (let ((cd (calendar-cursor-to-date)))
8452 (setq link
8453 (format-time-string
8454 (car org-time-stamp-formats)
8455 (apply 'encode-time
8456 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8457 nil nil nil))))
8458 (org-store-link-props :type "calendar" :date cd)))
8460 ((eq major-mode 'w3-mode)
8461 (setq cpltxt (if (and (buffer-name)
8462 (not (string-match "Untitled" (buffer-name))))
8463 (buffer-name)
8464 (url-view-url t))
8465 link (org-make-link (url-view-url t)))
8466 (org-store-link-props :type "w3" :url (url-view-url t)))
8468 ((eq major-mode 'w3m-mode)
8469 (setq cpltxt (or w3m-current-title w3m-current-url)
8470 link (org-make-link w3m-current-url))
8471 (org-store-link-props :type "w3m" :url (url-view-url t)))
8473 ((setq search (run-hook-with-args-until-success
8474 'org-create-file-search-functions))
8475 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8476 "::" search))
8477 (setq cpltxt (or description link)))
8479 ((eq major-mode 'image-mode)
8480 (setq cpltxt (concat "file:"
8481 (abbreviate-file-name buffer-file-name))
8482 link (org-make-link cpltxt))
8483 (org-store-link-props :type "image" :file buffer-file-name))
8485 ((eq major-mode 'dired-mode)
8486 ;; link to the file in the current line
8487 (let ((file (dired-get-filename nil t)))
8488 (setq file (if file
8489 (abbreviate-file-name
8490 (expand-file-name (dired-get-filename nil t)))
8491 ;; otherwise, no file so use current directory.
8492 default-directory))
8493 (setq cpltxt (concat "file:" file)
8494 link (org-make-link cpltxt))))
8496 ((and (buffer-file-name (buffer-base-buffer)) (org-mode-p))
8497 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8498 (cond
8499 ((org-in-regexp "<<\\(.*?\\)>>")
8500 (setq cpltxt
8501 (concat "file:"
8502 (abbreviate-file-name
8503 (buffer-file-name (buffer-base-buffer)))
8504 "::" (match-string 1))
8505 link (org-make-link cpltxt)))
8506 ((and (featurep 'org-id)
8507 (or (eq org-link-to-org-use-id t)
8508 (and (eq org-link-to-org-use-id 'create-if-interactive)
8509 (org-called-interactively-p 'any))
8510 (and (eq org-link-to-org-use-id
8511 'create-if-interactive-and-no-custom-id)
8512 (org-called-interactively-p 'any)
8513 (not custom-id))
8514 (and org-link-to-org-use-id
8515 (org-entry-get nil "ID"))))
8516 ;; We can make a link using the ID.
8517 (setq link (condition-case nil
8518 (prog1 (org-id-store-link)
8519 (setq desc (plist-get org-store-link-plist
8520 :description)))
8521 (error
8522 ;; probably before first headline, link to file only
8523 (concat "file:"
8524 (abbreviate-file-name
8525 (buffer-file-name (buffer-base-buffer))))))))
8527 ;; Just link to current headline
8528 (setq cpltxt (concat "file:"
8529 (abbreviate-file-name
8530 (buffer-file-name (buffer-base-buffer)))))
8531 ;; Add a context search string
8532 (when (org-xor org-context-in-file-links arg)
8533 (setq txt (cond
8534 ((org-on-heading-p) nil)
8535 ((org-region-active-p)
8536 (buffer-substring (region-beginning) (region-end)))
8537 (t nil)))
8538 (when (or (null txt) (string-match "\\S-" txt))
8539 (setq cpltxt
8540 (concat cpltxt "::"
8541 (condition-case nil
8542 (org-make-org-heading-search-string txt)
8543 (error "")))
8544 desc (or (nth 4 (ignore-errors
8545 (org-heading-components))) "NONE"))))
8546 (if (string-match "::\\'" cpltxt)
8547 (setq cpltxt (substring cpltxt 0 -2)))
8548 (setq link (org-make-link cpltxt)))))
8550 ((buffer-file-name (buffer-base-buffer))
8551 ;; Just link to this file here.
8552 (setq cpltxt (concat "file:"
8553 (abbreviate-file-name
8554 (buffer-file-name (buffer-base-buffer)))))
8555 ;; Add a context string
8556 (when (org-xor org-context-in-file-links arg)
8557 (setq txt (if (org-region-active-p)
8558 (buffer-substring (region-beginning) (region-end))
8559 (buffer-substring (point-at-bol) (point-at-eol))))
8560 ;; Only use search option if there is some text.
8561 (when (string-match "\\S-" txt)
8562 (setq cpltxt
8563 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8564 desc "NONE")))
8565 (setq link (org-make-link cpltxt)))
8567 ((org-called-interactively-p 'interactive)
8568 (error "Cannot link to a buffer which is not visiting a file"))
8570 (t (setq link nil)))
8572 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8573 (setq link (or link cpltxt)
8574 desc (or desc cpltxt))
8575 (if (equal desc "NONE") (setq desc nil))
8577 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8578 (progn
8579 (setq org-stored-links
8580 (cons (list link desc) org-stored-links))
8581 (message "Stored: %s" (or desc link))
8582 (when custom-id
8583 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8584 "::#" custom-id))
8585 (setq org-stored-links
8586 (cons (list link desc) org-stored-links))))
8587 (or agenda-link (and link (org-make-link-string link desc)))))))
8589 (defun org-store-link-props (&rest plist)
8590 "Store link properties, extract names and addresses."
8591 (let (x adr)
8592 (when (setq x (plist-get plist :from))
8593 (setq adr (mail-extract-address-components x))
8594 (setq plist (plist-put plist :fromname (car adr)))
8595 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8596 (when (setq x (plist-get plist :to))
8597 (setq adr (mail-extract-address-components x))
8598 (setq plist (plist-put plist :toname (car adr)))
8599 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8600 (let ((from (plist-get plist :from))
8601 (to (plist-get plist :to)))
8602 (when (and from to org-from-is-user-regexp)
8603 (setq plist
8604 (plist-put plist :fromto
8605 (if (string-match org-from-is-user-regexp from)
8606 (concat "to %t")
8607 (concat "from %f"))))))
8608 (setq org-store-link-plist plist))
8610 (defun org-add-link-props (&rest plist)
8611 "Add these properties to the link property list."
8612 (let (key value)
8613 (while plist
8614 (setq key (pop plist) value (pop plist))
8615 (setq org-store-link-plist
8616 (plist-put org-store-link-plist key value)))))
8618 (defun org-email-link-description (&optional fmt)
8619 "Return the description part of an email link.
8620 This takes information from `org-store-link-plist' and formats it
8621 according to FMT (default from `org-email-link-description-format')."
8622 (setq fmt (or fmt org-email-link-description-format))
8623 (let* ((p org-store-link-plist)
8624 (to (plist-get p :toaddress))
8625 (from (plist-get p :fromaddress))
8626 (table
8627 (list
8628 (cons "%c" (plist-get p :fromto))
8629 (cons "%F" (plist-get p :from))
8630 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8631 (cons "%T" (plist-get p :to))
8632 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8633 (cons "%s" (plist-get p :subject))
8634 (cons "%d" (plist-get p :date))
8635 (cons "%m" (plist-get p :message-id)))))
8636 (when (string-match "%c" fmt)
8637 ;; Check if the user wrote this message
8638 (if (and org-from-is-user-regexp from to
8639 (save-match-data (string-match org-from-is-user-regexp from)))
8640 (setq fmt (replace-match "to %t" t t fmt))
8641 (setq fmt (replace-match "from %f" t t fmt))))
8642 (org-replace-escapes fmt table)))
8644 (defun org-make-org-heading-search-string (&optional string heading)
8645 "Make search string for STRING or current headline."
8646 (interactive)
8647 (let ((s (or string (org-get-heading)))
8648 (lines org-context-in-file-links))
8649 (unless (and string (not heading))
8650 ;; We are using a headline, clean up garbage in there.
8651 (if (string-match org-todo-regexp s)
8652 (setq s (replace-match "" t t s)))
8653 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8654 (setq s (replace-match "" t t s)))
8655 (setq s (org-trim s))
8656 (if (string-match (concat "^\\(" org-quote-string "\\|"
8657 org-comment-string "\\)") s)
8658 (setq s (replace-match "" t t s)))
8659 (while (string-match org-ts-regexp s)
8660 (setq s (replace-match "" t t s))))
8661 (or string (setq s (concat "*" s))) ; Add * for headlines
8662 (when (and string (integerp lines) (> lines 0))
8663 (let ((slines (org-split-string s "\n")))
8664 (when (< lines (length slines))
8665 (setq s (mapconcat
8666 'identity
8667 (reverse (nthcdr (- (length slines) lines)
8668 (reverse slines))) "\n")))))
8669 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8671 (defun org-make-link (&rest strings)
8672 "Concatenate STRINGS."
8673 (apply 'concat strings))
8675 (defun org-make-link-string (link &optional description)
8676 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8677 (unless (string-match "\\S-" link)
8678 (error "Empty link"))
8679 (when (and description
8680 (stringp description)
8681 (not (string-match "\\S-" description)))
8682 (setq description nil))
8683 (when (stringp description)
8684 ;; Remove brackets from the description, they are fatal.
8685 (while (string-match "\\[" description)
8686 (setq description (replace-match "{" t t description)))
8687 (while (string-match "\\]" description)
8688 (setq description (replace-match "}" t t description))))
8689 (when (equal (org-link-escape link) description)
8690 ;; No description needed, it is identical
8691 (setq description nil))
8692 (when (and (not description)
8693 (not (equal link (org-link-escape link))))
8694 (setq description (org-extract-attributes link)))
8695 (setq link (if (string-match org-link-types-re link)
8696 (concat (match-string 1 link)
8697 (org-link-escape (substring link (match-end 1))))
8698 (org-link-escape link)))
8699 (concat "[[" link "]"
8700 (if description (concat "[" description "]") "")
8701 "]"))
8703 (defconst org-link-escape-chars
8704 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8705 "List of characters that should be escaped in link.
8706 This is the list that is used for internal purposes.")
8708 (defvar org-url-encoding-use-url-hexify nil)
8710 (defconst org-link-escape-chars-browser
8711 '(?\ )
8712 "List of escapes for characters that are problematic in links.
8713 This is the list that is used before handing over to the browser.")
8715 (defun org-link-escape (text &optional table merge)
8716 "Return percent escaped representation of TEXT.
8717 TEXT is a string with the text to escape.
8718 Optional argument TABLE is a list with characters that should be
8719 escaped. When nil, `org-link-escape-chars' is used.
8720 If optional argument MERGE is set, merge TABLE into
8721 `org-link-escape-chars'."
8722 (if (and org-url-encoding-use-url-hexify (not table))
8723 (url-hexify-string text)
8724 (cond
8725 ((and table merge)
8726 (mapc (lambda (defchr)
8727 (unless (member defchr table)
8728 (setq table (cons defchr table)))) org-link-escape-chars))
8729 ((null table)
8730 (setq table org-link-escape-chars)))
8731 (mapconcat
8732 (lambda (char)
8733 (if (or (member char table)
8734 (< char 32) (= char 37) (> char 126))
8735 (mapconcat (lambda (sequence-element)
8736 (format "%%%.2X" sequence-element))
8737 (or (encode-coding-char char 'utf-8)
8738 (error "Unable to percent escape character: %s"
8739 (char-to-string char))) "")
8740 (char-to-string char))) text "")))
8742 (defun org-link-unescape (str)
8743 "Unhex hexified unicode strings as returned from the JavaScript function
8744 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
8745 (unless (and (null str) (string= "" str))
8746 (let ((pos 0) (case-fold-search t) unhexed)
8747 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
8748 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
8749 (setq str (replace-match unhexed t t str))
8750 (setq pos (+ pos (length unhexed))))))
8751 str)
8753 (defun org-link-unescape-compound (hex)
8754 "Unhexify unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
8755 Note: this function also decodes single byte encodings like
8756 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
8757 (save-match-data
8758 (let* ((bytes (cdr (split-string hex "%")))
8759 (ret "")
8760 (eat 0)
8761 (sum 0))
8762 (while bytes
8763 (let* ((val (string-to-number (pop bytes) 16))
8764 (shift-xor
8765 (if (= 0 eat)
8766 (cond
8767 ((>= val 252) (cons 6 252))
8768 ((>= val 248) (cons 5 248))
8769 ((>= val 240) (cons 4 240))
8770 ((>= val 224) (cons 3 224))
8771 ((>= val 192) (cons 2 192))
8772 (t (cons 0 0)))
8773 (cons 6 128))))
8774 (if (>= val 192) (setq eat (car shift-xor)))
8775 (setq val (logxor val (cdr shift-xor)))
8776 (setq sum (+ (lsh sum (car shift-xor)) val))
8777 (if (> eat 0) (setq eat (- eat 1)))
8778 (cond
8779 ((= 0 eat) ;multi byte
8780 (setq ret (concat ret (org-char-to-string sum)))
8781 (setq sum 0))
8782 ((not bytes) ; single byte(s)
8783 (setq ret (org-link-unescape-single-byte-sequence hex))))
8784 )) ;; end (while bytes
8785 ret )))
8787 (defun org-link-unescape-single-byte-sequence (hex)
8788 "Unhexify hex-encoded single byte character sequences."
8789 (mapconcat (lambda (byte)
8790 (char-to-string (string-to-number byte 16)))
8791 (cdr (split-string hex "%")) ""))
8793 (defun org-xor (a b)
8794 "Exclusive or."
8795 (if a (not b) b))
8797 (defun org-fixup-message-id-for-http (s)
8798 "Replace special characters in a message id, so it can be used in an http query."
8799 (when (string-match "%" s)
8800 (setq s (mapconcat (lambda (c)
8801 (if (eq c ?%)
8802 "%25"
8803 (char-to-string c)))
8804 s "")))
8805 (while (string-match "<" s)
8806 (setq s (replace-match "%3C" t t s)))
8807 (while (string-match ">" s)
8808 (setq s (replace-match "%3E" t t s)))
8809 (while (string-match "@" s)
8810 (setq s (replace-match "%40" t t s)))
8813 ;;;###autoload
8814 (defun org-insert-link-global ()
8815 "Insert a link like Org-mode does.
8816 This command can be called in any mode to insert a link in Org-mode syntax."
8817 (interactive)
8818 (org-load-modules-maybe)
8819 (org-run-like-in-org-mode 'org-insert-link))
8821 (defun org-insert-link (&optional complete-file link-location)
8822 "Insert a link. At the prompt, enter the link.
8824 Completion can be used to insert any of the link protocol prefixes like
8825 http or ftp in use.
8827 The history can be used to select a link previously stored with
8828 `org-store-link'. When the empty string is entered (i.e. if you just
8829 press RET at the prompt), the link defaults to the most recently
8830 stored link. As SPC triggers completion in the minibuffer, you need to
8831 use M-SPC or C-q SPC to force the insertion of a space character.
8833 You will also be prompted for a description, and if one is given, it will
8834 be displayed in the buffer instead of the link.
8836 If there is already a link at point, this command will allow you to edit link
8837 and description parts.
8839 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
8840 be selected using completion. The path to the file will be relative to the
8841 current directory if the file is in the current directory or a subdirectory.
8842 Otherwise, the link will be the absolute path as completed in the minibuffer
8843 \(i.e. normally ~/path/to/file). You can configure this behavior using the
8844 option `org-link-file-path-type'.
8846 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
8847 the current directory or below.
8849 With three \\[universal-argument] prefixes, negate the meaning of
8850 `org-keep-stored-link-after-insertion'.
8852 If `org-make-link-description-function' is non-nil, this function will be
8853 called with the link target, and the result will be the default
8854 link description.
8856 If the LINK-LOCATION parameter is non-nil, this value will be
8857 used as the link location instead of reading one interactively."
8858 (interactive "P")
8859 (let* ((wcf (current-window-configuration))
8860 (region (if (org-region-active-p)
8861 (buffer-substring (region-beginning) (region-end))))
8862 (remove (and region (list (region-beginning) (region-end))))
8863 (desc region)
8864 tmphist ; byte-compile incorrectly complains about this
8865 (link link-location)
8866 entry file all-prefixes)
8867 (cond
8868 (link-location) ; specified by arg, just use it.
8869 ((org-in-regexp org-bracket-link-regexp 1)
8870 ;; We do have a link at point, and we are going to edit it.
8871 (setq remove (list (match-beginning 0) (match-end 0)))
8872 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8873 (setq link (read-string "Link: "
8874 (org-link-unescape
8875 (org-match-string-no-properties 1)))))
8876 ((or (org-in-regexp org-angle-link-re)
8877 (org-in-regexp org-plain-link-re))
8878 ;; Convert to bracket link
8879 (setq remove (list (match-beginning 0) (match-end 0))
8880 link (read-string "Link: "
8881 (org-remove-angle-brackets (match-string 0)))))
8882 ((member complete-file '((4) (16)))
8883 ;; Completing read for file names.
8884 (setq link (org-file-complete-link complete-file)))
8886 ;; Read link, with completion for stored links.
8887 (with-output-to-temp-buffer "*Org Links*"
8888 (princ "Insert a link.
8889 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8890 (when org-stored-links
8891 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8892 (princ (mapconcat
8893 (lambda (x)
8894 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8895 (reverse org-stored-links) "\n"))))
8896 (let ((cw (selected-window)))
8897 (select-window (get-buffer-window "*Org Links*" 'visible))
8898 (with-current-buffer "*Org Links*" (setq truncate-lines) t)
8899 (unless (pos-visible-in-window-p (point-max))
8900 (org-fit-window-to-buffer))
8901 (and (window-live-p cw) (select-window cw)))
8902 ;; Fake a link history, containing the stored links.
8903 (setq tmphist (append (mapcar 'car org-stored-links)
8904 org-insert-link-history))
8905 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8906 (mapcar 'car org-link-abbrev-alist)
8907 org-link-types))
8908 (unwind-protect
8909 (progn
8910 (setq link
8911 (let ((org-completion-use-ido nil)
8912 (org-completion-use-iswitchb nil))
8913 (org-completing-read
8914 "Link: "
8915 (append
8916 (mapcar (lambda (x) (list (concat x ":")))
8917 all-prefixes)
8918 (mapcar 'car org-stored-links))
8919 nil nil nil
8920 'tmphist
8921 (car (car org-stored-links)))))
8922 (if (not (string-match "\\S-" link))
8923 (error "No link selected"))
8924 (if (or (member link all-prefixes)
8925 (and (equal ":" (substring link -1))
8926 (member (substring link 0 -1) all-prefixes)
8927 (setq link (substring link 0 -1))))
8928 (setq link (org-link-try-special-completion link))))
8929 (set-window-configuration wcf)
8930 (kill-buffer "*Org Links*"))
8931 (setq entry (assoc link org-stored-links))
8932 (or entry (push link org-insert-link-history))
8933 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8934 (not org-keep-stored-link-after-insertion))
8935 (setq org-stored-links (delq (assoc link org-stored-links)
8936 org-stored-links)))
8937 (setq desc (or desc (nth 1 entry)))))
8939 (if (string-match org-plain-link-re link)
8940 ;; URL-like link, normalize the use of angular brackets.
8941 (setq link (org-make-link (org-remove-angle-brackets link))))
8943 ;; Check if we are linking to the current file with a search option
8944 ;; If yes, simplify the link by using only the search option.
8945 (when (and buffer-file-name
8946 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8947 (let* ((path (match-string 1 link))
8948 (case-fold-search nil)
8949 (search (match-string 2 link)))
8950 (save-match-data
8951 (if (equal (file-truename buffer-file-name) (file-truename path))
8952 ;; We are linking to this same file, with a search option
8953 (setq link search)))))
8955 ;; Check if we can/should use a relative path. If yes, simplify the link
8956 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8957 (let* ((type (match-string 1 link))
8958 (path (match-string 2 link))
8959 (origpath path)
8960 (case-fold-search nil))
8961 (cond
8962 ((or (eq org-link-file-path-type 'absolute)
8963 (equal complete-file '(16)))
8964 (setq path (abbreviate-file-name (expand-file-name path))))
8965 ((eq org-link-file-path-type 'noabbrev)
8966 (setq path (expand-file-name path)))
8967 ((eq org-link-file-path-type 'relative)
8968 (setq path (file-relative-name path)))
8970 (save-match-data
8971 (if (string-match (concat "^" (regexp-quote
8972 (expand-file-name
8973 (file-name-as-directory
8974 default-directory))))
8975 (expand-file-name path))
8976 ;; We are linking a file with relative path name.
8977 (setq path (substring (expand-file-name path)
8978 (match-end 0)))
8979 (setq path (abbreviate-file-name (expand-file-name path)))))))
8980 (setq link (concat type path))
8981 (if (equal desc origpath)
8982 (setq desc path))))
8984 (if org-make-link-description-function
8985 (setq desc (funcall org-make-link-description-function link desc)))
8987 (setq desc (read-string "Description: " desc))
8988 (unless (string-match "\\S-" desc) (setq desc nil))
8989 (if remove (apply 'delete-region remove))
8990 (insert (org-make-link-string link desc))))
8992 (defun org-link-try-special-completion (type)
8993 "If there is completion support for link type TYPE, offer it."
8994 (let ((fun (intern (concat "org-" type "-complete-link"))))
8995 (if (functionp fun)
8996 (funcall fun)
8997 (read-string "Link (no completion support): " (concat type ":")))))
8999 (defun org-file-complete-link (&optional arg)
9000 "Create a file link using completion."
9001 (let (file link)
9002 (setq file (read-file-name "File: "))
9003 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9004 (pwd1 (file-name-as-directory (abbreviate-file-name
9005 (expand-file-name ".")))))
9006 (cond
9007 ((equal arg '(16))
9008 (setq link (org-make-link
9009 "file:"
9010 (abbreviate-file-name (expand-file-name file)))))
9011 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9012 (setq link (org-make-link "file:" (match-string 1 file))))
9013 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9014 (expand-file-name file))
9015 (setq link (org-make-link
9016 "file:" (match-string 1 (expand-file-name file)))))
9017 (t (setq link (org-make-link "file:" file)))))
9018 link))
9020 (defun org-completing-read (&rest args)
9021 "Completing-read with SPACE being a normal character."
9022 (let ((minibuffer-local-completion-map
9023 (copy-keymap minibuffer-local-completion-map)))
9024 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9025 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9026 (apply 'org-icompleting-read args)))
9028 (defun org-completing-read-no-i (&rest args)
9029 (let (org-completion-use-ido org-completion-use-iswitchb)
9030 (apply 'org-completing-read args)))
9032 (defun org-iswitchb-completing-read (prompt choices &rest args)
9033 "Use iswitch as a completing-read replacement to choose from choices.
9034 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9035 from."
9036 (let* ((iswitchb-use-virtual-buffers nil)
9037 (iswitchb-make-buflist-hook
9038 (lambda ()
9039 (setq iswitchb-temp-buflist choices))))
9040 (iswitchb-read-buffer prompt)))
9042 (defun org-icompleting-read (&rest args)
9043 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9044 (org-without-partial-completion
9045 (if (and org-completion-use-ido
9046 (fboundp 'ido-completing-read)
9047 (boundp 'ido-mode) ido-mode
9048 (listp (second args)))
9049 (let ((ido-enter-matching-directory nil))
9050 (apply 'ido-completing-read (concat (car args))
9051 (if (consp (car (nth 1 args)))
9052 (mapcar 'car (nth 1 args))
9053 (nth 1 args))
9054 (cddr args)))
9055 (if (and org-completion-use-iswitchb
9056 (boundp 'iswitchb-mode) iswitchb-mode
9057 (listp (second args)))
9058 (apply 'org-iswitchb-completing-read (concat (car args))
9059 (if (consp (car (nth 1 args)))
9060 (mapcar 'car (nth 1 args))
9061 (nth 1 args))
9062 (cddr args))
9063 (apply 'completing-read args)))))
9065 (defun org-extract-attributes (s)
9066 "Extract the attributes cookie from a string and set as text property."
9067 (let (a attr (start 0) key value)
9068 (save-match-data
9069 (when (string-match "{{\\([^}]+\\)}}$" s)
9070 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9071 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9072 (setq key (match-string 1 a) value (match-string 2 a)
9073 start (match-end 0)
9074 attr (plist-put attr (intern key) value))))
9075 (org-add-props s nil 'org-attr attr))
9078 (defun org-extract-attributes-from-string (tag)
9079 (let (key value attr)
9080 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9081 (setq key (match-string 1 tag) value (match-string 2 tag)
9082 tag (replace-match "" t t tag)
9083 attr (plist-put attr (intern key) value)))
9084 (cons tag attr)))
9086 (defun org-attributes-to-string (plist)
9087 "Format a property list into an HTML attribute list."
9088 (let ((s "") key value)
9089 (while plist
9090 (setq key (pop plist) value (pop plist))
9091 (and value
9092 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9095 ;;; Opening/following a link
9097 (defvar org-link-search-failed nil)
9099 (defvar org-open-link-functions nil
9100 "Hook for functions finding a plain text link.
9101 These functions must take a single argument, the link content.
9102 They will be called for links that look like [[link text][description]]
9103 when LINK TEXT does not have a protocol like \"http:\" and does not look
9104 like a filename (e.g. \"./blue.png\").
9106 These functions will be called *before* Org attempts to resolve the
9107 link by doing text searches in the current buffer - so if you want a
9108 link \"[[target]]\" to still find \"<<target>>\", your function should
9109 handle this as a special case.
9111 When the function does handle the link, it must return a non-nil value.
9112 If it decides that it is not responsible for this link, it must return
9113 nil to indicate that that Org-mode can continue with other options
9114 like exact and fuzzy text search.")
9116 (defun org-next-link ()
9117 "Move forward to the next link.
9118 If the link is in hidden text, expose it."
9119 (interactive)
9120 (when (and org-link-search-failed (eq this-command last-command))
9121 (goto-char (point-min))
9122 (message "Link search wrapped back to beginning of buffer"))
9123 (setq org-link-search-failed nil)
9124 (let* ((pos (point))
9125 (ct (org-context))
9126 (a (assoc :link ct)))
9127 (if a (goto-char (nth 2 a)))
9128 (if (re-search-forward org-any-link-re nil t)
9129 (progn
9130 (goto-char (match-beginning 0))
9131 (if (outline-invisible-p) (org-show-context)))
9132 (goto-char pos)
9133 (setq org-link-search-failed t)
9134 (error "No further link found"))))
9136 (defun org-previous-link ()
9137 "Move backward to the previous 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-max))
9142 (message "Link search wrapped back to end 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 1 a)))
9148 (if (re-search-backward 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-translate-link (s)
9157 "Translate a link string if a translation function has been defined."
9158 (if (and org-link-translation-function
9159 (fboundp org-link-translation-function)
9160 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9161 (progn
9162 (setq s (funcall org-link-translation-function
9163 (match-string 1) (match-string 2)))
9164 (concat (car s) ":" (cdr s)))
9167 (defun org-translate-link-from-planner (type path)
9168 "Translate a link from Emacs Planner syntax so that Org can follow it.
9169 This is still an experimental function, your mileage may vary."
9170 (cond
9171 ((member type '("http" "https" "news" "ftp"))
9172 ;; standard Internet links are the same.
9173 nil)
9174 ((and (equal type "irc") (string-match "^//" path))
9175 ;; Planner has two / at the beginning of an irc link, we have 1.
9176 ;; We should have zero, actually....
9177 (setq path (substring path 1)))
9178 ((and (equal type "lisp") (string-match "^/" path))
9179 ;; Planner has a slash, we do not.
9180 (setq type "elisp" path (substring path 1)))
9181 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9182 ;; A typical message link. Planner has the id after the final slash,
9183 ;; we separate it with a hash mark
9184 (setq path (concat (match-string 1 path) "#"
9185 (org-remove-angle-brackets (match-string 2 path)))))
9187 (cons type path))
9189 (defun org-find-file-at-mouse (ev)
9190 "Open file link or URL at mouse."
9191 (interactive "e")
9192 (mouse-set-point ev)
9193 (org-open-at-point 'in-emacs))
9195 (defun org-open-at-mouse (ev)
9196 "Open file link or URL at mouse."
9197 (interactive "e")
9198 (mouse-set-point ev)
9199 (if (eq major-mode 'org-agenda-mode)
9200 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9201 (org-open-at-point))
9203 (defvar org-window-config-before-follow-link nil
9204 "The window configuration before following a link.
9205 This is saved in case the need arises to restore it.")
9207 (defvar org-open-link-marker (make-marker)
9208 "Marker pointing to the location where `org-open-at-point; was called.")
9210 ;;;###autoload
9211 (defun org-open-at-point-global ()
9212 "Follow a link like Org-mode does.
9213 This command can be called in any mode to follow a link that has
9214 Org-mode syntax."
9215 (interactive)
9216 (org-run-like-in-org-mode 'org-open-at-point))
9218 ;;;###autoload
9219 (defun org-open-link-from-string (s &optional arg reference-buffer)
9220 "Open a link in the string S, as if it was in Org-mode."
9221 (interactive "sLink: \nP")
9222 (let ((reference-buffer (or reference-buffer (current-buffer))))
9223 (with-temp-buffer
9224 (let ((org-inhibit-startup t))
9225 (org-mode)
9226 (insert s)
9227 (goto-char (point-min))
9228 (when reference-buffer
9229 (setq org-link-abbrev-alist-local
9230 (with-current-buffer reference-buffer
9231 org-link-abbrev-alist-local)))
9232 (org-open-at-point arg reference-buffer)))))
9234 (defvar org-open-at-point-functions nil
9235 "Hook that is run when following a link at point.
9237 Functions in this hook must return t if they identify and follow
9238 a link at point. If they don't find anything interesting at point,
9239 they must return nil.")
9241 (defun org-open-at-point (&optional arg reference-buffer)
9242 "Open link at or after point.
9243 If there is no link at point, this function will search forward up to
9244 the end of the current line.
9245 Normally, files will be opened by an appropriate application. If the
9246 optional prefix argument ARG is non-nil, Emacs will visit the file.
9247 With a double prefix argument, try to open outside of Emacs, in the
9248 application the system uses for this file type."
9249 (interactive "P")
9250 ;; if in a code block, then open the block's results
9251 (unless (call-interactively #'org-babel-open-src-block-result)
9252 (org-load-modules-maybe)
9253 (move-marker org-open-link-marker (point))
9254 (setq org-window-config-before-follow-link (current-window-configuration))
9255 (org-remove-occur-highlights nil nil t)
9256 (cond
9257 ((and (org-on-heading-p)
9258 (not (org-in-regexp
9259 (concat org-plain-link-re "\\|"
9260 org-bracket-link-regexp "\\|"
9261 org-angle-link-re "\\|"
9262 "[ \t]:[^ \t\n]+:[ \t]*$")))
9263 (not (get-text-property (point) 'org-linked-text)))
9264 (or (org-offer-links-in-entry arg)
9265 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9266 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9267 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9268 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9269 (not (org-in-regexp org-bracket-link-regexp)))
9270 (org-footnote-action))
9272 (let (type path link line search (pos (point)))
9273 (catch 'match
9274 (save-excursion
9275 (skip-chars-forward "^]\n\r")
9276 (when (org-in-regexp org-bracket-link-regexp 1)
9277 (setq link (org-extract-attributes
9278 (org-link-unescape (org-match-string-no-properties 1))))
9279 (while (string-match " *\n *" link)
9280 (setq link (replace-match " " t t link)))
9281 (setq link (org-link-expand-abbrev link))
9282 (cond
9283 ((or (file-name-absolute-p link)
9284 (string-match "^\\.\\.?/" link))
9285 (setq type "file" path link))
9286 ((string-match org-link-re-with-space3 link)
9287 (setq type (match-string 1 link) path (match-string 2 link)))
9288 (t (setq type "thisfile" path link)))
9289 (throw 'match t)))
9291 (when (get-text-property (point) 'org-linked-text)
9292 (setq type "thisfile"
9293 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9294 (1+ (point)) (point))
9295 path (buffer-substring
9296 (or (previous-single-property-change pos 'org-linked-text)
9297 (point-min))
9298 (or (next-single-property-change pos 'org-linked-text)
9299 (point-max))))
9300 (throw 'match t))
9302 (save-excursion
9303 (when (or (org-in-regexp org-angle-link-re)
9304 (org-in-regexp org-plain-link-re))
9305 (setq type (match-string 1) path (match-string 2))
9306 (throw 'match t)))
9307 (save-excursion
9308 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9309 (setq type "tags"
9310 path (match-string 1))
9311 (while (string-match ":" path)
9312 (setq path (replace-match "+" t t path)))
9313 (throw 'match t)))
9314 (when (org-in-regexp "<\\([^><\n]+\\)>")
9315 (setq type "tree-match"
9316 path (match-string 1))
9317 (throw 'match t)))
9318 (unless path
9319 (error "No link found"))
9321 ;; switch back to reference buffer
9322 ;; needed when if called in a temporary buffer through
9323 ;; org-open-link-from-string
9324 (with-current-buffer (or reference-buffer (current-buffer))
9326 ;; Remove any trailing spaces in path
9327 (if (string-match " +\\'" path)
9328 (setq path (replace-match "" t t path)))
9329 (if (and org-link-translation-function
9330 (fboundp org-link-translation-function))
9331 ;; Check if we need to translate the link
9332 (let ((tmp (funcall org-link-translation-function type path)))
9333 (setq type (car tmp) path (cdr tmp))))
9335 (cond
9337 ((assoc type org-link-protocols)
9338 (funcall (nth 1 (assoc type org-link-protocols)) path))
9340 ((equal type "mailto")
9341 (let ((cmd (car org-link-mailto-program))
9342 (args (cdr org-link-mailto-program)) args1
9343 (address path) (subject "") a)
9344 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9345 (setq address (match-string 1 path)
9346 subject (org-link-escape (match-string 2 path))))
9347 (while args
9348 (cond
9349 ((not (stringp (car args))) (push (pop args) args1))
9350 (t (setq a (pop args))
9351 (if (string-match "%a" a)
9352 (setq a (replace-match address t t a)))
9353 (if (string-match "%s" a)
9354 (setq a (replace-match subject t t a)))
9355 (push a args1))))
9356 (apply cmd (nreverse args1))))
9358 ((member type '("http" "https" "ftp" "news"))
9359 (browse-url (concat type ":" (org-link-escape
9360 path org-link-escape-chars-browser))))
9362 ((string= type "doi")
9363 (browse-url (concat "http://dx.doi.org/"
9364 (org-link-escape
9365 path org-link-escape-chars-browser))))
9367 ((member type '("message"))
9368 (browse-url (concat type ":" path)))
9370 ((string= type "tags")
9371 (org-tags-view arg path))
9373 ((string= type "tree-match")
9374 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9376 ((string= type "file")
9377 (if (string-match "::\\([0-9]+\\)\\'" path)
9378 (setq line (string-to-number (match-string 1 path))
9379 path (substring path 0 (match-beginning 0)))
9380 (if (string-match "::\\(.+\\)\\'" path)
9381 (setq search (match-string 1 path)
9382 path (substring path 0 (match-beginning 0)))))
9383 (if (string-match "[*?{]" (file-name-nondirectory path))
9384 (dired path)
9385 (org-open-file path arg line search)))
9387 ((string= type "shell")
9388 (let ((cmd path))
9389 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9390 (string-match org-confirm-shell-link-not-regexp cmd))
9391 (not org-confirm-shell-link-function)
9392 (funcall org-confirm-shell-link-function
9393 (format "Execute \"%s\" in shell? "
9394 (org-add-props cmd nil
9395 'face 'org-warning))))
9396 (progn
9397 (message "Executing %s" cmd)
9398 (shell-command cmd))
9399 (error "Abort"))))
9401 ((string= type "elisp")
9402 (let ((cmd path))
9403 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9404 (string-match org-confirm-elisp-link-not-regexp cmd))
9405 (not org-confirm-elisp-link-function)
9406 (funcall org-confirm-elisp-link-function
9407 (format "Execute \"%s\" as elisp? "
9408 (org-add-props cmd nil
9409 'face 'org-warning))))
9410 (message "%s => %s" cmd
9411 (if (equal (string-to-char cmd) ?\()
9412 (eval (read cmd))
9413 (call-interactively (read cmd))))
9414 (error "Abort"))))
9416 ((and (string= type "thisfile")
9417 (run-hook-with-args-until-success
9418 'org-open-link-functions path)))
9420 ((string= type "thisfile")
9421 (if arg
9422 (switch-to-buffer-other-window
9423 (org-get-buffer-for-internal-link (current-buffer)))
9424 (org-mark-ring-push))
9425 (let ((cmd `(org-link-search
9426 ,path
9427 ,(cond ((equal arg '(4)) ''occur)
9428 ((equal arg '(16)) ''org-occur)
9429 (t nil))
9430 ,pos)))
9431 (condition-case nil (eval cmd)
9432 (error (progn (widen) (eval cmd))))))
9435 (browse-url-at-point)))))))
9436 (move-marker org-open-link-marker nil)
9437 (run-hook-with-args 'org-follow-link-hook)))
9439 (defun org-offer-links-in-entry (&optional nth zero)
9440 "Offer links in the current entry and follow the selected link.
9441 If there is only one link, follow it immediately as well.
9442 If NTH is an integer, immediately pick the NTH link found.
9443 If ZERO is a string, check also this string for a link, and if
9444 there is one, offer it as link number zero."
9445 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9446 "\\(" org-angle-link-re "\\)\\|"
9447 "\\(" org-plain-link-re "\\)"))
9448 (cnt ?0)
9449 (in-emacs (if (integerp nth) nil nth))
9450 have-zero end links link c)
9451 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9452 (push (match-string 0 zero) links)
9453 (setq cnt (1- cnt) have-zero t))
9454 (save-excursion
9455 (org-back-to-heading t)
9456 (setq end (save-excursion (outline-next-heading) (point)))
9457 (while (re-search-forward re end t)
9458 (push (match-string 0) links))
9459 (setq links (org-uniquify (reverse links))))
9461 (cond
9462 ((null links)
9463 (message "No links"))
9464 ((equal (length links) 1)
9465 (setq link (list (car links))))
9466 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9467 (setq link (nth (if have-zero nth (1- nth)) links)))
9468 (t ; we have to select a link
9469 (save-excursion
9470 (save-window-excursion
9471 (delete-other-windows)
9472 (with-output-to-temp-buffer "*Select Link*"
9473 (mapc (lambda (l)
9474 (if (not (string-match org-bracket-link-regexp l))
9475 (princ (format "[%c] %s\n" (incf cnt)
9476 (org-remove-angle-brackets l)))
9477 (if (match-end 3)
9478 (princ (format "[%c] %s (%s)\n" (incf cnt)
9479 (match-string 3 l) (match-string 1 l)))
9480 (princ (format "[%c] %s\n" (incf cnt)
9481 (match-string 1 l))))))
9482 links))
9483 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9484 (message "Select link to open, RET to open all:")
9485 (setq c (read-char-exclusive))
9486 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9487 (when (equal c ?q) (error "Abort"))
9488 (if (equal c ?\C-m)
9489 (setq link links)
9490 (setq nth (- c ?0))
9491 (if have-zero (setq nth (1+ nth)))
9492 (unless (and (integerp nth) (>= (length links) nth))
9493 (error "Invalid link selection"))
9494 (setq link (list (nth (1- nth) links))))))
9495 (if link
9496 (let ((buf (current-buffer)))
9497 (dolist (l link)
9498 (org-open-link-from-string l in-emacs buf))
9500 nil)))
9502 ;; Add special file links that specify the way of opening
9504 (org-add-link-type "file+sys" 'org-open-file-with-system)
9505 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9506 (defun org-open-file-with-system (path)
9507 "Open file at PATH using the system way of opening it."
9508 (org-open-file path 'system))
9509 (defun org-open-file-with-emacs (path)
9510 "Open file at PATH in Emacs."
9511 (org-open-file path 'emacs))
9512 (defun org-remove-file-link-modifiers ()
9513 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9514 (goto-char (point-min))
9515 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9516 (org-if-unprotected
9517 (replace-match "file:" t t))))
9518 (eval-after-load "org-exp"
9519 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9520 'org-remove-file-link-modifiers))
9522 ;;;; Time estimates
9524 (defun org-get-effort (&optional pom)
9525 "Get the effort estimate for the current entry."
9526 (org-entry-get pom org-effort-property))
9528 ;;; File search
9530 (defvar org-create-file-search-functions nil
9531 "List of functions to construct the right search string for a file link.
9532 These functions are called in turn with point at the location to
9533 which the link should point.
9535 A function in the hook should first test if it would like to
9536 handle this file type, for example by checking the `major-mode'
9537 or the file extension. If it decides not to handle this file, it
9538 should just return nil to give other functions a chance. If it
9539 does handle the file, it must return the search string to be used
9540 when following the link. The search string will be part of the
9541 file link, given after a double colon, and `org-open-at-point'
9542 will automatically search for it. If special measures must be
9543 taken to make the search successful, another function should be
9544 added to the companion hook `org-execute-file-search-functions',
9545 which see.
9547 A function in this hook may also use `setq' to set the variable
9548 `description' to provide a suggestion for the descriptive text to
9549 be used for this link when it gets inserted into an Org-mode
9550 buffer with \\[org-insert-link].")
9552 (defvar org-execute-file-search-functions nil
9553 "List of functions to execute a file search triggered by a link.
9555 Functions added to this hook must accept a single argument, the
9556 search string that was part of the file link, the part after the
9557 double colon. The function must first check if it would like to
9558 handle this search, for example by checking the `major-mode' or
9559 the file extension. If it decides not to handle this search, it
9560 should just return nil to give other functions a chance. If it
9561 does handle the search, it must return a non-nil value to keep
9562 other functions from trying.
9564 Each function can access the current prefix argument through the
9565 variable `current-prefix-argument'. Note that a single prefix is
9566 used to force opening a link in Emacs, so it may be good to only
9567 use a numeric or double prefix to guide the search function.
9569 In case this is needed, a function in this hook can also restore
9570 the window configuration before `org-open-at-point' was called using:
9572 (set-window-configuration org-window-config-before-follow-link)")
9574 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9575 (defun org-link-search (s &optional type avoid-pos)
9576 "Search for a link search option.
9577 If S is surrounded by forward slashes, it is interpreted as a
9578 regular expression. In org-mode files, this will create an `org-occur'
9579 sparse tree. In ordinary files, `occur' will be used to list matches.
9580 If the current buffer is in `dired-mode', grep will be used to search
9581 in all files. If AVOID-POS is given, ignore matches near that position."
9582 (let ((case-fold-search t)
9583 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9584 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9585 (append '(("") (" ") ("\t") ("\n"))
9586 org-emphasis-alist)
9587 "\\|") "\\)"))
9588 (pos (point))
9589 (pre nil) (post nil)
9590 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9591 (cond
9592 ;; First check if there are any special search functions
9593 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9594 ;; Now try the builtin stuff
9595 ((and (equal (string-to-char s0) ?#)
9596 (> (length s0) 1)
9597 (save-excursion
9598 (goto-char (point-min))
9599 (and
9600 (re-search-forward
9601 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9602 (setq type 'dedicated
9603 pos (match-beginning 0))))
9604 ;; There is an exact target for this
9605 (goto-char pos)
9606 (org-back-to-heading t)))
9607 ((save-excursion
9608 (goto-char (point-min))
9609 (and
9610 (re-search-forward
9611 (concat "<<" (regexp-quote s0) ">>") nil t)
9612 (setq type 'dedicated
9613 pos (match-beginning 0))))
9614 ;; There is an exact target for this
9615 (goto-char pos))
9616 ((and (string-match "^(\\(.*\\))$" s0)
9617 (save-excursion
9618 (goto-char (point-min))
9619 (and
9620 (re-search-forward
9621 (concat "[^[]" (regexp-quote
9622 (format org-coderef-label-format
9623 (match-string 1 s0))))
9624 nil t)
9625 (setq type 'dedicated
9626 pos (1+ (match-beginning 0))))))
9627 ;; There is a coderef target for this
9628 (goto-char pos))
9629 ((string-match "^/\\(.*\\)/$" s)
9630 ;; A regular expression
9631 (cond
9632 ((org-mode-p)
9633 (org-occur (match-string 1 s)))
9634 ;;((eq major-mode 'dired-mode)
9635 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9636 (t (org-do-occur (match-string 1 s)))))
9637 ((and (org-mode-p) org-link-search-must-match-exact-headline)
9638 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9639 (goto-char (point-min))
9640 (cond
9641 ((let (case-fold-search)
9642 (re-search-forward (format org-complex-heading-regexp-format
9643 (regexp-quote s))
9644 nil t))
9645 ;; OK, found a match
9646 (setq type 'dedicated)
9647 (goto-char (match-beginning 0)))
9648 ((and (not org-link-search-inhibit-query)
9649 (eq org-link-search-must-match-exact-headline 'query-to-create)
9650 (y-or-n-p "No match - create this as a new heading? "))
9651 (goto-char (point-max))
9652 (or (bolp) (newline))
9653 (insert "* " s "\n")
9654 (beginning-of-line 0))
9656 (goto-char pos)
9657 (error "No match"))))
9659 ;; A normal search string
9660 (when (equal (string-to-char s) ?*)
9661 ;; Anchor on headlines, post may include tags.
9662 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9663 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9664 s (substring s 1)))
9665 (remove-text-properties
9666 0 (length s)
9667 '(face nil mouse-face nil keymap nil fontified nil) s)
9668 ;; Make a series of regular expressions to find a match
9669 (setq words (org-split-string s "[ \n\r\t]+")
9671 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9672 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9673 "\\)" markers)
9674 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9675 re2a (concat "[ \t\r\n]" re2a_)
9676 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9677 re4 (concat "[^a-zA-Z_]" re4_)
9679 re1 (concat pre re2 post)
9680 re3 (concat pre (if pre re4_ re4) post)
9681 re5 (concat pre ".*" re4)
9682 re2 (concat pre re2)
9683 re2a (concat pre (if pre re2a_ re2a))
9684 re4 (concat pre (if pre re4_ re4))
9685 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9686 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9687 re5 "\\)"
9689 (cond
9690 ((eq type 'org-occur) (org-occur reall))
9691 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9692 (t (goto-char (point-min))
9693 (setq type 'fuzzy)
9694 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9695 (org-search-not-self 1 re1 nil t)
9696 (org-search-not-self 1 re2 nil t)
9697 (org-search-not-self 1 re2a nil t)
9698 (org-search-not-self 1 re3 nil t)
9699 (org-search-not-self 1 re4 nil t)
9700 (org-search-not-self 1 re5 nil t)
9702 (goto-char (match-beginning 1))
9703 (goto-char pos)
9704 (error "No match"))))))
9705 (and (org-mode-p) (org-show-context 'link-search))
9706 type))
9708 (defun org-search-not-self (group &rest args)
9709 "Execute `re-search-forward', but only accept matches that do not
9710 enclose the position of `org-open-link-marker'."
9711 (let ((m org-open-link-marker))
9712 (catch 'exit
9713 (while (apply 're-search-forward args)
9714 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9715 (goto-char (match-end group))
9716 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9717 (> (match-beginning 0) (marker-position m))
9718 (< (match-end 0) (marker-position m)))
9719 (save-match-data
9720 (or (not (org-in-regexp
9721 org-bracket-link-analytic-regexp 1))
9722 (not (match-end 4)) ; no description
9723 (and (<= (match-beginning 4) (point))
9724 (>= (match-end 4) (point))))))
9725 (throw 'exit (point))))))))
9727 (defun org-get-buffer-for-internal-link (buffer)
9728 "Return a buffer to be used for displaying the link target of internal links."
9729 (cond
9730 ((not org-display-internal-link-with-indirect-buffer)
9731 buffer)
9732 ((string-match "(Clone)$" (buffer-name buffer))
9733 (message "Buffer is already a clone, not making another one")
9734 ;; we also do not modify visibility in this case
9735 buffer)
9736 (t ; make a new indirect buffer for displaying the link
9737 (let* ((bn (buffer-name buffer))
9738 (ibn (concat bn "(Clone)"))
9739 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9740 (with-current-buffer ib (org-overview))
9741 ib))))
9743 (defun org-do-occur (regexp &optional cleanup)
9744 "Call the Emacs command `occur'.
9745 If CLEANUP is non-nil, remove the printout of the regular expression
9746 in the *Occur* buffer. This is useful if the regex is long and not useful
9747 to read."
9748 (occur regexp)
9749 (when cleanup
9750 (let ((cwin (selected-window)) win beg end)
9751 (when (setq win (get-buffer-window "*Occur*"))
9752 (select-window win))
9753 (goto-char (point-min))
9754 (when (re-search-forward "match[a-z]+" nil t)
9755 (setq beg (match-end 0))
9756 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9757 (setq end (1- (match-beginning 0)))))
9758 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9759 (goto-char (point-min))
9760 (select-window cwin))))
9762 ;;; The mark ring for links jumps
9764 (defvar org-mark-ring nil
9765 "Mark ring for positions before jumps in Org-mode.")
9766 (defvar org-mark-ring-last-goto nil
9767 "Last position in the mark ring used to go back.")
9768 ;; Fill and close the ring
9769 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9770 (loop for i from 1 to org-mark-ring-length do
9771 (push (make-marker) org-mark-ring))
9772 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9773 org-mark-ring)
9775 (defun org-mark-ring-push (&optional pos buffer)
9776 "Put the current position or POS into the mark ring and rotate it."
9777 (interactive)
9778 (setq pos (or pos (point)))
9779 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9780 (move-marker (car org-mark-ring)
9781 (or pos (point))
9782 (or buffer (current-buffer)))
9783 (message "%s"
9784 (substitute-command-keys
9785 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9787 (defun org-mark-ring-goto (&optional n)
9788 "Jump to the previous position in the mark ring.
9789 With prefix arg N, jump back that many stored positions. When
9790 called several times in succession, walk through the entire ring.
9791 Org-mode commands jumping to a different position in the current file,
9792 or to another Org-mode file, automatically push the old position
9793 onto the ring."
9794 (interactive "p")
9795 (let (p m)
9796 (if (eq last-command this-command)
9797 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9798 (setq p org-mark-ring))
9799 (setq org-mark-ring-last-goto p)
9800 (setq m (car p))
9801 (switch-to-buffer (marker-buffer m))
9802 (goto-char m)
9803 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9805 (defun org-remove-angle-brackets (s)
9806 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9807 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9809 (defun org-add-angle-brackets (s)
9810 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9811 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9813 (defun org-remove-double-quotes (s)
9814 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9815 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
9818 ;;; Following specific links
9820 (defun org-follow-timestamp-link ()
9821 (cond
9822 ((org-at-date-range-p t)
9823 (let ((org-agenda-start-on-weekday)
9824 (t1 (match-string 1))
9825 (t2 (match-string 2)))
9826 (setq t1 (time-to-days (org-time-string-to-time t1))
9827 t2 (time-to-days (org-time-string-to-time t2)))
9828 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9829 ((org-at-timestamp-p t)
9830 (org-agenda-list nil (time-to-days (org-time-string-to-time
9831 (substring (match-string 1) 0 10)))
9833 (t (error "This should not happen"))))
9836 ;;; Following file links
9837 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
9838 (declare-function mailcap-extension-to-mime "mailcap" (extn))
9839 (declare-function mailcap-mime-info
9840 "mailcap" (string &optional request no-decode))
9841 (defvar org-wait nil)
9842 (defun org-open-file (path &optional in-emacs line search)
9843 "Open the file at PATH.
9844 First, this expands any special file name abbreviations. Then the
9845 configuration variable `org-file-apps' is checked if it contains an
9846 entry for this file type, and if yes, the corresponding command is launched.
9848 If no application is found, Emacs simply visits the file.
9850 With optional prefix argument IN-EMACS, Emacs will visit the file.
9851 With a double \\[universal-argument] \\[universal-argument] \
9852 prefix arg, Org tries to avoid opening in Emacs
9853 and to use an external application to visit the file.
9855 Optional LINE specifies a line to go to, optional SEARCH a string
9856 to search for. If LINE or SEARCH is given, the file will be
9857 opened in Emacs, unless an entry from org-file-apps that makes
9858 use of groups in a regexp matches.
9859 If the file does not exist, an error is thrown."
9860 (let* ((file (if (equal path "")
9861 buffer-file-name
9862 (substitute-in-file-name (expand-file-name path))))
9863 (file-apps (append org-file-apps (org-default-apps)))
9864 (apps (org-remove-if
9865 'org-file-apps-entry-match-against-dlink-p file-apps))
9866 (apps-dlink (org-remove-if-not
9867 'org-file-apps-entry-match-against-dlink-p file-apps))
9868 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9869 (dirp (if remp nil (file-directory-p file)))
9870 (file (if (and dirp org-open-directory-means-index-dot-org)
9871 (concat (file-name-as-directory file) "index.org")
9872 file))
9873 (a-m-a-p (assq 'auto-mode apps))
9874 (dfile (downcase file))
9875 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
9876 (link (cond ((and (eq line nil)
9877 (eq search nil))
9878 file)
9879 (line
9880 (concat file "::" (number-to-string line)))
9881 (search
9882 (concat file "::" search))))
9883 (dlink (downcase link))
9884 (old-buffer (current-buffer))
9885 (old-pos (point))
9886 (old-mode major-mode)
9887 ext cmd link-match-data)
9888 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9889 (setq ext (match-string 1 dfile))
9890 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9891 (setq ext (match-string 1 dfile))))
9892 (cond
9893 ((member in-emacs '((16) system))
9894 (setq cmd (cdr (assoc 'system apps))))
9895 (in-emacs (setq cmd 'emacs))
9897 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9898 (and dirp (cdr (assoc 'directory apps)))
9899 ; first, try matching against apps-dlink
9900 ; if we get a match here, store the match data for later
9901 (let ((match (assoc-default dlink apps-dlink
9902 'string-match)))
9903 (if match
9904 (progn (setq link-match-data (match-data))
9905 match)
9906 (progn (setq in-emacs (or in-emacs line search))
9907 nil))) ; if we have no match in apps-dlink,
9908 ; always open the file in emacs if line or search
9909 ; is given (for backwards compatibility)
9910 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
9911 'string-match)
9912 (cdr (assoc ext apps))
9913 (cdr (assoc t apps))))))
9914 (when (eq cmd 'system)
9915 (setq cmd (cdr (assoc 'system apps))))
9916 (when (eq cmd 'default)
9917 (setq cmd (cdr (assoc t apps))))
9918 (when (eq cmd 'mailcap)
9919 (require 'mailcap)
9920 (mailcap-parse-mailcaps)
9921 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9922 (command (mailcap-mime-info mime-type)))
9923 (if (stringp command)
9924 (setq cmd command)
9925 (setq cmd 'emacs))))
9926 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
9927 (not (file-exists-p file))
9928 (not org-open-non-existing-files))
9929 (error "No such file: %s" file))
9930 (cond
9931 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9932 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9933 (while (string-match "['\"]%s['\"]" cmd)
9934 (setq cmd (replace-match "%s" t t cmd)))
9935 (while (string-match "%s" cmd)
9936 (setq cmd (replace-match
9937 (save-match-data
9938 (shell-quote-argument
9939 (convert-standard-filename file)))
9940 t t cmd)))
9942 ;; Replace "%1", "%2" etc. in command with group matches from regex
9943 (save-match-data
9944 (let ((match-index 1)
9945 (number-of-groups (- (/ (length link-match-data) 2) 1)))
9946 (set-match-data link-match-data)
9947 (while (<= match-index number-of-groups)
9948 (let ((regex (concat "%" (number-to-string match-index)))
9949 (replace-with (match-string match-index dlink)))
9950 (while (string-match regex cmd)
9951 (setq cmd (replace-match replace-with t t cmd))))
9952 (setq match-index (+ match-index 1)))))
9954 (save-window-excursion
9955 (start-process-shell-command cmd nil cmd)
9956 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9958 ((or (stringp cmd)
9959 (eq cmd 'emacs))
9960 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9961 (widen)
9962 (if line (org-goto-line line)
9963 (if search (org-link-search search))))
9964 ((consp cmd)
9965 (let ((file (convert-standard-filename file)))
9966 (save-match-data
9967 (set-match-data link-match-data)
9968 (eval cmd))))
9969 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9970 (and (org-mode-p) (eq old-mode 'org-mode)
9971 (or (not (equal old-buffer (current-buffer)))
9972 (not (equal old-pos (point))))
9973 (org-mark-ring-push old-pos old-buffer))))
9975 (defun org-file-apps-entry-match-against-dlink-p (entry)
9976 "This function returns non-nil if `entry' uses a regular
9977 expression which should be matched against the whole link by
9978 org-open-file.
9980 It assumes that is the case when the entry uses a regular
9981 expression which has at least one grouping construct and the
9982 action is either a lisp form or a command string containing
9983 '%1', i.e. using at least one subexpression match as a
9984 parameter."
9985 (let ((selector (car entry))
9986 (action (cdr entry)))
9987 (if (stringp selector)
9988 (and (> (regexp-opt-depth selector) 0)
9989 (or (and (stringp action)
9990 (string-match "%[0-9]" action))
9991 (consp action)))
9992 nil)))
9994 (defun org-default-apps ()
9995 "Return the default applications for this operating system."
9996 (cond
9997 ((eq system-type 'darwin)
9998 org-file-apps-defaults-macosx)
9999 ((eq system-type 'windows-nt)
10000 org-file-apps-defaults-windowsnt)
10001 (t org-file-apps-defaults-gnu)))
10003 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10004 "Convert extensions to regular expressions in the cars of LIST.
10005 Also, weed out any non-string entries, because the return value is used
10006 only for regexp matching.
10007 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10008 point to the symbol `emacs', indicating that the file should
10009 be opened in Emacs."
10010 (append
10011 (delq nil
10012 (mapcar (lambda (x)
10013 (if (not (stringp (car x)))
10015 (if (string-match "\\W" (car x))
10017 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10018 list))
10019 (if add-auto-mode
10020 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10022 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10023 (defun org-file-remote-p (file)
10024 "Test whether FILE specifies a location on a remote system.
10025 Return non-nil if the location is indeed remote.
10027 For example, the filename \"/user@host:/foo\" specifies a location
10028 on the system \"/user@host:\"."
10029 (cond ((fboundp 'file-remote-p)
10030 (file-remote-p file))
10031 ((fboundp 'tramp-handle-file-remote-p)
10032 (tramp-handle-file-remote-p file))
10033 ((and (boundp 'ange-ftp-name-format)
10034 (string-match (car ange-ftp-name-format) file))
10036 (t nil)))
10039 ;;;; Refiling
10041 (defun org-get-org-file ()
10042 "Read a filename, with default directory `org-directory'."
10043 (let ((default (or org-default-notes-file remember-data-file)))
10044 (read-file-name (format "File name [%s]: " default)
10045 (file-name-as-directory org-directory)
10046 default)))
10048 (defun org-notes-order-reversed-p ()
10049 "Check if the current file should receive notes in reversed order."
10050 (cond
10051 ((not org-reverse-note-order) nil)
10052 ((eq t org-reverse-note-order) t)
10053 ((not (listp org-reverse-note-order)) nil)
10054 (t (catch 'exit
10055 (let ((all org-reverse-note-order)
10056 entry)
10057 (while (setq entry (pop all))
10058 (if (string-match (car entry) buffer-file-name)
10059 (throw 'exit (cdr entry))))
10060 nil)))))
10062 (defvar org-refile-target-table nil
10063 "The list of refile targets, created by `org-refile'.")
10065 (defvar org-agenda-new-buffers nil
10066 "Buffers created to visit agenda files.")
10068 (defvar org-refile-cache nil
10069 "Cache for refile targets.")
10071 (defvar org-refile-markers nil
10072 "All the markers used for caching refile locations.")
10074 (defun org-refile-marker (pos)
10075 "Get a new refile marker, but only if caching is in use."
10076 (if (not org-refile-use-cache)
10078 (let ((m (make-marker)))
10079 (move-marker m pos)
10080 (push m org-refile-markers)
10081 m)))
10083 (defun org-refile-cache-clear ()
10084 "Clear the refile cache and disable all the markers."
10085 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10086 (setq org-refile-markers nil)
10087 (setq org-refile-cache nil)
10088 (message "Refile cache has been cleared"))
10090 (defun org-refile-cache-check-set (set)
10091 "Check if all the markers in the cache still have live buffers."
10092 (let (marker)
10093 (catch 'exit
10094 (while (and set (setq marker (nth 3 (pop set))))
10095 ;; if org-refile-use-outline-path is 'file, marker may be nil
10096 (when (and marker (null (marker-buffer marker)))
10097 (message "not found") (sit-for 3)
10098 (throw 'exit nil)))
10099 t)))
10101 (defun org-refile-cache-put (set &rest identifiers)
10102 "Push the refile targets SET into the cache, under IDENTIFIERS."
10103 (let* ((key (sha1 (prin1-to-string identifiers)))
10104 (entry (assoc key org-refile-cache)))
10105 (if entry
10106 (setcdr entry set)
10107 (push (cons key set) org-refile-cache))))
10109 (defun org-refile-cache-get (&rest identifiers)
10110 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10111 (cond
10112 ((not org-refile-cache) nil)
10113 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10115 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10116 org-refile-cache))))
10117 (and set (org-refile-cache-check-set set) set)))))
10119 (defun org-refile-get-targets (&optional default-buffer)
10120 "Produce a table with refile targets."
10121 (let ((case-fold-search nil)
10122 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10123 (entries (or org-refile-targets '((nil . (:level . 1)))))
10124 targets tgs txt re files f desc descre fast-path-p level pos0)
10125 (message "Getting targets...")
10126 (with-current-buffer (or default-buffer (current-buffer))
10127 (while (setq entry (pop entries))
10128 (setq files (car entry) desc (cdr entry))
10129 (setq fast-path-p nil)
10130 (cond
10131 ((null files) (setq files (list (current-buffer))))
10132 ((eq files 'org-agenda-files)
10133 (setq files (org-agenda-files 'unrestricted)))
10134 ((and (symbolp files) (fboundp files))
10135 (setq files (funcall files)))
10136 ((and (symbolp files) (boundp files))
10137 (setq files (symbol-value files))))
10138 (if (stringp files) (setq files (list files)))
10139 (cond
10140 ((eq (car desc) :tag)
10141 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10142 ((eq (car desc) :todo)
10143 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10144 ((eq (car desc) :regexp)
10145 (setq descre (cdr desc)))
10146 ((eq (car desc) :level)
10147 (setq descre (concat "^\\*\\{" (number-to-string
10148 (if org-odd-levels-only
10149 (1- (* 2 (cdr desc)))
10150 (cdr desc)))
10151 "\\}[ \t]")))
10152 ((eq (car desc) :maxlevel)
10153 (setq fast-path-p t)
10154 (setq descre (concat "^\\*\\{1," (number-to-string
10155 (if org-odd-levels-only
10156 (1- (* 2 (cdr desc)))
10157 (cdr desc)))
10158 "\\}[ \t]")))
10159 (t (error "Bad refiling target description %s" desc)))
10160 (while (setq f (pop files))
10161 (with-current-buffer
10162 (if (bufferp f) f (org-get-agenda-file-buffer f))
10164 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10165 (progn
10166 (if (bufferp f) (setq f (buffer-file-name
10167 (buffer-base-buffer f))))
10168 (setq f (and f (expand-file-name f)))
10169 (if (eq org-refile-use-outline-path 'file)
10170 (push (list (file-name-nondirectory f) f nil nil) tgs))
10171 (save-excursion
10172 (save-restriction
10173 (widen)
10174 (goto-char (point-min))
10175 (while (re-search-forward descre nil t)
10176 (goto-char (setq pos0 (point-at-bol)))
10177 (catch 'next
10178 (when org-refile-target-verify-function
10179 (save-match-data
10180 (or (funcall org-refile-target-verify-function)
10181 (throw 'next t))))
10182 (when (looking-at org-complex-heading-regexp)
10183 (setq level (org-reduced-level
10184 (- (match-end 1) (match-beginning 1)))
10185 txt (org-link-display-format (match-string 4))
10186 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10187 re (format org-complex-heading-regexp-format
10188 (regexp-quote (match-string 4))))
10189 (when org-refile-use-outline-path
10190 (setq txt (mapconcat
10191 'org-protect-slash
10192 (append
10193 (if (eq org-refile-use-outline-path
10194 'file)
10195 (list (file-name-nondirectory
10196 (buffer-file-name
10197 (buffer-base-buffer))))
10198 (if (eq org-refile-use-outline-path
10199 'full-file-path)
10200 (list (buffer-file-name
10201 (buffer-base-buffer)))))
10202 (org-get-outline-path fast-path-p
10203 level txt)
10204 (list txt))
10205 "/")))
10206 (push (list txt f re (org-refile-marker (point)))
10207 tgs)))
10208 (when (= (point) pos0)
10209 ;; verification function has not moved point
10210 (goto-char (point-at-eol))))))))
10211 (when org-refile-use-cache
10212 (org-refile-cache-put tgs (buffer-file-name) descre))
10213 (setq targets (append tgs targets))
10214 ))))
10215 (message "Getting targets...done")
10216 (nreverse targets)))
10218 (defun org-protect-slash (s)
10219 (while (string-match "/" s)
10220 (setq s (replace-match "\\" t t s)))
10223 (defvar org-olpa (make-vector 20 nil))
10225 (defun org-get-outline-path (&optional fastp level heading)
10226 "Return the outline path to the current entry, as a list.
10228 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10229 routine which makes outline path derivations for an entire file,
10230 avoiding backtracing. Refile target collection makes use of that."
10231 (if fastp
10232 (progn
10233 (if (> level 19)
10234 (error "Outline path failure, more than 19 levels"))
10235 (loop for i from level upto 19 do
10236 (aset org-olpa i nil))
10237 (prog1
10238 (delq nil (append org-olpa nil))
10239 (aset org-olpa level heading)))
10240 (let (rtn case-fold-search)
10241 (save-excursion
10242 (save-restriction
10243 (widen)
10244 (while (org-up-heading-safe)
10245 (when (looking-at org-complex-heading-regexp)
10246 (push (org-match-string-no-properties 4) rtn)))
10247 rtn)))))
10249 (defun org-format-outline-path (path &optional width prefix)
10250 "Format the outline path PATH for display.
10251 Width is the maximum number of characters that is available.
10252 Prefix is a prefix to be included in the returned string,
10253 such as the file name."
10254 (setq width (or width 79))
10255 (if prefix (setq width (- width (length prefix))))
10256 (if (not path)
10257 (or prefix "")
10258 (let* ((nsteps (length path))
10259 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10260 (maxwidth (if (<= total-width width)
10261 10000 ;; everything fits
10262 ;; we need to shorten the level headings
10263 (/ (- width nsteps) nsteps)))
10264 (org-odd-levels-only nil)
10265 (n 0)
10266 (total (1+ (length prefix))))
10267 (setq maxwidth (max maxwidth 10))
10268 (concat prefix
10269 (mapconcat
10270 (lambda (h)
10271 (setq n (1+ n))
10272 (if (and (= n nsteps) (< maxwidth 10000))
10273 (setq maxwidth (- total-width total)))
10274 (if (< (length h) maxwidth)
10275 (progn (setq total (+ total (length h) 1)) h)
10276 (setq h (substring h 0 (- maxwidth 2))
10277 total (+ total maxwidth 1))
10278 (if (string-match "[ \t]+\\'" h)
10279 (setq h (substring h 0 (match-beginning 0))))
10280 (setq h (concat h "..")))
10281 (org-add-props h nil 'face
10282 (nth (% (1- n) org-n-level-faces)
10283 org-level-faces))
10285 path "/")))))
10287 (defun org-display-outline-path (&optional file current)
10288 "Display the current outline path in the echo area."
10289 (interactive "P")
10290 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10291 (case-fold-search nil)
10292 (path (and (org-mode-p) (org-get-outline-path))))
10293 (if current (setq path (append path
10294 (save-excursion
10295 (org-back-to-heading t)
10296 (if (looking-at org-complex-heading-regexp)
10297 (list (match-string 4)))))))
10298 (message "%s"
10299 (org-format-outline-path
10300 path
10301 (1- (frame-width))
10302 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10304 (defvar org-refile-history nil
10305 "History for refiling operations.")
10307 (defvar org-after-refile-insert-hook nil
10308 "Hook run after `org-refile' has inserted its stuff at the new location.
10309 Note that this is still *before* the stuff will be removed from
10310 the *old* location.")
10312 (defvar org-capture-last-stored-marker)
10313 (defun org-refile (&optional goto default-buffer rfloc)
10314 "Move the entry at point to another heading.
10315 The list of target headings is compiled using the information in
10316 `org-refile-targets', which see. This list is created before each use
10317 and will therefore always be up-to-date.
10319 At the target location, the entry is filed as a subitem of the target heading.
10320 Depending on `org-reverse-note-order', the new subitem will either be the
10321 first or the last subitem.
10323 If there is an active region, all entries in that region will be moved.
10324 However, the region must fulfill the requirement that the first heading
10325 is the first one sets the top-level of the moved text - at most siblings
10326 below it are allowed.
10328 With prefix arg GOTO, the command will only visit the target location,
10329 not actually move anything.
10330 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10331 go to the location where the last refiling
10332 operation has put the subtree.
10333 With a prefix argument of `2', refile to the running clock.
10335 RFLOC can be a refile location obtained in a different way.
10337 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10339 If you are using target caching (see `org-refile-use-cache'),
10340 You have to clear the target cache in order to find new targets.
10341 This can be done with a 0 prefix: `C-0 C-c C-w'"
10342 (interactive "P")
10343 (if (member goto '(0 (64)))
10344 (org-refile-cache-clear)
10345 (let* ((cbuf (current-buffer))
10346 (regionp (org-region-active-p))
10347 (region-start (and regionp (region-beginning)))
10348 (region-end (and regionp (region-end)))
10349 (region-length (and regionp (- region-end region-start)))
10350 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10351 pos it nbuf file re level reversed)
10352 (setq last-command nil)
10353 (when regionp
10354 (goto-char region-start)
10355 (or (bolp) (goto-char (point-at-bol)))
10356 (setq region-start (point))
10357 (unless (org-kill-is-subtree-p
10358 (buffer-substring region-start region-end))
10359 (error "The region is not a (sequence of) subtree(s)")))
10360 (if (equal goto '(16))
10361 (org-refile-goto-last-stored)
10362 (when (or
10363 (and (equal goto 2)
10364 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10365 (prog1
10366 (setq it (list (or org-clock-heading "running clock")
10367 (buffer-file-name
10368 (marker-buffer org-clock-hd-marker))
10370 (marker-position org-clock-hd-marker)))
10371 (setq goto nil)))
10372 (setq it (or rfloc
10373 (save-excursion
10374 (org-refile-get-location
10375 (if goto "Goto" "Refile to") default-buffer
10376 org-refile-allow-creating-parent-nodes)))))
10377 (setq file (nth 1 it)
10378 re (nth 2 it)
10379 pos (nth 3 it))
10380 (if (and (not goto)
10382 (equal (buffer-file-name) file)
10383 (if regionp
10384 (and (>= pos region-start)
10385 (<= pos region-end))
10386 (and (>= pos (point))
10387 (< pos (save-excursion
10388 (org-end-of-subtree t t))))))
10389 (error "Cannot refile to position inside the tree or region"))
10391 (setq nbuf (or (find-buffer-visiting file)
10392 (find-file-noselect file)))
10393 (if goto
10394 (progn
10395 (switch-to-buffer nbuf)
10396 (goto-char pos)
10397 (org-show-context 'org-goto))
10398 (if regionp
10399 (progn
10400 (org-kill-new (buffer-substring region-start region-end))
10401 (org-save-markers-in-region region-start region-end))
10402 (org-copy-subtree 1 nil t))
10403 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10404 (find-file-noselect file)))
10405 (setq reversed (org-notes-order-reversed-p))
10406 (save-excursion
10407 (save-restriction
10408 (widen)
10409 (if pos
10410 (progn
10411 (goto-char pos)
10412 (looking-at outline-regexp)
10413 (setq level (org-get-valid-level (funcall outline-level) 1))
10414 (goto-char
10415 (if reversed
10416 (or (outline-next-heading) (point-max))
10417 (or (save-excursion (org-get-next-sibling))
10418 (org-end-of-subtree t t)
10419 (point-max)))))
10420 (setq level 1)
10421 (if (not reversed)
10422 (goto-char (point-max))
10423 (goto-char (point-min))
10424 (or (outline-next-heading) (goto-char (point-max)))))
10425 (if (not (bolp)) (newline))
10426 (org-paste-subtree level)
10427 (when org-log-refile
10428 (org-add-log-setup 'refile nil nil 'findpos
10429 org-log-refile)
10430 (unless (eq org-log-refile 'note)
10431 (save-excursion (org-add-log-note))))
10432 (and org-auto-align-tags (org-set-tags nil t))
10433 (bookmark-set "org-refile-last-stored")
10434 ;; If we are refiling for capture, make sure that the
10435 ;; last-capture pointers point here
10436 (when (org-bound-and-true-p org-refile-for-capture)
10437 (bookmark-set "org-capture-last-stored-marker")
10438 (move-marker org-capture-last-stored-marker (point)))
10439 (if (fboundp 'deactivate-mark) (deactivate-mark))
10440 (run-hooks 'org-after-refile-insert-hook))))
10441 (if regionp
10442 (delete-region (point) (+ (point) region-length))
10443 (org-cut-subtree))
10444 (when (featurep 'org-inlinetask)
10445 (org-inlinetask-remove-END-maybe))
10446 (setq org-markers-to-move nil)
10447 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10449 (defun org-refile-goto-last-stored ()
10450 "Go to the location where the last refile was stored."
10451 (interactive)
10452 (bookmark-jump "org-refile-last-stored")
10453 (message "This is the location of the last refile"))
10455 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
10456 "Prompt the user for a refile location, using PROMPT.
10457 PROMPT should not be suffixed with a colon and a space, because
10458 this function appends the default value from
10459 `org-refile-history' automatically, if that is not empty."
10460 (let ((org-refile-targets org-refile-targets)
10461 (org-refile-use-outline-path org-refile-use-outline-path))
10462 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
10463 (unless org-refile-target-table
10464 (error "No refile targets"))
10465 (let* ((prompt (concat prompt
10466 (and (car org-refile-history)
10467 (concat " (default " (car org-refile-history) ")"))
10468 ": "))
10469 (cbuf (current-buffer))
10470 (partial-completion-mode nil)
10471 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10472 (cfunc (if (and org-refile-use-outline-path
10473 org-outline-path-complete-in-steps)
10474 'org-olpath-completing-read
10475 'org-icompleting-read))
10476 (extra (if org-refile-use-outline-path "/" ""))
10477 (filename (and cfn (expand-file-name cfn)))
10478 (tbl (mapcar
10479 (lambda (x)
10480 (if (and (not (member org-refile-use-outline-path
10481 '(file full-file-path)))
10482 (not (equal filename (nth 1 x))))
10483 (cons (concat (car x) extra " ("
10484 (file-name-nondirectory (nth 1 x)) ")")
10485 (cdr x))
10486 (cons (concat (car x) extra) (cdr x))))
10487 org-refile-target-table))
10488 (completion-ignore-case t)
10489 pa answ parent-target child parent old-hist)
10490 (setq old-hist org-refile-history)
10491 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10492 nil 'org-refile-history (car org-refile-history)))
10493 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10494 (org-refile-check-position pa)
10495 (if pa
10496 (progn
10497 (when (or (not org-refile-history)
10498 (not (eq old-hist org-refile-history))
10499 (not (equal (car pa) (car org-refile-history))))
10500 (setq org-refile-history
10501 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10502 org-refile-history
10503 (cdr org-refile-history))))
10504 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10505 (pop org-refile-history)))
10507 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10508 (progn
10509 (setq parent (match-string 1 answ)
10510 child (match-string 2 answ))
10511 (setq parent-target (or (assoc parent tbl)
10512 (assoc (concat parent "/") tbl)))
10513 (when (and parent-target
10514 (or (eq new-nodes t)
10515 (and (eq new-nodes 'confirm)
10516 (y-or-n-p (format "Create new node \"%s\"? "
10517 child)))))
10518 (org-refile-new-child parent-target child)))
10519 (error "Invalid target location")))))
10521 (defun org-refile-check-position (refile-pointer)
10522 "Check if the refile pointer matches the readline to which it points."
10523 (let* ((file (nth 1 refile-pointer))
10524 (re (nth 2 refile-pointer))
10525 (pos (nth 3 refile-pointer))
10526 buffer)
10527 (when (org-string-nw-p re)
10528 (setq buffer (if (markerp pos)
10529 (marker-buffer pos)
10530 (or (find-buffer-visiting file)
10531 (find-file-noselect file))))
10532 (with-current-buffer buffer
10533 (save-excursion
10534 (save-restriction
10535 (widen)
10536 (goto-char pos)
10537 (beginning-of-line 1)
10538 (unless (org-looking-at-p re)
10539 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10541 (defun org-refile-new-child (parent-target child)
10542 "Use refile target PARENT-TARGET to add new CHILD below it."
10543 (unless parent-target
10544 (error "Cannot find parent for new node"))
10545 (let ((file (nth 1 parent-target))
10546 (pos (nth 3 parent-target))
10547 level)
10548 (with-current-buffer (or (find-buffer-visiting file)
10549 (find-file-noselect file))
10550 (save-excursion
10551 (save-restriction
10552 (widen)
10553 (if pos
10554 (goto-char pos)
10555 (goto-char (point-max))
10556 (if (not (bolp)) (newline)))
10557 (when (looking-at outline-regexp)
10558 (setq level (funcall outline-level))
10559 (org-end-of-subtree t t))
10560 (org-back-over-empty-lines)
10561 (insert "\n" (make-string
10562 (if pos (org-get-valid-level level 1) 1) ?*)
10563 " " child "\n")
10564 (beginning-of-line 0)
10565 (list (concat (car parent-target) "/" child) file "" (point)))))))
10567 (defun org-olpath-completing-read (prompt collection &rest args)
10568 "Read an outline path like a file name."
10569 (let ((thetable collection)
10570 (org-completion-use-ido nil) ; does not work with ido.
10571 (org-completion-use-iswitchb nil)) ; or iswitchb
10572 (apply
10573 'org-icompleting-read prompt
10574 (lambda (string predicate &optional flag)
10575 (let (rtn r f (l (length string)))
10576 (cond
10577 ((eq flag nil)
10578 ;; try completion
10579 (try-completion string thetable))
10580 ((eq flag t)
10581 ;; all-completions
10582 (setq rtn (all-completions string thetable predicate))
10583 (mapcar
10584 (lambda (x)
10585 (setq r (substring x l))
10586 (if (string-match " ([^)]*)$" x)
10587 (setq f (match-string 0 x))
10588 (setq f ""))
10589 (if (string-match "/" r)
10590 (concat string (substring r 0 (match-end 0)) f)
10592 rtn))
10593 ((eq flag 'lambda)
10594 ;; exact match?
10595 (assoc string thetable)))
10597 args)))
10599 ;;;; Dynamic blocks
10601 (defun org-find-dblock (name)
10602 "Find the first dynamic block with name NAME in the buffer.
10603 If not found, stay at current position and return nil."
10604 (let (pos)
10605 (save-excursion
10606 (goto-char (point-min))
10607 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10608 nil t)
10609 (match-beginning 0))))
10610 (if pos (goto-char pos))
10611 pos))
10613 (defconst org-dblock-start-re
10614 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10615 "Matches the start line of a dynamic block, with parameters.")
10617 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10618 "Matches the end of a dynamic block.")
10620 (defun org-create-dblock (plist)
10621 "Create a dynamic block section, with parameters taken from PLIST.
10622 PLIST must contain a :name entry which is used as name of the block."
10623 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10624 (end-of-line 1)
10625 (newline))
10626 (let ((col (current-column))
10627 (name (plist-get plist :name)))
10628 (insert "#+BEGIN: " name)
10629 (while plist
10630 (if (eq (car plist) :name)
10631 (setq plist (cddr plist))
10632 (insert " " (prin1-to-string (pop plist)))))
10633 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10634 (beginning-of-line -2)))
10636 (defun org-prepare-dblock ()
10637 "Prepare dynamic block for refresh.
10638 This empties the block, puts the cursor at the insert position and returns
10639 the property list including an extra property :name with the block name."
10640 (unless (looking-at org-dblock-start-re)
10641 (error "Not at a dynamic block"))
10642 (let* ((begdel (1+ (match-end 0)))
10643 (name (org-no-properties (match-string 1)))
10644 (params (append (list :name name)
10645 (read (concat "(" (match-string 3) ")")))))
10646 (save-excursion
10647 (beginning-of-line 1)
10648 (skip-chars-forward " \t")
10649 (setq params (plist-put params :indentation-column (current-column))))
10650 (unless (re-search-forward org-dblock-end-re nil t)
10651 (error "Dynamic block not terminated"))
10652 (setq params
10653 (append params
10654 (list :content (buffer-substring
10655 begdel (match-beginning 0)))))
10656 (delete-region begdel (match-beginning 0))
10657 (goto-char begdel)
10658 (open-line 1)
10659 params))
10661 (defun org-map-dblocks (&optional command)
10662 "Apply COMMAND to all dynamic blocks in the current buffer.
10663 If COMMAND is not given, use `org-update-dblock'."
10664 (let ((cmd (or command 'org-update-dblock)))
10665 (save-excursion
10666 (goto-char (point-min))
10667 (while (re-search-forward org-dblock-start-re nil t)
10668 (goto-char (match-beginning 0))
10669 (save-excursion
10670 (condition-case nil
10671 (funcall cmd)
10672 (error (message "Error during update of dynamic block"))))
10673 (unless (re-search-forward org-dblock-end-re nil t)
10674 (error "Dynamic block not terminated"))))))
10676 (defun org-dblock-update (&optional arg)
10677 "User command for updating dynamic blocks.
10678 Update the dynamic block at point. With prefix ARG, update all dynamic
10679 blocks in the buffer."
10680 (interactive "P")
10681 (if arg
10682 (org-update-all-dblocks)
10683 (or (looking-at org-dblock-start-re)
10684 (org-beginning-of-dblock))
10685 (org-update-dblock)))
10687 (defun org-update-dblock ()
10688 "Update the dynamic block at point.
10689 This means to empty the block, parse for parameters and then call
10690 the correct writing function."
10691 (interactive)
10692 (save-window-excursion
10693 (let* ((pos (point))
10694 (line (org-current-line))
10695 (params (org-prepare-dblock))
10696 (name (plist-get params :name))
10697 (indent (plist-get params :indentation-column))
10698 (cmd (intern (concat "org-dblock-write:" name))))
10699 (message "Updating dynamic block `%s' at line %d..." name line)
10700 (funcall cmd params)
10701 (message "Updating dynamic block `%s' at line %d...done" name line)
10702 (goto-char pos)
10703 (when (and indent (> indent 0))
10704 (setq indent (make-string indent ?\ ))
10705 (save-excursion
10706 (org-beginning-of-dblock)
10707 (forward-line 1)
10708 (while (not (looking-at org-dblock-end-re))
10709 (insert indent)
10710 (beginning-of-line 2))
10711 (when (looking-at org-dblock-end-re)
10712 (and (looking-at "[ \t]+")
10713 (replace-match ""))
10714 (insert indent)))))))
10716 (defun org-beginning-of-dblock ()
10717 "Find the beginning of the dynamic block at point.
10718 Error if there is no such block at point."
10719 (let ((pos (point))
10720 beg)
10721 (end-of-line 1)
10722 (if (and (re-search-backward org-dblock-start-re nil t)
10723 (setq beg (match-beginning 0))
10724 (re-search-forward org-dblock-end-re nil t)
10725 (> (match-end 0) pos))
10726 (goto-char beg)
10727 (goto-char pos)
10728 (error "Not in a dynamic block"))))
10730 (defun org-update-all-dblocks ()
10731 "Update all dynamic blocks in the buffer.
10732 This function can be used in a hook."
10733 (interactive)
10734 (when (org-mode-p)
10735 (org-map-dblocks 'org-update-dblock)))
10738 ;;;; Completion
10740 (defconst org-additional-option-like-keywords
10741 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
10742 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
10743 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
10744 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
10745 "BEGIN:" "END:"
10746 "ORGTBL" "TBLFM:" "TBLNAME:"
10747 "BEGIN_EXAMPLE" "END_EXAMPLE"
10748 "BEGIN_QUOTE" "END_QUOTE"
10749 "BEGIN_VERSE" "END_VERSE"
10750 "BEGIN_CENTER" "END_CENTER"
10751 "BEGIN_SRC" "END_SRC"
10752 "BEGIN_RESULT" "END_RESULT"
10753 "SOURCE:" "SRCNAME:" "FUNCTION:"
10754 "RESULTS:"
10755 "HEADER:" "HEADERS:"
10756 "BABEL:"
10757 "CATEGORY:" "COLUMNS:" "PROPERTY:"
10758 "CAPTION:" "LABEL:"
10759 "SETUPFILE:"
10760 "INCLUDE:"
10761 "BIND:"
10762 "MACRO:"))
10764 (defcustom org-structure-template-alist
10766 ("s" "#+begin_src ?\n\n#+end_src"
10767 "<src lang=\"?\">\n\n</src>")
10768 ("e" "#+begin_example\n?\n#+end_example"
10769 "<example>\n?\n</example>")
10770 ("q" "#+begin_quote\n?\n#+end_quote"
10771 "<quote>\n?\n</quote>")
10772 ("v" "#+begin_verse\n?\n#+end_verse"
10773 "<verse>\n?\n/verse>")
10774 ("c" "#+begin_center\n?\n#+end_center"
10775 "<center>\n?\n/center>")
10776 ("l" "#+begin_latex\n?\n#+end_latex"
10777 "<literal style=\"latex\">\n?\n</literal>")
10778 ("L" "#+latex: "
10779 "<literal style=\"latex\">?</literal>")
10780 ("h" "#+begin_html\n?\n#+end_html"
10781 "<literal style=\"html\">\n?\n</literal>")
10782 ("H" "#+html: "
10783 "<literal style=\"html\">?</literal>")
10784 ("a" "#+begin_ascii\n?\n#+end_ascii")
10785 ("A" "#+ascii: ")
10786 ("o" "#+begin_odt\n?\n#+end_odt")
10787 ("i" "#+index: ?"
10788 "#+index: ?")
10789 ("I" "#+include %file ?"
10790 "<include file=%file markup=\"?\">")
10792 "Structure completion elements.
10793 This is a list of abbreviation keys and values. The value gets inserted
10794 if you type `<' followed by the key and then press the completion key,
10795 usually `M-TAB'. %file will be replaced by a file name after prompting
10796 for the file using completion. The cursor will be placed at the position
10797 of the `?` in the template.
10798 There are two templates for each key, the first uses the original Org syntax,
10799 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
10800 the default when the /org-mtags.el/ module has been loaded. See also the
10801 variable `org-mtags-prefer-muse-templates'.
10802 This is an experimental feature, it is undecided if it is going to stay in."
10803 :group 'org-completion
10804 :type '(repeat
10805 (string :tag "Key")
10806 (string :tag "Template")
10807 (string :tag "Muse Template")))
10809 (defun org-try-structure-completion ()
10810 "Try to complete a structure template before point.
10811 This looks for strings like \"<e\" on an otherwise empty line and
10812 expands them."
10813 (let ((l (buffer-substring (point-at-bol) (point)))
10815 (when (and (looking-at "[ \t]*$")
10816 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
10817 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
10818 (org-complete-expand-structure-template (+ -1 (point-at-bol)
10819 (match-beginning 1)) a)
10820 t)))
10822 (defun org-complete-expand-structure-template (start cell)
10823 "Expand a structure template."
10824 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
10825 (rpl (nth (if musep 2 1) cell))
10826 (ind ""))
10827 (delete-region start (point))
10828 (when (string-match "\\`#\\+" rpl)
10829 (cond
10830 ((bolp))
10831 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
10832 (setq ind (buffer-substring (point-at-bol) (point))))
10833 (t (newline))))
10834 (setq start (point))
10835 (if (string-match "%file" rpl)
10836 (setq rpl (replace-match
10837 (concat
10838 "\""
10839 (save-match-data
10840 (abbreviate-file-name (read-file-name "Include file: ")))
10841 "\"")
10842 t t rpl)))
10843 (setq rpl (mapconcat 'identity (split-string rpl "\n")
10844 (concat "\n" ind)))
10845 (insert rpl)
10846 (if (re-search-backward "\\?" start t) (delete-char 1))))
10848 ;;;; TODO, DEADLINE, Comments
10850 (defun org-toggle-comment ()
10851 "Change the COMMENT state of an entry."
10852 (interactive)
10853 (save-excursion
10854 (org-back-to-heading)
10855 (let (case-fold-search)
10856 (if (looking-at (concat outline-regexp
10857 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10858 (replace-match "" t t nil 1)
10859 (if (looking-at outline-regexp)
10860 (progn
10861 (goto-char (match-end 0))
10862 (insert org-comment-string " ")))))))
10864 (defvar org-last-todo-state-is-todo nil
10865 "This is non-nil when the last TODO state change led to a TODO state.
10866 If the last change removed the TODO tag or switched to DONE, then
10867 this is nil.")
10869 (defvar org-setting-tags nil) ; dynamically skipped
10871 (defvar org-todo-setup-filter-hook nil
10872 "Hook for functions that pre-filter todo specs.
10873 Each function takes a todo spec and returns either nil or the spec
10874 transformed into canonical form." )
10876 (defvar org-todo-get-default-hook nil
10877 "Hook for functions that get a default item for todo.
10878 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
10879 nil or a string to be used for the todo mark." )
10881 (defvar org-agenda-headline-snapshot-before-repeat)
10883 (defun org-todo (&optional arg)
10884 "Change the TODO state of an item.
10885 The state of an item is given by a keyword at the start of the heading,
10886 like
10887 *** TODO Write paper
10888 *** DONE Call mom
10890 The different keywords are specified in the variable `org-todo-keywords'.
10891 By default the available states are \"TODO\" and \"DONE\".
10892 So for this example: when the item starts with TODO, it is changed to DONE.
10893 When it starts with DONE, the DONE is removed. And when neither TODO nor
10894 DONE are present, add TODO at the beginning of the heading.
10896 With \\[universal-argument] prefix arg, use completion to determine the new \
10897 state.
10898 With numeric prefix arg, switch to that state.
10899 With a double \\[universal-argument] prefix, switch to the next set of TODO \
10900 keywords (nextset).
10901 With a triple \\[universal-argument] prefix, circumvent any state blocking.
10903 For calling through lisp, arg is also interpreted in the following way:
10904 'none -> empty state
10905 \"\"(empty string) -> switch to empty state
10906 'done -> switch to DONE
10907 'nextset -> switch to the next set of keywords
10908 'previousset -> switch to the previous set of keywords
10909 \"WAITING\" -> switch to the specified keyword, but only if it
10910 really is a member of `org-todo-keywords'."
10911 (interactive "P")
10912 (if (equal arg '(16)) (setq arg 'nextset))
10913 (let ((org-blocker-hook org-blocker-hook)
10914 (case-fold-search nil))
10915 (when (equal arg '(64))
10916 (setq arg nil org-blocker-hook nil))
10917 (when (and org-blocker-hook
10918 (or org-inhibit-blocking
10919 (org-entry-get nil "NOBLOCKING")))
10920 (setq org-blocker-hook nil))
10921 (save-excursion
10922 (catch 'exit
10923 (org-back-to-heading t)
10924 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
10925 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
10926 (looking-at " *"))
10927 (let* ((match-data (match-data))
10928 (startpos (point-at-bol))
10929 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
10930 (org-log-done org-log-done)
10931 (org-log-repeat org-log-repeat)
10932 (org-todo-log-states org-todo-log-states)
10933 (this (match-string 1))
10934 (hl-pos (match-beginning 0))
10935 (head (org-get-todo-sequence-head this))
10936 (ass (assoc head org-todo-kwd-alist))
10937 (interpret (nth 1 ass))
10938 (done-word (nth 3 ass))
10939 (final-done-word (nth 4 ass))
10940 (last-state (or this ""))
10941 (completion-ignore-case t)
10942 (member (member this org-todo-keywords-1))
10943 (tail (cdr member))
10944 (state (cond
10945 ((and org-todo-key-trigger
10946 (or (and (equal arg '(4))
10947 (eq org-use-fast-todo-selection 'prefix))
10948 (and (not arg) org-use-fast-todo-selection
10949 (not (eq org-use-fast-todo-selection
10950 'prefix)))))
10951 ;; Use fast selection
10952 (org-fast-todo-selection))
10953 ((and (equal arg '(4))
10954 (or (not org-use-fast-todo-selection)
10955 (not org-todo-key-trigger)))
10956 ;; Read a state with completion
10957 (org-icompleting-read
10958 "State: " (mapcar (lambda(x) (list x))
10959 org-todo-keywords-1)
10960 nil t))
10961 ((eq arg 'right)
10962 (if this
10963 (if tail (car tail) nil)
10964 (car org-todo-keywords-1)))
10965 ((eq arg 'left)
10966 (if (equal member org-todo-keywords-1)
10968 (if this
10969 (nth (- (length org-todo-keywords-1)
10970 (length tail) 2)
10971 org-todo-keywords-1)
10972 (org-last org-todo-keywords-1))))
10973 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10974 (setq arg nil))) ; hack to fall back to cycling
10975 (arg
10976 ;; user or caller requests a specific state
10977 (cond
10978 ((equal arg "") nil)
10979 ((eq arg 'none) nil)
10980 ((eq arg 'done) (or done-word (car org-done-keywords)))
10981 ((eq arg 'nextset)
10982 (or (car (cdr (member head org-todo-heads)))
10983 (car org-todo-heads)))
10984 ((eq arg 'previousset)
10985 (let ((org-todo-heads (reverse org-todo-heads)))
10986 (or (car (cdr (member head org-todo-heads)))
10987 (car org-todo-heads))))
10988 ((car (member arg org-todo-keywords-1)))
10989 ((stringp arg)
10990 (error "State `%s' not valid in this file" arg))
10991 ((nth (1- (prefix-numeric-value arg))
10992 org-todo-keywords-1))))
10993 ((null member) (or head (car org-todo-keywords-1)))
10994 ((equal this final-done-word) nil) ;; -> make empty
10995 ((null tail) nil) ;; -> first entry
10996 ((memq interpret '(type priority))
10997 (if (eq this-command last-command)
10998 (car tail)
10999 (if (> (length tail) 0)
11000 (or done-word (car org-done-keywords))
11001 nil)))
11003 (car tail))))
11004 (state (or
11005 (run-hook-with-args-until-success
11006 'org-todo-get-default-hook state last-state)
11007 state))
11008 (next (if state (concat " " state " ") " "))
11009 (change-plist (list :type 'todo-state-change :from this :to state
11010 :position startpos))
11011 dolog now-done-p)
11012 (when org-blocker-hook
11013 (setq org-last-todo-state-is-todo
11014 (not (member this org-done-keywords)))
11015 (unless (save-excursion
11016 (save-match-data
11017 (org-with-wide-buffer
11018 (run-hook-with-args-until-failure
11019 'org-blocker-hook change-plist))))
11020 (if (org-called-interactively-p 'interactive)
11021 (error "TODO state change from %s to %s blocked" this state)
11022 ;; fail silently
11023 (message "TODO state change from %s to %s blocked" this state)
11024 (throw 'exit nil))))
11025 (store-match-data match-data)
11026 (replace-match next t t)
11027 (unless (pos-visible-in-window-p hl-pos)
11028 (message "TODO state changed to %s" (org-trim next)))
11029 (unless head
11030 (setq head (org-get-todo-sequence-head state)
11031 ass (assoc head org-todo-kwd-alist)
11032 interpret (nth 1 ass)
11033 done-word (nth 3 ass)
11034 final-done-word (nth 4 ass)))
11035 (when (memq arg '(nextset previousset))
11036 (message "Keyword-Set %d/%d: %s"
11037 (- (length org-todo-sets) -1
11038 (length (memq (assoc state org-todo-sets) org-todo-sets)))
11039 (length org-todo-sets)
11040 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11041 (setq org-last-todo-state-is-todo
11042 (not (member state org-done-keywords)))
11043 (setq now-done-p (and (member state org-done-keywords)
11044 (not (member this org-done-keywords))))
11045 (and logging (org-local-logging logging))
11046 (when (and (or org-todo-log-states org-log-done)
11047 (not (eq org-inhibit-logging t))
11048 (not (memq arg '(nextset previousset))))
11049 ;; we need to look at recording a time and note
11050 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
11051 (nth 2 (assoc this org-todo-log-states))))
11052 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11053 (setq dolog 'time))
11054 (when (and state
11055 (member state org-not-done-keywords)
11056 (not (member this org-not-done-keywords)))
11057 ;; This is now a todo state and was not one before
11058 ;; If there was a CLOSED time stamp, get rid of it.
11059 (org-add-planning-info nil nil 'closed))
11060 (when (and now-done-p org-log-done)
11061 ;; It is now done, and it was not done before
11062 (org-add-planning-info 'closed (org-current-time))
11063 (if (and (not dolog) (eq 'note org-log-done))
11064 (org-add-log-setup 'done state this 'findpos 'note)))
11065 (when (and state dolog)
11066 ;; This is a non-nil state, and we need to log it
11067 (org-add-log-setup 'state state this 'findpos dolog)))
11068 ;; Fixup tag positioning
11069 (org-todo-trigger-tag-changes state)
11070 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11071 (when org-provide-todo-statistics
11072 (org-update-parent-todo-statistics))
11073 (run-hooks 'org-after-todo-state-change-hook)
11074 (if (and arg (not (member state org-done-keywords)))
11075 (setq head (org-get-todo-sequence-head state)))
11076 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11077 ;; Do we need to trigger a repeat?
11078 (when now-done-p
11079 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11080 ;; This is for the agenda, take a snapshot of the headline.
11081 (save-match-data
11082 (setq org-agenda-headline-snapshot-before-repeat
11083 (org-get-heading))))
11084 (org-auto-repeat-maybe state))
11085 ;; Fixup cursor location if close to the keyword
11086 (if (and (outline-on-heading-p)
11087 (not (bolp))
11088 (save-excursion (beginning-of-line 1)
11089 (looking-at org-todo-line-regexp))
11090 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11091 (progn
11092 (goto-char (or (match-end 2) (match-end 1)))
11093 (and (looking-at " ") (just-one-space))))
11094 (when org-trigger-hook
11095 (save-excursion
11096 (run-hook-with-args 'org-trigger-hook change-plist))))))))
11098 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11099 "Block turning an entry into a TODO, using the hierarchy.
11100 This checks whether the current task should be blocked from state
11101 changes. Such blocking occurs when:
11103 1. The task has children which are not all in a completed state.
11105 2. A task has a parent with the property :ORDERED:, and there
11106 are siblings prior to the current task with incomplete
11107 status.
11109 3. The parent of the task is blocked because it has siblings that should
11110 be done first, or is child of a block grandparent TODO entry."
11112 (if (not org-enforce-todo-dependencies)
11113 t ; if locally turned off don't block
11114 (catch 'dont-block
11115 ;; If this is not a todo state change, or if this entry is already DONE,
11116 ;; do not block
11117 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11118 (member (plist-get change-plist :from)
11119 (cons 'done org-done-keywords))
11120 (member (plist-get change-plist :to)
11121 (cons 'todo org-not-done-keywords))
11122 (not (plist-get change-plist :to)))
11123 (throw 'dont-block t))
11124 ;; If this task has children, and any are undone, it's blocked
11125 (save-excursion
11126 (org-back-to-heading t)
11127 (let ((this-level (funcall outline-level)))
11128 (outline-next-heading)
11129 (let ((child-level (funcall outline-level)))
11130 (while (and (not (eobp))
11131 (> child-level this-level))
11132 ;; this todo has children, check whether they are all
11133 ;; completed
11134 (if (and (not (org-entry-is-done-p))
11135 (org-entry-is-todo-p))
11136 (throw 'dont-block nil))
11137 (outline-next-heading)
11138 (setq child-level (funcall outline-level))))))
11139 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11140 ;; any previous siblings are undone, it's blocked
11141 (save-excursion
11142 (org-back-to-heading t)
11143 (let* ((pos (point))
11144 (parent-pos (and (org-up-heading-safe) (point))))
11145 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11146 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11147 (forward-line 1)
11148 (re-search-forward org-not-done-heading-regexp pos t))
11149 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11150 ;; Search further up the hierarchy, to see if an anchestor is blocked
11151 (while t
11152 (goto-char parent-pos)
11153 (if (not (looking-at org-not-done-heading-regexp))
11154 (throw 'dont-block t)) ; do not block, parent is not a TODO
11155 (setq pos (point))
11156 (setq parent-pos (and (org-up-heading-safe) (point)))
11157 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11158 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11159 (forward-line 1)
11160 (re-search-forward org-not-done-heading-regexp pos t))
11161 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11163 (defcustom org-track-ordered-property-with-tag nil
11164 "Should the ORDERED property also be shown as a tag?
11165 The ORDERED property decides if an entry should require subtasks to be
11166 completed in sequence. Since a property is not very visible, setting
11167 this option means that toggling the ORDERED property with the command
11168 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11169 not relevant for the behavior, but it makes things more visible.
11171 Note that toggling the tag with tags commands will not change the property
11172 and therefore not influence behavior!
11174 This can be t, meaning the tag ORDERED should be used, It can also be a
11175 string to select a different tag for this task."
11176 :group 'org-todo
11177 :type '(choice
11178 (const :tag "No tracking" nil)
11179 (const :tag "Track with ORDERED tag" t)
11180 (string :tag "Use other tag")))
11182 (defun org-toggle-ordered-property ()
11183 "Toggle the ORDERED property of the current entry.
11184 For better visibility, you can track the value of this property with a tag.
11185 See variable `org-track-ordered-property-with-tag'."
11186 (interactive)
11187 (let* ((t1 org-track-ordered-property-with-tag)
11188 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11189 (save-excursion
11190 (org-back-to-heading)
11191 (if (org-entry-get nil "ORDERED")
11192 (progn
11193 (org-delete-property "ORDERED")
11194 (and tag (org-toggle-tag tag 'off))
11195 (message "Subtasks can be completed in arbitrary order"))
11196 (org-entry-put nil "ORDERED" "t")
11197 (and tag (org-toggle-tag tag 'on))
11198 (message "Subtasks must be completed in sequence")))))
11200 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11201 (defun org-block-todo-from-checkboxes (change-plist)
11202 "Block turning an entry into a TODO, using checkboxes.
11203 This checks whether the current task should be blocked from state
11204 changes because there are unchecked boxes in this entry."
11205 (if (not org-enforce-todo-checkbox-dependencies)
11206 t ; if locally turned off don't block
11207 (catch 'dont-block
11208 ;; If this is not a todo state change, or if this entry is already DONE,
11209 ;; do not block
11210 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11211 (member (plist-get change-plist :from)
11212 (cons 'done org-done-keywords))
11213 (member (plist-get change-plist :to)
11214 (cons 'todo org-not-done-keywords))
11215 (not (plist-get change-plist :to)))
11216 (throw 'dont-block t))
11217 ;; If this task has checkboxes that are not checked, it's blocked
11218 (save-excursion
11219 (org-back-to-heading t)
11220 (let ((beg (point)) end)
11221 (outline-next-heading)
11222 (setq end (point))
11223 (goto-char beg)
11224 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
11225 end t)
11226 (progn
11227 (if (boundp 'org-blocked-by-checkboxes)
11228 (setq org-blocked-by-checkboxes t))
11229 (throw 'dont-block nil)))))
11230 t))) ; do not block
11232 (defun org-entry-blocked-p ()
11233 "Is the current entry blocked?"
11234 (if (org-entry-get nil "NOBLOCKING")
11235 nil ;; Never block this entry
11236 (not
11237 (run-hook-with-args-until-failure
11238 'org-blocker-hook
11239 (list :type 'todo-state-change
11240 :position (point)
11241 :from 'todo
11242 :to 'done)))))
11244 (defun org-update-statistics-cookies (all)
11245 "Update the statistics cookie, either from TODO or from checkboxes.
11246 This should be called with the cursor in a line with a statistics cookie."
11247 (interactive "P")
11248 (if all
11249 (progn
11250 (org-update-checkbox-count 'all)
11251 (org-map-entries 'org-update-parent-todo-statistics))
11252 (if (not (org-on-heading-p))
11253 (org-update-checkbox-count)
11254 (let ((pos (move-marker (make-marker) (point)))
11255 end l1 l2)
11256 (ignore-errors (org-back-to-heading t))
11257 (if (not (org-on-heading-p))
11258 (org-update-checkbox-count)
11259 (setq l1 (org-outline-level))
11260 (setq end (save-excursion
11261 (outline-next-heading)
11262 (if (org-on-heading-p) (setq l2 (org-outline-level)))
11263 (point)))
11264 (if (and (save-excursion
11265 (re-search-forward
11266 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11267 (not (save-excursion (re-search-forward
11268 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11269 (org-update-checkbox-count)
11270 (if (and l2 (> l2 l1))
11271 (progn
11272 (goto-char end)
11273 (org-update-parent-todo-statistics))
11274 (goto-char pos)
11275 (beginning-of-line 1)
11276 (while (re-search-forward
11277 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11278 (point-at-eol) t)
11279 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11280 (goto-char pos)
11281 (move-marker pos nil)))))
11283 (defvar org-entry-property-inherited-from) ;; defined below
11284 (defun org-update-parent-todo-statistics ()
11285 "Update any statistics cookie in the parent of the current headline.
11286 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11287 the entire subtree and this will travel up the hierarchy and update
11288 statistics everywhere."
11289 (interactive)
11290 (let* ((lim 0) prop
11291 (recursive (or (not org-hierarchical-todo-statistics)
11292 (string-match
11293 "\\<recursive\\>"
11294 (or (setq prop (org-entry-get
11295 nil "COOKIE_DATA" 'inherit)) ""))))
11296 (lim (or (and prop (marker-position
11297 org-entry-property-inherited-from))
11298 lim))
11299 (first t)
11300 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11301 level ltoggle l1 new ndel
11302 (cnt-all 0) (cnt-done 0) is-percent kwd
11303 checkbox-beg ov ovs ove cookie-present)
11304 (catch 'exit
11305 (save-excursion
11306 (beginning-of-line 1)
11307 (if (org-at-heading-p)
11308 (setq ltoggle (funcall outline-level))
11309 (error "This should not happen"))
11310 (while (and (setq level (org-up-heading-safe))
11311 (or recursive first)
11312 (>= (point) lim))
11313 (setq first nil cookie-present nil)
11314 (unless (and level
11315 (not (string-match
11316 "\\<checkbox\\>"
11317 (downcase
11318 (or (org-entry-get
11319 nil "COOKIE_DATA")
11320 "")))))
11321 (throw 'exit nil))
11322 (while (re-search-forward box-re (point-at-eol) t)
11323 (setq cnt-all 0 cnt-done 0 cookie-present t)
11324 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11325 (save-match-data
11326 (unless (outline-next-heading) (throw 'exit nil))
11327 (while (and (looking-at org-complex-heading-regexp)
11328 (> (setq l1 (length (match-string 1))) level))
11329 (setq kwd (and (or recursive (= l1 ltoggle))
11330 (match-string 2)))
11331 (if (or (eq org-provide-todo-statistics 'all-headlines)
11332 (and (listp org-provide-todo-statistics)
11333 (or (member kwd org-provide-todo-statistics)
11334 (member kwd org-done-keywords))))
11335 (setq cnt-all (1+ cnt-all))
11336 (if (eq org-provide-todo-statistics t)
11337 (and kwd (setq cnt-all (1+ cnt-all)))))
11338 (and (member kwd org-done-keywords)
11339 (setq cnt-done (1+ cnt-done)))
11340 (outline-next-heading)))
11341 (setq new
11342 (if is-percent
11343 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11344 (format "[%d/%d]" cnt-done cnt-all))
11345 ndel (- (match-end 0) checkbox-beg))
11346 ;; handle overlays when updating cookie from column view
11347 (when (setq ov (car (overlays-at checkbox-beg)))
11348 (setq ovs (overlay-start ov) ove (overlay-end ov))
11349 (delete-overlay ov))
11350 (goto-char checkbox-beg)
11351 (insert new)
11352 (delete-region (point) (+ (point) ndel))
11353 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11354 (when ov (move-overlay ov ovs ove)))
11355 (when cookie-present
11356 (run-hook-with-args 'org-after-todo-statistics-hook
11357 cnt-done (- cnt-all cnt-done))))))
11358 (run-hooks 'org-todo-statistics-hook)))
11360 (defvar org-after-todo-statistics-hook nil
11361 "Hook that is called after a TODO statistics cookie has been updated.
11362 Each function is called with two arguments: the number of not-done entries
11363 and the number of done entries.
11365 For example, the following function, when added to this hook, will switch
11366 an entry to DONE when all children are done, and back to TODO when new
11367 entries are set to a TODO status. Note that this hook is only called
11368 when there is a statistics cookie in the headline!
11370 (defun org-summary-todo (n-done n-not-done)
11371 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11372 (let (org-log-done org-log-states) ; turn off logging
11373 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11376 (defvar org-todo-statistics-hook nil
11377 "Hook that is run whenever Org thinks TODO statistics should be updated.
11378 This hook runs even if there is no statistics cookie present, in which case
11379 `org-after-todo-statistics-hook' would not run.")
11381 (defun org-todo-trigger-tag-changes (state)
11382 "Apply the changes defined in `org-todo-state-tags-triggers'."
11383 (let ((l org-todo-state-tags-triggers)
11384 changes)
11385 (when (or (not state) (equal state ""))
11386 (setq changes (append changes (cdr (assoc "" l)))))
11387 (when (and (stringp state) (> (length state) 0))
11388 (setq changes (append changes (cdr (assoc state l)))))
11389 (when (member state org-not-done-keywords)
11390 (setq changes (append changes (cdr (assoc 'todo l)))))
11391 (when (member state org-done-keywords)
11392 (setq changes (append changes (cdr (assoc 'done l)))))
11393 (dolist (c changes)
11394 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11396 (defun org-local-logging (value)
11397 "Get logging settings from a property VALUE."
11398 (let* (words w a)
11399 ;; directly set the variables, they are already local.
11400 (setq org-log-done nil
11401 org-log-repeat nil
11402 org-todo-log-states nil)
11403 (setq words (org-split-string value))
11404 (while (setq w (pop words))
11405 (cond
11406 ((setq a (assoc w org-startup-options))
11407 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11408 (set (nth 1 a) (nth 2 a))))
11409 ((setq a (org-extract-log-state-settings w))
11410 (and (member (car a) org-todo-keywords-1)
11411 (push a org-todo-log-states)))))))
11413 (defun org-get-todo-sequence-head (kwd)
11414 "Return the head of the TODO sequence to which KWD belongs.
11415 If KWD is not set, check if there is a text property remembering the
11416 right sequence."
11417 (let (p)
11418 (cond
11419 ((not kwd)
11420 (or (get-text-property (point-at-bol) 'org-todo-head)
11421 (progn
11422 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11423 nil (point-at-eol)))
11424 (get-text-property p 'org-todo-head))))
11425 ((not (member kwd org-todo-keywords-1))
11426 (car org-todo-keywords-1))
11427 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11429 (defun org-fast-todo-selection ()
11430 "Fast TODO keyword selection with single keys.
11431 Returns the new TODO keyword, or nil if no state change should occur."
11432 (let* ((fulltable org-todo-key-alist)
11433 (done-keywords org-done-keywords) ;; needed for the faces.
11434 (maxlen (apply 'max (mapcar
11435 (lambda (x)
11436 (if (stringp (car x)) (string-width (car x)) 0))
11437 fulltable)))
11438 (expert nil)
11439 (fwidth (+ maxlen 3 1 3))
11440 (ncol (/ (- (window-width) 4) fwidth))
11441 tg cnt e c tbl
11442 groups ingroup)
11443 (save-excursion
11444 (save-window-excursion
11445 (if expert
11446 (set-buffer (get-buffer-create " *Org todo*"))
11447 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11448 (erase-buffer)
11449 (org-set-local 'org-done-keywords done-keywords)
11450 (setq tbl fulltable cnt 0)
11451 (while (setq e (pop tbl))
11452 (cond
11453 ((equal e '(:startgroup))
11454 (push '() groups) (setq ingroup t)
11455 (when (not (= cnt 0))
11456 (setq cnt 0)
11457 (insert "\n"))
11458 (insert "{ "))
11459 ((equal e '(:endgroup))
11460 (setq ingroup nil cnt 0)
11461 (insert "}\n"))
11462 ((equal e '(:newline))
11463 (when (not (= cnt 0))
11464 (setq cnt 0)
11465 (insert "\n")
11466 (setq e (car tbl))
11467 (while (equal (car tbl) '(:newline))
11468 (insert "\n")
11469 (setq tbl (cdr tbl)))))
11471 (setq tg (car e) c (cdr e))
11472 (if ingroup (push tg (car groups)))
11473 (setq tg (org-add-props tg nil 'face
11474 (org-get-todo-face tg)))
11475 (if (and (= cnt 0) (not ingroup)) (insert " "))
11476 (insert "[" c "] " tg (make-string
11477 (- fwidth 4 (length tg)) ?\ ))
11478 (when (= (setq cnt (1+ cnt)) ncol)
11479 (insert "\n")
11480 (if ingroup (insert " "))
11481 (setq cnt 0)))))
11482 (insert "\n")
11483 (goto-char (point-min))
11484 (if (not expert) (org-fit-window-to-buffer))
11485 (message "[a-z..]:Set [SPC]:clear")
11486 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11487 (cond
11488 ((or (= c ?\C-g)
11489 (and (= c ?q) (not (rassoc c fulltable))))
11490 (setq quit-flag t))
11491 ((= c ?\ ) nil)
11492 ((setq e (rassoc c fulltable) tg (car e))
11494 (t (setq quit-flag t)))))))
11496 (defun org-entry-is-todo-p ()
11497 (member (org-get-todo-state) org-not-done-keywords))
11499 (defun org-entry-is-done-p ()
11500 (member (org-get-todo-state) org-done-keywords))
11502 (defun org-get-todo-state ()
11503 (save-excursion
11504 (org-back-to-heading t)
11505 (and (looking-at org-todo-line-regexp)
11506 (match-end 2)
11507 (match-string 2))))
11509 (defun org-at-date-range-p (&optional inactive-ok)
11510 "Is the cursor inside a date range?"
11511 (interactive)
11512 (save-excursion
11513 (catch 'exit
11514 (let ((pos (point)))
11515 (skip-chars-backward "^[<\r\n")
11516 (skip-chars-backward "<[")
11517 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11518 (>= (match-end 0) pos)
11519 (throw 'exit t))
11520 (skip-chars-backward "^<[\r\n")
11521 (skip-chars-backward "<[")
11522 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11523 (>= (match-end 0) pos)
11524 (throw 'exit t)))
11525 nil)))
11527 (defun org-get-repeat (&optional tagline)
11528 "Check if there is a deadline/schedule with repeater in this entry."
11529 (save-match-data
11530 (save-excursion
11531 (org-back-to-heading t)
11532 (and (re-search-forward (if tagline
11533 (concat tagline "\\s-*" org-repeat-re)
11534 org-repeat-re)
11535 (org-entry-end-position) t)
11536 (match-string-no-properties 1)))))
11538 (defvar org-last-changed-timestamp)
11539 (defvar org-last-inserted-timestamp)
11540 (defvar org-log-post-message)
11541 (defvar org-log-note-purpose)
11542 (defvar org-log-note-how)
11543 (defvar org-log-note-extra)
11544 (defun org-auto-repeat-maybe (done-word)
11545 "Check if the current headline contains a repeated deadline/schedule.
11546 If yes, set TODO state back to what it was and change the base date
11547 of repeating deadline/scheduled time stamps to new date.
11548 This function is run automatically after each state change to a DONE state."
11549 ;; last-state is dynamically scoped into this function
11550 (let* ((repeat (org-get-repeat))
11551 (aa (assoc last-state org-todo-kwd-alist))
11552 (interpret (nth 1 aa))
11553 (head (nth 2 aa))
11554 (whata '(("d" . day) ("m" . month) ("y" . year)))
11555 (msg "Entry repeats: ")
11556 (org-log-done nil)
11557 (org-todo-log-states nil)
11558 re type n what ts time to-state)
11559 (when repeat
11560 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11561 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11562 org-todo-repeat-to-state))
11563 (unless (and to-state (member to-state org-todo-keywords-1))
11564 (setq to-state (if (eq interpret 'type) last-state head)))
11565 (org-todo to-state)
11566 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11567 (org-entry-put nil "LAST_REPEAT" (format-time-string
11568 (org-time-stamp-format t t))))
11569 (when org-log-repeat
11570 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11571 (memq 'org-add-log-note post-command-hook))
11572 ;; OK, we are already setup for some record
11573 (if (eq org-log-repeat 'note)
11574 ;; make sure we take a note, not only a time stamp
11575 (setq org-log-note-how 'note))
11576 ;; Set up for taking a record
11577 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11578 last-state
11579 'findpos org-log-repeat)))
11580 (org-back-to-heading t)
11581 (org-add-planning-info nil nil 'closed)
11582 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11583 org-deadline-time-regexp "\\)\\|\\("
11584 org-ts-regexp "\\)"))
11585 (while (re-search-forward
11586 re (save-excursion (outline-next-heading) (point)) t)
11587 (setq type (if (match-end 1) org-scheduled-string
11588 (if (match-end 3) org-deadline-string "Plain:"))
11589 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11590 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11591 (setq n (string-to-number (match-string 2 ts))
11592 what (match-string 3 ts))
11593 (if (equal what "w") (setq n (* n 7) what "d"))
11594 ;; Preparation, see if we need to modify the start date for the change
11595 (when (match-end 1)
11596 (setq time (save-match-data (org-time-string-to-time ts)))
11597 (cond
11598 ((equal (match-string 1 ts) ".")
11599 ;; Shift starting date to today
11600 (org-timestamp-change
11601 (- (time-to-days (current-time)) (time-to-days time))
11602 'day))
11603 ((equal (match-string 1 ts) "+")
11604 (let ((nshiftmax 10) (nshift 0))
11605 (while (or (= nshift 0)
11606 (<= (time-to-days time)
11607 (time-to-days (current-time))))
11608 (when (= (incf nshift) nshiftmax)
11609 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11610 (error "Abort")))
11611 (org-timestamp-change n (cdr (assoc what whata)))
11612 (org-at-timestamp-p t)
11613 (setq ts (match-string 1))
11614 (setq time (save-match-data (org-time-string-to-time ts)))))
11615 (org-timestamp-change (- n) (cdr (assoc what whata)))
11616 ;; rematch, so that we have everything in place for the real shift
11617 (org-at-timestamp-p t)
11618 (setq ts (match-string 1))
11619 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11620 (org-timestamp-change n (cdr (assoc what whata)))
11621 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11622 (setq org-log-post-message msg)
11623 (message "%s" msg))))
11625 (defun org-show-todo-tree (arg)
11626 "Make a compact tree which shows all headlines marked with TODO.
11627 The tree will show the lines where the regexp matches, and all higher
11628 headlines above the match.
11629 With a \\[universal-argument] prefix, prompt for a regexp to match.
11630 With a numeric prefix N, construct a sparse tree for the Nth element
11631 of `org-todo-keywords-1'."
11632 (interactive "P")
11633 (let ((case-fold-search nil)
11634 (kwd-re
11635 (cond ((null arg) org-not-done-regexp)
11636 ((equal arg '(4))
11637 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11638 (mapcar 'list org-todo-keywords-1))))
11639 (concat "\\("
11640 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11641 "\\)\\>")))
11642 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11643 (regexp-quote (nth (1- (prefix-numeric-value arg))
11644 org-todo-keywords-1)))
11645 (t (error "Invalid prefix argument: %s" arg)))))
11646 (message "%d TODO entries found"
11647 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
11649 (defun org-deadline (&optional remove time)
11650 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11651 With argument REMOVE, remove any deadline from the item.
11652 When TIME is set, it should be an internal time specification, and the
11653 scheduling will use the corresponding date."
11654 (interactive "P")
11655 (let* ((old-date (org-entry-get nil "DEADLINE"))
11656 (repeater (and old-date
11657 (string-match
11658 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11659 old-date)
11660 (match-string 1 old-date))))
11661 (if remove
11662 (progn
11663 (when (and old-date org-log-redeadline)
11664 (org-add-log-setup 'deldeadline nil old-date 'findpos
11665 org-log-redeadline))
11666 (org-remove-timestamp-with-keyword org-deadline-string)
11667 (message "Item no longer has a deadline."))
11668 (org-add-planning-info 'deadline time 'closed)
11669 (when (and old-date org-log-redeadline
11670 (not (equal old-date
11671 (substring org-last-inserted-timestamp 1 -1))))
11672 (org-add-log-setup 'redeadline nil old-date 'findpos
11673 org-log-redeadline))
11674 (when repeater
11675 (save-excursion
11676 (org-back-to-heading t)
11677 (when (re-search-forward (concat org-deadline-string " "
11678 org-last-inserted-timestamp)
11679 (save-excursion
11680 (outline-next-heading) (point)) t)
11681 (goto-char (1- (match-end 0)))
11682 (insert " " repeater)
11683 (setq org-last-inserted-timestamp
11684 (concat (substring org-last-inserted-timestamp 0 -1)
11685 " " repeater
11686 (substring org-last-inserted-timestamp -1))))))
11687 (message "Deadline on %s" org-last-inserted-timestamp))))
11689 (defun org-schedule (&optional remove time)
11690 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11691 With argument REMOVE, remove any scheduling date from the item.
11692 When TIME is set, it should be an internal time specification, and the
11693 scheduling will use the corresponding date."
11694 (interactive "P")
11695 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11696 (repeater (and old-date
11697 (string-match
11698 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11699 old-date)
11700 (match-string 1 old-date))))
11701 (if remove
11702 (progn
11703 (when (and old-date org-log-reschedule)
11704 (org-add-log-setup 'delschedule nil old-date 'findpos
11705 org-log-reschedule))
11706 (org-remove-timestamp-with-keyword org-scheduled-string)
11707 (message "Item is no longer scheduled."))
11708 (org-add-planning-info 'scheduled time 'closed)
11709 (when (and old-date org-log-reschedule
11710 (not (equal old-date
11711 (substring org-last-inserted-timestamp 1 -1))))
11712 (org-add-log-setup 'reschedule nil old-date 'findpos
11713 org-log-reschedule))
11714 (when repeater
11715 (save-excursion
11716 (org-back-to-heading t)
11717 (when (re-search-forward (concat org-scheduled-string " "
11718 org-last-inserted-timestamp)
11719 (save-excursion
11720 (outline-next-heading) (point)) t)
11721 (goto-char (1- (match-end 0)))
11722 (insert " " repeater)
11723 (setq org-last-inserted-timestamp
11724 (concat (substring org-last-inserted-timestamp 0 -1)
11725 " " repeater
11726 (substring org-last-inserted-timestamp -1))))))
11727 (message "Scheduled to %s" org-last-inserted-timestamp))))
11729 (defun org-get-scheduled-time (pom &optional inherit)
11730 "Get the scheduled time as a time tuple, of a format suitable
11731 for calling org-schedule with, or if there is no scheduling,
11732 returns nil."
11733 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
11734 (when time
11735 (apply 'encode-time (org-parse-time-string time)))))
11737 (defun org-get-deadline-time (pom &optional inherit)
11738 "Get the deadline as a time tuple, of a format suitable for
11739 calling org-deadline with, or if there is no scheduling, returns
11740 nil."
11741 (let ((time (org-entry-get pom "DEADLINE" inherit)))
11742 (when time
11743 (apply 'encode-time (org-parse-time-string time)))))
11745 (defun org-remove-timestamp-with-keyword (keyword)
11746 "Remove all time stamps with KEYWORD in the current entry."
11747 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
11748 beg)
11749 (save-excursion
11750 (org-back-to-heading t)
11751 (setq beg (point))
11752 (outline-next-heading)
11753 (while (re-search-backward re beg t)
11754 (replace-match "")
11755 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
11756 (equal (char-before) ?\ ))
11757 (backward-delete-char 1)
11758 (if (string-match "^[ \t]*$" (buffer-substring
11759 (point-at-bol) (point-at-eol)))
11760 (delete-region (point-at-bol)
11761 (min (point-max) (1+ (point-at-eol))))))))))
11763 (defun org-add-planning-info (what &optional time &rest remove)
11764 "Insert new timestamp with keyword in the line directly after the headline.
11765 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11766 If non is given, the user is prompted for a date.
11767 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11768 be removed."
11769 (interactive)
11770 (let (org-time-was-given org-end-time-was-given ts
11771 end default-time default-input)
11773 (catch 'exit
11774 (when (and (not time) (memq what '(scheduled deadline)))
11775 ;; Try to get a default date/time from existing timestamp
11776 (save-excursion
11777 (org-back-to-heading t)
11778 (setq end (save-excursion (outline-next-heading) (point)))
11779 (when (re-search-forward (if (eq what 'scheduled)
11780 org-scheduled-time-regexp
11781 org-deadline-time-regexp)
11782 end t)
11783 (setq ts (match-string 1)
11784 default-time
11785 (apply 'encode-time (org-parse-time-string ts))
11786 default-input (and ts (org-get-compact-tod ts))))))
11787 (when what
11788 ;; If necessary, get the time from the user
11789 (setq time (or time (org-read-date nil 'to-time nil nil
11790 default-time default-input))))
11792 (when (and org-insert-labeled-timestamps-at-point
11793 (member what '(scheduled deadline)))
11794 (insert
11795 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11796 (org-insert-time-stamp time org-time-was-given
11797 nil nil nil (list org-end-time-was-given))
11798 (setq what nil))
11799 (save-excursion
11800 (save-restriction
11801 (let (col list elt ts buffer-invisibility-spec)
11802 (org-back-to-heading t)
11803 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11804 (goto-char (match-end 1))
11805 (setq col (current-column))
11806 (goto-char (match-end 0))
11807 (if (eobp) (insert "\n") (forward-char 1))
11808 (when (and (not what)
11809 (not (looking-at
11810 (concat "[ \t]*"
11811 org-keyword-time-not-clock-regexp))))
11812 ;; Nothing to add, nothing to remove...... :-)
11813 (throw 'exit nil))
11814 (if (and (not (looking-at outline-regexp))
11815 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11816 "[^\r\n]*"))
11817 (not (equal (match-string 1) org-clock-string)))
11818 (narrow-to-region (match-beginning 0) (match-end 0))
11819 (insert-before-markers "\n")
11820 (backward-char 1)
11821 (narrow-to-region (point) (point))
11822 (and org-adapt-indentation (org-indent-to-column col)))
11823 ;; Check if we have to remove something.
11824 (setq list (cons what remove))
11825 (while list
11826 (setq elt (pop list))
11827 (goto-char (point-min))
11828 (when (or (and (eq elt 'scheduled)
11829 (re-search-forward org-scheduled-time-regexp nil t))
11830 (and (eq elt 'deadline)
11831 (re-search-forward org-deadline-time-regexp nil t))
11832 (and (eq elt 'closed)
11833 (re-search-forward org-closed-time-regexp nil t)))
11834 (replace-match "")
11835 (if (looking-at "--+<[^>]+>") (replace-match ""))
11836 (skip-chars-backward " ")
11837 (if (looking-at " +") (replace-match ""))))
11838 (goto-char (point-max))
11839 (and org-adapt-indentation (bolp) (org-indent-to-column col))
11840 (when what
11841 (insert
11842 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
11843 (cond ((eq what 'scheduled) org-scheduled-string)
11844 ((eq what 'deadline) org-deadline-string)
11845 ((eq what 'closed) org-closed-string))
11846 " ")
11847 (setq ts (org-insert-time-stamp
11848 time
11849 (or org-time-was-given
11850 (and (eq what 'closed) org-log-done-with-time))
11851 (eq what 'closed)
11852 nil nil (list org-end-time-was-given)))
11853 (end-of-line 1))
11854 (goto-char (point-min))
11855 (widen)
11856 (if (and (looking-at "[ \t]*\n")
11857 (equal (char-before) ?\n))
11858 (delete-region (1- (point)) (point-at-eol)))
11859 ts))))))
11861 (defvar org-log-note-marker (make-marker))
11862 (defvar org-log-note-purpose nil)
11863 (defvar org-log-note-state nil)
11864 (defvar org-log-note-previous-state nil)
11865 (defvar org-log-note-how nil)
11866 (defvar org-log-note-extra nil)
11867 (defvar org-log-note-window-configuration nil)
11868 (defvar org-log-note-return-to (make-marker))
11869 (defvar org-log-post-message nil
11870 "Message to be displayed after a log note has been stored.
11871 The auto-repeater uses this.")
11873 (defun org-add-note ()
11874 "Add a note to the current entry.
11875 This is done in the same way as adding a state change note."
11876 (interactive)
11877 (org-add-log-setup 'note nil nil 'findpos nil))
11879 (defvar org-property-end-re)
11880 (defun org-add-log-setup (&optional purpose state prev-state
11881 findpos how extra)
11882 "Set up the post command hook to take a note.
11883 If this is about to TODO state change, the new state is expected in STATE.
11884 When FINDPOS is non-nil, find the correct position for the note in
11885 the current entry. If not, assume that it can be inserted at point.
11886 HOW is an indicator what kind of note should be created.
11887 EXTRA is additional text that will be inserted into the notes buffer."
11888 (let* ((org-log-into-drawer (org-log-into-drawer))
11889 (drawer (cond ((stringp org-log-into-drawer)
11890 org-log-into-drawer)
11891 (org-log-into-drawer "LOGBOOK")
11892 (t nil))))
11893 (save-restriction
11894 (save-excursion
11895 (when findpos
11896 (org-back-to-heading t)
11897 (narrow-to-region (point) (save-excursion
11898 (outline-next-heading) (point)))
11899 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11900 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11901 "[^\r\n]*\\)?"))
11902 (goto-char (match-end 0))
11903 (cond
11904 (drawer
11905 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
11906 nil t)
11907 (progn
11908 (goto-char (match-end 0))
11909 (or org-log-states-order-reversed
11910 (and (re-search-forward org-property-end-re nil t)
11911 (goto-char (1- (match-beginning 0))))))
11912 (insert "\n:" drawer ":\n:END:")
11913 (beginning-of-line 0)
11914 (org-indent-line-function)
11915 (beginning-of-line 2)
11916 (org-indent-line-function)
11917 (end-of-line 0)))
11918 ((and org-log-state-notes-insert-after-drawers
11919 (save-excursion
11920 (forward-line) (looking-at org-drawer-regexp)))
11921 (forward-line)
11922 (while (looking-at org-drawer-regexp)
11923 (goto-char (match-end 0))
11924 (re-search-forward org-property-end-re (point-max) t)
11925 (forward-line))
11926 (forward-line -1)))
11927 (unless org-log-states-order-reversed
11928 (and (= (char-after) ?\n) (forward-char 1))
11929 (org-skip-over-state-notes)
11930 (skip-chars-backward " \t\n\r")))
11931 (move-marker org-log-note-marker (point))
11932 (setq org-log-note-purpose purpose
11933 org-log-note-state state
11934 org-log-note-previous-state prev-state
11935 org-log-note-how how
11936 org-log-note-extra extra)
11937 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
11939 (defun org-skip-over-state-notes ()
11940 "Skip past the list of State notes in an entry."
11941 (if (looking-at "\n[ \t]*- State") (forward-char 1))
11942 (when (ignore-errors (goto-char (org-in-item-p)))
11943 (let* ((struct (org-list-struct))
11944 (prevs (org-list-prevs-alist struct)))
11945 (while (looking-at "[ \t]*- State")
11946 (goto-char (or (org-list-get-next-item (point) struct prevs)
11947 (org-list-get-item-end (point) struct)))))))
11949 (defun org-add-log-note (&optional purpose)
11950 "Pop up a window for taking a note, and add this note later at point."
11951 (remove-hook 'post-command-hook 'org-add-log-note)
11952 (setq org-log-note-window-configuration (current-window-configuration))
11953 (delete-other-windows)
11954 (move-marker org-log-note-return-to (point))
11955 (switch-to-buffer (marker-buffer org-log-note-marker))
11956 (goto-char org-log-note-marker)
11957 (org-switch-to-buffer-other-window "*Org Note*")
11958 (erase-buffer)
11959 (if (memq org-log-note-how '(time state))
11960 (let (current-prefix-arg) (org-store-log-note))
11961 (let ((org-inhibit-startup t)) (org-mode))
11962 (insert (format "# Insert note for %s.
11963 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
11964 (cond
11965 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11966 ((eq org-log-note-purpose 'done) "closed todo item")
11967 ((eq org-log-note-purpose 'state)
11968 (format "state change from \"%s\" to \"%s\""
11969 (or org-log-note-previous-state "")
11970 (or org-log-note-state "")))
11971 ((eq org-log-note-purpose 'reschedule)
11972 "rescheduling")
11973 ((eq org-log-note-purpose 'delschedule)
11974 "no longer scheduled")
11975 ((eq org-log-note-purpose 'redeadline)
11976 "changing deadline")
11977 ((eq org-log-note-purpose 'deldeadline)
11978 "removing deadline")
11979 ((eq org-log-note-purpose 'refile)
11980 "refiling")
11981 ((eq org-log-note-purpose 'note)
11982 "this entry")
11983 (t (error "This should not happen")))))
11984 (if org-log-note-extra (insert org-log-note-extra))
11985 (org-set-local 'org-finish-function 'org-store-log-note)))
11987 (defvar org-note-abort nil) ; dynamically scoped
11988 (defun org-store-log-note ()
11989 "Finish taking a log note, and insert it to where it belongs."
11990 (let ((txt (buffer-string))
11991 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11992 lines ind bul)
11993 (kill-buffer (current-buffer))
11994 (while (string-match "\\`#.*\n[ \t\n]*" txt)
11995 (setq txt (replace-match "" t t txt)))
11996 (if (string-match "\\s-+\\'" txt)
11997 (setq txt (replace-match "" t t txt)))
11998 (setq lines (org-split-string txt "\n"))
11999 (when (and note (string-match "\\S-" note))
12000 (setq note
12001 (org-replace-escapes
12002 note
12003 (list (cons "%u" (user-login-name))
12004 (cons "%U" user-full-name)
12005 (cons "%t" (format-time-string
12006 (org-time-stamp-format 'long 'inactive)
12007 (current-time)))
12008 (cons "%T" (format-time-string
12009 (org-time-stamp-format 'long nil)
12010 (current-time)))
12011 (cons "%s" (if org-log-note-state
12012 (concat "\"" org-log-note-state "\"")
12013 ""))
12014 (cons "%S" (if org-log-note-previous-state
12015 (concat "\"" org-log-note-previous-state "\"")
12016 "\"\"")))))
12017 (if lines (setq note (concat note " \\\\")))
12018 (push note lines))
12019 (when (or current-prefix-arg org-note-abort)
12020 (when org-log-into-drawer
12021 (org-remove-empty-drawer-at
12022 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12023 org-log-note-marker))
12024 (setq lines nil))
12025 (when lines
12026 (with-current-buffer (marker-buffer org-log-note-marker)
12027 (save-excursion
12028 (goto-char org-log-note-marker)
12029 (move-marker org-log-note-marker nil)
12030 (end-of-line 1)
12031 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12032 (setq ind (save-excursion
12033 (if (ignore-errors (goto-char (org-in-item-p)))
12034 (let ((struct (org-list-struct)))
12035 (org-list-get-ind
12036 (org-list-get-top-point struct) struct))
12037 (skip-chars-backward " \r\t\n")
12038 (cond
12039 ((and (org-at-heading-p)
12040 org-adapt-indentation)
12041 (1+ (org-current-level)))
12042 ((org-at-heading-p) 0)
12043 (t (org-get-indentation))))))
12044 (setq bul (org-list-bullet-string "-"))
12045 (org-indent-line-to ind)
12046 (insert bul (pop lines))
12047 (let ((ind-body (+ (length bul) ind)))
12048 (while lines
12049 (insert "\n")
12050 (org-indent-line-to ind-body)
12051 (insert (pop lines))))
12052 (message "Note stored")
12053 (org-back-to-heading t)
12054 (org-cycle-hide-drawers 'children)))))
12055 (set-window-configuration org-log-note-window-configuration)
12056 (with-current-buffer (marker-buffer org-log-note-return-to)
12057 (goto-char org-log-note-return-to))
12058 (move-marker org-log-note-return-to nil)
12059 (and org-log-post-message (message "%s" org-log-post-message)))
12061 (defun org-remove-empty-drawer-at (drawer pos)
12062 "Remove an empty drawer DRAWER at position POS.
12063 POS may also be a marker."
12064 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12065 (save-excursion
12066 (save-restriction
12067 (widen)
12068 (goto-char pos)
12069 (if (org-in-regexp
12070 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12071 (replace-match ""))))))
12073 (defun org-sparse-tree (&optional arg)
12074 "Create a sparse tree, prompt for the details.
12075 This command can create sparse trees. You first need to select the type
12076 of match used to create the tree:
12078 t Show all TODO entries.
12079 T Show entries with a specific TODO keyword.
12080 m Show entries selected by a tags/property match.
12081 p Enter a property name and its value (both with completion on existing
12082 names/values) and show entries with that property.
12083 r Show entries matching a regular expression (`/' can be used as well)
12084 d Show deadlines due within `org-deadline-warning-days'.
12085 b Show deadlines and scheduled items before a date.
12086 a Show deadlines and scheduled items after a date."
12087 (interactive "P")
12088 (let (ans kwd value)
12089 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date")
12090 (setq ans (read-char-exclusive))
12091 (cond
12092 ((equal ans ?d)
12093 (call-interactively 'org-check-deadlines))
12094 ((equal ans ?b)
12095 (call-interactively 'org-check-before-date))
12096 ((equal ans ?a)
12097 (call-interactively 'org-check-after-date))
12098 ((equal ans ?t)
12099 (org-show-todo-tree nil))
12100 ((equal ans ?T)
12101 (org-show-todo-tree '(4)))
12102 ((member ans '(?T ?m))
12103 (call-interactively 'org-match-sparse-tree))
12104 ((member ans '(?p ?P))
12105 (setq kwd (org-icompleting-read "Property: "
12106 (mapcar 'list (org-buffer-property-keys))))
12107 (setq value (org-icompleting-read "Value: "
12108 (mapcar 'list (org-property-values kwd))))
12109 (unless (string-match "\\`{.*}\\'" value)
12110 (setq value (concat "\"" value "\"")))
12111 (org-match-sparse-tree arg (concat kwd "=" value)))
12112 ((member ans '(?r ?R ?/))
12113 (call-interactively 'org-occur))
12114 (t (error "No such sparse tree command \"%c\"" ans)))))
12116 (defvar org-occur-highlights nil
12117 "List of overlays used for occur matches.")
12118 (make-variable-buffer-local 'org-occur-highlights)
12119 (defvar org-occur-parameters nil
12120 "Parameters of the active org-occur calls.
12121 This is a list, each call to org-occur pushes as cons cell,
12122 containing the regular expression and the callback, onto the list.
12123 The list can contain several entries if `org-occur' has been called
12124 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12125 will only contain one set of parameters. When the highlights are
12126 removed (for example with `C-c C-c', or with the next edit (depending
12127 on `org-remove-highlights-with-change'), this variable is emptied
12128 as well.")
12129 (make-variable-buffer-local 'org-occur-parameters)
12131 (defun org-occur (regexp &optional keep-previous callback)
12132 "Make a compact tree which shows all matches of REGEXP.
12133 The tree will show the lines where the regexp matches, and all higher
12134 headlines above the match. It will also show the heading after the match,
12135 to make sure editing the matching entry is easy.
12136 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12137 call to `org-occur' will be kept, to allow stacking of calls to this
12138 command.
12139 If CALLBACK is non-nil, it is a function which is called to confirm
12140 that the match should indeed be shown."
12141 (interactive "sRegexp: \nP")
12142 (when (equal regexp "")
12143 (error "Regexp cannot be empty"))
12144 (unless keep-previous
12145 (org-remove-occur-highlights nil nil t))
12146 (push (cons regexp callback) org-occur-parameters)
12147 (let ((cnt 0))
12148 (save-excursion
12149 (goto-char (point-min))
12150 (if (or (not keep-previous) ; do not want to keep
12151 (not org-occur-highlights)) ; no previous matches
12152 ;; hide everything
12153 (org-overview))
12154 (while (re-search-forward regexp nil t)
12155 (when (or (not callback)
12156 (save-match-data (funcall callback)))
12157 (setq cnt (1+ cnt))
12158 (when org-highlight-sparse-tree-matches
12159 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12160 (org-show-context 'occur-tree))))
12161 (when org-remove-highlights-with-change
12162 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12163 nil 'local))
12164 (unless org-sparse-tree-open-archived-trees
12165 (org-hide-archived-subtrees (point-min) (point-max)))
12166 (run-hooks 'org-occur-hook)
12167 (if (org-called-interactively-p 'interactive)
12168 (message "%d match(es) for regexp %s" cnt regexp))
12169 cnt))
12171 (defun org-occur-next-match (&optional n reset)
12172 "Function for `next-error-function' to find sparse tree matches.
12173 N is the number of matches to move, when negative move backwards.
12174 RESET is entirely ignored - this function always goes back to the
12175 starting point when no match is found."
12176 (let* ((limit (if (< n 0) (point-min) (point-max)))
12177 (search-func (if (< n 0)
12178 'previous-single-char-property-change
12179 'next-single-char-property-change))
12180 (n (abs n))
12181 (pos (point))
12183 (catch 'exit
12184 (while (setq p1 (funcall search-func (point) 'org-type))
12185 (when (equal p1 limit)
12186 (goto-char pos)
12187 (error "No more matches"))
12188 (when (equal (get-char-property p1 'org-type) 'org-occur)
12189 (setq n (1- n))
12190 (when (= n 0)
12191 (goto-char p1)
12192 (throw 'exit (point))))
12193 (goto-char p1))
12194 (goto-char p1)
12195 (error "No more matches"))))
12197 (defun org-show-context (&optional key)
12198 "Make sure point and context are visible.
12199 How much context is shown depends upon the variables
12200 `org-show-hierarchy-above', `org-show-following-heading'. and
12201 `org-show-siblings'."
12202 (let ((heading-p (org-on-heading-p t))
12203 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12204 (following-p (org-get-alist-option org-show-following-heading key))
12205 (entry-p (org-get-alist-option org-show-entry-below key))
12206 (siblings-p (org-get-alist-option org-show-siblings key)))
12207 (catch 'exit
12208 ;; Show heading or entry text
12209 (if (and heading-p (not entry-p))
12210 (org-flag-heading nil) ; only show the heading
12211 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12212 (org-show-hidden-entry))) ; show entire entry
12213 (when following-p
12214 ;; Show next sibling, or heading below text
12215 (save-excursion
12216 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12217 (org-flag-heading nil))))
12218 (when siblings-p (org-show-siblings))
12219 (when hierarchy-p
12220 ;; show all higher headings, possibly with siblings
12221 (save-excursion
12222 (while (and (condition-case nil
12223 (progn (org-up-heading-all 1) t)
12224 (error nil))
12225 (not (bobp)))
12226 (org-flag-heading nil)
12227 (when siblings-p (org-show-siblings))))))))
12229 (defvar org-reveal-start-hook nil
12230 "Hook run before revealing a location.")
12232 (defun org-reveal (&optional siblings)
12233 "Show current entry, hierarchy above it, and the following headline.
12234 This can be used to show a consistent set of context around locations
12235 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12236 not t for the search context.
12238 With optional argument SIBLINGS, on each level of the hierarchy all
12239 siblings are shown. This repairs the tree structure to what it would
12240 look like when opened with hierarchical calls to `org-cycle'.
12241 With double optional argument \\[universal-argument] \\[universal-argument], \
12242 go to the parent and show the
12243 entire tree."
12244 (interactive "P")
12245 (run-hooks 'org-reveal-start-hook)
12246 (let ((org-show-hierarchy-above t)
12247 (org-show-following-heading t)
12248 (org-show-siblings (if siblings t org-show-siblings)))
12249 (org-show-context nil))
12250 (when (equal siblings '(16))
12251 (save-excursion
12252 (when (org-up-heading-safe)
12253 (org-show-subtree)
12254 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12256 (defun org-highlight-new-match (beg end)
12257 "Highlight from BEG to END and mark the highlight is an occur headline."
12258 (let ((ov (make-overlay beg end)))
12259 (overlay-put ov 'face 'secondary-selection)
12260 (overlay-put ov 'org-type 'org-occur)
12261 (push ov org-occur-highlights)))
12263 (defun org-remove-occur-highlights (&optional beg end noremove)
12264 "Remove the occur highlights from the buffer.
12265 BEG and END are ignored. If NOREMOVE is nil, remove this function
12266 from the `before-change-functions' in the current buffer."
12267 (interactive)
12268 (unless org-inhibit-highlight-removal
12269 (mapc 'delete-overlay org-occur-highlights)
12270 (setq org-occur-highlights nil)
12271 (setq org-occur-parameters nil)
12272 (unless noremove
12273 (remove-hook 'before-change-functions
12274 'org-remove-occur-highlights 'local))))
12276 ;;;; Priorities
12278 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12279 "Regular expression matching the priority indicator.")
12281 (defvar org-remove-priority-next-time nil)
12283 (defun org-priority-up ()
12284 "Increase the priority of the current item."
12285 (interactive)
12286 (org-priority 'up))
12288 (defun org-priority-down ()
12289 "Decrease the priority of the current item."
12290 (interactive)
12291 (org-priority 'down))
12293 (defun org-priority (&optional action)
12294 "Change the priority of an item by ARG.
12295 ACTION can be `set', `up', `down', or a character."
12296 (interactive)
12297 (unless org-enable-priority-commands
12298 (error "Priority commands are disabled"))
12299 (setq action (or action 'set))
12300 (let (current new news have remove)
12301 (save-excursion
12302 (org-back-to-heading t)
12303 (if (looking-at org-priority-regexp)
12304 (setq current (string-to-char (match-string 2))
12305 have t))
12306 (cond
12307 ((eq action 'remove)
12308 (setq remove t new ?\ ))
12309 ((or (eq action 'set)
12310 (if (featurep 'xemacs) (characterp action) (integerp action)))
12311 (if (not (eq action 'set))
12312 (setq new action)
12313 (message "Priority %c-%c, SPC to remove: "
12314 org-highest-priority org-lowest-priority)
12315 (save-match-data
12316 (setq new (read-char-exclusive))))
12317 (if (and (= (upcase org-highest-priority) org-highest-priority)
12318 (= (upcase org-lowest-priority) org-lowest-priority))
12319 (setq new (upcase new)))
12320 (cond ((equal new ?\ ) (setq remove t))
12321 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12322 (error "Priority must be between `%c' and `%c'"
12323 org-highest-priority org-lowest-priority))))
12324 ((eq action 'up)
12325 (setq new (if have
12326 (1- current) ; normal cycling
12327 ;; last priority was empty
12328 (if (eq last-command this-command)
12329 org-lowest-priority ; wrap around empty to lowest
12330 ;; default
12331 (if org-priority-start-cycle-with-default
12332 org-default-priority
12333 (1- org-default-priority))))))
12334 ((eq action 'down)
12335 (setq new (if have
12336 (1+ current) ; normal cycling
12337 ;; last priority was empty
12338 (if (eq last-command this-command)
12339 org-highest-priority ; wrap around empty to highest
12340 ;; default
12341 (if org-priority-start-cycle-with-default
12342 org-default-priority
12343 (1+ org-default-priority))))))
12344 (t (error "Invalid action")))
12345 (if (or (< (upcase new) org-highest-priority)
12346 (> (upcase new) org-lowest-priority))
12347 (if (and (memq action '(up down))
12348 (not have) (not (eq last-command this-command)))
12349 ;; `new' is from default priority
12350 (error
12351 "The default can not be set, see `org-default-priority' why")
12352 ;; normal cycling: `new' is beyond highest/lowest priority
12353 ;; and is wrapped around to the empty priority
12354 (setq remove t)))
12355 (setq news (format "%c" new))
12356 (if have
12357 (if remove
12358 (replace-match "" t t nil 1)
12359 (replace-match news t t nil 2))
12360 (if remove
12361 (error "No priority cookie found in line")
12362 (let ((case-fold-search nil))
12363 (looking-at org-todo-line-regexp))
12364 (if (match-end 2)
12365 (progn
12366 (goto-char (match-end 2))
12367 (insert " [#" news "]"))
12368 (goto-char (match-beginning 3))
12369 (insert "[#" news "] "))))
12370 (org-preserve-lc (org-set-tags nil 'align)))
12371 (if remove
12372 (message "Priority removed")
12373 (message "Priority of current item set to %s" news))))
12375 (defun org-get-priority (s)
12376 "Find priority cookie and return priority."
12377 (if (functionp org-get-priority-function)
12378 (funcall org-get-priority-function)
12379 (save-match-data
12380 (if (not (string-match org-priority-regexp s))
12381 (* 1000 (- org-lowest-priority org-default-priority))
12382 (* 1000 (- org-lowest-priority
12383 (string-to-char (match-string 2 s))))))))
12385 ;;;; Tags
12387 (defvar org-agenda-archives-mode)
12388 (defvar org-map-continue-from nil
12389 "Position from where mapping should continue.
12390 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
12392 (defvar org-scanner-tags nil
12393 "The current tag list while the tags scanner is running.")
12394 (defvar org-trust-scanner-tags nil
12395 "Should `org-get-tags-at' use the tags for the scanner.
12396 This is for internal dynamical scoping only.
12397 When this is non-nil, the function `org-get-tags-at' will return the value
12398 of `org-scanner-tags' instead of building the list by itself. This
12399 can lead to large speed-ups when the tags scanner is used in a file with
12400 many entries, and when the list of tags is retrieved, for example to
12401 obtain a list of properties. Building the tags list for each entry in such
12402 a file becomes an N^2 operation - but with this variable set, it scales
12403 as N.")
12405 (defun org-scan-tags (action matcher &optional todo-only)
12406 "Scan headline tags with inheritance and produce output ACTION.
12408 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12409 or `agenda' to produce an entry list for an agenda view. It can also be
12410 a Lisp form or a function that should be called at each matched headline, in
12411 this case the return value is a list of all return values from these calls.
12413 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12414 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12415 only lines with a TODO keyword are included in the output."
12416 (require 'org-agenda)
12417 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
12418 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12419 (org-re
12420 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12421 (props (list 'face 'default
12422 'done-face 'org-agenda-done
12423 'undone-face 'default
12424 'mouse-face 'highlight
12425 'org-not-done-regexp org-not-done-regexp
12426 'org-todo-regexp org-todo-regexp
12427 'help-echo
12428 (format "mouse-2 or RET jump to org file %s"
12429 (abbreviate-file-name
12430 (or (buffer-file-name (buffer-base-buffer))
12431 (buffer-name (buffer-base-buffer)))))))
12432 (case-fold-search nil)
12433 (org-map-continue-from nil)
12434 lspos tags tags-list
12435 (tags-alist (list (cons 0 org-file-tags)))
12436 (llast 0) rtn rtn1 level category i txt
12437 todo marker entry priority)
12438 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12439 (setq action (list 'lambda nil action)))
12440 (save-excursion
12441 (goto-char (point-min))
12442 (when (eq action 'sparse-tree)
12443 (org-overview)
12444 (org-remove-occur-highlights))
12445 (while (re-search-forward re nil t)
12446 (catch :skip
12447 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12448 tags (if (match-end 4) (org-match-string-no-properties 4)))
12449 (goto-char (setq lspos (match-beginning 0)))
12450 (setq level (org-reduced-level (funcall outline-level))
12451 category (org-get-category))
12452 (setq i llast llast level)
12453 ;; remove tag lists from same and sublevels
12454 (while (>= i level)
12455 (when (setq entry (assoc i tags-alist))
12456 (setq tags-alist (delete entry tags-alist)))
12457 (setq i (1- i)))
12458 ;; add the next tags
12459 (when tags
12460 (setq tags (org-split-string tags ":")
12461 tags-alist
12462 (cons (cons level tags) tags-alist)))
12463 ;; compile tags for current headline
12464 (setq tags-list
12465 (if org-use-tag-inheritance
12466 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12467 tags)
12468 org-scanner-tags tags-list)
12469 (when org-use-tag-inheritance
12470 (setcdr (car tags-alist)
12471 (mapcar (lambda (x)
12472 (setq x (copy-sequence x))
12473 (org-add-prop-inherited x))
12474 (cdar tags-alist))))
12475 (when (and tags org-use-tag-inheritance
12476 (or (not (eq t org-use-tag-inheritance))
12477 org-tags-exclude-from-inheritance))
12478 ;; selective inheritance, remove uninherited ones
12479 (setcdr (car tags-alist)
12480 (org-remove-uninherited-tags (cdar tags-alist))))
12481 (when (and
12483 ;; eval matcher only when the todo condition is OK
12484 (and (or (not todo-only) (member todo org-not-done-keywords))
12485 (let ((case-fold-search t)) (eval matcher)))
12487 ;; Call the skipper, but return t if it does not skip,
12488 ;; so that the `and' form continues evaluating
12489 (progn
12490 (unless (eq action 'sparse-tree) (org-agenda-skip))
12493 ;; Check if timestamps are deselecting this entry
12494 (or (not todo-only)
12495 (and (member todo org-not-done-keywords)
12496 (or (not org-agenda-tags-todo-honor-ignore-options)
12497 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12499 ;; Extra check for the archive tag
12500 ;; FIXME: Does the skipper already do this????
12502 (not (member org-archive-tag tags-list))
12503 ;; we have an archive tag, should we use this anyway?
12504 (or (not org-agenda-skip-archived-trees)
12505 (and (eq action 'agenda) org-agenda-archives-mode))))
12507 ;; select this headline
12509 (cond
12510 ((eq action 'sparse-tree)
12511 (and org-highlight-sparse-tree-matches
12512 (org-get-heading) (match-end 0)
12513 (org-highlight-new-match
12514 (match-beginning 0) (match-beginning 1)))
12515 (org-show-context 'tags-tree))
12516 ((eq action 'agenda)
12517 (setq txt (org-format-agenda-item
12519 (concat
12520 (if (eq org-tags-match-list-sublevels 'indented)
12521 (make-string (1- level) ?.) "")
12522 (org-get-heading))
12523 category
12524 tags-list
12526 priority (org-get-priority txt))
12527 (goto-char lspos)
12528 (setq marker (org-agenda-new-marker))
12529 (org-add-props txt props
12530 'org-marker marker 'org-hd-marker marker 'org-category category
12531 'todo-state todo
12532 'priority priority 'type "tagsmatch")
12533 (push txt rtn))
12534 ((functionp action)
12535 (setq org-map-continue-from nil)
12536 (save-excursion
12537 (setq rtn1 (funcall action))
12538 (push rtn1 rtn)))
12539 (t (error "Invalid action")))
12541 ;; if we are to skip sublevels, jump to end of subtree
12542 (unless org-tags-match-list-sublevels
12543 (org-end-of-subtree t)
12544 (backward-char 1))))
12545 ;; Get the correct position from where to continue
12546 (if org-map-continue-from
12547 (goto-char org-map-continue-from)
12548 (and (= (point) lspos) (end-of-line 1)))))
12549 (when (and (eq action 'sparse-tree)
12550 (not org-sparse-tree-open-archived-trees))
12551 (org-hide-archived-subtrees (point-min) (point-max)))
12552 (nreverse rtn)))
12554 (defun org-remove-uninherited-tags (tags)
12555 "Remove all tags that are not inherited from the list TAGS."
12556 (cond
12557 ((eq org-use-tag-inheritance t)
12558 (if org-tags-exclude-from-inheritance
12559 (org-delete-all org-tags-exclude-from-inheritance tags)
12560 tags))
12561 ((not org-use-tag-inheritance) nil)
12562 ((stringp org-use-tag-inheritance)
12563 (delq nil (mapcar
12564 (lambda (x)
12565 (if (and (string-match org-use-tag-inheritance x)
12566 (not (member x org-tags-exclude-from-inheritance)))
12567 x nil))
12568 tags)))
12569 ((listp org-use-tag-inheritance)
12570 (delq nil (mapcar
12571 (lambda (x)
12572 (if (member x org-use-tag-inheritance) x nil))
12573 tags)))))
12575 (defvar todo-only) ;; dynamically scoped
12577 (defun org-match-sparse-tree (&optional todo-only match)
12578 "Create a sparse tree according to tags string MATCH.
12579 MATCH can contain positive and negative selection of tags, like
12580 \"+WORK+URGENT-WITHBOSS\".
12581 If optional argument TODO-ONLY is non-nil, only select lines that are
12582 also TODO lines."
12583 (interactive "P")
12584 (org-prepare-agenda-buffers (list (current-buffer)))
12585 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12587 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12589 (defvar org-cached-props nil)
12590 (defun org-cached-entry-get (pom property)
12591 (if (or (eq t org-use-property-inheritance)
12592 (and (stringp org-use-property-inheritance)
12593 (string-match org-use-property-inheritance property))
12594 (and (listp org-use-property-inheritance)
12595 (member property org-use-property-inheritance)))
12596 ;; Caching is not possible, check it directly
12597 (org-entry-get pom property 'inherit)
12598 ;; Get all properties, so that we can do complicated checks easily
12599 (cdr (assoc property (or org-cached-props
12600 (setq org-cached-props
12601 (org-entry-properties pom)))))))
12603 (defun org-global-tags-completion-table (&optional files)
12604 "Return the list of all tags in all agenda buffer/files.
12605 Optional FILES argument is a list of files to which can be used
12606 instead of the agenda files."
12607 (save-excursion
12608 (org-uniquify
12609 (delq nil
12610 (apply 'append
12611 (mapcar
12612 (lambda (file)
12613 (set-buffer (find-file-noselect file))
12614 (append (org-get-buffer-tags)
12615 (mapcar (lambda (x) (if (stringp (car-safe x))
12616 (list (car-safe x)) nil))
12617 org-tag-alist)))
12618 (if (and files (car files))
12619 files
12620 (org-agenda-files))))))))
12622 (defun org-make-tags-matcher (match)
12623 "Create the TAGS/TODO matcher form for the selection string MATCH."
12624 ;; todo-only is scoped dynamically into this function, and the function
12625 ;; may change it if the matcher asks for it.
12626 (unless match
12627 ;; Get a new match request, with completion
12628 (let ((org-last-tags-completion-table
12629 (org-global-tags-completion-table)))
12630 (setq match (org-completing-read-no-i
12631 "Match: " 'org-tags-completion-function nil nil nil
12632 'org-tags-history))))
12634 ;; Parse the string and create a lisp form
12635 (let ((match0 match)
12636 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
12637 minus tag mm
12638 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12639 orterms term orlist re-p str-p level-p level-op time-p
12640 prop-p pn pv po gv rest)
12641 (if (string-match "/+" match)
12642 ;; match contains also a todo-matching request
12643 (progn
12644 (setq tagsmatch (substring match 0 (match-beginning 0))
12645 todomatch (substring match (match-end 0)))
12646 (if (string-match "^!" todomatch)
12647 (setq todo-only t todomatch (substring todomatch 1)))
12648 (if (string-match "^\\s-*$" todomatch)
12649 (setq todomatch nil)))
12650 ;; only matching tags
12651 (setq tagsmatch match todomatch nil))
12653 ;; Make the tags matcher
12654 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12655 (setq tagsmatcher t)
12656 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12657 (while (setq term (pop orterms))
12658 (while (and (equal (substring term -1) "\\") orterms)
12659 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12660 (while (string-match re term)
12661 (setq rest (substring term (match-end 0))
12662 minus (and (match-end 1)
12663 (equal (match-string 1 term) "-"))
12664 tag (save-match-data (replace-regexp-in-string
12665 "\\\\-" "-"
12666 (match-string 2 term)))
12667 re-p (equal (string-to-char tag) ?{)
12668 level-p (match-end 4)
12669 prop-p (match-end 5)
12670 mm (cond
12671 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12672 (level-p
12673 (setq level-op (org-op-to-function (match-string 3 term)))
12674 `(,level-op level ,(string-to-number
12675 (match-string 4 term))))
12676 (prop-p
12677 (setq pn (match-string 5 term)
12678 po (match-string 6 term)
12679 pv (match-string 7 term)
12680 re-p (equal (string-to-char pv) ?{)
12681 str-p (equal (string-to-char pv) ?\")
12682 time-p (save-match-data
12683 (string-match "^\"[[<].*[]>]\"$" pv))
12684 pv (if (or re-p str-p) (substring pv 1 -1) pv))
12685 (if time-p (setq pv (org-matcher-time pv)))
12686 (setq po (org-op-to-function po (if time-p 'time str-p)))
12687 (cond
12688 ((equal pn "CATEGORY")
12689 (setq gv '(get-text-property (point) 'org-category)))
12690 ((equal pn "TODO")
12691 (setq gv 'todo))
12693 (setq gv `(org-cached-entry-get nil ,pn))))
12694 (if re-p
12695 (if (eq po 'org<>)
12696 `(not (string-match ,pv (or ,gv "")))
12697 `(string-match ,pv (or ,gv "")))
12698 (if str-p
12699 `(,po (or ,gv "") ,pv)
12700 `(,po (string-to-number (or ,gv ""))
12701 ,(string-to-number pv) ))))
12702 (t `(member ,tag tags-list)))
12703 mm (if minus (list 'not mm) mm)
12704 term rest)
12705 (push mm tagsmatcher))
12706 (push (if (> (length tagsmatcher) 1)
12707 (cons 'and tagsmatcher)
12708 (car tagsmatcher))
12709 orlist)
12710 (setq tagsmatcher nil))
12711 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
12712 (setq tagsmatcher
12713 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
12714 ;; Make the todo matcher
12715 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
12716 (setq todomatcher t)
12717 (setq orterms (org-split-string todomatch "|") orlist nil)
12718 (while (setq term (pop orterms))
12719 (while (string-match re term)
12720 (setq minus (and (match-end 1)
12721 (equal (match-string 1 term) "-"))
12722 kwd (match-string 2 term)
12723 re-p (equal (string-to-char kwd) ?{)
12724 term (substring term (match-end 0))
12725 mm (if re-p
12726 `(string-match ,(substring kwd 1 -1) todo)
12727 (list 'equal 'todo kwd))
12728 mm (if minus (list 'not mm) mm))
12729 (push mm todomatcher))
12730 (push (if (> (length todomatcher) 1)
12731 (cons 'and todomatcher)
12732 (car todomatcher))
12733 orlist)
12734 (setq todomatcher nil))
12735 (setq todomatcher (if (> (length orlist) 1)
12736 (cons 'or orlist) (car orlist))))
12738 ;; Return the string and lisp forms of the matcher
12739 (setq matcher (if todomatcher
12740 (list 'and tagsmatcher todomatcher)
12741 tagsmatcher))
12742 (cons match0 matcher)))
12744 (defun org-op-to-function (op &optional stringp)
12745 "Turn an operator into the appropriate function."
12746 (setq op
12747 (cond
12748 ((equal op "<" ) '(< string< org-time<))
12749 ((equal op ">" ) '(> org-string> org-time>))
12750 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
12751 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
12752 ((member op '("=" "==")) '(= string= org-time=))
12753 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
12754 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
12756 (defun org<> (a b) (not (= a b)))
12757 (defun org-string<= (a b) (or (string= a b) (string< a b)))
12758 (defun org-string>= (a b) (not (string< a b)))
12759 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
12760 (defun org-string<> (a b) (not (string= a b)))
12761 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
12762 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
12763 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
12764 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
12765 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
12766 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
12767 (defun org-2ft (s)
12768 "Convert S to a floating point time.
12769 If S is already a number, just return it. If it is a string, parse
12770 it as a time string and apply `float-time' to it. If S is nil, just return 0."
12771 (cond
12772 ((numberp s) s)
12773 ((stringp s)
12774 (condition-case nil
12775 (float-time (apply 'encode-time (org-parse-time-string s)))
12776 (error 0.)))
12777 (t 0.)))
12779 (defun org-time-today ()
12780 "Time in seconds today at 0:00.
12781 Returns the float number of seconds since the beginning of the
12782 epoch to the beginning of today (00:00)."
12783 (float-time (apply 'encode-time
12784 (append '(0 0 0) (nthcdr 3 (decode-time))))))
12786 (defun org-matcher-time (s)
12787 "Interpret a time comparison value."
12788 (save-match-data
12789 (cond
12790 ((string= s "<now>") (float-time))
12791 ((string= s "<today>") (org-time-today))
12792 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
12793 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
12794 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
12795 (+ (org-time-today)
12796 (* (string-to-number (match-string 1 s))
12797 (cdr (assoc (match-string 2 s)
12798 '(("d" . 86400.0) ("w" . 604800.0)
12799 ("m" . 2678400.0) ("y" . 31557600.0)))))))
12800 (t (org-2ft s)))))
12802 (defun org-match-any-p (re list)
12803 "Does re match any element of list?"
12804 (setq list (mapcar (lambda (x) (string-match re x)) list))
12805 (delq nil list))
12807 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
12808 (defvar org-tags-overlay (make-overlay 1 1))
12809 (org-detach-overlay org-tags-overlay)
12811 (defun org-get-local-tags-at (&optional pos)
12812 "Get a list of tags defined in the current headline."
12813 (org-get-tags-at pos 'local))
12815 (defun org-get-local-tags ()
12816 "Get a list of tags defined in the current headline."
12817 (org-get-tags-at nil 'local))
12819 (defun org-get-tags-at (&optional pos local)
12820 "Get a list of all headline tags applicable at POS.
12821 POS defaults to point. If tags are inherited, the list contains
12822 the targets in the same sequence as the headlines appear, i.e.
12823 the tags of the current headline come last.
12824 When LOCAL is non-nil, only return tags from the current headline,
12825 ignore inherited ones."
12826 (interactive)
12827 (if (and org-trust-scanner-tags
12828 (or (not pos) (equal pos (point)))
12829 (not local))
12830 org-scanner-tags
12831 (let (tags ltags lastpos parent)
12832 (save-excursion
12833 (save-restriction
12834 (widen)
12835 (goto-char (or pos (point)))
12836 (save-match-data
12837 (catch 'done
12838 (condition-case nil
12839 (progn
12840 (org-back-to-heading t)
12841 (while (not (equal lastpos (point)))
12842 (setq lastpos (point))
12843 (when (looking-at
12844 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
12845 (setq ltags (org-split-string
12846 (org-match-string-no-properties 1) ":"))
12847 (when parent
12848 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
12849 (setq tags (append
12850 (if parent
12851 (org-remove-uninherited-tags ltags)
12852 ltags)
12853 tags)))
12854 (or org-use-tag-inheritance (throw 'done t))
12855 (if local (throw 'done t))
12856 (or (org-up-heading-safe) (error nil))
12857 (setq parent t)))
12858 (error nil)))))
12859 (if local
12860 tags
12861 (append (org-remove-uninherited-tags org-file-tags) tags))))))
12863 (defun org-add-prop-inherited (s)
12864 (add-text-properties 0 (length s) '(inherited t) s)
12867 (defun org-toggle-tag (tag &optional onoff)
12868 "Toggle the tag TAG for the current line.
12869 If ONOFF is `on' or `off', don't toggle but set to this state."
12870 (let (res current)
12871 (save-excursion
12872 (org-back-to-heading t)
12873 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
12874 (point-at-eol) t)
12875 (progn
12876 (setq current (match-string 1))
12877 (replace-match ""))
12878 (setq current ""))
12879 (setq current (nreverse (org-split-string current ":")))
12880 (cond
12881 ((eq onoff 'on)
12882 (setq res t)
12883 (or (member tag current) (push tag current)))
12884 ((eq onoff 'off)
12885 (or (not (member tag current)) (setq current (delete tag current))))
12886 (t (if (member tag current)
12887 (setq current (delete tag current))
12888 (setq res t)
12889 (push tag current))))
12890 (end-of-line 1)
12891 (if current
12892 (progn
12893 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
12894 (org-set-tags nil t))
12895 (delete-horizontal-space))
12896 (run-hooks 'org-after-tags-change-hook))
12897 res))
12899 (defun org-align-tags-here (to-col)
12900 ;; Assumes that this is a headline
12901 (let ((pos (point)) (col (current-column)) ncol tags-l p)
12902 (beginning-of-line 1)
12903 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
12904 (< pos (match-beginning 2)))
12905 (progn
12906 (setq tags-l (- (match-end 2) (match-beginning 2)))
12907 (goto-char (match-beginning 1))
12908 (insert " ")
12909 (delete-region (point) (1+ (match-beginning 2)))
12910 (setq ncol (max (1+ (current-column))
12911 (1+ col)
12912 (if (> to-col 0)
12913 to-col
12914 (- (abs to-col) tags-l))))
12915 (setq p (point))
12916 (insert (make-string (- ncol (current-column)) ?\ ))
12917 (setq ncol (current-column))
12918 (when indent-tabs-mode (tabify p (point-at-eol)))
12919 (org-move-to-column (min ncol col) t))
12920 (goto-char pos))))
12922 (defun org-set-tags-command (&optional arg just-align)
12923 "Call the set-tags command for the current entry."
12924 (interactive "P")
12925 (if (org-on-heading-p)
12926 (org-set-tags arg just-align)
12927 (save-excursion
12928 (org-back-to-heading t)
12929 (org-set-tags arg just-align))))
12931 (defun org-set-tags-to (data)
12932 "Set the tags of the current entry to DATA, replacing the current tags.
12933 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
12934 If DATA is nil or the empty string, any tags will be removed."
12935 (interactive "sTags: ")
12936 (setq data
12937 (cond
12938 ((eq data nil) "")
12939 ((equal data "") "")
12940 ((stringp data)
12941 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
12942 ":"))
12943 ((listp data)
12944 (concat ":" (mapconcat 'identity data ":") ":"))
12945 (t nil)))
12946 (when data
12947 (save-excursion
12948 (org-back-to-heading t)
12949 (when (looking-at org-complex-heading-regexp)
12950 (if (match-end 5)
12951 (progn
12952 (goto-char (match-beginning 5))
12953 (insert data)
12954 (delete-region (point) (point-at-eol))
12955 (org-set-tags nil 'align))
12956 (goto-char (point-at-eol))
12957 (insert " " data)
12958 (org-set-tags nil 'align)))
12959 (beginning-of-line 1)
12960 (if (looking-at ".*?\\([ \t]+\\)$")
12961 (delete-region (match-beginning 1) (match-end 1))))))
12963 (defun org-align-all-tags ()
12964 "Align the tags i all headings."
12965 (interactive)
12966 (save-excursion
12967 (or (ignore-errors (org-back-to-heading t))
12968 (outline-next-heading))
12969 (if (org-on-heading-p)
12970 (org-set-tags t)
12971 (message "No headings"))))
12973 (defvar org-indent-indentation-per-level)
12974 (defun org-set-tags (&optional arg just-align)
12975 "Set the tags for the current headline.
12976 With prefix ARG, realign all tags in headings in the current buffer."
12977 (interactive "P")
12978 (let* ((re (concat "^" outline-regexp))
12979 (current (org-get-tags-string))
12980 (col (current-column))
12981 (org-setting-tags t)
12982 table current-tags inherited-tags ; computed below when needed
12983 tags p0 c0 c1 rpl di tc level)
12984 (if arg
12985 (save-excursion
12986 (goto-char (point-min))
12987 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12988 (while (re-search-forward re nil t)
12989 (org-set-tags nil t)
12990 (end-of-line 1)))
12991 (message "All tags realigned to column %d" org-tags-column))
12992 (if just-align
12993 (setq tags current)
12994 ;; Get a new set of tags from the user
12995 (save-excursion
12996 (setq table (append org-tag-persistent-alist
12997 (or org-tag-alist (org-get-buffer-tags))
12998 (and
12999 org-complete-tags-always-offer-all-agenda-tags
13000 (org-global-tags-completion-table
13001 (org-agenda-files))))
13002 org-last-tags-completion-table table
13003 current-tags (org-split-string current ":")
13004 inherited-tags (nreverse
13005 (nthcdr (length current-tags)
13006 (nreverse (org-get-tags-at))))
13007 tags
13008 (if (or (eq t org-use-fast-tag-selection)
13009 (and org-use-fast-tag-selection
13010 (delq nil (mapcar 'cdr table))))
13011 (org-fast-tag-selection
13012 current-tags inherited-tags table
13013 (if org-fast-tag-selection-include-todo
13014 org-todo-key-alist))
13015 (let ((org-add-colon-after-tag-completion t))
13016 (org-trim
13017 (org-without-partial-completion
13018 (org-icompleting-read "Tags: "
13019 'org-tags-completion-function
13020 nil nil current 'org-tags-history)))))))
13021 (while (string-match "[-+&]+" tags)
13022 ;; No boolean logic, just a list
13023 (setq tags (replace-match ":" t t tags))))
13025 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13027 (if org-tags-sort-function
13028 (setq tags (mapconcat 'identity
13029 (sort (org-split-string
13030 tags (org-re "[^[:alnum:]_@#%]+"))
13031 org-tags-sort-function) ":")))
13033 (if (string-match "\\`[\t ]*\\'" tags)
13034 (setq tags "")
13035 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13036 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13038 ;; Insert new tags at the correct column
13039 (beginning-of-line 1)
13040 (setq level (or (and (looking-at org-outline-regexp)
13041 (- (match-end 0) (point) 1))
13043 (cond
13044 ((and (equal current "") (equal tags "")))
13045 ((re-search-forward
13046 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13047 (point-at-eol) t)
13048 (if (equal tags "")
13049 (setq rpl "")
13050 (goto-char (match-beginning 0))
13051 (setq c0 (current-column)
13052 ;; compute offset for the case of org-indent-mode active
13053 di (if org-indent-mode
13054 (* (1- org-indent-indentation-per-level) (1- level))
13056 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13057 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13058 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13059 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13060 (replace-match rpl t t)
13061 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13062 tags)
13063 (t (error "Tags alignment failed")))
13064 (org-move-to-column col)
13065 (unless just-align
13066 (run-hooks 'org-after-tags-change-hook)))))
13068 (defun org-change-tag-in-region (beg end tag off)
13069 "Add or remove TAG for each entry in the region.
13070 This works in the agenda, and also in an org-mode buffer."
13071 (interactive
13072 (list (region-beginning) (region-end)
13073 (let ((org-last-tags-completion-table
13074 (if (org-mode-p)
13075 (org-get-buffer-tags)
13076 (org-global-tags-completion-table))))
13077 (org-icompleting-read
13078 "Tag: " 'org-tags-completion-function nil nil nil
13079 'org-tags-history))
13080 (progn
13081 (message "[s]et or [r]emove? ")
13082 (equal (read-char-exclusive) ?r))))
13083 (if (fboundp 'deactivate-mark) (deactivate-mark))
13084 (let ((agendap (equal major-mode 'org-agenda-mode))
13085 l1 l2 m buf pos newhead (cnt 0))
13086 (goto-char end)
13087 (setq l2 (1- (org-current-line)))
13088 (goto-char beg)
13089 (setq l1 (org-current-line))
13090 (loop for l from l1 to l2 do
13091 (org-goto-line l)
13092 (setq m (get-text-property (point) 'org-hd-marker))
13093 (when (or (and (org-mode-p) (org-on-heading-p))
13094 (and agendap m))
13095 (setq buf (if agendap (marker-buffer m) (current-buffer))
13096 pos (if agendap m (point)))
13097 (with-current-buffer buf
13098 (save-excursion
13099 (save-restriction
13100 (goto-char pos)
13101 (setq cnt (1+ cnt))
13102 (org-toggle-tag tag (if off 'off 'on))
13103 (setq newhead (org-get-heading)))))
13104 (and agendap (org-agenda-change-all-lines newhead m))))
13105 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13107 (defun org-tags-completion-function (string predicate &optional flag)
13108 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13109 (confirm (lambda (x) (stringp (car x)))))
13110 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13111 (setq s1 (match-string 1 string)
13112 s2 (match-string 2 string))
13113 (setq s1 "" s2 string))
13114 (cond
13115 ((eq flag nil)
13116 ;; try completion
13117 (setq rtn (try-completion s2 ctable confirm))
13118 (if (stringp rtn)
13119 (setq rtn
13120 (concat s1 s2 (substring rtn (length s2))
13121 (if (and org-add-colon-after-tag-completion
13122 (assoc rtn ctable))
13123 ":" ""))))
13124 rtn)
13125 ((eq flag t)
13126 ;; all-completions
13127 (all-completions s2 ctable confirm)
13129 ((eq flag 'lambda)
13130 ;; exact match?
13131 (assoc s2 ctable)))
13134 (defun org-fast-tag-insert (kwd tags face &optional end)
13135 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13136 (insert (format "%-12s" (concat kwd ":"))
13137 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13138 (or end "")))
13140 (defun org-fast-tag-show-exit (flag)
13141 (save-excursion
13142 (org-goto-line 3)
13143 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13144 (replace-match ""))
13145 (when flag
13146 (end-of-line 1)
13147 (org-move-to-column (- (window-width) 19) t)
13148 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13150 (defun org-set-current-tags-overlay (current prefix)
13151 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13152 (if (featurep 'xemacs)
13153 (org-overlay-display org-tags-overlay (concat prefix s)
13154 'secondary-selection)
13155 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13156 (org-overlay-display org-tags-overlay (concat prefix s)))))
13158 (defvar org-last-tag-selection-key nil)
13159 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13160 "Fast tag selection with single keys.
13161 CURRENT is the current list of tags in the headline, INHERITED is the
13162 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13163 possibly with grouping information. TODO-TABLE is a similar table with
13164 TODO keywords, should these have keys assigned to them.
13165 If the keys are nil, a-z are automatically assigned.
13166 Returns the new tags string, or nil to not change the current settings."
13167 (let* ((fulltable (append table todo-table))
13168 (maxlen (apply 'max (mapcar
13169 (lambda (x)
13170 (if (stringp (car x)) (string-width (car x)) 0))
13171 fulltable)))
13172 (buf (current-buffer))
13173 (expert (eq org-fast-tag-selection-single-key 'expert))
13174 (buffer-tags nil)
13175 (fwidth (+ maxlen 3 1 3))
13176 (ncol (/ (- (window-width) 4) fwidth))
13177 (i-face 'org-done)
13178 (c-face 'org-todo)
13179 tg cnt e c char c1 c2 ntable tbl rtn
13180 ov-start ov-end ov-prefix
13181 (exit-after-next org-fast-tag-selection-single-key)
13182 (done-keywords org-done-keywords)
13183 groups ingroup)
13184 (save-excursion
13185 (beginning-of-line 1)
13186 (if (looking-at
13187 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13188 (setq ov-start (match-beginning 1)
13189 ov-end (match-end 1)
13190 ov-prefix "")
13191 (setq ov-start (1- (point-at-eol))
13192 ov-end (1+ ov-start))
13193 (skip-chars-forward "^\n\r")
13194 (setq ov-prefix
13195 (concat
13196 (buffer-substring (1- (point)) (point))
13197 (if (> (current-column) org-tags-column)
13199 (make-string (- org-tags-column (current-column)) ?\ ))))))
13200 (move-overlay org-tags-overlay ov-start ov-end)
13201 (save-window-excursion
13202 (if expert
13203 (set-buffer (get-buffer-create " *Org tags*"))
13204 (delete-other-windows)
13205 (split-window-vertically)
13206 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13207 (erase-buffer)
13208 (org-set-local 'org-done-keywords done-keywords)
13209 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13210 (org-fast-tag-insert "Current" current c-face "\n\n")
13211 (org-fast-tag-show-exit exit-after-next)
13212 (org-set-current-tags-overlay current ov-prefix)
13213 (setq tbl fulltable char ?a cnt 0)
13214 (while (setq e (pop tbl))
13215 (cond
13216 ((equal (car e) :startgroup)
13217 (push '() groups) (setq ingroup t)
13218 (when (not (= cnt 0))
13219 (setq cnt 0)
13220 (insert "\n"))
13221 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13222 ((equal (car e) :endgroup)
13223 (setq ingroup nil cnt 0)
13224 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13225 ((equal e '(:newline))
13226 (when (not (= cnt 0))
13227 (setq cnt 0)
13228 (insert "\n")
13229 (setq e (car tbl))
13230 (while (equal (car tbl) '(:newline))
13231 (insert "\n")
13232 (setq tbl (cdr tbl)))))
13234 (setq tg (copy-sequence (car e)) c2 nil)
13235 (if (cdr e)
13236 (setq c (cdr e))
13237 ;; automatically assign a character.
13238 (setq c1 (string-to-char
13239 (downcase (substring
13240 tg (if (= (string-to-char tg) ?@) 1 0)))))
13241 (if (or (rassoc c1 ntable) (rassoc c1 table))
13242 (while (or (rassoc char ntable) (rassoc char table))
13243 (setq char (1+ char)))
13244 (setq c2 c1))
13245 (setq c (or c2 char)))
13246 (if ingroup (push tg (car groups)))
13247 (setq tg (org-add-props tg nil 'face
13248 (cond
13249 ((not (assoc tg table))
13250 (org-get-todo-face tg))
13251 ((member tg current) c-face)
13252 ((member tg inherited) i-face)
13253 (t nil))))
13254 (if (and (= cnt 0) (not ingroup)) (insert " "))
13255 (insert "[" c "] " tg (make-string
13256 (- fwidth 4 (length tg)) ?\ ))
13257 (push (cons tg c) ntable)
13258 (when (= (setq cnt (1+ cnt)) ncol)
13259 (insert "\n")
13260 (if ingroup (insert " "))
13261 (setq cnt 0)))))
13262 (setq ntable (nreverse ntable))
13263 (insert "\n")
13264 (goto-char (point-min))
13265 (if (not expert) (org-fit-window-to-buffer))
13266 (setq rtn
13267 (catch 'exit
13268 (while t
13269 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13270 (if (not groups) "no " "")
13271 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13272 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13273 (setq org-last-tag-selection-key c)
13274 (cond
13275 ((= c ?\r) (throw 'exit t))
13276 ((= c ?!)
13277 (setq groups (not groups))
13278 (goto-char (point-min))
13279 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13280 ((= c ?\C-c)
13281 (if (not expert)
13282 (org-fast-tag-show-exit
13283 (setq exit-after-next (not exit-after-next)))
13284 (setq expert nil)
13285 (delete-other-windows)
13286 (set-window-buffer (split-window-vertically) " *Org tags*")
13287 (org-switch-to-buffer-other-window " *Org tags*")
13288 (org-fit-window-to-buffer)))
13289 ((or (= c ?\C-g)
13290 (and (= c ?q) (not (rassoc c ntable))))
13291 (org-detach-overlay org-tags-overlay)
13292 (setq quit-flag t))
13293 ((= c ?\ )
13294 (setq current nil)
13295 (if exit-after-next (setq exit-after-next 'now)))
13296 ((= c ?\t)
13297 (condition-case nil
13298 (setq tg (org-icompleting-read
13299 "Tag: "
13300 (or buffer-tags
13301 (with-current-buffer buf
13302 (org-get-buffer-tags)))))
13303 (quit (setq tg "")))
13304 (when (string-match "\\S-" tg)
13305 (add-to-list 'buffer-tags (list tg))
13306 (if (member tg current)
13307 (setq current (delete tg current))
13308 (push tg current)))
13309 (if exit-after-next (setq exit-after-next 'now)))
13310 ((setq e (rassoc c todo-table) tg (car e))
13311 (with-current-buffer buf
13312 (save-excursion (org-todo tg)))
13313 (if exit-after-next (setq exit-after-next 'now)))
13314 ((setq e (rassoc c ntable) tg (car e))
13315 (if (member tg current)
13316 (setq current (delete tg current))
13317 (loop for g in groups do
13318 (if (member tg g)
13319 (mapc (lambda (x)
13320 (setq current (delete x current)))
13321 g)))
13322 (push tg current))
13323 (if exit-after-next (setq exit-after-next 'now))))
13325 ;; Create a sorted list
13326 (setq current
13327 (sort current
13328 (lambda (a b)
13329 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13330 (if (eq exit-after-next 'now) (throw 'exit t))
13331 (goto-char (point-min))
13332 (beginning-of-line 2)
13333 (delete-region (point) (point-at-eol))
13334 (org-fast-tag-insert "Current" current c-face)
13335 (org-set-current-tags-overlay current ov-prefix)
13336 (while (re-search-forward
13337 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13338 (setq tg (match-string 1))
13339 (add-text-properties
13340 (match-beginning 1) (match-end 1)
13341 (list 'face
13342 (cond
13343 ((member tg current) c-face)
13344 ((member tg inherited) i-face)
13345 (t (get-text-property (match-beginning 1) 'face))))))
13346 (goto-char (point-min)))))
13347 (org-detach-overlay org-tags-overlay)
13348 (if rtn
13349 (mapconcat 'identity current ":")
13350 nil))))
13352 (defun org-get-tags-string ()
13353 "Get the TAGS string in the current headline."
13354 (unless (org-on-heading-p t)
13355 (error "Not on a heading"))
13356 (save-excursion
13357 (beginning-of-line 1)
13358 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13359 (org-match-string-no-properties 1)
13360 "")))
13362 (defun org-get-tags ()
13363 "Get the list of tags specified in the current headline."
13364 (org-split-string (org-get-tags-string) ":"))
13366 (defun org-get-buffer-tags ()
13367 "Get a table of all tags used in the buffer, for completion."
13368 (let (tags)
13369 (save-excursion
13370 (goto-char (point-min))
13371 (while (re-search-forward
13372 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13373 (when (equal (char-after (point-at-bol 0)) ?*)
13374 (mapc (lambda (x) (add-to-list 'tags x))
13375 (org-split-string (org-match-string-no-properties 1) ":")))))
13376 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13377 (mapcar 'list tags)))
13379 ;;;; The mapping API
13381 ;;;###autoload
13382 (defun org-map-entries (func &optional match scope &rest skip)
13383 "Call FUNC at each headline selected by MATCH in SCOPE.
13385 FUNC is a function or a lisp form. The function will be called without
13386 arguments, with the cursor positioned at the beginning of the headline.
13387 The return values of all calls to the function will be collected and
13388 returned as a list.
13390 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13391 does not need to preserve point. After evaluation, the cursor will be
13392 moved to the end of the line (presumably of the headline of the
13393 processed entry) and search continues from there. Under some
13394 circumstances, this may not produce the wanted results. For example,
13395 if you have removed (e.g. archived) the current (sub)tree it could
13396 mean that the next entry will be skipped entirely. In such cases, you
13397 can specify the position from where search should continue by making
13398 FUNC set the variable `org-map-continue-from' to the desired buffer
13399 position.
13401 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13402 Only headlines that are matched by this query will be considered during
13403 the iteration. When MATCH is nil or t, all headlines will be
13404 visited by the iteration.
13406 SCOPE determines the scope of this command. It can be any of:
13408 nil The current buffer, respecting the restriction if any
13409 tree The subtree started with the entry at point
13410 file The current buffer, without restriction
13411 file-with-archives
13412 The current buffer, and any archives associated with it
13413 agenda All agenda files
13414 agenda-with-archives
13415 All agenda files with any archive files associated with them
13416 \(file1 file2 ...)
13417 If this is a list, all files in the list will be scanned
13419 The remaining args are treated as settings for the skipping facilities of
13420 the scanner. The following items can be given here:
13422 archive skip trees with the archive tag.
13423 comment skip trees with the COMMENT keyword
13424 function or Emacs Lisp form:
13425 will be used as value for `org-agenda-skip-function', so whenever
13426 the function returns t, FUNC will not be called for that
13427 entry and search will continue from the point where the
13428 function leaves it.
13430 If your function needs to retrieve the tags including inherited tags
13431 at the *current* entry, you can use the value of the variable
13432 `org-scanner-tags' which will be much faster than getting the value
13433 with `org-get-tags-at'. If your function gets properties with
13434 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13435 to t around the call to `org-entry-properties' to get the same speedup.
13436 Note that if your function moves around to retrieve tags and properties at
13437 a *different* entry, you cannot use these techniques."
13438 (let* ((org-agenda-archives-mode nil) ; just to make sure
13439 (org-agenda-skip-archived-trees (memq 'archive skip))
13440 (org-agenda-skip-comment-trees (memq 'comment skip))
13441 (org-agenda-skip-function
13442 (car (org-delete-all '(comment archive) skip)))
13443 (org-tags-match-list-sublevels t)
13444 matcher file res
13445 org-todo-keywords-for-agenda
13446 org-done-keywords-for-agenda
13447 org-todo-keyword-alist-for-agenda
13448 org-drawers-for-agenda
13449 org-tag-alist-for-agenda)
13451 (cond
13452 ((eq match t) (setq matcher t))
13453 ((eq match nil) (setq matcher t))
13454 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13456 (save-excursion
13457 (save-restriction
13458 (when (eq scope 'tree)
13459 (org-back-to-heading t)
13460 (org-narrow-to-subtree)
13461 (setq scope nil))
13463 (if (not scope)
13464 (progn
13465 (org-prepare-agenda-buffers
13466 (list (buffer-file-name (current-buffer))))
13467 (setq res (org-scan-tags func matcher)))
13468 ;; Get the right scope
13469 (cond
13470 ((and scope (listp scope) (symbolp (car scope)))
13471 (setq scope (eval scope)))
13472 ((eq scope 'agenda)
13473 (setq scope (org-agenda-files t)))
13474 ((eq scope 'agenda-with-archives)
13475 (setq scope (org-agenda-files t))
13476 (setq scope (org-add-archive-files scope)))
13477 ((eq scope 'file)
13478 (setq scope (list (buffer-file-name))))
13479 ((eq scope 'file-with-archives)
13480 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13481 (org-prepare-agenda-buffers scope)
13482 (while (setq file (pop scope))
13483 (with-current-buffer (org-find-base-buffer-visiting file)
13484 (save-excursion
13485 (save-restriction
13486 (widen)
13487 (goto-char (point-min))
13488 (setq res (append res (org-scan-tags func matcher))))))))))
13489 res))
13491 ;;;; Properties
13493 ;;; Setting and retrieving properties
13495 (defconst org-special-properties
13496 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13497 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13498 "The special properties valid in Org-mode.
13500 These are properties that are not defined in the property drawer,
13501 but in some other way.")
13503 (defconst org-default-properties
13504 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13505 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13506 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13507 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13508 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13509 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13510 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13511 "Some properties that are used by Org-mode for various purposes.
13512 Being in this list makes sure that they are offered for completion.")
13514 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13515 "Regular expression matching the first line of a property drawer.")
13517 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13518 "Regular expression matching the last line of a property drawer.")
13520 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13521 "Regular expression matching the first line of a property drawer.")
13523 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13524 "Regular expression matching the first line of a property drawer.")
13526 (defconst org-property-drawer-re
13527 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13528 org-property-end-re "\\)\n?")
13529 "Matches an entire property drawer.")
13531 (defconst org-clock-drawer-re
13532 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13533 org-property-end-re "\\)\n?")
13534 "Matches an entire clock drawer.")
13536 (defsubst org-re-property (property)
13537 "Return a regexp matching PROPERTY.
13538 Match group 1 will be set to the value "
13539 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
13541 (defun org-property-action ()
13542 "Do an action on properties."
13543 (interactive)
13544 (let (c)
13545 (org-at-property-p)
13546 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13547 (setq c (read-char-exclusive))
13548 (cond
13549 ((equal c ?s)
13550 (call-interactively 'org-set-property))
13551 ((equal c ?d)
13552 (call-interactively 'org-delete-property))
13553 ((equal c ?D)
13554 (call-interactively 'org-delete-property-globally))
13555 ((equal c ?c)
13556 (call-interactively 'org-compute-property-at-point))
13557 (t (error "No such property action %c" c)))))
13559 (defun org-set-effort (&optional value)
13560 "Set the effort property of the current entry.
13561 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13562 allowed value."
13563 (interactive "P")
13564 (if (equal value 0) (setq value 10))
13565 (let* ((completion-ignore-case t)
13566 (prop org-effort-property)
13567 (cur (org-entry-get nil prop))
13568 (allowed (org-property-get-allowed-values nil prop 'table))
13569 (existing (mapcar 'list (org-property-values prop)))
13571 (val (cond
13572 ((stringp value) value)
13573 ((and allowed (integerp value))
13574 (or (car (nth (1- value) allowed))
13575 (car (org-last allowed))))
13576 (allowed
13577 (message "Select 1-9,0, [RET%s]: %s"
13578 (if cur (concat "=" cur) "")
13579 (mapconcat 'car allowed " "))
13580 (setq rpl (read-char-exclusive))
13581 (if (equal rpl ?\r)
13583 (setq rpl (- rpl ?0))
13584 (if (equal rpl 0) (setq rpl 10))
13585 (if (and (> rpl 0) (<= rpl (length allowed)))
13586 (car (nth (1- rpl) allowed))
13587 (org-completing-read "Effort: " allowed nil))))
13589 (let (org-completion-use-ido org-completion-use-iswitchb)
13590 (org-completing-read
13591 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13592 (concat "[" cur "]") "")
13593 ": ")
13594 existing nil nil "" nil cur))))))
13595 (unless (equal (org-entry-get nil prop) val)
13596 (org-entry-put nil prop val))
13597 (message "%s is now %s" prop val)))
13599 (defun org-at-property-p ()
13600 "Is cursor inside a property drawer?"
13601 (save-excursion
13602 (beginning-of-line 1)
13603 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13604 (save-match-data ;; Used by calling procedures
13605 (let ((p (point))
13606 (range (unless (org-before-first-heading-p)
13607 (org-get-property-block))))
13608 (and range (<= (car range) p) (< p (cdr range))))))))
13610 (defun org-get-property-block (&optional beg end force)
13611 "Return the (beg . end) range of the body of the property drawer.
13612 BEG and END can be beginning and end of subtree, if not given
13613 they will be found.
13614 If the drawer does not exist and FORCE is non-nil, create the drawer."
13615 (catch 'exit
13616 (save-excursion
13617 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13618 (end (or end (progn (outline-next-heading) (point)))))
13619 (goto-char beg)
13620 (if (re-search-forward org-property-start-re end t)
13621 (setq beg (1+ (match-end 0)))
13622 (if force
13623 (save-excursion
13624 (org-insert-property-drawer)
13625 (setq end (progn (outline-next-heading) (point))))
13626 (throw 'exit nil))
13627 (goto-char beg)
13628 (if (re-search-forward org-property-start-re end t)
13629 (setq beg (1+ (match-end 0)))))
13630 (if (re-search-forward org-property-end-re end t)
13631 (setq end (match-beginning 0))
13632 (or force (throw 'exit nil))
13633 (goto-char beg)
13634 (setq end beg)
13635 (org-indent-line-function)
13636 (insert ":END:\n"))
13637 (cons beg end)))))
13639 (defun org-entry-properties (&optional pom which specific)
13640 "Get all properties of the entry at point-or-marker POM.
13641 This includes the TODO keyword, the tags, time strings for deadline,
13642 scheduled, and clocking, and any additional properties defined in the
13643 entry. The return value is an alist, keys may occur multiple times
13644 if the property key was used several times.
13645 POM may also be nil, in which case the current entry is used.
13646 If WHICH is nil or `all', get all properties. If WHICH is
13647 `special' or `standard', only get that subclass. If WHICH
13648 is a string only get exactly this property. SPECIFIC can be a string, the
13649 specific property we are interested in. Specifying it can speed
13650 things up because then unnecessary parsing is avoided."
13651 (setq which (or which 'all))
13652 (org-with-point-at pom
13653 (let ((clockstr (substring org-clock-string 0 -1))
13654 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13655 (case-fold-search nil)
13656 beg end range props sum-props key key1 value string clocksum)
13657 (save-excursion
13658 (when (condition-case nil
13659 (and (org-mode-p) (org-back-to-heading t))
13660 (error nil))
13661 (setq beg (point))
13662 (setq sum-props (get-text-property (point) 'org-summaries))
13663 (setq clocksum (get-text-property (point) :org-clock-minutes))
13664 (outline-next-heading)
13665 (setq end (point))
13666 (when (memq which '(all special))
13667 ;; Get the special properties, like TODO and tags
13668 (goto-char beg)
13669 (when (and (or (not specific) (string= specific "TODO"))
13670 (looking-at org-todo-line-regexp) (match-end 2))
13671 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13672 (when (and (or (not specific) (string= specific "PRIORITY"))
13673 (looking-at org-priority-regexp))
13674 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13675 (when (or (not specific) (string= specific "FILE"))
13676 (push (cons "FILE" buffer-file-name) props))
13677 (when (and (or (not specific) (string= specific "TAGS"))
13678 (setq value (org-get-tags-string))
13679 (string-match "\\S-" value))
13680 (push (cons "TAGS" value) props))
13681 (when (and (or (not specific) (string= specific "ALLTAGS"))
13682 (setq value (org-get-tags-at)))
13683 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
13684 ":"))
13685 props))
13686 (when (or (not specific) (string= specific "BLOCKED"))
13687 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
13688 (when (or (not specific)
13689 (member specific
13690 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
13691 "TIMESTAMP" "TIMESTAMP_IA")))
13692 (catch 'match
13693 (while (re-search-forward org-maybe-keyword-time-regexp end t)
13694 (setq key (if (match-end 1)
13695 (substring (org-match-string-no-properties 1)
13696 0 -1))
13697 string (if (equal key clockstr)
13698 (org-no-properties
13699 (org-trim
13700 (buffer-substring
13701 (match-beginning 3) (goto-char
13702 (point-at-eol)))))
13703 (substring (org-match-string-no-properties 3)
13704 1 -1)))
13705 ;; Get the correct property name from the key. This is
13706 ;; necessary if the user has configured time keywords.
13707 (setq key1 (concat key ":"))
13708 (cond
13709 ((not key)
13710 (setq key
13711 (if (= (char-after (match-beginning 3)) ?\[)
13712 "TIMESTAMP_IA" "TIMESTAMP")))
13713 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
13714 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
13715 ((equal key1 org-closed-string) (setq key "CLOSED"))
13716 ((equal key1 org-clock-string) (setq key "CLOCK")))
13717 (if (and specific (equal key specific) (not (equal key "CLOCK")))
13718 (progn
13719 (push (cons key string) props)
13720 ;; no need to search further if match is found
13721 (throw 'match t))
13722 (when (or (equal key "CLOCK") (not (assoc key props)))
13723 (push (cons key string) props))))))
13726 (when (memq which '(all standard))
13727 ;; Get the standard properties, like :PROP: ...
13728 (setq range (org-get-property-block beg end))
13729 (when range
13730 (goto-char (car range))
13731 (while (re-search-forward
13732 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
13733 (cdr range) t)
13734 (setq key (org-match-string-no-properties 1)
13735 value (org-trim (or (org-match-string-no-properties 2) "")))
13736 (unless (member key excluded)
13737 (push (cons key (or value "")) props)))))
13738 (if clocksum
13739 (push (cons "CLOCKSUM"
13740 (org-columns-number-to-string (/ (float clocksum) 60.)
13741 'add_times))
13742 props))
13743 (unless (assoc "CATEGORY" props)
13744 (push (cons "CATEGORY" (org-get-category)) props))
13745 (append sum-props (nreverse props)))))))
13747 (defun org-entry-get (pom property &optional inherit literal-nil)
13748 "Get value of PROPERTY for entry at point-or-marker POM.
13749 If INHERIT is non-nil and the entry does not have the property,
13750 then also check higher levels of the hierarchy.
13751 If INHERIT is the symbol `selective', use inheritance only if the setting
13752 in `org-use-property-inheritance' selects PROPERTY for inheritance.
13753 If the property is present but empty, the return value is the empty string.
13754 If the property is not present at all, nil is returned.
13756 If LITERAL-NIL is set, return the string value \"nil\" as a string,
13757 do not interpret it as the list atom nil. This is used for inheritance
13758 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
13759 (org-with-point-at pom
13760 (if (and inherit (if (eq inherit 'selective)
13761 (org-property-inherit-p property)
13763 (org-entry-get-with-inheritance property literal-nil)
13764 (if (member property org-special-properties)
13765 ;; We need a special property. Use `org-entry-properties' to
13766 ;; retrieve it, but specify the wanted property
13767 (cdr (assoc property (org-entry-properties nil 'special property)))
13768 (let ((range (unless (org-before-first-heading-p)
13769 (org-get-property-block))))
13770 (if (and range
13771 (goto-char (car range))
13772 (re-search-forward
13773 (org-re-property property)
13774 (cdr range) t))
13775 ;; Found the property, return it.
13776 (if (match-end 1)
13777 (if literal-nil
13778 (org-match-string-no-properties 1)
13779 (org-not-nil (org-match-string-no-properties 1)))
13780 "")))))))
13782 (defun org-property-or-variable-value (var &optional inherit)
13783 "Check if there is a property fixing the value of VAR.
13784 If yes, return this value. If not, return the current value of the variable."
13785 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13786 (if (and prop (stringp prop) (string-match "\\S-" prop))
13787 (read prop)
13788 (symbol-value var))))
13790 (defun org-entry-delete (pom property)
13791 "Delete the property PROPERTY from entry at point-or-marker POM."
13792 (org-with-point-at pom
13793 (if (member property org-special-properties)
13794 nil ; cannot delete these properties.
13795 (let ((range (org-get-property-block)))
13796 (if (and range
13797 (goto-char (car range))
13798 (re-search-forward
13799 (org-re-property property)
13800 (cdr range) t))
13801 (progn
13802 (delete-region (match-beginning 0) (1+ (point-at-eol)))
13804 nil)))))
13806 ;; Multi-values properties are properties that contain multiple values
13807 ;; These values are assumed to be single words, separated by whitespace.
13808 (defun org-entry-add-to-multivalued-property (pom property value)
13809 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
13810 (let* ((old (org-entry-get pom property))
13811 (values (and old (org-split-string old "[ \t]"))))
13812 (setq value (org-entry-protect-space value))
13813 (unless (member value values)
13814 (setq values (cons value values))
13815 (org-entry-put pom property
13816 (mapconcat 'identity values " ")))))
13818 (defun org-entry-remove-from-multivalued-property (pom property value)
13819 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
13820 (let* ((old (org-entry-get pom property))
13821 (values (and old (org-split-string old "[ \t]"))))
13822 (setq value (org-entry-protect-space value))
13823 (when (member value values)
13824 (setq values (delete value values))
13825 (org-entry-put pom property
13826 (mapconcat 'identity values " ")))))
13828 (defun org-entry-member-in-multivalued-property (pom property value)
13829 "Is VALUE one of 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 (member value values)))
13835 (defun org-entry-get-multivalued-property (pom property)
13836 "Return a list of values in a multivalued property."
13837 (let* ((value (org-entry-get pom property))
13838 (values (and value (org-split-string value "[ \t]"))))
13839 (mapcar 'org-entry-restore-space values)))
13841 (defun org-entry-put-multivalued-property (pom property &rest values)
13842 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
13843 VALUES should be a list of strings. Spaces will be protected."
13844 (org-entry-put pom property
13845 (mapconcat 'org-entry-protect-space values " "))
13846 (let* ((value (org-entry-get pom property))
13847 (values (and value (org-split-string value "[ \t]"))))
13848 (mapcar 'org-entry-restore-space values)))
13850 (defun org-entry-protect-space (s)
13851 "Protect spaces and newline in string S."
13852 (while (string-match " " s)
13853 (setq s (replace-match "%20" t t s)))
13854 (while (string-match "\n" s)
13855 (setq s (replace-match "%0A" t t s)))
13858 (defun org-entry-restore-space (s)
13859 "Restore spaces and newline in string S."
13860 (while (string-match "%20" s)
13861 (setq s (replace-match " " t t s)))
13862 (while (string-match "%0A" s)
13863 (setq s (replace-match "\n" t t s)))
13866 (defvar org-entry-property-inherited-from (make-marker)
13867 "Marker pointing to the entry from where a property was inherited.
13868 Each call to `org-entry-get-with-inheritance' will set this marker to the
13869 location of the entry where the inheritance search matched. If there was
13870 no match, the marker will point nowhere.
13871 Note that also `org-entry-get' calls this function, if the INHERIT flag
13872 is set.")
13874 (defun org-entry-get-with-inheritance (property &optional literal-nil)
13875 "Get entry property, and search higher levels if not present.
13876 The search will stop at the first ancestor which has the property defined.
13877 If the value found is \"nil\", return nil to show that the property
13878 should be considered as undefined (this is the meaning of nil here).
13879 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
13880 (move-marker org-entry-property-inherited-from nil)
13881 (let (tmp)
13882 (unless (org-before-first-heading-p)
13883 (save-excursion
13884 (save-restriction
13885 (widen)
13886 (catch 'ex
13887 (while t
13888 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
13889 (org-back-to-heading t)
13890 (move-marker org-entry-property-inherited-from (point))
13891 (throw 'ex tmp))
13892 (or (org-up-heading-safe) (throw 'ex nil)))))))
13893 (setq tmp (or tmp
13894 (cdr (assoc property org-file-properties))
13895 (cdr (assoc property org-global-properties))
13896 (cdr (assoc property org-global-properties-fixed))))
13897 (if literal-nil tmp (org-not-nil tmp))))
13899 (defvar org-property-changed-functions nil
13900 "Hook called when the value of a property has changed.
13901 Each hook function should accept two arguments, the name of the property
13902 and the new value.")
13904 (defun org-entry-put (pom property value)
13905 "Set PROPERTY to VALUE for entry at point-or-marker POM."
13906 (org-with-point-at pom
13907 (org-back-to-heading t)
13908 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
13909 range)
13910 (cond
13911 ((equal property "TODO")
13912 (when (and (stringp value) (string-match "\\S-" value)
13913 (not (member value org-todo-keywords-1)))
13914 (error "\"%s\" is not a valid TODO state" value))
13915 (if (or (not value)
13916 (not (string-match "\\S-" value)))
13917 (setq value 'none))
13918 (org-todo value)
13919 (org-set-tags nil 'align))
13920 ((equal property "PRIORITY")
13921 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
13922 (string-to-char value) ?\ ))
13923 (org-set-tags nil 'align))
13924 ((equal property "SCHEDULED")
13925 (if (re-search-forward org-scheduled-time-regexp end t)
13926 (cond
13927 ((eq value 'earlier) (org-timestamp-change -1 'day))
13928 ((eq value 'later) (org-timestamp-change 1 'day))
13929 (t (call-interactively 'org-schedule)))
13930 (call-interactively 'org-schedule)))
13931 ((equal property "DEADLINE")
13932 (if (re-search-forward org-deadline-time-regexp end t)
13933 (cond
13934 ((eq value 'earlier) (org-timestamp-change -1 'day))
13935 ((eq value 'later) (org-timestamp-change 1 'day))
13936 (t (call-interactively 'org-deadline)))
13937 (call-interactively 'org-deadline)))
13938 ((member property org-special-properties)
13939 (error "The %s property can not yet be set with `org-entry-put'"
13940 property))
13941 (t ; a non-special property
13942 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
13943 (setq range (org-get-property-block beg end 'force))
13944 (goto-char (car range))
13945 (if (re-search-forward
13946 (org-re-property property) (cdr range) t)
13947 (progn
13948 (delete-region (match-beginning 0) (match-end 0))
13949 (goto-char (match-beginning 0)))
13950 (goto-char (cdr range))
13951 (insert "\n")
13952 (backward-char 1)
13953 (org-indent-line-function))
13954 (insert ":" property ":")
13955 (and value (insert " " value))
13956 (org-indent-line-function)))))
13957 (run-hook-with-args 'org-property-changed-functions property value)))
13959 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
13960 "Get all property keys in the current buffer.
13961 With INCLUDE-SPECIALS, also list the special properties that reflect things
13962 like tags and TODO state.
13963 With INCLUDE-DEFAULTS, also include properties that has special meaning
13964 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
13965 and others.
13966 With INCLUDE-COLUMNS, also include property names given in COLUMN
13967 formats in the current buffer."
13968 (let (rtn range cfmt s p)
13969 (save-excursion
13970 (save-restriction
13971 (widen)
13972 (goto-char (point-min))
13973 (while (re-search-forward org-property-start-re nil t)
13974 (setq range (org-get-property-block))
13975 (goto-char (car range))
13976 (while (re-search-forward
13977 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
13978 (cdr range) t)
13979 (add-to-list 'rtn (org-match-string-no-properties 1)))
13980 (outline-next-heading))))
13982 (when include-specials
13983 (setq rtn (append org-special-properties rtn)))
13985 (when include-defaults
13986 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
13987 (add-to-list 'rtn org-effort-property))
13989 (when include-columns
13990 (save-excursion
13991 (save-restriction
13992 (widen)
13993 (goto-char (point-min))
13994 (while (re-search-forward
13995 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
13996 nil t)
13997 (setq cfmt (match-string 2) s 0)
13998 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
13999 cfmt s)
14000 (setq s (match-end 0)
14001 p (match-string 1 cfmt))
14002 (unless (or (equal p "ITEM")
14003 (member p org-special-properties))
14004 (add-to-list 'rtn (match-string 1 cfmt))))))))
14006 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14008 (defun org-property-values (key)
14009 "Return a list of all values of property KEY in the current buffer."
14010 (save-excursion
14011 (save-restriction
14012 (widen)
14013 (goto-char (point-min))
14014 (let ((re (org-re-property key))
14015 values)
14016 (while (re-search-forward re nil t)
14017 (add-to-list 'values (org-trim (match-string 1))))
14018 (delete "" values)))))
14020 (defun org-insert-property-drawer ()
14021 "Insert a property drawer into the current entry."
14022 (interactive)
14023 (org-back-to-heading t)
14024 (looking-at outline-regexp)
14025 (let ((indent (if org-adapt-indentation
14026 (- (match-end 0)(match-beginning 0))
14028 (beg (point))
14029 (re (concat "^[ \t]*" org-keyword-time-regexp))
14030 end hiddenp)
14031 (outline-next-heading)
14032 (setq end (point))
14033 (goto-char beg)
14034 (while (re-search-forward re end t))
14035 (setq hiddenp (outline-invisible-p))
14036 (end-of-line 1)
14037 (and (equal (char-after) ?\n) (forward-char 1))
14038 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14039 (if (member (match-string 1) '("CLOCK:" ":END:"))
14040 ;; just skip this line
14041 (beginning-of-line 2)
14042 ;; Drawer start, find the end
14043 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14044 (beginning-of-line 1)))
14045 (org-skip-over-state-notes)
14046 (skip-chars-backward " \t\n\r")
14047 (if (eq (char-before) ?*) (forward-char 1))
14048 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14049 (beginning-of-line 0)
14050 (org-indent-to-column indent)
14051 (beginning-of-line 2)
14052 (org-indent-to-column indent)
14053 (beginning-of-line 0)
14054 (if hiddenp
14055 (save-excursion
14056 (org-back-to-heading t)
14057 (hide-entry))
14058 (org-flag-drawer t))))
14060 (defvar org-property-set-functions-alist nil
14061 "Property set function alist.
14062 Each entry should have the following format:
14064 (PROPERTY . READ-FUNCTION)
14066 The read function will be called with the same argument as
14067 `org-completing-read'.")
14069 (defun org-set-property-function (property)
14070 "Get the function that should be used to set PROPERTY.
14071 This is computed according to `org-property-set-functions-alist'."
14072 (or (cdr (assoc property org-property-set-functions-alist))
14073 'org-completing-read))
14075 (defun org-read-property-value (property)
14076 "Read PROPERTY value from user."
14077 (let* ((completion-ignore-case t)
14078 (allowed (org-property-get-allowed-values nil property 'table))
14079 (cur (org-entry-get nil property))
14080 (prompt (concat property " value"
14081 (if (and cur (string-match "\\S-" cur))
14082 (concat " [" cur "]") "") ": "))
14083 (set-function (org-set-property-function property))
14084 (val (if allowed
14085 (funcall set-function prompt allowed nil
14086 (not (get-text-property 0 'org-unrestricted
14087 (caar allowed))))
14088 (let (org-completion-use-ido org-completion-use-iswitchb)
14089 (funcall set-function prompt
14090 (mapcar 'list (org-property-values property))
14091 nil nil "" nil cur)))))
14092 (if (equal val "")
14094 val)))
14096 (defun org-read-property-name ()
14097 "Read a property name."
14098 (let* ((completion-ignore-case t)
14099 (keys (org-buffer-property-keys nil t t))
14100 (default-prop (save-excursion
14101 (save-match-data
14102 (beginning-of-line)
14103 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14104 (null (string= (match-string 1) "END"))
14105 (match-string 1)))))
14106 (property (org-icompleting-read
14107 (concat "Property"
14108 (if default-prop (concat " [" default-prop "]") "")
14109 ": ")
14110 (mapcar 'list keys)
14111 nil nil nil nil
14112 default-prop
14114 (if (member property keys)
14115 property
14116 (or (cdr (assoc (downcase property)
14117 (mapcar (lambda (x) (cons (downcase x) x))
14118 keys)))
14119 property))))
14121 (defun org-set-property (property value)
14122 "In the current entry, set PROPERTY to VALUE.
14123 When called interactively, this will prompt for a property name, offering
14124 completion on existing and default properties. And then it will prompt
14125 for a value, offering completion either on allowed values (via an inherited
14126 xxx_ALL property) or on existing values in other instances of this property
14127 in the current file."
14128 (interactive (list nil nil))
14129 (let* ((property (or property (org-read-property-name)))
14130 (value (or value (org-read-property-value property))))
14131 (unless (equal (org-entry-get nil property) value)
14132 (org-entry-put nil property value))))
14134 (defun org-delete-property (property)
14135 "In the current entry, delete PROPERTY."
14136 (interactive
14137 (let* ((completion-ignore-case t)
14138 (prop (org-icompleting-read "Property: "
14139 (org-entry-properties nil 'standard))))
14140 (list prop)))
14141 (message "Property %s %s" property
14142 (if (org-entry-delete nil property)
14143 "deleted"
14144 "was not present in the entry")))
14146 (defun org-delete-property-globally (property)
14147 "Remove PROPERTY globally, from all entries."
14148 (interactive
14149 (let* ((completion-ignore-case t)
14150 (prop (org-icompleting-read
14151 "Globally remove property: "
14152 (mapcar 'list (org-buffer-property-keys)))))
14153 (list prop)))
14154 (save-excursion
14155 (save-restriction
14156 (widen)
14157 (goto-char (point-min))
14158 (let ((cnt 0))
14159 (while (re-search-forward
14160 (org-re-property property)
14161 nil t)
14162 (setq cnt (1+ cnt))
14163 (replace-match ""))
14164 (message "Property \"%s\" removed from %d entries" property cnt)))))
14166 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14168 (defun org-compute-property-at-point ()
14169 "Compute the property at point.
14170 This looks for an enclosing column format, extracts the operator and
14171 then applies it to the property in the column format's scope."
14172 (interactive)
14173 (unless (org-at-property-p)
14174 (error "Not at a property"))
14175 (let ((prop (org-match-string-no-properties 2)))
14176 (org-columns-get-format-and-top-level)
14177 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14178 (error "No operator defined for property %s" prop))
14179 (org-columns-compute prop)))
14181 (defvar org-property-allowed-value-functions nil
14182 "Hook for functions supplying allowed values for a specific property.
14183 The functions must take a single argument, the name of the property, and
14184 return a flat list of allowed values. If \":ETC\" is one of
14185 the values, this means that these values are intended as defaults for
14186 completion, but that other values should be allowed too.
14187 The functions must return nil if they are not responsible for this
14188 property.")
14190 (defun org-property-get-allowed-values (pom property &optional table)
14191 "Get allowed values for the property PROPERTY.
14192 When TABLE is non-nil, return an alist that can directly be used for
14193 completion."
14194 (let (vals)
14195 (cond
14196 ((equal property "TODO")
14197 (setq vals (org-with-point-at pom
14198 (append org-todo-keywords-1 '("")))))
14199 ((equal property "PRIORITY")
14200 (let ((n org-lowest-priority))
14201 (while (>= n org-highest-priority)
14202 (push (char-to-string n) vals)
14203 (setq n (1- n)))))
14204 ((member property org-special-properties))
14205 ((setq vals (run-hook-with-args-until-success
14206 'org-property-allowed-value-functions property)))
14208 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14209 (when (and vals (string-match "\\S-" vals))
14210 (setq vals (car (read-from-string (concat "(" vals ")"))))
14211 (setq vals (mapcar (lambda (x)
14212 (cond ((stringp x) x)
14213 ((numberp x) (number-to-string x))
14214 ((symbolp x) (symbol-name x))
14215 (t "???")))
14216 vals)))))
14217 (when (member ":ETC" vals)
14218 (setq vals (remove ":ETC" vals))
14219 (org-add-props (car vals) '(org-unrestricted t)))
14220 (if table (mapcar 'list vals) vals)))
14222 (defun org-property-previous-allowed-value (&optional previous)
14223 "Switch to the next allowed value for this property."
14224 (interactive)
14225 (org-property-next-allowed-value t))
14227 (defun org-property-next-allowed-value (&optional previous)
14228 "Switch to the next allowed value for this property."
14229 (interactive)
14230 (unless (org-at-property-p)
14231 (error "Not at a property"))
14232 (let* ((key (match-string 2))
14233 (value (match-string 3))
14234 (allowed (or (org-property-get-allowed-values (point) key)
14235 (and (member value '("[ ]" "[-]" "[X]"))
14236 '("[ ]" "[X]"))))
14237 nval)
14238 (unless allowed
14239 (error "Allowed values for this property have not been defined"))
14240 (if previous (setq allowed (reverse allowed)))
14241 (if (member value allowed)
14242 (setq nval (car (cdr (member value allowed)))))
14243 (setq nval (or nval (car allowed)))
14244 (if (equal nval value)
14245 (error "Only one allowed value for this property"))
14246 (org-at-property-p)
14247 (replace-match (concat " :" key ": " nval) t t)
14248 (org-indent-line-function)
14249 (beginning-of-line 1)
14250 (skip-chars-forward " \t")
14251 (run-hook-with-args 'org-property-changed-functions key nval)))
14253 (defun org-find-olp (path &optional this-buffer)
14254 "Return a marker pointing to the entry at outline path OLP.
14255 If anything goes wrong, throw an error.
14256 You can wrap this call to catch the error like this:
14258 (condition-case msg
14259 (org-mobile-locate-entry (match-string 4))
14260 (error (nth 1 msg)))
14262 The return value will then be either a string with the error message,
14263 or a marker if everything is OK.
14265 If THIS-BUFFER is set, the outline path does not contain a file,
14266 only headings."
14267 (let* ((file (if this-buffer buffer-file-name (pop path)))
14268 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14269 (level 1)
14270 (lmin 1)
14271 (lmax 1)
14272 limit re end found pos heading cnt flevel)
14273 (unless buffer (error "File not found :%s" file))
14274 (with-current-buffer buffer
14275 (save-excursion
14276 (save-restriction
14277 (widen)
14278 (setq limit (point-max))
14279 (goto-char (point-min))
14280 (while (setq heading (pop path))
14281 (setq re (format org-complex-heading-regexp-format
14282 (regexp-quote heading)))
14283 (setq cnt 0 pos (point))
14284 (while (re-search-forward re end t)
14285 (setq level (- (match-end 1) (match-beginning 1)))
14286 (if (and (>= level lmin) (<= level lmax))
14287 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14288 (when (= cnt 0) (error "Heading not found on level %d: %s"
14289 lmax heading))
14290 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14291 lmax heading))
14292 (goto-char found)
14293 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14294 (setq end (save-excursion (org-end-of-subtree t t))))
14295 (when (org-on-heading-p)
14296 (move-marker (make-marker) (point))))))))
14298 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14299 "Find node HEADING in BUFFER.
14300 Return a marker to the heading if it was found, or nil if not.
14301 If POS-ONLY is set, return just the position instead of a marker.
14303 The heading text must match exact, but it may have a TODO keyword,
14304 a priority cookie and tags in the standard locations."
14305 (with-current-buffer (or buffer (current-buffer))
14306 (save-excursion
14307 (save-restriction
14308 (widen)
14309 (goto-char (point-min))
14310 (let (case-fold-search)
14311 (if (re-search-forward
14312 (format org-complex-heading-regexp-format
14313 (regexp-quote heading)) nil t)
14314 (if pos-only
14315 (match-beginning 0)
14316 (move-marker (make-marker) (match-beginning 0)))))))))
14318 (defun org-find-exact-heading-in-directory (heading &optional dir)
14319 "Find Org node headline HEADING in all .org files in directory DIR.
14320 When the target headline is found, return a marker to this location."
14321 (let ((files (directory-files (or dir default-directory)
14322 nil "\\`[^.#].*\\.org\\'"))
14323 file visiting m buffer)
14324 (catch 'found
14325 (while (setq file (pop files))
14326 (message "trying %s" file)
14327 (setq visiting (org-find-base-buffer-visiting file))
14328 (setq buffer (or visiting (find-file-noselect file)))
14329 (setq m (org-find-exact-headline-in-buffer
14330 heading buffer))
14331 (when (and (not m) (not visiting)) (kill-buffer buffer))
14332 (and m (throw 'found m))))))
14334 (defun org-find-entry-with-id (ident)
14335 "Locate the entry that contains the ID property with exact value IDENT.
14336 IDENT can be a string, a symbol or a number, this function will search for
14337 the string representation of it.
14338 Return the position where this entry starts, or nil if there is no such entry."
14339 (interactive "sID: ")
14340 (let ((id (cond
14341 ((stringp ident) ident)
14342 ((symbol-name ident) (symbol-name ident))
14343 ((numberp ident) (number-to-string ident))
14344 (t (error "IDENT %s must be a string, symbol or number" ident))))
14345 (case-fold-search nil))
14346 (save-excursion
14347 (save-restriction
14348 (widen)
14349 (goto-char (point-min))
14350 (when (re-search-forward
14351 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14352 nil t)
14353 (org-back-to-heading t)
14354 (point))))))
14356 ;;;; Timestamps
14358 (defvar org-last-changed-timestamp nil)
14359 (defvar org-last-inserted-timestamp nil
14360 "The last time stamp inserted with `org-insert-time-stamp'.")
14361 (defvar org-time-was-given) ; dynamically scoped parameter
14362 (defvar org-end-time-was-given) ; dynamically scoped parameter
14363 (defvar org-ts-what) ; dynamically scoped parameter
14365 (defun org-time-stamp (arg &optional inactive)
14366 "Prompt for a date/time and insert a time stamp.
14367 If the user specifies a time like HH:MM, or if this command is called
14368 with a prefix argument, the time stamp will contain date and time.
14369 Otherwise, only the date will be included. All parts of a date not
14370 specified by the user will be filled in from the current date/time.
14371 So if you press just return without typing anything, the time stamp
14372 will represent the current date/time. If there is already a timestamp
14373 at the cursor, it will be modified."
14374 (interactive "P")
14375 (let* ((ts nil)
14376 (default-time
14377 ;; Default time is either today, or, when entering a range,
14378 ;; the range start.
14379 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14380 (save-excursion
14381 (re-search-backward
14382 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14383 (- (point) 20) t)))
14384 (apply 'encode-time (org-parse-time-string (match-string 1)))
14385 (current-time)))
14386 (default-input (and ts (org-get-compact-tod ts)))
14387 (repeater (save-excursion
14388 (save-match-data
14389 (beginning-of-line)
14390 (when (re-search-forward
14391 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14392 (save-excursion (progn (end-of-line) (point))) t)
14393 (match-string 0)))))
14394 org-time-was-given org-end-time-was-given time)
14395 (cond
14396 ((and (org-at-timestamp-p t)
14397 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14398 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14399 (insert "--")
14400 (setq time (let ((this-command this-command))
14401 (org-read-date arg 'totime nil nil
14402 default-time default-input)))
14403 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14404 ((org-at-timestamp-p t)
14405 (setq time (let ((this-command this-command))
14406 (org-read-date arg 'totime nil nil default-time default-input)))
14407 (when (org-at-timestamp-p t) ; just to get the match data
14408 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14409 (replace-match "")
14410 (setq org-last-changed-timestamp
14411 (org-insert-time-stamp
14412 time (or org-time-was-given arg)
14413 inactive nil nil (list org-end-time-was-given)))
14414 (when repeater (goto-char (1- (point))) (insert " " repeater)
14415 (setq org-last-changed-timestamp
14416 (concat (substring org-last-inserted-timestamp 0 -1)
14417 " " repeater ">"))))
14418 (message "Timestamp updated"))
14420 (setq time (let ((this-command this-command))
14421 (org-read-date arg 'totime nil nil default-time default-input)))
14422 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14423 nil nil (list org-end-time-was-given))))))
14425 ;; FIXME: can we use this for something else, like computing time differences?
14426 (defun org-get-compact-tod (s)
14427 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14428 (let* ((t1 (match-string 1 s))
14429 (h1 (string-to-number (match-string 2 s)))
14430 (m1 (string-to-number (match-string 3 s)))
14431 (t2 (and (match-end 4) (match-string 5 s)))
14432 (h2 (and t2 (string-to-number (match-string 6 s))))
14433 (m2 (and t2 (string-to-number (match-string 7 s))))
14434 dh dm)
14435 (if (not t2)
14437 (setq dh (- h2 h1) dm (- m2 m1))
14438 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14439 (concat t1 "+" (number-to-string dh)
14440 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14442 (defun org-time-stamp-inactive (&optional arg)
14443 "Insert an inactive time stamp.
14444 An inactive time stamp is enclosed in square brackets instead of angle
14445 brackets. It is inactive in the sense that it does not trigger agenda entries,
14446 does not link to the calendar and cannot be changed with the S-cursor keys.
14447 So these are more for recording a certain time/date."
14448 (interactive "P")
14449 (org-time-stamp arg 'inactive))
14451 (defvar org-date-ovl (make-overlay 1 1))
14452 (overlay-put org-date-ovl 'face 'org-warning)
14453 (org-detach-overlay org-date-ovl)
14455 (defvar org-ans1) ; dynamically scoped parameter
14456 (defvar org-ans2) ; dynamically scoped parameter
14458 (defvar org-plain-time-of-day-regexp) ; defined below
14460 (defvar org-overriding-default-time nil) ; dynamically scoped
14461 (defvar org-read-date-overlay nil)
14462 (defvar org-dcst nil) ; dynamically scoped
14463 (defvar org-read-date-history nil)
14464 (defvar org-read-date-final-answer nil)
14465 (defvar org-read-date-analyze-futurep nil)
14466 (defvar org-read-date-analyze-forced-year nil)
14468 (defun org-read-date (&optional with-time to-time from-string prompt
14469 default-time default-input)
14470 "Read a date, possibly a time, and make things smooth for the user.
14471 The prompt will suggest to enter an ISO date, but you can also enter anything
14472 which will at least partially be understood by `parse-time-string'.
14473 Unrecognized parts of the date will default to the current day, month, year,
14474 hour and minute. If this command is called to replace a timestamp at point,
14475 of to enter the second timestamp of a range, the default time is taken
14476 from the existing stamp. Furthermore, the command prefers the future,
14477 so if you are giving a date where the year is not given, and the day-month
14478 combination is already past in the current year, it will assume you
14479 mean next year. For details, see the manual. A few examples:
14481 3-2-5 --> 2003-02-05
14482 feb 15 --> currentyear-02-15
14483 2/15 --> currentyear-02-15
14484 sep 12 9 --> 2009-09-12
14485 12:45 --> today 12:45
14486 22 sept 0:34 --> currentyear-09-22 0:34
14487 12 --> currentyear-currentmonth-12
14488 Fri --> nearest Friday (today or later)
14489 etc.
14491 Furthermore you can specify a relative date by giving, as the *first* thing
14492 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14493 change in days weeks, months, years.
14494 With a single plus or minus, the date is relative to today. With a double
14495 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14496 +4d --> four days from today
14497 +4 --> same as above
14498 +2w --> two weeks from today
14499 ++5 --> five days from default date
14501 The function understands only English month and weekday abbreviations,
14502 but this can be configured with the variables `parse-time-months' and
14503 `parse-time-weekdays'.
14505 While prompting, a calendar is popped up - you can also select the
14506 date with the mouse (button 1). The calendar shows a period of three
14507 months. To scroll it to other months, use the keys `>' and `<'.
14508 If you don't like the calendar, turn it off with
14509 \(setq org-read-date-popup-calendar nil)
14511 With optional argument TO-TIME, the date will immediately be converted
14512 to an internal time.
14513 With an optional argument WITH-TIME, the prompt will suggest to also
14514 insert a time. Note that when WITH-TIME is not set, you can still
14515 enter a time, and this function will inform the calling routine about
14516 this change. The calling routine may then choose to change the format
14517 used to insert the time stamp into the buffer to include the time.
14518 With optional argument FROM-STRING, read from this string instead from
14519 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14520 the time/date that is used for everything that is not specified by the
14521 user."
14522 (require 'parse-time)
14523 (let* ((org-time-stamp-rounding-minutes
14524 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14525 (org-dcst org-display-custom-times)
14526 (ct (org-current-time))
14527 (def (or org-overriding-default-time default-time ct))
14528 (defdecode (decode-time def))
14529 (dummy (progn
14530 (when (< (nth 2 defdecode) org-extend-today-until)
14531 (setcar (nthcdr 2 defdecode) -1)
14532 (setcar (nthcdr 1 defdecode) 59)
14533 (setq def (apply 'encode-time defdecode)
14534 defdecode (decode-time def)))))
14535 (calendar-frame-setup nil)
14536 (calendar-setup nil)
14537 (calendar-move-hook nil)
14538 (calendar-view-diary-initially-flag nil)
14539 (calendar-view-holidays-initially-flag nil)
14540 (timestr (format-time-string
14541 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14542 (prompt (concat (if prompt (concat prompt " ") "")
14543 (format "Date+time [%s]: " timestr)))
14544 ans (org-ans0 "") org-ans1 org-ans2 final)
14546 (cond
14547 (from-string (setq ans from-string))
14548 (org-read-date-popup-calendar
14549 (save-excursion
14550 (save-window-excursion
14551 (calendar)
14552 (unwind-protect
14553 (progn
14554 (calendar-forward-day (- (time-to-days def)
14555 (calendar-absolute-from-gregorian
14556 (calendar-current-date))))
14557 (org-eval-in-calendar nil t)
14558 (let* ((old-map (current-local-map))
14559 (map (copy-keymap calendar-mode-map))
14560 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14561 (org-defkey map (kbd "RET") 'org-calendar-select)
14562 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14563 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14564 (org-defkey minibuffer-local-map [(meta shift left)]
14565 (lambda () (interactive)
14566 (org-eval-in-calendar '(calendar-backward-month 1))))
14567 (org-defkey minibuffer-local-map [(meta shift right)]
14568 (lambda () (interactive)
14569 (org-eval-in-calendar '(calendar-forward-month 1))))
14570 (org-defkey minibuffer-local-map [(meta shift up)]
14571 (lambda () (interactive)
14572 (org-eval-in-calendar '(calendar-backward-year 1))))
14573 (org-defkey minibuffer-local-map [(meta shift down)]
14574 (lambda () (interactive)
14575 (org-eval-in-calendar '(calendar-forward-year 1))))
14576 (org-defkey minibuffer-local-map [?\e (shift left)]
14577 (lambda () (interactive)
14578 (org-eval-in-calendar '(calendar-backward-month 1))))
14579 (org-defkey minibuffer-local-map [?\e (shift right)]
14580 (lambda () (interactive)
14581 (org-eval-in-calendar '(calendar-forward-month 1))))
14582 (org-defkey minibuffer-local-map [?\e (shift up)]
14583 (lambda () (interactive)
14584 (org-eval-in-calendar '(calendar-backward-year 1))))
14585 (org-defkey minibuffer-local-map [?\e (shift down)]
14586 (lambda () (interactive)
14587 (org-eval-in-calendar '(calendar-forward-year 1))))
14588 (org-defkey minibuffer-local-map [(shift up)]
14589 (lambda () (interactive)
14590 (org-eval-in-calendar '(calendar-backward-week 1))))
14591 (org-defkey minibuffer-local-map [(shift down)]
14592 (lambda () (interactive)
14593 (org-eval-in-calendar '(calendar-forward-week 1))))
14594 (org-defkey minibuffer-local-map [(shift left)]
14595 (lambda () (interactive)
14596 (org-eval-in-calendar '(calendar-backward-day 1))))
14597 (org-defkey minibuffer-local-map [(shift right)]
14598 (lambda () (interactive)
14599 (org-eval-in-calendar '(calendar-forward-day 1))))
14600 (org-defkey minibuffer-local-map ">"
14601 (lambda () (interactive)
14602 (org-eval-in-calendar '(scroll-calendar-left 1))))
14603 (org-defkey minibuffer-local-map "<"
14604 (lambda () (interactive)
14605 (org-eval-in-calendar '(scroll-calendar-right 1))))
14606 (org-defkey minibuffer-local-map "\C-v"
14607 (lambda () (interactive)
14608 (org-eval-in-calendar
14609 '(calendar-scroll-left-three-months 1))))
14610 (org-defkey minibuffer-local-map "\M-v"
14611 (lambda () (interactive)
14612 (org-eval-in-calendar
14613 '(calendar-scroll-right-three-months 1))))
14614 (run-hooks 'org-read-date-minibuffer-setup-hook)
14615 (unwind-protect
14616 (progn
14617 (use-local-map map)
14618 (add-hook 'post-command-hook 'org-read-date-display)
14619 (setq org-ans0 (read-string prompt default-input
14620 'org-read-date-history nil))
14621 ;; org-ans0: from prompt
14622 ;; org-ans1: from mouse click
14623 ;; org-ans2: from calendar motion
14624 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14625 (remove-hook 'post-command-hook 'org-read-date-display)
14626 (use-local-map old-map)
14627 (when org-read-date-overlay
14628 (delete-overlay org-read-date-overlay)
14629 (setq org-read-date-overlay nil)))))
14630 (bury-buffer "*Calendar*")))))
14632 (t ; Naked prompt only
14633 (unwind-protect
14634 (setq ans (read-string prompt default-input
14635 'org-read-date-history timestr))
14636 (when org-read-date-overlay
14637 (delete-overlay org-read-date-overlay)
14638 (setq org-read-date-overlay nil)))))
14640 (setq final (org-read-date-analyze ans def defdecode))
14642 (when org-read-date-analyze-forced-year
14643 (message "Year was forced into %s"
14644 (if org-read-date-force-compatible-dates
14645 "compatible range (1970-2037)"
14646 "range representable on this machine"))
14647 (ding))
14649 ;; One round trip to get rid of 34th of August and stuff like that....
14650 (setq final (decode-time (apply 'encode-time final)))
14652 (setq org-read-date-final-answer ans)
14654 (if to-time
14655 (apply 'encode-time final)
14656 (if (and (boundp 'org-time-was-given) org-time-was-given)
14657 (format "%04d-%02d-%02d %02d:%02d"
14658 (nth 5 final) (nth 4 final) (nth 3 final)
14659 (nth 2 final) (nth 1 final))
14660 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
14662 (defvar def)
14663 (defvar defdecode)
14664 (defvar with-time)
14665 (defun org-read-date-display ()
14666 "Display the current date prompt interpretation in the minibuffer."
14667 (when org-read-date-display-live
14668 (when org-read-date-overlay
14669 (delete-overlay org-read-date-overlay))
14670 (let ((p (point)))
14671 (end-of-line 1)
14672 (while (not (equal (buffer-substring
14673 (max (point-min) (- (point) 4)) (point))
14674 " "))
14675 (insert " "))
14676 (goto-char p))
14677 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
14678 " " (or org-ans1 org-ans2)))
14679 (org-end-time-was-given nil)
14680 (f (org-read-date-analyze ans def defdecode))
14681 (fmts (if org-dcst
14682 org-time-stamp-custom-formats
14683 org-time-stamp-formats))
14684 (fmt (if (or with-time
14685 (and (boundp 'org-time-was-given) org-time-was-given))
14686 (cdr fmts)
14687 (car fmts)))
14688 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
14689 (when (and org-end-time-was-given
14690 (string-match org-plain-time-of-day-regexp txt))
14691 (setq txt (concat (substring txt 0 (match-end 0)) "-"
14692 org-end-time-was-given
14693 (substring txt (match-end 0)))))
14694 (when org-read-date-analyze-futurep
14695 (setq txt (concat txt " (=>F)")))
14696 (setq org-read-date-overlay
14697 (make-overlay (1- (point-at-eol)) (point-at-eol)))
14698 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
14700 (defun org-read-date-analyze (ans def defdecode)
14701 "Analyze the combined answer of the date prompt."
14702 ;; FIXME: cleanup and comment
14703 (let ((nowdecode (decode-time (current-time)))
14704 delta deltan deltaw deltadef year month day
14705 hour minute second wday pm h2 m2 tl wday1
14706 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
14707 (setq org-read-date-analyze-futurep nil
14708 org-read-date-analyze-forced-year nil)
14709 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
14710 (setq ans "+0"))
14712 (when (setq delta (org-read-date-get-relative ans (current-time) def))
14713 (setq ans (replace-match "" t t ans)
14714 deltan (car delta)
14715 deltaw (nth 1 delta)
14716 deltadef (nth 2 delta)))
14718 ;; Check if there is an iso week date in there
14719 ;; If yes, store the info and postpone interpreting it until the rest
14720 ;; of the parsing is done
14721 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
14722 (setq iso-year (if (match-end 1)
14723 (org-small-year-to-year
14724 (string-to-number (match-string 1 ans))))
14725 iso-weekday (if (match-end 3)
14726 (string-to-number (match-string 3 ans)))
14727 iso-week (string-to-number (match-string 2 ans)))
14728 (setq ans (replace-match "" t t ans)))
14730 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
14731 (when (string-match
14732 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
14733 (setq year (if (match-end 2)
14734 (string-to-number (match-string 2 ans))
14735 (progn (setq kill-year t)
14736 (string-to-number (format-time-string "%Y"))))
14737 month (string-to-number (match-string 3 ans))
14738 day (string-to-number (match-string 4 ans)))
14739 (if (< year 100) (setq year (+ 2000 year)))
14740 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14741 t nil ans)))
14743 ;; Help matching dottet european dates
14744 (when (string-match
14745 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
14746 (setq year (if (match-end 3)
14747 (string-to-number (match-string 3 ans))
14748 (progn (setq kill-year t)
14749 (string-to-number (format-time-string "%Y"))))
14750 day (string-to-number (match-string 1 ans))
14751 month (string-to-number (match-string 2 ans))
14752 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14753 t nil ans)))
14755 ;; Help matching american dates, like 5/30 or 5/30/7
14756 (when (string-match
14757 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
14758 (setq year (if (match-end 4)
14759 (string-to-number (match-string 4 ans))
14760 (progn (setq kill-year t)
14761 (string-to-number (format-time-string "%Y"))))
14762 month (string-to-number (match-string 1 ans))
14763 day (string-to-number (match-string 2 ans)))
14764 (if (< year 100) (setq year (+ 2000 year)))
14765 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14766 t nil ans)))
14767 ;; Help matching am/pm times, because `parse-time-string' does not do that.
14768 ;; If there is a time with am/pm, and *no* time without it, we convert
14769 ;; so that matching will be successful.
14770 (loop for i from 1 to 2 do ; twice, for end time as well
14771 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
14772 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
14773 (setq hour (string-to-number (match-string 1 ans))
14774 minute (if (match-end 3)
14775 (string-to-number (match-string 3 ans))
14777 pm (equal ?p
14778 (string-to-char (downcase (match-string 4 ans)))))
14779 (if (and (= hour 12) (not pm))
14780 (setq hour 0)
14781 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
14782 (setq ans (replace-match (format "%02d:%02d" hour minute)
14783 t t ans))))
14785 ;; Check if a time range is given as a duration
14786 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
14787 (setq hour (string-to-number (match-string 1 ans))
14788 h2 (+ hour (string-to-number (match-string 3 ans)))
14789 minute (string-to-number (match-string 2 ans))
14790 m2 (+ minute (if (match-end 5) (string-to-number
14791 (match-string 5 ans))0)))
14792 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
14793 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
14794 t t ans)))
14796 ;; Check if there is a time range
14797 (when (boundp 'org-end-time-was-given)
14798 (setq org-time-was-given nil)
14799 (when (and (string-match org-plain-time-of-day-regexp ans)
14800 (match-end 8))
14801 (setq org-end-time-was-given (match-string 8 ans))
14802 (setq ans (concat (substring ans 0 (match-beginning 7))
14803 (substring ans (match-end 7))))))
14805 (setq tl (parse-time-string ans)
14806 day (or (nth 3 tl) (nth 3 defdecode))
14807 month (or (nth 4 tl)
14808 (if (and org-read-date-prefer-future
14809 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
14810 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
14811 (nth 4 defdecode)))
14812 year (or (and (not kill-year) (nth 5 tl))
14813 (if (and org-read-date-prefer-future
14814 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
14815 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
14816 (nth 5 defdecode)))
14817 hour (or (nth 2 tl) (nth 2 defdecode))
14818 minute (or (nth 1 tl) (nth 1 defdecode))
14819 second (or (nth 0 tl) 0)
14820 wday (nth 6 tl))
14822 (when (and (eq org-read-date-prefer-future 'time)
14823 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
14824 (equal day (nth 3 nowdecode))
14825 (equal month (nth 4 nowdecode))
14826 (equal year (nth 5 nowdecode))
14827 (nth 2 tl)
14828 (or (< (nth 2 tl) (nth 2 nowdecode))
14829 (and (= (nth 2 tl) (nth 2 nowdecode))
14830 (nth 1 tl)
14831 (< (nth 1 tl) (nth 1 nowdecode)))))
14832 (setq day (1+ day)
14833 futurep t))
14835 ;; Special date definitions below
14836 (cond
14837 (iso-week
14838 ;; There was an iso week
14839 (require 'cal-iso)
14840 (setq futurep nil)
14841 (setq year (or iso-year year)
14842 day (or iso-weekday wday 1)
14843 wday nil ; to make sure that the trigger below does not match
14844 iso-date (calendar-gregorian-from-absolute
14845 (calendar-absolute-from-iso
14846 (list iso-week day year))))
14847 ; FIXME: Should we also push ISO weeks into the future?
14848 ; (when (and org-read-date-prefer-future
14849 ; (not iso-year)
14850 ; (< (calendar-absolute-from-gregorian iso-date)
14851 ; (time-to-days (current-time))))
14852 ; (setq year (1+ year)
14853 ; iso-date (calendar-gregorian-from-absolute
14854 ; (calendar-absolute-from-iso
14855 ; (list iso-week day year)))))
14856 (setq month (car iso-date)
14857 year (nth 2 iso-date)
14858 day (nth 1 iso-date)))
14859 (deltan
14860 (setq futurep nil)
14861 (unless deltadef
14862 (let ((now (decode-time (current-time))))
14863 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
14864 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
14865 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
14866 ((equal deltaw "m") (setq month (+ month deltan)))
14867 ((equal deltaw "y") (setq year (+ year deltan)))))
14868 ((and wday (not (nth 3 tl)))
14869 (setq futurep nil)
14870 ;; Weekday was given, but no day, so pick that day in the week
14871 ;; on or after the derived date.
14872 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
14873 (unless (equal wday wday1)
14874 (setq day (+ day (% (- wday wday1 -7) 7))))))
14875 (if (and (boundp 'org-time-was-given)
14876 (nth 2 tl))
14877 (setq org-time-was-given t))
14878 (if (< year 100) (setq year (+ 2000 year)))
14879 ;; Check of the date is representable
14880 (if org-read-date-force-compatible-dates
14881 (progn
14882 (if (< year 1970)
14883 (setq year 1970 org-read-date-analyze-forced-year t))
14884 (if (> year 2037)
14885 (setq year 2037 org-read-date-analyze-forced-year t)))
14886 (condition-case nil
14887 (ignore (encode-time second minute hour day month year))
14888 (error
14889 (setq year (nth 5 defdecode))
14890 (setq org-read-date-analyze-forced-year t))))
14891 (setq org-read-date-analyze-futurep futurep)
14892 (list second minute hour day month year)))
14894 (defvar parse-time-weekdays)
14896 (defun org-read-date-get-relative (s today default)
14897 "Check string S for special relative date string.
14898 TODAY and DEFAULT are internal times, for today and for a default.
14899 Return shift list (N what def-flag)
14900 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
14901 N is the number of WHATs to shift.
14902 DEF-FLAG is t when a double ++ or -- indicates shift relative to
14903 the DEFAULT date rather than TODAY."
14904 (when (and
14905 (string-match
14906 (concat
14907 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
14908 "\\([0-9]+\\)?"
14909 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
14910 "\\([ \t]\\|$\\)") s)
14911 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
14912 (let* ((dir (if (> (match-end 1) (match-beginning 1))
14913 (string-to-char (substring (match-string 1 s) -1))
14914 ?+))
14915 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
14916 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
14917 (what (if (match-end 3) (match-string 3 s) "d"))
14918 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
14919 (date (if rel default today))
14920 (wday (nth 6 (decode-time date)))
14921 delta)
14922 (if wday1
14923 (progn
14924 (setq delta (mod (+ 7 (- wday1 wday)) 7))
14925 (if (= dir ?-) (setq delta (- delta 7)))
14926 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
14927 (list delta "d" rel))
14928 (list (* n (if (= dir ?-) -1 1)) what rel)))))
14930 (defun org-order-calendar-date-args (arg1 arg2 arg3)
14931 "Turn a user-specified date into the internal representation.
14932 The internal representation needed by the calendar is (month day year).
14933 This is a wrapper to handle the brain-dead convention in calendar that
14934 user function argument order change dependent on argument order."
14935 (if (boundp 'calendar-date-style)
14936 (cond
14937 ((eq calendar-date-style 'american)
14938 (list arg1 arg2 arg3))
14939 ((eq calendar-date-style 'european)
14940 (list arg2 arg1 arg3))
14941 ((eq calendar-date-style 'iso)
14942 (list arg2 arg3 arg1)))
14943 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
14944 (if (org-bound-and-true-p european-calendar-style)
14945 (list arg2 arg1 arg3)
14946 (list arg1 arg2 arg3)))))
14948 (defun org-eval-in-calendar (form &optional keepdate)
14949 "Eval FORM in the calendar window and return to current window.
14950 Also, store the cursor date in variable org-ans2."
14951 (let ((sf (selected-frame))
14952 (sw (selected-window)))
14953 (select-window (get-buffer-window "*Calendar*" t))
14954 (eval form)
14955 (when (and (not keepdate) (calendar-cursor-to-date))
14956 (let* ((date (calendar-cursor-to-date))
14957 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14958 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
14959 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
14960 (select-window sw)
14961 (org-select-frame-set-input-focus sf)))
14963 (defun org-calendar-select ()
14964 "Return to `org-read-date' with the date currently selected.
14965 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14966 (interactive)
14967 (when (calendar-cursor-to-date)
14968 (let* ((date (calendar-cursor-to-date))
14969 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14970 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14971 (if (active-minibuffer-window) (exit-minibuffer))))
14973 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
14974 "Insert a date stamp for the date given by the internal TIME.
14975 WITH-HM means use the stamp format that includes the time of the day.
14976 INACTIVE means use square brackets instead of angular ones, so that the
14977 stamp will not contribute to the agenda.
14978 PRE and POST are optional strings to be inserted before and after the
14979 stamp.
14980 The command returns the inserted time stamp."
14981 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
14982 stamp)
14983 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
14984 (insert-before-markers (or pre ""))
14985 (when (listp extra)
14986 (setq extra (car extra))
14987 (if (and (stringp extra)
14988 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
14989 (setq extra (format "-%02d:%02d"
14990 (string-to-number (match-string 1 extra))
14991 (string-to-number (match-string 2 extra))))
14992 (setq extra nil)))
14993 (when extra
14994 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
14995 (insert-before-markers (setq stamp (format-time-string fmt time)))
14996 (insert-before-markers (or post ""))
14997 (setq org-last-inserted-timestamp stamp)))
14999 (defun org-toggle-time-stamp-overlays ()
15000 "Toggle the use of custom time stamp formats."
15001 (interactive)
15002 (setq org-display-custom-times (not org-display-custom-times))
15003 (unless org-display-custom-times
15004 (let ((p (point-min)) (bmp (buffer-modified-p)))
15005 (while (setq p (next-single-property-change p 'display))
15006 (if (and (get-text-property p 'display)
15007 (eq (get-text-property p 'face) 'org-date))
15008 (remove-text-properties
15009 p (setq p (next-single-property-change p 'display))
15010 '(display t))))
15011 (set-buffer-modified-p bmp)))
15012 (if (featurep 'xemacs)
15013 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15014 (org-restart-font-lock)
15015 (setq org-table-may-need-update t)
15016 (if org-display-custom-times
15017 (message "Time stamps are overlayed with custom format")
15018 (message "Time stamp overlays removed")))
15020 (defun org-display-custom-time (beg end)
15021 "Overlay modified time stamp format over timestamp between BEG and END."
15022 (let* ((ts (buffer-substring beg end))
15023 t1 w1 with-hm tf time str w2 (off 0))
15024 (save-match-data
15025 (setq t1 (org-parse-time-string ts t))
15026 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15027 (setq off (- (match-end 0) (match-beginning 0)))))
15028 (setq end (- end off))
15029 (setq w1 (- end beg)
15030 with-hm (and (nth 1 t1) (nth 2 t1))
15031 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15032 time (org-fix-decoded-time t1)
15033 str (org-add-props
15034 (format-time-string
15035 (substring tf 1 -1) (apply 'encode-time time))
15036 nil 'mouse-face 'highlight)
15037 w2 (length str))
15038 (if (not (= w2 w1))
15039 (add-text-properties (1+ beg) (+ 2 beg)
15040 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15041 (if (featurep 'xemacs)
15042 (progn
15043 (put-text-property beg end 'invisible t)
15044 (put-text-property beg end 'end-glyph (make-glyph str)))
15045 (put-text-property beg end 'display str))))
15047 (defun org-translate-time (string)
15048 "Translate all timestamps in STRING to custom format.
15049 But do this only if the variable `org-display-custom-times' is set."
15050 (when org-display-custom-times
15051 (save-match-data
15052 (let* ((start 0)
15053 (re org-ts-regexp-both)
15054 t1 with-hm inactive tf time str beg end)
15055 (while (setq start (string-match re string start))
15056 (setq beg (match-beginning 0)
15057 end (match-end 0)
15058 t1 (save-match-data
15059 (org-parse-time-string (substring string beg end) t))
15060 with-hm (and (nth 1 t1) (nth 2 t1))
15061 inactive (equal (substring string beg (1+ beg)) "[")
15062 tf (funcall (if with-hm 'cdr 'car)
15063 org-time-stamp-custom-formats)
15064 time (org-fix-decoded-time t1)
15065 str (format-time-string
15066 (concat
15067 (if inactive "[" "<") (substring tf 1 -1)
15068 (if inactive "]" ">"))
15069 (apply 'encode-time time))
15070 string (replace-match str t t string)
15071 start (+ start (length str)))))))
15072 string)
15074 (defun org-fix-decoded-time (time)
15075 "Set 0 instead of nil for the first 6 elements of time.
15076 Don't touch the rest."
15077 (let ((n 0))
15078 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15080 (defun org-days-to-time (timestamp-string)
15081 "Difference between TIMESTAMP-STRING and now in days."
15082 (- (time-to-days (org-time-string-to-time timestamp-string))
15083 (time-to-days (current-time))))
15085 (defun org-deadline-close (timestamp-string &optional ndays)
15086 "Is the time in TIMESTAMP-STRING close to the current date?"
15087 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15088 (and (< (org-days-to-time timestamp-string) ndays)
15089 (not (org-entry-is-done-p))))
15091 (defun org-get-wdays (ts)
15092 "Get the deadline lead time appropriate for timestring TS."
15093 (cond
15094 ((<= org-deadline-warning-days 0)
15095 ;; 0 or negative, enforce this value no matter what
15096 (- org-deadline-warning-days))
15097 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15098 ;; lead time is specified.
15099 (floor (* (string-to-number (match-string 1 ts))
15100 (cdr (assoc (match-string 2 ts)
15101 '(("d" . 1) ("w" . 7)
15102 ("m" . 30.4) ("y" . 365.25)))))))
15103 ;; go for the default.
15104 (t org-deadline-warning-days)))
15106 (defun org-calendar-select-mouse (ev)
15107 "Return to `org-read-date' with the date currently selected.
15108 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15109 (interactive "e")
15110 (mouse-set-point ev)
15111 (when (calendar-cursor-to-date)
15112 (let* ((date (calendar-cursor-to-date))
15113 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15114 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15115 (if (active-minibuffer-window) (exit-minibuffer))))
15117 (defun org-check-deadlines (ndays)
15118 "Check if there are any deadlines due or past due.
15119 A deadline is considered due if it happens within `org-deadline-warning-days'
15120 days from today's date. If the deadline appears in an entry marked DONE,
15121 it is not shown. The prefix arg NDAYS can be used to test that many
15122 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15123 (interactive "P")
15124 (let* ((org-warn-days
15125 (cond
15126 ((equal ndays '(4)) 100000)
15127 (ndays (prefix-numeric-value ndays))
15128 (t (abs org-deadline-warning-days))))
15129 (case-fold-search nil)
15130 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15131 (callback
15132 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15134 (message "%d deadlines past-due or due within %d days"
15135 (org-occur regexp nil callback)
15136 org-warn-days)))
15138 (defun org-check-before-date (date)
15139 "Check if there are deadlines or scheduled entries before DATE."
15140 (interactive (list (org-read-date)))
15141 (let ((case-fold-search nil)
15142 (regexp (concat "\\<\\(" org-deadline-string
15143 "\\|" org-scheduled-string
15144 "\\) *<\\([^>]+\\)>"))
15145 (callback
15146 (lambda () (time-less-p
15147 (org-time-string-to-time (match-string 2))
15148 (org-time-string-to-time date)))))
15149 (message "%d entries before %s"
15150 (org-occur regexp nil callback) date)))
15152 (defun org-check-after-date (date)
15153 "Check if there are deadlines or scheduled entries after DATE."
15154 (interactive (list (org-read-date)))
15155 (let ((case-fold-search nil)
15156 (regexp (concat "\\<\\(" org-deadline-string
15157 "\\|" org-scheduled-string
15158 "\\) *<\\([^>]+\\)>"))
15159 (callback
15160 (lambda () (not
15161 (time-less-p
15162 (org-time-string-to-time (match-string 2))
15163 (org-time-string-to-time date))))))
15164 (message "%d entries after %s"
15165 (org-occur regexp nil callback) date)))
15167 (defun org-evaluate-time-range (&optional to-buffer)
15168 "Evaluate a time range by computing the difference between start and end.
15169 Normally the result is just printed in the echo area, but with prefix arg
15170 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15171 If the time range is actually in a table, the result is inserted into the
15172 next column.
15173 For time difference computation, a year is assumed to be exactly 365
15174 days in order to avoid rounding problems."
15175 (interactive "P")
15177 (org-clock-update-time-maybe)
15178 (save-excursion
15179 (unless (org-at-date-range-p t)
15180 (goto-char (point-at-bol))
15181 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15182 (if (not (org-at-date-range-p t))
15183 (error "Not at a time-stamp range, and none found in current line")))
15184 (let* ((ts1 (match-string 1))
15185 (ts2 (match-string 2))
15186 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15187 (match-end (match-end 0))
15188 (time1 (org-time-string-to-time ts1))
15189 (time2 (org-time-string-to-time ts2))
15190 (t1 (org-float-time time1))
15191 (t2 (org-float-time time2))
15192 (diff (abs (- t2 t1)))
15193 (negative (< (- t2 t1) 0))
15194 ;; (ys (floor (* 365 24 60 60)))
15195 (ds (* 24 60 60))
15196 (hs (* 60 60))
15197 (fy "%dy %dd %02d:%02d")
15198 (fy1 "%dy %dd")
15199 (fd "%dd %02d:%02d")
15200 (fd1 "%dd")
15201 (fh "%02d:%02d")
15202 y d h m align)
15203 (if havetime
15204 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15206 d (floor (/ diff ds)) diff (mod diff ds)
15207 h (floor (/ diff hs)) diff (mod diff hs)
15208 m (floor (/ diff 60)))
15209 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15211 d (floor (+ (/ diff ds) 0.5))
15212 h 0 m 0))
15213 (if (not to-buffer)
15214 (message "%s" (org-make-tdiff-string y d h m))
15215 (if (org-at-table-p)
15216 (progn
15217 (goto-char match-end)
15218 (setq align t)
15219 (and (looking-at " *|") (goto-char (match-end 0))))
15220 (goto-char match-end))
15221 (if (looking-at
15222 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15223 (replace-match ""))
15224 (if negative (insert " -"))
15225 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15226 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15227 (insert " " (format fh h m))))
15228 (if align (org-table-align))
15229 (message "Time difference inserted")))))
15231 (defun org-make-tdiff-string (y d h m)
15232 (let ((fmt "")
15233 (l nil))
15234 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15235 l (push y l)))
15236 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15237 l (push d l)))
15238 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15239 l (push h l)))
15240 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15241 l (push m l)))
15242 (apply 'format fmt (nreverse l))))
15244 (defun org-time-string-to-time (s)
15245 (apply 'encode-time (org-parse-time-string s)))
15246 (defun org-time-string-to-seconds (s)
15247 (org-float-time (org-time-string-to-time s)))
15249 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
15250 "Convert a time stamp to an absolute day number.
15251 If there is a specifier for a cyclic time stamp, get the closest date to
15252 DAYNR.
15253 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15254 The variable date is bound by the calendar when this is called."
15255 (cond
15256 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15257 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15258 daynr
15259 (+ daynr 1000)))
15260 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15261 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15262 (time-to-days (current-time))) (match-string 0 s)
15263 prefer show-all))
15264 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
15266 (defun org-days-to-iso-week (days)
15267 "Return the iso week number."
15268 (require 'cal-iso)
15269 (car (calendar-iso-from-absolute days)))
15271 (defun org-small-year-to-year (year)
15272 "Convert 2-digit years into 4-digit years.
15273 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15274 The year 2000 cannot be abbreviated. Any year larger than 99
15275 is returned unchanged."
15276 (if (< year 38)
15277 (setq year (+ 2000 year))
15278 (if (< year 100)
15279 (setq year (+ 1900 year))))
15280 year)
15282 (defun org-time-from-absolute (d)
15283 "Return the time corresponding to date D.
15284 D may be an absolute day number, or a calendar-type list (month day year)."
15285 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15286 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15288 (defun org-calendar-holiday ()
15289 "List of holidays, for Diary display in Org-mode."
15290 (require 'holidays)
15291 (let ((hl (funcall
15292 (if (fboundp 'calendar-check-holidays)
15293 'calendar-check-holidays 'check-calendar-holidays) date)))
15294 (if hl (mapconcat 'identity hl "; "))))
15296 (defun org-diary-sexp-entry (sexp entry date)
15297 "Process a SEXP diary ENTRY for DATE."
15298 (require 'diary-lib)
15299 (let ((result (if calendar-debug-sexp
15300 (let ((stack-trace-on-error t))
15301 (eval (car (read-from-string sexp))))
15302 (condition-case nil
15303 (eval (car (read-from-string sexp)))
15304 (error
15305 (beep)
15306 (message "Bad sexp at line %d in %s: %s"
15307 (org-current-line)
15308 (buffer-file-name) sexp)
15309 (sleep-for 2))))))
15310 (cond ((stringp result) (split-string result "; "))
15311 ((and (consp result)
15312 (not (consp (cdr result)))
15313 (stringp (cdr result))) (cdr result))
15314 ((and (consp result)
15315 (stringp (car result))) result)
15316 (result entry)
15317 (t nil))))
15319 (defun org-diary-to-ical-string (frombuf)
15320 "Get iCalendar entries from diary entries in buffer FROMBUF.
15321 This uses the icalendar.el library."
15322 (let* ((tmpdir (if (featurep 'xemacs)
15323 (temp-directory)
15324 temporary-file-directory))
15325 (tmpfile (make-temp-name
15326 (expand-file-name "orgics" tmpdir)))
15327 buf rtn b e)
15328 (with-current-buffer frombuf
15329 (icalendar-export-region (point-min) (point-max) tmpfile)
15330 (setq buf (find-buffer-visiting tmpfile))
15331 (set-buffer buf)
15332 (goto-char (point-min))
15333 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15334 (setq b (match-beginning 0)))
15335 (goto-char (point-max))
15336 (if (re-search-backward "^END:VEVENT" nil t)
15337 (setq e (match-end 0)))
15338 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15339 (kill-buffer buf)
15340 (delete-file tmpfile)
15341 rtn))
15343 (defun org-closest-date (start current change prefer show-all)
15344 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15345 When PREFER is `past', return a date that is either CURRENT or past.
15346 When PREFER is `future', return a date that is either CURRENT or future.
15347 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15348 ;; Make the proper lists from the dates
15349 (catch 'exit
15350 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15351 dn dw sday cday n1 n2 n0
15352 d m y y1 y2 date1 date2 nmonths nm ny m2)
15354 (setq start (org-date-to-gregorian start)
15355 current (org-date-to-gregorian
15356 (if show-all
15357 current
15358 (time-to-days (current-time))))
15359 sday (calendar-absolute-from-gregorian start)
15360 cday (calendar-absolute-from-gregorian current))
15362 (if (<= cday sday) (throw 'exit sday))
15364 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15365 (setq dn (string-to-number (match-string 1 change))
15366 dw (cdr (assoc (match-string 2 change) a1)))
15367 (error "Invalid change specifier: %s" change))
15368 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15369 (cond
15370 ((eq dw 'day)
15371 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15372 n2 (+ n1 dn)))
15373 ((eq dw 'year)
15374 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15375 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15376 (setq date1 (list m d y1)
15377 n1 (calendar-absolute-from-gregorian date1)
15378 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15379 n2 (calendar-absolute-from-gregorian date2)))
15380 ((eq dw 'month)
15381 ;; approx number of month between the two dates
15382 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15383 ;; How often does dn fit in there?
15384 (setq d (nth 1 start) m (car start) y (nth 2 start)
15385 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15386 m (+ m nm)
15387 ny (floor (/ m 12))
15388 y (+ y ny)
15389 m (- m (* ny 12)))
15390 (while (> m 12) (setq m (- m 12) y (1+ y)))
15391 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15392 (setq m2 (+ m dn) y2 y)
15393 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15394 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15395 (while (<= n2 cday)
15396 (setq n1 n2 m m2 y y2)
15397 (setq m2 (+ m dn) y2 y)
15398 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15399 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15400 ;; Make sure n1 is the earlier date
15401 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15402 (if show-all
15403 (cond
15404 ((eq prefer 'past) (if (= cday n2) n2 n1))
15405 ((eq prefer 'future) (if (= cday n1) n1 n2))
15406 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15407 (cond
15408 ((eq prefer 'past) (if (= cday n2) n2 n1))
15409 ((eq prefer 'future) (if (= cday n1) n1 n2))
15410 (t (if (= cday n1) n1 n2)))))))
15412 (defun org-date-to-gregorian (date)
15413 "Turn any specification of DATE into a Gregorian date for the calendar."
15414 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15415 ((and (listp date) (= (length date) 3)) date)
15416 ((stringp date)
15417 (setq date (org-parse-time-string date))
15418 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15419 ((listp date)
15420 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15422 (defun org-parse-time-string (s &optional nodefault)
15423 "Parse the standard Org-mode time string.
15424 This should be a lot faster than the normal `parse-time-string'.
15425 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15426 hour and minute fields will be nil if not given."
15427 (if (string-match org-ts-regexp0 s)
15428 (list 0
15429 (if (or (match-beginning 8) (not nodefault))
15430 (string-to-number (or (match-string 8 s) "0")))
15431 (if (or (match-beginning 7) (not nodefault))
15432 (string-to-number (or (match-string 7 s) "0")))
15433 (string-to-number (match-string 4 s))
15434 (string-to-number (match-string 3 s))
15435 (string-to-number (match-string 2 s))
15436 nil nil nil)
15437 (error "Not a standard Org-mode time string: %s" s)))
15439 (defun org-timestamp-up (&optional arg)
15440 "Increase the date item at the cursor by one.
15441 If the cursor is on the year, change the year. If it is on the month or
15442 the day, change that.
15443 With prefix ARG, change by that many units."
15444 (interactive "p")
15445 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15447 (defun org-timestamp-down (&optional arg)
15448 "Decrease the date item at the cursor by one.
15449 If the cursor is on the year, change the year. If it is on the month or
15450 the day, change that.
15451 With prefix ARG, change by that many units."
15452 (interactive "p")
15453 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15455 (defun org-timestamp-up-day (&optional arg)
15456 "Increase the date in the time stamp by one day.
15457 With prefix ARG, change that many days."
15458 (interactive "p")
15459 (if (and (not (org-at-timestamp-p t))
15460 (org-on-heading-p))
15461 (org-todo 'up)
15462 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15464 (defun org-timestamp-down-day (&optional arg)
15465 "Decrease the date in the time stamp by one day.
15466 With prefix ARG, change that many days."
15467 (interactive "p")
15468 (if (and (not (org-at-timestamp-p t))
15469 (org-on-heading-p))
15470 (org-todo 'down)
15471 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15473 (defun org-at-timestamp-p (&optional inactive-ok)
15474 "Determine if the cursor is in or at a timestamp."
15475 (interactive)
15476 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15477 (pos (point))
15478 (ans (or (looking-at tsr)
15479 (save-excursion
15480 (skip-chars-backward "^[<\n\r\t")
15481 (if (> (point) (point-min)) (backward-char 1))
15482 (and (looking-at tsr)
15483 (> (- (match-end 0) pos) -1))))))
15484 (and ans
15485 (boundp 'org-ts-what)
15486 (setq org-ts-what
15487 (cond
15488 ((= pos (match-beginning 0)) 'bracket)
15489 ((= pos (1- (match-end 0))) 'bracket)
15490 ((org-pos-in-match-range pos 2) 'year)
15491 ((org-pos-in-match-range pos 3) 'month)
15492 ((org-pos-in-match-range pos 7) 'hour)
15493 ((org-pos-in-match-range pos 8) 'minute)
15494 ((or (org-pos-in-match-range pos 4)
15495 (org-pos-in-match-range pos 5)) 'day)
15496 ((and (> pos (or (match-end 8) (match-end 5)))
15497 (< pos (match-end 0)))
15498 (- pos (or (match-end 8) (match-end 5))))
15499 (t 'day))))
15500 ans))
15502 (defun org-toggle-timestamp-type ()
15503 "Toggle the type (<active> or [inactive]) of a time stamp."
15504 (interactive)
15505 (when (org-at-timestamp-p t)
15506 (let ((beg (match-beginning 0)) (end (match-end 0))
15507 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
15508 (save-excursion
15509 (goto-char beg)
15510 (while (re-search-forward "[][<>]" end t)
15511 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
15512 t t)))
15513 (message "Timestamp is now %sactive"
15514 (if (equal (char-after beg) ?<) "" "in")))))
15516 (defun org-timestamp-change (n &optional what updown)
15517 "Change the date in the time stamp at point.
15518 The date will be changed by N times WHAT. WHAT can be `day', `month',
15519 `year', `minute', `second'. If WHAT is not given, the cursor position
15520 in the timestamp determines what will be changed."
15521 (let ((pos (point))
15522 with-hm inactive
15523 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
15524 org-ts-what
15525 extra rem
15526 ts time time0)
15527 (if (not (org-at-timestamp-p t))
15528 (error "Not at a timestamp"))
15529 (if (and (not what) (eq org-ts-what 'bracket))
15530 (org-toggle-timestamp-type)
15531 (if (and (not what) (not (eq org-ts-what 'day))
15532 org-display-custom-times
15533 (get-text-property (point) 'display)
15534 (not (get-text-property (1- (point)) 'display)))
15535 (setq org-ts-what 'day))
15536 (setq org-ts-what (or what org-ts-what)
15537 inactive (= (char-after (match-beginning 0)) ?\[)
15538 ts (match-string 0))
15539 (replace-match "")
15540 (if (string-match
15541 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
15543 (setq extra (match-string 1 ts)))
15544 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15545 (setq with-hm t))
15546 (setq time0 (org-parse-time-string ts))
15547 (when (and updown
15548 (eq org-ts-what 'minute)
15549 (not current-prefix-arg))
15550 ;; This looks like s-up and s-down. Change by one rounding step.
15551 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
15552 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
15553 (setcar (cdr time0) (+ (nth 1 time0)
15554 (if (> n 0) (- rem) (- dm rem))))))
15555 (setq time
15556 (encode-time (or (car time0) 0)
15557 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
15558 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
15559 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
15560 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
15561 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
15562 (nthcdr 6 time0)))
15563 (when (and (member org-ts-what '(hour minute))
15564 extra
15565 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
15566 (setq extra (org-modify-ts-extra
15567 extra
15568 (if (eq org-ts-what 'hour) 2 5)
15569 n dm)))
15570 (when (integerp org-ts-what)
15571 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
15572 (if (eq what 'calendar)
15573 (let ((cal-date (org-get-date-from-calendar)))
15574 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15575 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15576 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15577 (setcar time0 (or (car time0) 0))
15578 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15579 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15580 (setq time (apply 'encode-time time0))))
15581 (setq org-last-changed-timestamp
15582 (org-insert-time-stamp time with-hm inactive nil nil extra))
15583 (org-clock-update-time-maybe)
15584 (goto-char pos)
15585 ;; Try to recenter the calendar window, if any
15586 (if (and org-calendar-follow-timestamp-change
15587 (get-buffer-window "*Calendar*" t)
15588 (memq org-ts-what '(day month year)))
15589 (org-recenter-calendar (time-to-days time))))))
15591 (defun org-modify-ts-extra (s pos n dm)
15592 "Change the different parts of the lead-time and repeat fields in timestamp."
15593 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15594 ng h m new rem)
15595 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15596 (cond
15597 ((or (org-pos-in-match-range pos 2)
15598 (org-pos-in-match-range pos 3))
15599 (setq m (string-to-number (match-string 3 s))
15600 h (string-to-number (match-string 2 s)))
15601 (if (org-pos-in-match-range pos 2)
15602 (setq h (+ h n))
15603 (setq n (* dm (org-no-warnings (signum n))))
15604 (when (not (= 0 (setq rem (% m dm))))
15605 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
15606 (setq m (+ m n)))
15607 (if (< m 0) (setq m (+ m 60) h (1- h)))
15608 (if (> m 59) (setq m (- m 60) h (1+ h)))
15609 (setq h (min 24 (max 0 h)))
15610 (setq ng 1 new (format "-%02d:%02d" h m)))
15611 ((org-pos-in-match-range pos 6)
15612 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15613 ((org-pos-in-match-range pos 5)
15614 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
15616 ((org-pos-in-match-range pos 9)
15617 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
15618 ((org-pos-in-match-range pos 8)
15619 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
15621 (when ng
15622 (setq s (concat
15623 (substring s 0 (match-beginning ng))
15625 (substring s (match-end ng))))))
15628 (defun org-recenter-calendar (date)
15629 "If the calendar is visible, recenter it to DATE."
15630 (let* ((win (selected-window))
15631 (cwin (get-buffer-window "*Calendar*" t))
15632 (calendar-move-hook nil))
15633 (when cwin
15634 (select-window cwin)
15635 (calendar-goto-date (if (listp date) date
15636 (calendar-gregorian-from-absolute date)))
15637 (select-window win))))
15639 (defun org-goto-calendar (&optional arg)
15640 "Go to the Emacs calendar at the current date.
15641 If there is a time stamp in the current line, go to that date.
15642 A prefix ARG can be used to force the current date."
15643 (interactive "P")
15644 (let ((tsr org-ts-regexp) diff
15645 (calendar-move-hook nil)
15646 (calendar-view-holidays-initially-flag nil)
15647 (calendar-view-diary-initially-flag nil))
15648 (if (or (org-at-timestamp-p)
15649 (save-excursion
15650 (beginning-of-line 1)
15651 (looking-at (concat ".*" tsr))))
15652 (let ((d1 (time-to-days (current-time)))
15653 (d2 (time-to-days
15654 (org-time-string-to-time (match-string 1)))))
15655 (setq diff (- d2 d1))))
15656 (calendar)
15657 (calendar-goto-today)
15658 (if (and diff (not arg)) (calendar-forward-day diff))))
15660 (defun org-get-date-from-calendar ()
15661 "Return a list (month day year) of date at point in calendar."
15662 (with-current-buffer "*Calendar*"
15663 (save-match-data
15664 (calendar-cursor-to-date))))
15666 (defun org-date-from-calendar ()
15667 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
15668 If there is already a time stamp at the cursor position, update it."
15669 (interactive)
15670 (if (org-at-timestamp-p t)
15671 (org-timestamp-change 0 'calendar)
15672 (let ((cal-date (org-get-date-from-calendar)))
15673 (org-insert-time-stamp
15674 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
15676 (defun org-minutes-to-hh:mm-string (m)
15677 "Compute H:MM from a number of minutes."
15678 (let ((h (/ m 60)))
15679 (setq m (- m (* 60 h)))
15680 (format org-time-clocksum-format h m)))
15682 (defun org-hh:mm-string-to-minutes (s)
15683 "Convert a string H:MM to a number of minutes.
15684 If the string is just a number, interpret it as minutes.
15685 In fact, the first hh:mm or number in the string will be taken,
15686 there can be extra stuff in the string.
15687 If no number is found, the return value is 0."
15688 (cond
15689 ((integerp s) s)
15690 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
15691 (+ (* (string-to-number (match-string 1 s)) 60)
15692 (string-to-number (match-string 2 s))))
15693 ((string-match "\\([0-9]+\\)" s)
15694 (string-to-number (match-string 1 s)))
15695 (t 0)))
15697 (defcustom org-effort-durations
15698 `(("h" . 60)
15699 ("d" . ,(* 60 8))
15700 ("w" . ,(* 60 8 5))
15701 ("m" . ,(* 60 8 5 4))
15702 ("y" . ,(* 60 8 5 40)))
15703 "Conversion factor to minutes for an effort modifier.
15705 Each entry has the form (MODIFIER . MINUTES).
15707 In an effort string, a number followed by MODIFIER is multiplied
15708 by the specified number of MINUTES to obtain an effort in
15709 minutes.
15711 For example, if the value of this variable is ((\"hours\" . 60)), then an
15712 effort string \"2hours\" is equivalent to 120 minutes."
15713 :group 'org-agenda
15714 :type '(alist :key-type (string :tag "Modifier")
15715 :value-type (number :tag "Minutes")))
15717 (defun org-duration-string-to-minutes (s)
15718 "Convert a duration string S to minutes.
15720 A bare number is interpreted as minutes, modifiers can be set by
15721 customizing `org-effort-durations' (which see).
15723 Entries containing a colon are interpreted as H:MM by
15724 `org-hh:mm-string-to-minutes'."
15725 (let ((result 0)
15726 (re (concat "\\([0-9]+\\) *\\("
15727 (regexp-opt (mapcar 'car org-effort-durations))
15728 "\\)")))
15729 (while (string-match re s)
15730 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
15731 (string-to-number (match-string 1 s))))
15732 (setq s (replace-match "" nil t s)))
15733 (incf result (org-hh:mm-string-to-minutes s))
15734 result))
15736 ;;;; Files
15738 (defun org-save-all-org-buffers ()
15739 "Save all Org-mode buffers without user confirmation."
15740 (interactive)
15741 (message "Saving all Org-mode buffers...")
15742 (save-some-buffers t 'org-mode-p)
15743 (when (featurep 'org-id) (org-id-locations-save))
15744 (message "Saving all Org-mode buffers... done"))
15746 (defun org-revert-all-org-buffers ()
15747 "Revert all Org-mode buffers.
15748 Prompt for confirmation when there are unsaved changes.
15749 Be sure you know what you are doing before letting this function
15750 overwrite your changes.
15752 This function is useful in a setup where one tracks org files
15753 with a version control system, to revert on one machine after pulling
15754 changes from another. I believe the procedure must be like this:
15756 1. M-x org-save-all-org-buffers
15757 2. Pull changes from the other machine, resolve conflicts
15758 3. M-x org-revert-all-org-buffers"
15759 (interactive)
15760 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
15761 (error "Abort"))
15762 (save-excursion
15763 (save-window-excursion
15764 (mapc
15765 (lambda (b)
15766 (when (and (with-current-buffer b (org-mode-p))
15767 (with-current-buffer b buffer-file-name))
15768 (switch-to-buffer b)
15769 (revert-buffer t 'no-confirm)))
15770 (buffer-list))
15771 (when (and (featurep 'org-id) org-id-track-globally)
15772 (org-id-locations-load)))))
15774 ;;;; Agenda files
15776 ;;;###autoload
15777 (defun org-switchb (&optional arg)
15778 "Switch between Org buffers.
15779 With a prefix argument, restrict available to files.
15780 With two prefix arguments, restrict available buffers to agenda files.
15782 Defaults to `iswitchb' for buffer name completion.
15783 Set `org-completion-use-ido' to make it use ido instead."
15784 (interactive "P")
15785 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
15786 ((equal arg '(16)) (org-buffer-list 'agenda))
15787 (t (org-buffer-list))))
15788 (org-completion-use-iswitchb org-completion-use-iswitchb)
15789 (org-completion-use-ido org-completion-use-ido))
15790 (unless (or org-completion-use-ido org-completion-use-iswitchb)
15791 (setq org-completion-use-iswitchb t))
15792 (switch-to-buffer
15793 (org-icompleting-read "Org buffer: "
15794 (mapcar 'list (mapcar 'buffer-name blist))
15795 nil t))))
15797 ;;; Define some older names previously used for this functionality
15798 ;;;###autoload
15799 (defalias 'org-ido-switchb 'org-switchb)
15800 ;;;###autoload
15801 (defalias 'org-iswitchb 'org-switchb)
15803 (defun org-buffer-list (&optional predicate exclude-tmp)
15804 "Return a list of Org buffers.
15805 PREDICATE can be `export', `files' or `agenda'.
15807 export restrict the list to Export buffers.
15808 files restrict the list to buffers visiting Org files.
15809 agenda restrict the list to buffers visiting agenda files.
15811 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
15812 (let* ((bfn nil)
15813 (agenda-files (and (eq predicate 'agenda)
15814 (mapcar 'file-truename (org-agenda-files t))))
15815 (filter
15816 (cond
15817 ((eq predicate 'files)
15818 (lambda (b) (with-current-buffer b (org-mode-p))))
15819 ((eq predicate 'export)
15820 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
15821 ((eq predicate 'agenda)
15822 (lambda (b)
15823 (with-current-buffer b
15824 (and (org-mode-p)
15825 (setq bfn (buffer-file-name b))
15826 (member (file-truename bfn) agenda-files)))))
15827 (t (lambda (b) (with-current-buffer b
15828 (or (org-mode-p)
15829 (string-match "\*Org .*Export"
15830 (buffer-name b)))))))))
15831 (delq nil
15832 (mapcar
15833 (lambda(b)
15834 (if (and (funcall filter b)
15835 (or (not exclude-tmp)
15836 (not (string-match "tmp" (buffer-name b)))))
15838 nil))
15839 (buffer-list)))))
15841 (defun org-agenda-files (&optional unrestricted archives)
15842 "Get the list of agenda files.
15843 Optional UNRESTRICTED means return the full list even if a restriction
15844 is currently in place.
15845 When ARCHIVES is t, include all archive files that are really being
15846 used by the agenda files. If ARCHIVE is `ifmode', do this only if
15847 `org-agenda-archives-mode' is t."
15848 (let ((files
15849 (cond
15850 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
15851 ((stringp org-agenda-files) (org-read-agenda-file-list))
15852 ((listp org-agenda-files) org-agenda-files)
15853 (t (error "Invalid value of `org-agenda-files'")))))
15854 (setq files (apply 'append
15855 (mapcar (lambda (f)
15856 (if (file-directory-p f)
15857 (directory-files
15858 f t org-agenda-file-regexp)
15859 (list f)))
15860 files)))
15861 (when org-agenda-skip-unavailable-files
15862 (setq files (delq nil
15863 (mapcar (function
15864 (lambda (file)
15865 (and (file-readable-p file) file)))
15866 files))))
15867 (when (or (eq archives t)
15868 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
15869 (setq files (org-add-archive-files files)))
15870 files))
15872 (defun org-agenda-file-p (&optional file)
15873 "Return non-nil, if FILE is an agenda file.
15874 If FILE is omitted, use the file associated with the current
15875 buffer."
15876 (member (or file (buffer-file-name))
15877 (org-agenda-files t)))
15879 (defun org-edit-agenda-file-list ()
15880 "Edit the list of agenda files.
15881 Depending on setup, this either uses customize to edit the variable
15882 `org-agenda-files', or it visits the file that is holding the list. In the
15883 latter case, the buffer is set up in a way that saving it automatically kills
15884 the buffer and restores the previous window configuration."
15885 (interactive)
15886 (if (stringp org-agenda-files)
15887 (let ((cw (current-window-configuration)))
15888 (find-file org-agenda-files)
15889 (org-set-local 'org-window-configuration cw)
15890 (org-add-hook 'after-save-hook
15891 (lambda ()
15892 (set-window-configuration
15893 (prog1 org-window-configuration
15894 (kill-buffer (current-buffer))))
15895 (org-install-agenda-files-menu)
15896 (message "New agenda file list installed"))
15897 nil 'local)
15898 (message "%s" (substitute-command-keys
15899 "Edit list and finish with \\[save-buffer]")))
15900 (customize-variable 'org-agenda-files)))
15902 (defun org-store-new-agenda-file-list (list)
15903 "Set new value for the agenda file list and save it correctly."
15904 (if (stringp org-agenda-files)
15905 (let ((fe (org-read-agenda-file-list t)) b u)
15906 (while (setq b (find-buffer-visiting org-agenda-files))
15907 (kill-buffer b))
15908 (with-temp-file org-agenda-files
15909 (insert
15910 (mapconcat
15911 (lambda (f) ;; Keep un-expanded entries.
15912 (if (setq u (assoc f fe))
15913 (cdr u)
15915 list "\n")
15916 "\n")))
15917 (let ((org-mode-hook nil) (org-inhibit-startup t)
15918 (org-insert-mode-line-in-empty-file nil))
15919 (setq org-agenda-files list)
15920 (customize-save-variable 'org-agenda-files org-agenda-files))))
15922 (defun org-read-agenda-file-list (&optional pair-with-expansion)
15923 "Read the list of agenda files from a file.
15924 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
15925 filenames, used by `org-store-new-agenda-file-list' to write back
15926 un-expanded file names."
15927 (when (file-directory-p org-agenda-files)
15928 (error "`org-agenda-files' cannot be a single directory"))
15929 (when (stringp org-agenda-files)
15930 (with-temp-buffer
15931 (insert-file-contents org-agenda-files)
15932 (mapcar
15933 (lambda (f)
15934 (let ((e (expand-file-name (substitute-in-file-name f)
15935 org-directory)))
15936 (if pair-with-expansion
15937 (cons e f)
15938 e)))
15939 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
15941 ;;;###autoload
15942 (defun org-cycle-agenda-files ()
15943 "Cycle through the files in `org-agenda-files'.
15944 If the current buffer visits an agenda file, find the next one in the list.
15945 If the current buffer does not, find the first agenda file."
15946 (interactive)
15947 (let* ((fs (org-agenda-files t))
15948 (files (append fs (list (car fs))))
15949 (tcf (if buffer-file-name (file-truename buffer-file-name)))
15950 file)
15951 (unless files (error "No agenda files"))
15952 (catch 'exit
15953 (while (setq file (pop files))
15954 (if (equal (file-truename file) tcf)
15955 (when (car files)
15956 (find-file (car files))
15957 (throw 'exit t))))
15958 (find-file (car fs)))
15959 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
15961 (defun org-agenda-file-to-front (&optional to-end)
15962 "Move/add the current file to the top of the agenda file list.
15963 If the file is not present in the list, it is added to the front. If it is
15964 present, it is moved there. With optional argument TO-END, add/move to the
15965 end of the list."
15966 (interactive "P")
15967 (let ((org-agenda-skip-unavailable-files nil)
15968 (file-alist (mapcar (lambda (x)
15969 (cons (file-truename x) x))
15970 (org-agenda-files t)))
15971 (ctf (file-truename buffer-file-name))
15972 x had)
15973 (setq x (assoc ctf file-alist) had x)
15975 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
15976 (if to-end
15977 (setq file-alist (append (delq x file-alist) (list x)))
15978 (setq file-alist (cons x (delq x file-alist))))
15979 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
15980 (org-install-agenda-files-menu)
15981 (message "File %s to %s of agenda file list"
15982 (if had "moved" "added") (if to-end "end" "front"))))
15984 (defun org-remove-file (&optional file)
15985 "Remove current file from the list of files in variable `org-agenda-files'.
15986 These are the files which are being checked for agenda entries.
15987 Optional argument FILE means use this file instead of the current."
15988 (interactive)
15989 (let* ((org-agenda-skip-unavailable-files nil)
15990 (file (or file buffer-file-name))
15991 (true-file (file-truename file))
15992 (afile (abbreviate-file-name file))
15993 (files (delq nil (mapcar
15994 (lambda (x)
15995 (if (equal true-file
15996 (file-truename x))
15997 nil x))
15998 (org-agenda-files t)))))
15999 (if (not (= (length files) (length (org-agenda-files t))))
16000 (progn
16001 (org-store-new-agenda-file-list files)
16002 (org-install-agenda-files-menu)
16003 (message "Removed file: %s" afile))
16004 (message "File was not in list: %s (not removed)" afile))))
16006 (defun org-file-menu-entry (file)
16007 (vector file (list 'find-file file) t))
16009 (defun org-check-agenda-file (file)
16010 "Make sure FILE exists. If not, ask user what to do."
16011 (when (not (file-exists-p file))
16012 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16013 (abbreviate-file-name file))
16014 (let ((r (downcase (read-char-exclusive))))
16015 (cond
16016 ((equal r ?r)
16017 (org-remove-file file)
16018 (throw 'nextfile t))
16019 (t (error "Abort"))))))
16021 (defun org-get-agenda-file-buffer (file)
16022 "Get a buffer visiting FILE. If the buffer needs to be created, add
16023 it to the list of buffers which might be released later."
16024 (let ((buf (org-find-base-buffer-visiting file)))
16025 (if buf
16026 buf ; just return it
16027 ;; Make a new buffer and remember it
16028 (setq buf (find-file-noselect file))
16029 (if buf (push buf org-agenda-new-buffers))
16030 buf)))
16032 (defun org-release-buffers (blist)
16033 "Release all buffers in list, asking the user for confirmation when needed.
16034 When a buffer is unmodified, it is just killed. When modified, it is saved
16035 \(if the user agrees) and then killed."
16036 (let (buf file)
16037 (while (setq buf (pop blist))
16038 (setq file (buffer-file-name buf))
16039 (when (and (buffer-modified-p buf)
16040 file
16041 (y-or-n-p (format "Save file %s? " file)))
16042 (with-current-buffer buf (save-buffer)))
16043 (kill-buffer buf))))
16045 (defun org-prepare-agenda-buffers (files)
16046 "Create buffers for all agenda files, protect archived trees and comments."
16047 (interactive)
16048 (let ((pa '(:org-archived t))
16049 (pc '(:org-comment t))
16050 (pall '(:org-archived t :org-comment t))
16051 (inhibit-read-only t)
16052 (rea (concat ":" org-archive-tag ":"))
16053 bmp file re)
16054 (save-excursion
16055 (save-restriction
16056 (while (setq file (pop files))
16057 (catch 'nextfile
16058 (if (bufferp file)
16059 (set-buffer file)
16060 (org-check-agenda-file file)
16061 (set-buffer (org-get-agenda-file-buffer file)))
16062 (widen)
16063 (setq bmp (buffer-modified-p))
16064 (org-refresh-category-properties)
16065 (setq org-todo-keywords-for-agenda
16066 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16067 (setq org-done-keywords-for-agenda
16068 (append org-done-keywords-for-agenda org-done-keywords))
16069 (setq org-todo-keyword-alist-for-agenda
16070 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16071 (setq org-drawers-for-agenda
16072 (append org-drawers-for-agenda org-drawers))
16073 (setq org-tag-alist-for-agenda
16074 (append org-tag-alist-for-agenda org-tag-alist))
16076 (save-excursion
16077 (remove-text-properties (point-min) (point-max) pall)
16078 (when org-agenda-skip-archived-trees
16079 (goto-char (point-min))
16080 (while (re-search-forward rea nil t)
16081 (if (org-on-heading-p t)
16082 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16083 (goto-char (point-min))
16084 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
16085 (while (re-search-forward re nil t)
16086 (add-text-properties
16087 (match-beginning 0) (org-end-of-subtree t) pc)))
16088 (set-buffer-modified-p bmp)))))
16089 (setq org-todo-keywords-for-agenda
16090 (org-uniquify org-todo-keywords-for-agenda))
16091 (setq org-todo-keyword-alist-for-agenda
16092 (org-uniquify org-todo-keyword-alist-for-agenda)
16093 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16095 ;;;; Embedded LaTeX
16097 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16098 "Keymap for the minor `org-cdlatex-mode'.")
16100 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16101 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16102 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16103 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16104 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16106 (defvar org-cdlatex-texmathp-advice-is-done nil
16107 "Flag remembering if we have applied the advice to texmathp already.")
16109 (define-minor-mode org-cdlatex-mode
16110 "Toggle the minor `org-cdlatex-mode'.
16111 This mode supports entering LaTeX environment and math in LaTeX fragments
16112 in Org-mode.
16113 \\{org-cdlatex-mode-map}"
16114 nil " OCDL" nil
16115 (when org-cdlatex-mode (require 'cdlatex))
16116 (unless org-cdlatex-texmathp-advice-is-done
16117 (setq org-cdlatex-texmathp-advice-is-done t)
16118 (defadvice texmathp (around org-math-always-on activate)
16119 "Always return t in org-mode buffers.
16120 This is because we want to insert math symbols without dollars even outside
16121 the LaTeX math segments. If Orgmode thinks that point is actually inside
16122 an embedded LaTeX fragment, let texmathp do its job.
16123 \\[org-cdlatex-mode-map]"
16124 (interactive)
16125 (let (p)
16126 (cond
16127 ((not (org-mode-p)) ad-do-it)
16128 ((eq this-command 'cdlatex-math-symbol)
16129 (setq ad-return-value t
16130 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16132 (let ((p (org-inside-LaTeX-fragment-p)))
16133 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16134 (setq ad-return-value t
16135 texmathp-why '("Org-mode embedded math" . 0))
16136 (if p ad-do-it)))))))))
16138 (defun turn-on-org-cdlatex ()
16139 "Unconditionally turn on `org-cdlatex-mode'."
16140 (org-cdlatex-mode 1))
16142 (defun org-inside-LaTeX-fragment-p ()
16143 "Test if point is inside a LaTeX fragment.
16144 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16145 sequence appearing also before point.
16146 Even though the matchers for math are configurable, this function assumes
16147 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16148 delimiters are skipped when they have been removed by customization.
16149 The return value is nil, or a cons cell with the delimiter and the
16150 position of this delimiter.
16152 This function does a reasonably good job, but can locally be fooled by
16153 for example currency specifications. For example it will assume being in
16154 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16155 fragments that are properly closed, but during editing, we have to live
16156 with the uncertainty caused by missing closing delimiters. This function
16157 looks only before point, not after."
16158 (catch 'exit
16159 (let ((pos (point))
16160 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16161 (lim (progn
16162 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16163 (point)))
16164 dd-on str (start 0) m re)
16165 (goto-char pos)
16166 (when dodollar
16167 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16168 re (nth 1 (assoc "$" org-latex-regexps)))
16169 (while (string-match re str start)
16170 (cond
16171 ((= (match-end 0) (length str))
16172 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16173 ((= (match-end 0) (- (length str) 5))
16174 (throw 'exit nil))
16175 (t (setq start (match-end 0))))))
16176 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16177 (goto-char pos)
16178 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16179 (and (match-beginning 2) (throw 'exit nil))
16180 ;; count $$
16181 (while (re-search-backward "\\$\\$" lim t)
16182 (setq dd-on (not dd-on)))
16183 (goto-char pos)
16184 (if dd-on (cons "$$" m))))))
16186 (defun org-inside-latex-macro-p ()
16187 "Is point inside a LaTeX macro or its arguments?"
16188 (save-match-data
16189 (org-in-regexp
16190 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16192 (defun org-try-cdlatex-tab ()
16193 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16194 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16195 - inside a LaTeX fragment, or
16196 - after the first word in a line, where an abbreviation expansion could
16197 insert a LaTeX environment."
16198 (when org-cdlatex-mode
16199 (cond
16200 ((save-excursion
16201 (skip-chars-backward "a-zA-Z0-9*")
16202 (skip-chars-backward " \t")
16203 (bolp))
16204 (cdlatex-tab) t)
16205 ((org-inside-LaTeX-fragment-p)
16206 (cdlatex-tab) t)
16207 (t nil))))
16209 (defun org-cdlatex-underscore-caret (&optional arg)
16210 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16211 Revert to the normal definition outside of these fragments."
16212 (interactive "P")
16213 (if (org-inside-LaTeX-fragment-p)
16214 (call-interactively 'cdlatex-sub-superscript)
16215 (let (org-cdlatex-mode)
16216 (call-interactively (key-binding (vector last-input-event))))))
16218 (defun org-cdlatex-math-modify (&optional arg)
16219 "Execute `cdlatex-math-modify' in LaTeX fragments.
16220 Revert to the normal definition outside of these fragments."
16221 (interactive "P")
16222 (if (org-inside-LaTeX-fragment-p)
16223 (call-interactively 'cdlatex-math-modify)
16224 (let (org-cdlatex-mode)
16225 (call-interactively (key-binding (vector last-input-event))))))
16227 (defvar org-latex-fragment-image-overlays nil
16228 "List of overlays carrying the images of latex fragments.")
16229 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16231 (defun org-remove-latex-fragment-image-overlays ()
16232 "Remove all overlays with LaTeX fragment images in current buffer."
16233 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16234 (setq org-latex-fragment-image-overlays nil))
16236 (defun org-preview-latex-fragment (&optional subtree)
16237 "Preview the LaTeX fragment at point, or all locally or globally.
16238 If the cursor is in a LaTeX fragment, create the image and overlay
16239 it over the source code. If there is no fragment at point, display
16240 all fragments in the current text, from one headline to the next. With
16241 prefix SUBTREE, display all fragments in the current subtree. With a
16242 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16243 the cursor is before the first headline,
16244 display all fragments in the buffer.
16245 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16246 (interactive "P")
16247 (org-remove-latex-fragment-image-overlays)
16248 (save-excursion
16249 (save-restriction
16250 (let (beg end at msg)
16251 (cond
16252 ((or (equal subtree '(16))
16253 (not (save-excursion
16254 (re-search-backward (concat "^" outline-regexp) nil t))))
16255 (setq beg (point-min) end (point-max)
16256 msg "Creating images for buffer...%s"))
16257 ((equal subtree '(4))
16258 (org-back-to-heading)
16259 (setq beg (point) end (org-end-of-subtree t)
16260 msg "Creating images for subtree...%s"))
16262 (if (setq at (org-inside-LaTeX-fragment-p))
16263 (goto-char (max (point-min) (- (cdr at) 2)))
16264 (org-back-to-heading))
16265 (setq beg (point) end (progn (outline-next-heading) (point))
16266 msg (if at "Creating image...%s"
16267 "Creating images for entry...%s"))))
16268 (message msg "")
16269 (narrow-to-region beg end)
16270 (goto-char beg)
16271 (org-format-latex
16272 (concat "ltxpng/" (file-name-sans-extension
16273 (file-name-nondirectory
16274 buffer-file-name)))
16275 default-directory 'overlays msg at 'forbuffer 'dvipng)
16276 (message msg "done. Use `C-c C-c' to remove images.")))))
16278 (defvar org-latex-regexps
16279 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16280 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16281 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16282 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16283 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16284 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16285 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16286 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16287 "Regular expressions for matching embedded LaTeX.")
16289 (defvar org-export-have-math nil) ;; dynamic scoping
16290 (defun org-format-latex (prefix &optional dir overlays msg at
16291 forbuffer processing-type)
16292 "Replace LaTeX fragments with links to an image, and produce images.
16293 Some of the options can be changed using the variable
16294 `org-format-latex-options'."
16295 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16296 (let* ((prefixnodir (file-name-nondirectory prefix))
16297 (absprefix (expand-file-name prefix dir))
16298 (todir (file-name-directory absprefix))
16299 (opt org-format-latex-options)
16300 (matchers (plist-get opt :matchers))
16301 (re-list org-latex-regexps)
16302 (org-format-latex-header-extra
16303 (plist-get (org-infile-export-plist) :latex-header-extra))
16304 (cnt 0) txt hash link beg end re e checkdir
16305 executables-checked string
16306 m n block linkfile movefile ov)
16307 ;; Check the different regular expressions
16308 (while (setq e (pop re-list))
16309 (setq m (car e) re (nth 1 e) n (nth 2 e)
16310 block (if (nth 3 e) "\n\n" ""))
16311 (when (member m matchers)
16312 (goto-char (point-min))
16313 (while (re-search-forward re nil t)
16314 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16315 (not (get-text-property (match-beginning n)
16316 'org-protected))
16317 (or (not overlays)
16318 (not (eq (get-char-property (match-beginning n)
16319 'org-overlay-type)
16320 'org-latex-overlay))))
16321 (setq org-export-have-math t)
16322 (cond
16323 ((eq processing-type 'verbatim)
16324 ;; Leave the text verbatim, just protect it
16325 (add-text-properties (match-beginning n) (match-end n)
16326 '(org-protected t)))
16327 ((eq processing-type 'mathjax)
16328 ;; Prepare for MathJax processing
16329 (setq string (match-string n))
16330 (if (member m '("$" "$1"))
16331 (save-excursion
16332 (delete-region (match-beginning n) (match-end n))
16333 (goto-char (match-beginning n))
16334 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16335 "\\)")
16336 '(org-protected t))))
16337 (add-text-properties (match-beginning n) (match-end n)
16338 '(org-protected t))))
16339 ((or (eq processing-type 'dvipng) t)
16340 ;; Process to an image
16341 (setq txt (match-string n)
16342 beg (match-beginning n) end (match-end n)
16343 cnt (1+ cnt))
16344 (let (print-length print-level) ; make sure full list is printed
16345 (setq hash (sha1 (prin1-to-string
16346 (list org-format-latex-header
16347 org-format-latex-header-extra
16348 org-export-latex-default-packages-alist
16349 org-export-latex-packages-alist
16350 org-format-latex-options
16351 forbuffer txt)))
16352 linkfile (format "%s_%s.png" prefix hash)
16353 movefile (format "%s_%s.png" absprefix hash)))
16354 (setq link (concat block "[[file:" linkfile "]]" block))
16355 (if msg (message msg cnt))
16356 (goto-char beg)
16357 (unless checkdir ; make sure the directory exists
16358 (setq checkdir t)
16359 (or (file-directory-p todir) (make-directory todir t)))
16361 (unless executables-checked
16362 (org-check-external-command
16363 "latex" "needed to convert LaTeX fragments to images")
16364 (org-check-external-command
16365 "dvipng" "needed to convert LaTeX fragments to images")
16366 (setq executables-checked t))
16368 (unless (file-exists-p movefile)
16369 (org-create-formula-image
16370 txt movefile opt forbuffer))
16371 (if overlays
16372 (progn
16373 (mapc (lambda (o)
16374 (if (eq (overlay-get o 'org-overlay-type)
16375 'org-latex-overlay)
16376 (delete-overlay o)))
16377 (overlays-in beg end))
16378 (setq ov (make-overlay beg end))
16379 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16380 (if (featurep 'xemacs)
16381 (progn
16382 (overlay-put ov 'invisible t)
16383 (overlay-put
16384 ov 'end-glyph
16385 (make-glyph (vector 'png :file movefile))))
16386 (overlay-put
16387 ov 'display
16388 (list 'image :type 'png :file movefile :ascent 'center)))
16389 (push ov org-latex-fragment-image-overlays)
16390 (goto-char end))
16391 (delete-region beg end)
16392 (insert (org-add-props link
16393 (list 'org-latex-src
16394 (replace-regexp-in-string
16395 "\"" "" txt)))))))))))))
16397 ;; This function borrows from Ganesh Swami's latex2png.el
16398 (defun org-create-formula-image (string tofile options buffer)
16399 "This calls dvipng."
16400 (require 'org-latex)
16401 (let* ((tmpdir (if (featurep 'xemacs)
16402 (temp-directory)
16403 temporary-file-directory))
16404 (texfilebase (make-temp-name
16405 (expand-file-name "orgtex" tmpdir)))
16406 (texfile (concat texfilebase ".tex"))
16407 (dvifile (concat texfilebase ".dvi"))
16408 (pngfile (concat texfilebase ".png"))
16409 (fnh (if (featurep 'xemacs)
16410 (font-height (get-face-font 'default))
16411 (face-attribute 'default :height nil)))
16412 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
16413 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
16414 (fg (or (plist-get options (if buffer :foreground :html-foreground))
16415 "Black"))
16416 (bg (or (plist-get options (if buffer :background :html-background))
16417 "Transparent")))
16418 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
16419 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
16420 (with-temp-file texfile
16421 (insert (org-splice-latex-header
16422 org-format-latex-header
16423 org-export-latex-default-packages-alist
16424 org-export-latex-packages-alist t
16425 org-format-latex-header-extra))
16426 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
16427 (require 'org-latex)
16428 (org-export-latex-fix-inputenc))
16429 (let ((dir default-directory))
16430 (condition-case nil
16431 (progn
16432 (cd tmpdir)
16433 (call-process "latex" nil nil nil texfile))
16434 (error nil))
16435 (cd dir))
16436 (if (not (file-exists-p dvifile))
16437 (progn (message "Failed to create dvi file from %s" texfile) nil)
16438 (condition-case nil
16439 (call-process "dvipng" nil nil nil
16440 "-fg" fg "-bg" bg
16441 "-D" dpi
16442 ;;"-x" scale "-y" scale
16443 "-T" "tight"
16444 "-o" pngfile
16445 dvifile)
16446 (error nil))
16447 (if (not (file-exists-p pngfile))
16448 (if org-format-latex-signal-error
16449 (error "Failed to create png file from %s" texfile)
16450 (message "Failed to create png file from %s" texfile)
16451 nil)
16452 ;; Use the requested file name and clean up
16453 (copy-file pngfile tofile 'replace)
16454 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16455 (delete-file (concat texfilebase e)))
16456 pngfile))))
16458 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
16459 "Fill a LaTeX header template TPL.
16460 In the template, the following place holders will be recognized:
16462 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
16463 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
16464 [PACKAGES] \\usepackage statements for PKG
16465 [NO-PACKAGES] do not include PKG
16466 [EXTRA] the string EXTRA
16467 [NO-EXTRA] do not include EXTRA
16469 For backward compatibility, if both the positive and the negative place
16470 holder is missing, the positive one (without the \"NO-\") will be
16471 assumed to be present at the end of the template.
16472 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
16473 EXTRA is a string.
16474 SNIPPETS-P indicates if this is run to create snippet images for HTML."
16475 (let (rpl (end ""))
16476 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
16477 (setq rpl (if (or (match-end 1) (not def-pkg))
16478 "" (org-latex-packages-to-string def-pkg snippets-p t))
16479 tpl (replace-match rpl t t tpl))
16480 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
16482 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
16483 (setq rpl (if (or (match-end 1) (not pkg))
16484 "" (org-latex-packages-to-string pkg snippets-p t))
16485 tpl (replace-match rpl t t tpl))
16486 (if pkg (setq end
16487 (concat end "\n"
16488 (org-latex-packages-to-string pkg snippets-p)))))
16490 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
16491 (setq rpl (if (or (match-end 1) (not extra))
16492 "" (concat extra "\n"))
16493 tpl (replace-match rpl t t tpl))
16494 (if (and extra (string-match "\\S-" extra))
16495 (setq end (concat end "\n" extra))))
16497 (if (string-match "\\S-" end)
16498 (concat tpl "\n" end)
16499 tpl)))
16501 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
16502 "Turn an alist of packages into a string with the \\usepackage macros."
16503 (setq pkg (mapconcat (lambda(p)
16504 (cond
16505 ((stringp p) p)
16506 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
16507 (format "%% Package %s omitted" (cadr p)))
16508 ((equal "" (car p))
16509 (format "\\usepackage{%s}" (cadr p)))
16511 (format "\\usepackage[%s]{%s}"
16512 (car p) (cadr p)))))
16514 "\n"))
16515 (if newline (concat pkg "\n") pkg))
16517 (defun org-dvipng-color (attr)
16518 "Return an rgb color specification for dvipng."
16519 (apply 'format "rgb %s %s %s"
16520 (mapcar 'org-normalize-color
16521 (color-values (face-attribute 'default attr nil)))))
16523 (defun org-normalize-color (value)
16524 "Return string to be used as color value for an RGB component."
16525 (format "%g" (/ value 65535.0)))
16527 ;; Image display
16530 (defvar org-inline-image-overlays nil)
16531 (make-variable-buffer-local 'org-inline-image-overlays)
16533 (defun org-toggle-inline-images (&optional include-linked)
16534 "Toggle the display of inline images.
16535 INCLUDE-LINKED is passed to `org-display-inline-images'."
16536 (interactive "P")
16537 (if org-inline-image-overlays
16538 (progn
16539 (org-remove-inline-images)
16540 (message "Inline image display turned off"))
16541 (org-display-inline-images include-linked)
16542 (if org-inline-image-overlays
16543 (message "%d images displayed inline"
16544 (length org-inline-image-overlays))
16545 (message "No images to display inline"))))
16547 (defun org-display-inline-images (&optional include-linked refresh beg end)
16548 "Display inline images.
16549 Normally only links without a description part are inlined, because this
16550 is how it will work for export. When INCLUDE-LINKED is set, also links
16551 with a description part will be inlined. This can be nice for a quick
16552 look at those images, but it does not reflect what exported files will look
16553 like.
16554 When REFRESH is set, refresh existing images between BEG and END.
16555 This will create new image displays only if necessary.
16556 BEG and END default to the buffer boundaries."
16557 (interactive "P")
16558 (unless refresh
16559 (org-remove-inline-images)
16560 (if (fboundp 'clear-image-cache) (clear-image-cache)))
16561 (save-excursion
16562 (save-restriction
16563 (widen)
16564 (setq beg (or beg (point-min)) end (or end (point-max)))
16565 (goto-char (point-min))
16566 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
16567 (substring (org-image-file-name-regexp) 0 -2)
16568 "\\)\\]" (if include-linked "" "\\]")))
16569 old file ov img)
16570 (while (re-search-forward re end t)
16571 (setq old (get-char-property-and-overlay (match-beginning 1)
16572 'org-image-overlay))
16573 (setq file (expand-file-name
16574 (concat (or (match-string 3) "") (match-string 4))))
16575 (when (file-exists-p file)
16576 (if (and (car-safe old) refresh)
16577 (image-refresh (overlay-get (cdr old) 'display))
16578 (setq img (save-match-data (create-image file)))
16579 (when img
16580 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
16581 (overlay-put ov 'display img)
16582 (overlay-put ov 'face 'default)
16583 (overlay-put ov 'org-image-overlay t)
16584 (overlay-put ov 'modification-hooks
16585 (list 'org-display-inline-modification-hook))
16586 (push ov org-inline-image-overlays)))))))))
16588 (defun org-display-inline-modification-hook (ov after beg end &optional len)
16589 "Remove inline-display overlay if a corresponding region is modified."
16590 (let ((inhibit-modification-hooks t))
16591 (when (and ov after)
16592 (delete ov org-inline-image-overlays)
16593 (delete-overlay ov))))
16595 (defun org-remove-inline-images ()
16596 "Remove inline display of images."
16597 (interactive)
16598 (mapc 'delete-overlay org-inline-image-overlays)
16599 (setq org-inline-image-overlays nil))
16601 ;;;; Key bindings
16603 ;; Make `C-c C-x' a prefix key
16604 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
16606 ;; TAB key with modifiers
16607 (org-defkey org-mode-map "\C-i" 'org-cycle)
16608 (org-defkey org-mode-map [(tab)] 'org-cycle)
16609 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
16610 (org-defkey org-mode-map [(meta tab)] 'pcomplete)
16611 (org-defkey org-mode-map "\M-\t" 'pcomplete)
16612 (org-defkey org-mode-map "\M-\C-i" 'pcomplete)
16613 ;; The following line is necessary under Suse GNU/Linux
16614 (unless (featurep 'xemacs)
16615 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
16616 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
16617 (define-key org-mode-map [backtab] 'org-shifttab)
16619 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
16620 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
16621 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
16623 ;; Cursor keys with modifiers
16624 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
16625 (org-defkey org-mode-map [(meta right)] 'org-metaright)
16626 (org-defkey org-mode-map [(meta up)] 'org-metaup)
16627 (org-defkey org-mode-map [(meta down)] 'org-metadown)
16629 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
16630 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
16631 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
16632 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
16634 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
16635 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
16636 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
16637 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
16639 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
16640 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
16642 ;; Babel keys
16643 (define-key org-mode-map org-babel-key-prefix org-babel-map)
16644 (mapc (lambda (pair)
16645 (define-key org-babel-map (car pair) (cdr pair)))
16646 org-babel-key-bindings)
16648 ;;; Extra keys for tty access.
16649 ;; We only set them when really needed because otherwise the
16650 ;; menus don't show the simple keys
16652 (when (or org-use-extra-keys
16653 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
16654 (not window-system))
16655 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
16656 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
16657 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
16658 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
16659 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
16660 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
16661 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
16662 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
16663 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
16664 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
16665 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
16666 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
16667 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
16668 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
16669 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
16670 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
16671 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
16672 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
16673 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
16674 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
16675 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
16676 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
16677 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
16678 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
16679 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
16680 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
16681 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
16682 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
16684 ;; All the other keys
16686 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
16687 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
16688 (if (boundp 'narrow-map)
16689 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
16690 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
16691 (if (boundp 'narrow-map)
16692 (org-defkey narrow-map "b" 'org-narrow-to-block)
16693 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
16694 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
16695 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
16696 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
16697 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
16698 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
16699 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
16700 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
16701 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
16702 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
16703 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
16704 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
16705 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
16706 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
16707 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
16708 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
16709 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
16710 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
16711 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
16712 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
16713 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
16714 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
16715 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
16716 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
16717 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
16718 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
16719 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
16720 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
16721 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
16722 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
16723 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
16724 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
16725 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
16726 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
16727 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
16728 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
16729 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
16730 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
16731 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
16732 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
16733 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
16734 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16735 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
16736 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
16737 (org-defkey org-mode-map "\C-c^" 'org-sort)
16738 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
16739 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
16740 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
16741 (org-defkey org-mode-map "\C-m" 'org-return)
16742 (org-defkey org-mode-map "\C-j" 'org-return-indent)
16743 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
16744 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
16745 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
16746 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
16747 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
16748 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
16749 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
16750 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
16751 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
16752 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
16753 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
16754 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
16755 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
16756 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
16757 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
16758 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
16759 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
16760 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
16761 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
16762 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
16763 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
16765 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
16766 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
16767 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
16768 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
16770 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
16771 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
16772 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
16773 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
16774 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
16775 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
16776 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
16777 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
16778 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
16779 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
16780 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
16781 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
16782 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
16783 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
16784 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
16785 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
16786 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
16787 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
16789 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
16790 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
16791 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
16792 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
16793 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
16795 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
16797 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
16799 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
16800 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
16802 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
16805 (when (featurep 'xemacs)
16806 (org-defkey org-mode-map 'button3 'popup-mode-menu))
16809 (defconst org-speed-commands-default
16811 ("Outline Navigation")
16812 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
16813 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
16814 ("f" . (org-speed-move-safe 'org-forward-same-level))
16815 ("b" . (org-speed-move-safe 'org-backward-same-level))
16816 ("u" . (org-speed-move-safe 'outline-up-heading))
16817 ("j" . org-goto)
16818 ("g" . (org-refile t))
16819 ("Outline Visibility")
16820 ("c" . org-cycle)
16821 ("C" . org-shifttab)
16822 (" " . org-display-outline-path)
16823 ("Outline Structure Editing")
16824 ("U" . org-shiftmetaup)
16825 ("D" . org-shiftmetadown)
16826 ("r" . org-metaright)
16827 ("l" . org-metaleft)
16828 ("R" . org-shiftmetaright)
16829 ("L" . org-shiftmetaleft)
16830 ("i" . (progn (forward-char 1) (call-interactively
16831 'org-insert-heading-respect-content)))
16832 ("^" . org-sort)
16833 ("w" . org-refile)
16834 ("a" . org-archive-subtree-default-with-confirmation)
16835 ("." . org-mark-subtree)
16836 ("Clock Commands")
16837 ("I" . org-clock-in)
16838 ("O" . org-clock-out)
16839 ("Meta Data Editing")
16840 ("t" . org-todo)
16841 ("0" . (org-priority ?\ ))
16842 ("1" . (org-priority ?A))
16843 ("2" . (org-priority ?B))
16844 ("3" . (org-priority ?C))
16845 (";" . org-set-tags-command)
16846 ("e" . org-set-effort)
16847 ("Agenda Views etc")
16848 ("v" . org-agenda)
16849 ("/" . org-sparse-tree)
16850 ("Misc")
16851 ("o" . org-open-at-point)
16852 ("?" . org-speed-command-help)
16853 ("<" . (org-agenda-set-restriction-lock 'subtree))
16854 (">" . (org-agenda-remove-restriction-lock))
16856 "The default speed commands.")
16858 (defun org-print-speed-command (e)
16859 (if (> (length (car e)) 1)
16860 (progn
16861 (princ "\n")
16862 (princ (car e))
16863 (princ "\n")
16864 (princ (make-string (length (car e)) ?-))
16865 (princ "\n"))
16866 (princ (car e))
16867 (princ " ")
16868 (if (symbolp (cdr e))
16869 (princ (symbol-name (cdr e)))
16870 (prin1 (cdr e)))
16871 (princ "\n")))
16873 (defun org-speed-command-help ()
16874 "Show the available speed commands."
16875 (interactive)
16876 (if (not org-use-speed-commands)
16877 (error "Speed commands are not activated, customize `org-use-speed-commands'")
16878 (with-output-to-temp-buffer "*Help*"
16879 (princ "User-defined Speed commands\n===========================\n")
16880 (mapc 'org-print-speed-command org-speed-commands-user)
16881 (princ "\n")
16882 (princ "Built-in Speed commands\n=======================\n")
16883 (mapc 'org-print-speed-command org-speed-commands-default))
16884 (with-current-buffer "*Help*"
16885 (setq truncate-lines t))))
16887 (defun org-speed-move-safe (cmd)
16888 "Execute CMD, but make sure that the cursor always ends up in a headline.
16889 If not, return to the original position and throw an error."
16890 (interactive)
16891 (let ((pos (point)))
16892 (call-interactively cmd)
16893 (unless (and (bolp) (org-on-heading-p))
16894 (goto-char pos)
16895 (error "Boundary reached while executing %s" cmd))))
16897 (defvar org-self-insert-command-undo-counter 0)
16899 (defvar org-table-auto-blank-field) ; defined in org-table.el
16900 (defvar org-speed-command nil)
16902 (defun org-speed-command-default-hook (keys)
16903 "Hook for activating single-letter speed commands.
16904 `org-speed-commands-default' specifies a minimal command set. Use
16905 `org-speed-commands-user' for further customization."
16906 (when (or (and (bolp) (looking-at outline-regexp))
16907 (and (functionp org-use-speed-commands)
16908 (funcall org-use-speed-commands)))
16909 (cdr (assoc keys (append org-speed-commands-user
16910 org-speed-commands-default)))))
16912 (defun org-babel-speed-command-hook (keys)
16913 "Hook for activating single-letter code block commands."
16914 (when (and (bolp) (looking-at org-babel-src-block-regexp))
16915 (cdr (assoc keys org-babel-key-bindings))))
16917 (defcustom org-speed-command-hook
16918 '(org-speed-command-default-hook org-babel-speed-command-hook)
16919 "Hook for activating speed commands at strategic locations.
16920 Hook functions are called in sequence until a valid handler is
16921 found.
16923 Each hook takes a single argument, a user-pressed command key
16924 which is also a `self-insert-command' from the global map.
16926 Within the hook, examine the cursor position and the command key
16927 and return nil or a valid handler as appropriate. Handler could
16928 be one of an interactive command, a function, or a form.
16930 Set `org-use-speed-commands' to non-nil value to enable this
16931 hook. The default setting is `org-speed-command-default-hook'."
16932 :group 'org-structure
16933 :type 'hook)
16935 (defun org-self-insert-command (N)
16936 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
16937 If the cursor is in a table looking at whitespace, the whitespace is
16938 overwritten, and the table is not marked as requiring realignment."
16939 (interactive "p")
16940 (cond
16941 ((and org-use-speed-commands
16942 (setq org-speed-command
16943 (run-hook-with-args-until-success
16944 'org-speed-command-hook (this-command-keys))))
16945 (cond
16946 ((commandp org-speed-command)
16947 (setq this-command org-speed-command)
16948 (call-interactively org-speed-command))
16949 ((functionp org-speed-command)
16950 (funcall org-speed-command))
16951 ((and org-speed-command (listp org-speed-command))
16952 (eval org-speed-command))
16953 (t (let (org-use-speed-commands)
16954 (call-interactively 'org-self-insert-command)))))
16955 ((and
16956 (org-table-p)
16957 (progn
16958 ;; check if we blank the field, and if that triggers align
16959 (and (featurep 'org-table) org-table-auto-blank-field
16960 (member last-command
16961 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
16962 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
16963 ;; got extra space, this field does not determine column width
16964 (let (org-table-may-need-update) (org-table-blank-field))
16965 ;; no extra space, this field may determine column width
16966 (org-table-blank-field)))
16968 (eq N 1)
16969 (looking-at "[^|\n]* |"))
16970 (let (org-table-may-need-update)
16971 (goto-char (1- (match-end 0)))
16972 (delete-char -1)
16973 (goto-char (match-beginning 0))
16974 (self-insert-command N)))
16976 (setq org-table-may-need-update t)
16977 (self-insert-command N)
16978 (org-fix-tags-on-the-fly)
16979 (if org-self-insert-cluster-for-undo
16980 (if (not (eq last-command 'org-self-insert-command))
16981 (setq org-self-insert-command-undo-counter 1)
16982 (if (>= org-self-insert-command-undo-counter 20)
16983 (setq org-self-insert-command-undo-counter 1)
16984 (and (> org-self-insert-command-undo-counter 0)
16985 buffer-undo-list (listp buffer-undo-list)
16986 (not (cadr buffer-undo-list)) ; remove nil entry
16987 (setcdr buffer-undo-list (cddr buffer-undo-list)))
16988 (setq org-self-insert-command-undo-counter
16989 (1+ org-self-insert-command-undo-counter))))))))
16991 (defun org-fix-tags-on-the-fly ()
16992 (when (and (equal (char-after (point-at-bol)) ?*)
16993 (org-on-heading-p))
16994 (org-align-tags-here org-tags-column)))
16996 (defun org-delete-backward-char (N)
16997 "Like `delete-backward-char', insert whitespace at field end in tables.
16998 When deleting backwards, in tables this function will insert whitespace in
16999 front of the next \"|\" separator, to keep the table aligned. The table will
17000 still be marked for re-alignment if the field did fill the entire column,
17001 because, in this case the deletion might narrow the column."
17002 (interactive "p")
17003 (if (and (org-table-p)
17004 (eq N 1)
17005 (string-match "|" (buffer-substring (point-at-bol) (point)))
17006 (looking-at ".*?|"))
17007 (let ((pos (point))
17008 (noalign (looking-at "[^|\n\r]* |"))
17009 (c org-table-may-need-update))
17010 (backward-delete-char N)
17011 (if (not overwrite-mode)
17012 (progn
17013 (skip-chars-forward "^|")
17014 (insert " ")
17015 (goto-char (1- pos))))
17016 ;; noalign: if there were two spaces at the end, this field
17017 ;; does not determine the width of the column.
17018 (if noalign (setq org-table-may-need-update c)))
17019 (backward-delete-char N)
17020 (org-fix-tags-on-the-fly)))
17022 (defun org-delete-char (N)
17023 "Like `delete-char', but insert whitespace at field end in tables.
17024 When deleting characters, in tables this function will insert whitespace in
17025 front of the next \"|\" separator, to keep the table aligned. The table will
17026 still be marked for re-alignment if the field did fill the entire column,
17027 because, in this case the deletion might narrow the column."
17028 (interactive "p")
17029 (if (and (org-table-p)
17030 (not (bolp))
17031 (not (= (char-after) ?|))
17032 (eq N 1))
17033 (if (looking-at ".*?|")
17034 (let ((pos (point))
17035 (noalign (looking-at "[^|\n\r]* |"))
17036 (c org-table-may-need-update))
17037 (replace-match (concat
17038 (substring (match-string 0) 1 -1)
17039 " |"))
17040 (goto-char 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 (delete-char N))
17045 (delete-char N)
17046 (org-fix-tags-on-the-fly)))
17048 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17049 (put 'org-self-insert-command 'delete-selection t)
17050 (put 'orgtbl-self-insert-command 'delete-selection t)
17051 (put 'org-delete-char 'delete-selection 'supersede)
17052 (put 'org-delete-backward-char 'delete-selection 'supersede)
17053 (put 'org-yank 'delete-selection 'yank)
17055 ;; Make `flyspell-mode' delay after some commands
17056 (put 'org-self-insert-command 'flyspell-delayed t)
17057 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17058 (put 'org-delete-char 'flyspell-delayed t)
17059 (put 'org-delete-backward-char 'flyspell-delayed t)
17061 ;; Make pabbrev-mode expand after org-mode commands
17062 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17063 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17065 ;; How to do this: Measure non-white length of current string
17066 ;; If equal to column width, we should realign.
17068 (defun org-remap (map &rest commands)
17069 "In MAP, remap the functions given in COMMANDS.
17070 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17071 (let (new old)
17072 (while commands
17073 (setq old (pop commands) new (pop commands))
17074 (if (fboundp 'command-remapping)
17075 (org-defkey map (vector 'remap old) new)
17076 (substitute-key-definition old new map global-map)))))
17078 (when (eq org-enable-table-editor 'optimized)
17079 ;; If the user wants maximum table support, we need to hijack
17080 ;; some standard editing functions
17081 (org-remap org-mode-map
17082 'self-insert-command 'org-self-insert-command
17083 'delete-char 'org-delete-char
17084 'delete-backward-char 'org-delete-backward-char)
17085 (org-defkey org-mode-map "|" 'org-force-self-insert))
17087 (defvar org-ctrl-c-ctrl-c-hook nil
17088 "Hook for functions attaching themselves to `C-c C-c'.
17089 This can be used to add additional functionality to the C-c C-c key which
17090 executes context-dependent commands.
17091 Each function will be called with no arguments. The function must check
17092 if the context is appropriate for it to act. If yes, it should do its
17093 thing and then return a non-nil value. If the context is wrong,
17094 just do nothing and return nil.")
17096 (defvar org-tab-first-hook nil
17097 "Hook for functions to attach themselves to TAB.
17098 See `org-ctrl-c-ctrl-c-hook' for more information.
17099 This hook runs as the first action when TAB is pressed, even before
17100 `org-cycle' messes around with the `outline-regexp' to cater for
17101 inline tasks and plain list item folding.
17102 If any function in this hook returns t, any other actions that
17103 would have been caused by TAB (such as table field motion or visibility
17104 cycling) will not occur.")
17106 (defvar org-tab-after-check-for-table-hook nil
17107 "Hook for functions to attach themselves to TAB.
17108 See `org-ctrl-c-ctrl-c-hook' for more information.
17109 This hook runs after it has been established that the cursor is not in a
17110 table, but before checking if the cursor is in a headline or if global cycling
17111 should be done.
17112 If any function in this hook returns t, not other actions like visibility
17113 cycling will be done.")
17115 (defvar org-tab-after-check-for-cycling-hook nil
17116 "Hook for functions to attach themselves to TAB.
17117 See `org-ctrl-c-ctrl-c-hook' for more information.
17118 This hook runs after it has been established that not table field motion and
17119 not visibility should be done because of current context. This is probably
17120 the place where a package like yasnippets can hook in.")
17122 (defvar org-tab-before-tab-emulation-hook nil
17123 "Hook for functions to attach themselves to TAB.
17124 See `org-ctrl-c-ctrl-c-hook' for more information.
17125 This hook runs after every other options for TAB have been exhausted, but
17126 before indentation and \t insertion takes place.")
17128 (defvar org-metaleft-hook nil
17129 "Hook for functions attaching themselves to `M-left'.
17130 See `org-ctrl-c-ctrl-c-hook' for more information.")
17131 (defvar org-metaright-hook nil
17132 "Hook for functions attaching themselves to `M-right'.
17133 See `org-ctrl-c-ctrl-c-hook' for more information.")
17134 (defvar org-metaup-hook nil
17135 "Hook for functions attaching themselves to `M-up'.
17136 See `org-ctrl-c-ctrl-c-hook' for more information.")
17137 (defvar org-metadown-hook nil
17138 "Hook for functions attaching themselves to `M-down'.
17139 See `org-ctrl-c-ctrl-c-hook' for more information.")
17140 (defvar org-shiftmetaleft-hook nil
17141 "Hook for functions attaching themselves to `M-S-left'.
17142 See `org-ctrl-c-ctrl-c-hook' for more information.")
17143 (defvar org-shiftmetaright-hook nil
17144 "Hook for functions attaching themselves to `M-S-right'.
17145 See `org-ctrl-c-ctrl-c-hook' for more information.")
17146 (defvar org-shiftmetaup-hook nil
17147 "Hook for functions attaching themselves to `M-S-up'.
17148 See `org-ctrl-c-ctrl-c-hook' for more information.")
17149 (defvar org-shiftmetadown-hook nil
17150 "Hook for functions attaching themselves to `M-S-down'.
17151 See `org-ctrl-c-ctrl-c-hook' for more information.")
17152 (defvar org-metareturn-hook nil
17153 "Hook for functions attaching themselves to `M-RET'.
17154 See `org-ctrl-c-ctrl-c-hook' for more information.")
17155 (defvar org-shiftup-hook nil
17156 "Hook for functions attaching themselves to `S-up'.
17157 See `org-ctrl-c-ctrl-c-hook' for more information.")
17158 (defvar org-shiftup-final-hook nil
17159 "Hook for functions attaching themselves to `S-up'.
17160 This one runs after all other options except shift-select have been excluded.
17161 See `org-ctrl-c-ctrl-c-hook' for more information.")
17162 (defvar org-shiftdown-hook nil
17163 "Hook for functions attaching themselves to `S-down'.
17164 See `org-ctrl-c-ctrl-c-hook' for more information.")
17165 (defvar org-shiftdown-final-hook nil
17166 "Hook for functions attaching themselves to `S-down'.
17167 This one runs after all other options except shift-select have been excluded.
17168 See `org-ctrl-c-ctrl-c-hook' for more information.")
17169 (defvar org-shiftleft-hook nil
17170 "Hook for functions attaching themselves to `S-left'.
17171 See `org-ctrl-c-ctrl-c-hook' for more information.")
17172 (defvar org-shiftleft-final-hook nil
17173 "Hook for functions attaching themselves to `S-left'.
17174 This one runs after all other options except shift-select have been excluded.
17175 See `org-ctrl-c-ctrl-c-hook' for more information.")
17176 (defvar org-shiftright-hook nil
17177 "Hook for functions attaching themselves to `S-right'.
17178 See `org-ctrl-c-ctrl-c-hook' for more information.")
17179 (defvar org-shiftright-final-hook nil
17180 "Hook for functions attaching themselves to `S-right'.
17181 This one runs after all other options except shift-select have been excluded.
17182 See `org-ctrl-c-ctrl-c-hook' for more information.")
17184 (defun org-modifier-cursor-error ()
17185 "Throw an error, a modified cursor command was applied in wrong context."
17186 (error "This command is active in special context like tables, headlines or items"))
17188 (defun org-shiftselect-error ()
17189 "Throw an error because Shift-Cursor command was applied in wrong context."
17190 (if (and (boundp 'shift-select-mode) shift-select-mode)
17191 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
17192 (error "This command works only in special context like headlines or timestamps")))
17194 (defun org-call-for-shift-select (cmd)
17195 (let ((this-command-keys-shift-translated t))
17196 (call-interactively cmd)))
17198 (defun org-shifttab (&optional arg)
17199 "Global visibility cycling or move to previous table field.
17200 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17201 on context.
17202 See the individual commands for more information."
17203 (interactive "P")
17204 (cond
17205 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17206 ((integerp arg)
17207 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
17208 (message "Content view to level: %d" arg)
17209 (org-content (prefix-numeric-value arg2))
17210 (setq org-cycle-global-status 'overview)))
17211 (t (call-interactively 'org-global-cycle))))
17213 (defun org-shiftmetaleft ()
17214 "Promote subtree or delete table column.
17215 Calls `org-promote-subtree', `org-outdent-item',
17216 or `org-table-delete-column', depending on context.
17217 See the individual commands for more information."
17218 (interactive)
17219 (cond
17220 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
17221 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17222 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
17223 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
17224 (t (org-modifier-cursor-error))))
17226 (defun org-shiftmetaright ()
17227 "Demote subtree or insert table column.
17228 Calls `org-demote-subtree', `org-indent-item',
17229 or `org-table-insert-column', depending on context.
17230 See the individual commands for more information."
17231 (interactive)
17232 (cond
17233 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
17234 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17235 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
17236 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
17237 (t (org-modifier-cursor-error))))
17239 (defun org-shiftmetaup (&optional arg)
17240 "Move subtree up or kill table row.
17241 Calls `org-move-subtree-up' or `org-table-kill-row' or
17242 `org-move-item-up' depending on context. See the individual commands
17243 for more information."
17244 (interactive "P")
17245 (cond
17246 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
17247 ((org-at-table-p) (call-interactively 'org-table-kill-row))
17248 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17249 ((org-at-item-p) (call-interactively 'org-move-item-up))
17250 (t (org-modifier-cursor-error))))
17252 (defun org-shiftmetadown (&optional arg)
17253 "Move subtree down or insert table row.
17254 Calls `org-move-subtree-down' or `org-table-insert-row' or
17255 `org-move-item-down', depending on context. See the individual
17256 commands for more information."
17257 (interactive "P")
17258 (cond
17259 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
17260 ((org-at-table-p) (call-interactively 'org-table-insert-row))
17261 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17262 ((org-at-item-p) (call-interactively 'org-move-item-down))
17263 (t (org-modifier-cursor-error))))
17265 (defsubst org-hidden-tree-error ()
17266 (error
17267 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
17269 (defun org-metaleft (&optional arg)
17270 "Promote heading or move table column to left.
17271 Calls `org-do-promote' or `org-table-move-column', depending on context.
17272 With no specific context, calls the Emacs default `backward-word'.
17273 See the individual commands for more information."
17274 (interactive "P")
17275 (cond
17276 ((run-hook-with-args-until-success 'org-metaleft-hook))
17277 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
17278 ((org-with-limited-levels
17279 (or (org-on-heading-p)
17280 (and (org-region-active-p)
17281 (save-excursion
17282 (goto-char (region-beginning))
17283 (org-on-heading-p)))))
17284 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17285 (call-interactively 'org-do-promote))
17286 ;; At an inline task.
17287 ((org-on-heading-p)
17288 (call-interactively 'org-inlinetask-promote))
17289 ((or (org-at-item-p)
17290 (and (org-region-active-p)
17291 (save-excursion
17292 (goto-char (region-beginning))
17293 (org-at-item-p))))
17294 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17295 (call-interactively 'org-outdent-item))
17296 (t (call-interactively 'backward-word))))
17298 (defun org-metaright (&optional arg)
17299 "Demote subtree or move table column to right.
17300 Calls `org-do-demote' or `org-table-move-column', depending on context.
17301 With no specific context, calls the Emacs default `forward-word'.
17302 See the individual commands for more information."
17303 (interactive "P")
17304 (cond
17305 ((run-hook-with-args-until-success 'org-metaright-hook))
17306 ((org-at-table-p) (call-interactively 'org-table-move-column))
17307 ((org-with-limited-levels
17308 (or (org-on-heading-p)
17309 (and (org-region-active-p)
17310 (save-excursion
17311 (goto-char (region-beginning))
17312 (org-on-heading-p)))))
17313 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17314 (call-interactively 'org-do-demote))
17315 ;; At an inline task.
17316 ((org-on-heading-p)
17317 (call-interactively 'org-inlinetask-demote))
17318 ((or (org-at-item-p)
17319 (and (org-region-active-p)
17320 (save-excursion
17321 (goto-char (region-beginning))
17322 (org-at-item-p))))
17323 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17324 (call-interactively 'org-indent-item))
17325 (t (call-interactively 'forward-word))))
17327 (defun org-check-for-hidden (what)
17328 "Check if there are hidden headlines/items in the current visual line.
17329 WHAT can be either `headlines' or `items'. If the current line is
17330 an outline or item heading and it has a folded subtree below it,
17331 this function returns t, nil otherwise."
17332 (let ((re (cond
17333 ((eq what 'headlines) (concat "^" org-outline-regexp))
17334 ((eq what 'items) (org-item-beginning-re))
17335 (t (error "This should not happen"))))
17336 beg end)
17337 (save-excursion
17338 (catch 'exit
17339 (unless (org-region-active-p)
17340 (setq beg (point-at-bol))
17341 (beginning-of-line 2)
17342 (while (and (not (eobp)) ;; this is like `next-line'
17343 (get-char-property (1- (point)) 'invisible))
17344 (beginning-of-line 2))
17345 (setq end (point))
17346 (goto-char beg)
17347 (goto-char (point-at-eol))
17348 (setq end (max end (point)))
17349 (while (re-search-forward re end t)
17350 (if (get-char-property (match-beginning 0) 'invisible)
17351 (throw 'exit t))))
17352 nil))))
17354 (defun org-metaup (&optional arg)
17355 "Move subtree up or move table row up.
17356 Calls `org-move-subtree-up' or `org-table-move-row' or
17357 `org-move-item-up', depending on context. See the individual commands
17358 for more information."
17359 (interactive "P")
17360 (cond
17361 ((run-hook-with-args-until-success 'org-metaup-hook))
17362 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
17363 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17364 ((org-at-item-p) (call-interactively 'org-move-item-up))
17365 (t (transpose-lines 1) (beginning-of-line -1))))
17367 (defun org-metadown (&optional arg)
17368 "Move subtree down or move table row down.
17369 Calls `org-move-subtree-down' or `org-table-move-row' or
17370 `org-move-item-down', depending on context. See the individual
17371 commands for more information."
17372 (interactive "P")
17373 (cond
17374 ((run-hook-with-args-until-success 'org-metadown-hook))
17375 ((org-at-table-p) (call-interactively 'org-table-move-row))
17376 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17377 ((org-at-item-p) (call-interactively 'org-move-item-down))
17378 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
17380 (defun org-shiftup (&optional arg)
17381 "Increase item in timestamp or increase priority of current headline.
17382 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
17383 depending on context. See the individual commands for more information."
17384 (interactive "P")
17385 (cond
17386 ((run-hook-with-args-until-success 'org-shiftup-hook))
17387 ((and org-support-shift-select (org-region-active-p))
17388 (org-call-for-shift-select 'previous-line))
17389 ((org-at-timestamp-p t)
17390 (call-interactively (if org-edit-timestamp-down-means-later
17391 'org-timestamp-down 'org-timestamp-up)))
17392 ((and (not (eq org-support-shift-select 'always))
17393 org-enable-priority-commands
17394 (org-on-heading-p))
17395 (call-interactively 'org-priority-up))
17396 ((and (not org-support-shift-select) (org-at-item-p))
17397 (call-interactively 'org-previous-item))
17398 ((org-clocktable-try-shift 'up arg))
17399 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
17400 (org-support-shift-select
17401 (org-call-for-shift-select 'previous-line))
17402 (t (org-shiftselect-error))))
17404 (defun org-shiftdown (&optional arg)
17405 "Decrease item in timestamp or decrease priority of current headline.
17406 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
17407 depending on context. See the individual commands for more information."
17408 (interactive "P")
17409 (cond
17410 ((run-hook-with-args-until-success 'org-shiftdown-hook))
17411 ((and org-support-shift-select (org-region-active-p))
17412 (org-call-for-shift-select 'next-line))
17413 ((org-at-timestamp-p t)
17414 (call-interactively (if org-edit-timestamp-down-means-later
17415 'org-timestamp-up 'org-timestamp-down)))
17416 ((and (not (eq org-support-shift-select 'always))
17417 org-enable-priority-commands
17418 (org-on-heading-p))
17419 (call-interactively 'org-priority-down))
17420 ((and (not org-support-shift-select) (org-at-item-p))
17421 (call-interactively 'org-next-item))
17422 ((org-clocktable-try-shift 'down arg))
17423 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
17424 (org-support-shift-select
17425 (org-call-for-shift-select 'next-line))
17426 (t (org-shiftselect-error))))
17428 (defun org-shiftright (&optional arg)
17429 "Cycle the thing at point or in the current line, depending on context.
17430 Depending on context, this does one of the following:
17432 - switch a timestamp at point one day into the future
17433 - on a headline, switch to the next TODO keyword.
17434 - on an item, switch entire list to the next bullet type
17435 - on a property line, switch to the next allowed value
17436 - on a clocktable definition line, move time block into the future"
17437 (interactive "P")
17438 (cond
17439 ((run-hook-with-args-until-success 'org-shiftright-hook))
17440 ((and org-support-shift-select (org-region-active-p))
17441 (org-call-for-shift-select 'forward-char))
17442 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
17443 ((and (not (eq org-support-shift-select 'always))
17444 (org-on-heading-p))
17445 (let ((org-inhibit-logging
17446 (not org-treat-S-cursor-todo-selection-as-state-change))
17447 (org-inhibit-blocking
17448 (not org-treat-S-cursor-todo-selection-as-state-change)))
17449 (org-call-with-arg 'org-todo 'right)))
17450 ((or (and org-support-shift-select
17451 (not (eq org-support-shift-select 'always))
17452 (org-at-item-bullet-p))
17453 (and (not org-support-shift-select) (org-at-item-p)))
17454 (org-call-with-arg 'org-cycle-list-bullet nil))
17455 ((and (not (eq org-support-shift-select 'always))
17456 (org-at-property-p))
17457 (call-interactively 'org-property-next-allowed-value))
17458 ((org-clocktable-try-shift 'right arg))
17459 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
17460 (org-support-shift-select
17461 (org-call-for-shift-select 'forward-char))
17462 (t (org-shiftselect-error))))
17464 (defun org-shiftleft (&optional arg)
17465 "Cycle the thing at point or in the current line, depending on context.
17466 Depending on context, this does one of the following:
17468 - switch a timestamp at point one day into the past
17469 - on a headline, switch to the previous TODO keyword.
17470 - on an item, switch entire list to the previous bullet type
17471 - on a property line, switch to the previous allowed value
17472 - on a clocktable definition line, move time block into the past"
17473 (interactive "P")
17474 (cond
17475 ((run-hook-with-args-until-success 'org-shiftleft-hook))
17476 ((and org-support-shift-select (org-region-active-p))
17477 (org-call-for-shift-select 'backward-char))
17478 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
17479 ((and (not (eq org-support-shift-select 'always))
17480 (org-on-heading-p))
17481 (let ((org-inhibit-logging
17482 (not org-treat-S-cursor-todo-selection-as-state-change))
17483 (org-inhibit-blocking
17484 (not org-treat-S-cursor-todo-selection-as-state-change)))
17485 (org-call-with-arg 'org-todo 'left)))
17486 ((or (and org-support-shift-select
17487 (not (eq org-support-shift-select 'always))
17488 (org-at-item-bullet-p))
17489 (and (not org-support-shift-select) (org-at-item-p)))
17490 (org-call-with-arg 'org-cycle-list-bullet 'previous))
17491 ((and (not (eq org-support-shift-select 'always))
17492 (org-at-property-p))
17493 (call-interactively 'org-property-previous-allowed-value))
17494 ((org-clocktable-try-shift 'left arg))
17495 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
17496 (org-support-shift-select
17497 (org-call-for-shift-select 'backward-char))
17498 (t (org-shiftselect-error))))
17500 (defun org-shiftcontrolright ()
17501 "Switch to next TODO set."
17502 (interactive)
17503 (cond
17504 ((and org-support-shift-select (org-region-active-p))
17505 (org-call-for-shift-select 'forward-word))
17506 ((and (not (eq org-support-shift-select 'always))
17507 (org-on-heading-p))
17508 (org-call-with-arg 'org-todo 'nextset))
17509 (org-support-shift-select
17510 (org-call-for-shift-select 'forward-word))
17511 (t (org-shiftselect-error))))
17513 (defun org-shiftcontrolleft ()
17514 "Switch to previous TODO set."
17515 (interactive)
17516 (cond
17517 ((and org-support-shift-select (org-region-active-p))
17518 (org-call-for-shift-select 'backward-word))
17519 ((and (not (eq org-support-shift-select 'always))
17520 (org-on-heading-p))
17521 (org-call-with-arg 'org-todo 'previousset))
17522 (org-support-shift-select
17523 (org-call-for-shift-select 'backward-word))
17524 (t (org-shiftselect-error))))
17526 (defun org-ctrl-c-ret ()
17527 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
17528 (interactive)
17529 (cond
17530 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
17531 (t (call-interactively 'org-insert-heading))))
17533 (defun org-copy-special ()
17534 "Copy region in table or copy current subtree.
17535 Calls `org-table-copy' or `org-copy-subtree', depending on context.
17536 See the individual commands for more information."
17537 (interactive)
17538 (call-interactively
17539 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
17541 (defun org-cut-special ()
17542 "Cut region in table or cut current subtree.
17543 Calls `org-table-copy' or `org-cut-subtree', depending on context.
17544 See the individual commands for more information."
17545 (interactive)
17546 (call-interactively
17547 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
17549 (defun org-paste-special (arg)
17550 "Paste rectangular region into table, or past subtree relative to level.
17551 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
17552 See the individual commands for more information."
17553 (interactive "P")
17554 (if (org-at-table-p)
17555 (org-table-paste-rectangle)
17556 (org-paste-subtree arg)))
17558 (defun org-edit-special (&optional arg)
17559 "Call a special editor for the stuff at point.
17560 When at a table, call the formula editor with `org-table-edit-formulas'.
17561 When at the first line of an src example, call `org-edit-src-code'.
17562 When in an #+include line, visit the include file. Otherwise call
17563 `ffap' to visit the file at point."
17564 (interactive)
17565 ;; possibly prep session before editing source
17566 (when arg
17567 (let* ((info (org-babel-get-src-block-info))
17568 (lang (nth 0 info))
17569 (params (nth 2 info))
17570 (session (cdr (assoc :session params))))
17571 (when (and info session) ;; we are in a source-code block with a session
17572 (funcall
17573 (intern (concat "org-babel-prep-session:" lang)) session params))))
17574 (cond ;; proceed with `org-edit-special'
17575 ((save-excursion
17576 (beginning-of-line 1)
17577 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
17578 (find-file (org-trim (match-string 1))))
17579 ((org-edit-src-code))
17580 ((org-edit-fixed-width-region))
17581 ((org-at-table.el-p)
17582 (org-edit-src-code))
17583 ((or (org-at-table-p)
17584 (save-excursion
17585 (beginning-of-line 1)
17586 (looking-at "[ \t]*#\\+TBLFM:")))
17587 (call-interactively 'org-table-edit-formulas))
17588 (t (call-interactively 'ffap))))
17590 (defun org-ctrl-c-ctrl-c (&optional arg)
17591 "Set tags in headline, or update according to changed information at point.
17593 This command does many different things, depending on context:
17595 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
17596 this is what we do.
17598 - If the cursor is on a statistics cookie, update it.
17600 - If the cursor is in a headline, prompt for tags and insert them
17601 into the current line, aligned to `org-tags-column'. When called
17602 with prefix arg, realign all tags in the current buffer.
17604 - If the cursor is in one of the special #+KEYWORD lines, this
17605 triggers scanning the buffer for these lines and updating the
17606 information.
17608 - If the cursor is inside a table, realign the table. This command
17609 works even if the automatic table editor has been turned off.
17611 - If the cursor is on a #+TBLFM line, re-apply the formulas to
17612 the entire table.
17614 - If the cursor is at a footnote reference or definition, jump to
17615 the corresponding definition or references, respectively.
17617 - If the cursor is a the beginning of a dynamic block, update it.
17619 - If the current buffer is a capture buffer, close note and file it.
17621 - If the cursor is on a <<<target>>>, update radio targets and
17622 corresponding links in this buffer.
17624 - If the cursor is on a numbered item in a plain list, renumber the
17625 ordered list.
17627 - If the cursor is on a checkbox, toggle it.
17629 - If the cursor is on a code block, evaluate it. The variable
17630 `org-confirm-babel-evaluate' can be used to control prompting
17631 before code block evaluation, by default every code block
17632 evaluation requires confirmation. Code block evaluation can be
17633 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
17634 (interactive "P")
17635 (let ((org-enable-table-editor t))
17636 (cond
17637 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
17638 org-occur-highlights
17639 org-latex-fragment-image-overlays)
17640 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
17641 (org-remove-occur-highlights)
17642 (org-remove-latex-fragment-image-overlays)
17643 (message "Temporary highlights/overlays removed from current buffer"))
17644 ((and (local-variable-p 'org-finish-function (current-buffer))
17645 (fboundp org-finish-function))
17646 (funcall org-finish-function))
17647 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
17648 ((or (looking-at org-property-start-re)
17649 (org-at-property-p))
17650 (call-interactively 'org-property-action))
17651 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
17652 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
17653 (or (org-on-heading-p) (org-at-item-p)))
17654 (call-interactively 'org-update-statistics-cookies))
17655 ((org-on-heading-p) (call-interactively 'org-set-tags))
17656 ((org-at-table.el-p)
17657 (message "Use C-c ' to edit table.el tables"))
17658 ((org-at-table-p)
17659 (org-table-maybe-eval-formula)
17660 (if arg
17661 (call-interactively 'org-table-recalculate)
17662 (org-table-maybe-recalculate-line))
17663 (call-interactively 'org-table-align)
17664 (orgtbl-send-table 'maybe))
17665 ((or (org-footnote-at-reference-p)
17666 (org-footnote-at-definition-p))
17667 (call-interactively 'org-footnote-action))
17668 ((org-at-item-checkbox-p)
17669 ;; Cursor at a checkbox: repair list and update checkboxes. Send
17670 ;; list only if at top item.
17671 (let* ((cbox (match-string 1))
17672 (struct (org-list-struct))
17673 (old-struct (copy-tree struct))
17674 (parents (org-list-parents-alist struct))
17675 (prevs (org-list-prevs-alist struct))
17676 (orderedp (org-entry-get nil "ORDERED"))
17677 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
17678 block-item)
17679 ;; Use a light version of `org-toggle-checkbox' to avoid
17680 ;; computing list structure twice.
17681 (org-list-set-checkbox (point-at-bol) struct
17682 (cond
17683 ((equal arg '(16)) "[-]")
17684 ((equal arg '(4)) nil)
17685 ((equal "[X]" cbox) "[ ]")
17686 (t "[X]")))
17687 (org-list-struct-fix-ind struct parents)
17688 (org-list-struct-fix-bul struct prevs)
17689 (setq block-item
17690 (org-list-struct-fix-box struct parents prevs orderedp))
17691 (when block-item
17692 (message
17693 "Checkboxes were removed due to unchecked box at line %d"
17694 (org-current-line block-item)))
17695 (org-list-struct-apply-struct struct old-struct)
17696 (org-update-checkbox-count-maybe)
17697 (when firstp (org-list-send-list 'maybe))))
17698 ((org-at-item-p)
17699 ;; Cursor at an item: repair list. Do checkbox related actions
17700 ;; only if function was called with an argument. Send list only
17701 ;; if at top item.
17702 (let* ((struct (org-list-struct))
17703 (old-struct (copy-tree struct))
17704 (parents (org-list-parents-alist struct))
17705 (prevs (org-list-prevs-alist struct))
17706 (firstp (= (org-list-get-top-point struct) (point-at-bol))))
17707 (org-list-struct-fix-ind struct parents)
17708 (org-list-struct-fix-bul struct prevs)
17709 (when arg
17710 (org-list-set-checkbox (point-at-bol) struct "[ ]")
17711 (org-list-struct-fix-box struct parents prevs))
17712 (org-list-struct-apply-struct struct old-struct)
17713 (when arg (org-update-checkbox-count-maybe))
17714 (when firstp (org-list-send-list 'maybe))))
17715 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
17716 ;; Dynamic block
17717 (beginning-of-line 1)
17718 (save-excursion (org-update-dblock)))
17719 ((save-excursion
17720 (beginning-of-line 1)
17721 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
17722 (cond
17723 ((equal (match-string 1) "TBLFM")
17724 ;; Recalculate the table before this line
17725 (save-excursion
17726 (beginning-of-line 1)
17727 (skip-chars-backward " \r\n\t")
17728 (if (org-at-table-p)
17729 (org-call-with-arg 'org-table-recalculate (or arg t)))))
17731 (let ((org-inhibit-startup-visibility-stuff t)
17732 (org-startup-align-all-tables nil))
17733 (org-save-outline-visibility 'use-markers (org-mode-restart)))
17734 (message "Local setup has been refreshed"))))
17735 ((org-clock-update-time-maybe))
17736 (t (error "C-c C-c can do nothing useful at this location")))))
17738 (defun org-mode-restart ()
17739 "Restart Org-mode, to scan again for special lines.
17740 Also updates the keyword regular expressions."
17741 (interactive)
17742 (org-mode)
17743 (message "Org-mode restarted"))
17745 (defun org-kill-note-or-show-branches ()
17746 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
17747 (interactive)
17748 (if (not org-finish-function)
17749 (progn
17750 (hide-subtree)
17751 (call-interactively 'show-branches))
17752 (let ((org-note-abort t))
17753 (funcall org-finish-function))))
17755 (defun org-return (&optional indent)
17756 "Goto next table row or insert a newline.
17757 Calls `org-table-next-row' or `newline', depending on context.
17758 See the individual commands for more information."
17759 (interactive)
17760 (cond
17761 ((bobp) (if indent (newline-and-indent) (newline)))
17762 ((org-at-table-p)
17763 (org-table-justify-field-maybe)
17764 (call-interactively 'org-table-next-row))
17765 ;; when `newline-and-indent' is called within a list, make sure
17766 ;; text moved stays inside the item.
17767 ((and (org-in-item-p) indent)
17768 (if (and (org-at-item-p) (>= (point) (match-end 0)))
17769 (progn
17770 (newline)
17771 (org-indent-line-to (length (match-string 0))))
17772 (let ((ind (org-get-indentation)))
17773 (newline)
17774 (if (org-looking-back org-list-end-re)
17775 (org-indent-line-function)
17776 (org-indent-line-to ind)))))
17777 ((and org-return-follows-link
17778 (eq (get-text-property (point) 'face) 'org-link))
17779 (call-interactively 'org-open-at-point))
17780 ((and (org-at-heading-p)
17781 (looking-at
17782 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
17783 (org-show-entry)
17784 (end-of-line 1)
17785 (newline))
17786 (t (if indent (newline-and-indent) (newline)))))
17788 (defun org-return-indent ()
17789 "Goto next table row or insert a newline and indent.
17790 Calls `org-table-next-row' or `newline-and-indent', depending on
17791 context. See the individual commands for more information."
17792 (interactive)
17793 (org-return t))
17795 (defun org-ctrl-c-star ()
17796 "Compute table, or change heading status of lines.
17797 Calls `org-table-recalculate' or `org-toggle-heading',
17798 depending on context."
17799 (interactive)
17800 (cond
17801 ((org-at-table-p)
17802 (call-interactively 'org-table-recalculate))
17804 ;; Convert all lines in region to list items
17805 (call-interactively 'org-toggle-heading))))
17807 (defun org-ctrl-c-minus ()
17808 "Insert separator line in table or modify bullet status of line.
17809 Also turns a plain line or a region of lines into list items.
17810 Calls `org-table-insert-hline', `org-toggle-item', or
17811 `org-cycle-list-bullet', depending on context."
17812 (interactive)
17813 (cond
17814 ((org-at-table-p)
17815 (call-interactively 'org-table-insert-hline))
17816 ((org-region-active-p)
17817 (call-interactively 'org-toggle-item))
17818 ((org-in-item-p)
17819 (call-interactively 'org-cycle-list-bullet))
17821 (call-interactively 'org-toggle-item))))
17823 (defun org-toggle-item (arg)
17824 "Convert headings or normal lines to items, items to normal lines.
17825 If there is no active region, only the current line is considered.
17827 If the first non blank line in the region is an headline, convert
17828 all headlines to items, shifting text accordingly.
17830 If it is an item, convert all items to normal lines.
17832 If it is normal text, change region into an item. With a prefix
17833 argument ARG, change each line in region into an item."
17834 (interactive "P")
17835 (let ((shift-text
17836 (function
17837 ;; Shift text in current section to IND, from point to END.
17838 ;; The function leaves point to END line.
17839 (lambda (ind end)
17840 (let ((min-i 1000) (end (copy-marker end)))
17841 ;; First determine the minimum indentation (MIN-I) of
17842 ;; the text.
17843 (save-excursion
17844 (catch 'exit
17845 (while (< (point) end)
17846 (let ((i (org-get-indentation)))
17847 (cond
17848 ;; Skip blank lines and inline tasks.
17849 ((looking-at "^[ \t]*$"))
17850 ((looking-at "^\\*+ "))
17851 ;; We can't find less than 0 indentation.
17852 ((zerop i) (throw 'exit (setq min-i 0)))
17853 ((< i min-i) (setq min-i i))))
17854 (forward-line))))
17855 ;; Then indent each line so that a line indented to
17856 ;; MIN-I becomes indented to IND. Ignore blank lines
17857 ;; and inline tasks in the process.
17858 (let ((delta (- ind min-i)))
17859 (while (< (point) end)
17860 (unless (or (looking-at "^[ \t]*$")
17861 (looking-at "^\\*+ "))
17862 (org-indent-line-to (+ (org-get-indentation) delta)))
17863 (forward-line)))))))
17864 (skip-blanks
17865 (function
17866 ;; Return beginning of first non-blank line, starting from
17867 ;; line at POS.
17868 (lambda (pos)
17869 (save-excursion
17870 (goto-char pos)
17871 (skip-chars-forward " \r\t\n")
17872 (point-at-bol)))))
17873 beg end)
17874 ;; Determine boundaries of changes.
17875 (if (org-region-active-p)
17876 (setq beg (funcall skip-blanks (region-beginning))
17877 end (copy-marker (region-end)))
17878 (setq beg (funcall skip-blanks (point-at-bol))
17879 end (copy-marker (point-at-eol))))
17880 ;; Depending on the starting line, choose an action on the text
17881 ;; between BEG and END.
17882 (org-with-limited-levels
17883 (save-excursion
17884 (goto-char beg)
17885 (cond
17886 ;; Case 1. Start at an item: de-itemize. Note that it only
17887 ;; happens when a region is active: `org-ctrl-c-minus'
17888 ;; would call `org-cycle-list-bullet' otherwise.
17889 ((org-at-item-p)
17890 (while (< (point) end)
17891 (when (org-at-item-p)
17892 (skip-chars-forward " \t")
17893 (delete-region (point) (match-end 0)))
17894 (forward-line)))
17895 ;; Case 2. Start at an heading: convert to items.
17896 ((org-on-heading-p)
17897 (let* ((bul (org-list-bullet-string "-"))
17898 (bul-len (length bul))
17899 ;; Indentation of the first heading. It should be
17900 ;; relative to the indentation of its parent, if any.
17901 (start-ind (save-excursion
17902 (cond
17903 ((not org-adapt-indentation) 0)
17904 ((not (outline-previous-heading)) 0)
17905 (t (length (match-string 0))))))
17906 ;; Level of first heading. Further headings will be
17907 ;; compared to it to determine hierarchy in the list.
17908 (ref-level (org-reduced-level (org-outline-level))))
17909 (while (< (point) end)
17910 (let* ((level (org-reduced-level (org-outline-level)))
17911 (delta (max 0 (- level ref-level))))
17912 ;; If current headline is less indented than the first
17913 ;; one, set it as reference, in order to preserve
17914 ;; subtrees.
17915 (when (< level ref-level) (setq ref-level level))
17916 (replace-match bul t t)
17917 (org-indent-line-to (+ start-ind (* delta bul-len)))
17918 ;; Ensure all text down to END (or SECTION-END) belongs
17919 ;; to the newly created item.
17920 (let ((section-end (save-excursion
17921 (or (outline-next-heading) (point)))))
17922 (forward-line)
17923 (funcall shift-text
17924 (+ start-ind (* (1+ delta) bul-len))
17925 (min end section-end)))))))
17926 ;; Case 3. Normal line with ARG: turn each non-item line into
17927 ;; an item.
17928 (arg
17929 (while (< (point) end)
17930 (unless (or (org-on-heading-p) (org-at-item-p))
17931 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
17932 (replace-match
17933 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
17934 (forward-line)))
17935 ;; Case 4. Normal line without ARG: make the first line of
17936 ;; region an item, and shift indentation of others
17937 ;; lines to set them as item's body.
17938 (t (let* ((bul (org-list-bullet-string "-"))
17939 (bul-len (length bul))
17940 (ref-ind (org-get-indentation)))
17941 (skip-chars-forward " \t")
17942 (insert bul)
17943 (forward-line)
17944 (while (< (point) end)
17945 ;; Ensure that lines less indented than first one
17946 ;; still get included in item body.
17947 (funcall shift-text
17948 (+ ref-ind bul-len)
17949 (min end (save-excursion (or (outline-next-heading)
17950 (point)))))
17951 (forward-line)))))))))
17953 (defun org-toggle-heading (&optional nstars)
17954 "Convert headings to normal text, or items or text to headings.
17955 If there is no active region, only the current line is considered.
17957 If the first non blank line is an headline, remove the stars from
17958 all headlines in the region.
17960 If it is a plain list item, turn all plain list items into headings.
17962 If it is a normal line, turn each and every normal line (i.e. not
17963 an heading or an item) in the region into a heading.
17965 When converting a line into a heading, the number of stars is chosen
17966 such that the lines become children of the current entry. However,
17967 when a prefix argument is given, its value determines the number of
17968 stars to add."
17969 (interactive "P")
17970 (let ((skip-blanks
17971 (function
17972 ;; Return beginning of first non-blank line, starting from
17973 ;; line at POS.
17974 (lambda (pos)
17975 (save-excursion
17976 (goto-char pos)
17977 (skip-chars-forward " \r\t\n")
17978 (point-at-bol)))))
17979 beg end)
17980 ;; Determine boundaries of changes. If region ends at a bol, do
17981 ;; not consider the last line to be in the region.
17982 (if (org-region-active-p)
17983 (setq beg (funcall skip-blanks (region-beginning))
17984 end (copy-marker (save-excursion
17985 (goto-char (region-end))
17986 (if (bolp) (point) (point-at-eol)))))
17987 (setq beg (funcall skip-blanks (point-at-bol))
17988 end (copy-marker (point-at-eol))))
17989 ;; Ensure inline tasks don't count as headings.
17990 (org-with-limited-levels
17991 (save-excursion
17992 (goto-char beg)
17993 (cond
17994 ;; Case 1. Started at an heading: de-star headings.
17995 ((org-on-heading-p)
17996 (while (< (point) end)
17997 (when (org-on-heading-p t)
17998 (looking-at outline-regexp) (replace-match ""))
17999 (forward-line)))
18000 ;; Case 2. Started at an item: change items into headlines.
18001 ;; One star will be added by `org-list-to-subtree'.
18002 ((org-at-item-p)
18003 (let* ((stars (make-string
18004 (if nstars
18005 ;; subtract the star that will be added again by
18006 ;; `org-list-to-subtree'
18007 (1- (prefix-numeric-value current-prefix-arg))
18008 (or (org-current-level) 0))
18009 ?*))
18010 (add-stars
18011 (cond (nstars "") ; stars from prefix only
18012 ((equal stars "") "") ; before first heading
18013 (org-odd-levels-only "*") ; inside heading, odd
18014 (t "")))) ; inside heading, oddeven
18015 (while (< (point) end)
18016 (when (org-at-item-p)
18017 ;; Pay attention to cases when region ends before list.
18018 (let* ((struct (org-list-struct))
18019 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18020 (save-restriction
18021 (narrow-to-region (point) list-end)
18022 (insert
18023 (org-list-to-subtree
18024 (org-list-parse-list t)
18025 '(:istart (concat stars add-stars (funcall get-stars depth))
18026 :icount (concat stars add-stars (funcall get-stars depth))))))))
18027 (forward-line))))
18028 ;; Case 3. Started at normal text: make every line an heading,
18029 ;; skipping headlines and items.
18030 (t (let* ((stars (make-string
18031 (if nstars
18032 (prefix-numeric-value current-prefix-arg)
18033 (or (org-current-level) 0))
18034 ?*))
18035 (add-stars
18036 (cond (nstars "") ; stars from prefix only
18037 ((equal stars "") "*") ; before first heading
18038 (org-odd-levels-only "**") ; inside heading, odd
18039 (t "*"))) ; inside heading, oddeven
18040 (rpl (concat stars add-stars " ")))
18041 (while (< (point) end)
18042 (when (and (not (org-on-heading-p)) (not (org-at-item-p))
18043 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18044 (replace-match (concat rpl (match-string 2))))
18045 (forward-line)))))))))
18047 (defun org-meta-return (&optional arg)
18048 "Insert a new heading or wrap a region in a table.
18049 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18050 See the individual commands for more information."
18051 (interactive "P")
18052 (cond
18053 ((run-hook-with-args-until-success 'org-metareturn-hook))
18054 ((org-at-table-p)
18055 (call-interactively 'org-table-wrap-region))
18056 (t (call-interactively 'org-insert-heading))))
18058 ;;; Menu entries
18060 ;; Define the Org-mode menus
18061 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18062 '("Tbl"
18063 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18064 ["Next Field" org-cycle (org-at-table-p)]
18065 ["Previous Field" org-shifttab (org-at-table-p)]
18066 ["Next Row" org-return (org-at-table-p)]
18067 "--"
18068 ["Blank Field" org-table-blank-field (org-at-table-p)]
18069 ["Edit Field" org-table-edit-field (org-at-table-p)]
18070 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18071 "--"
18072 ("Column"
18073 ["Move Column Left" org-metaleft (org-at-table-p)]
18074 ["Move Column Right" org-metaright (org-at-table-p)]
18075 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18076 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18077 ("Row"
18078 ["Move Row Up" org-metaup (org-at-table-p)]
18079 ["Move Row Down" org-metadown (org-at-table-p)]
18080 ["Delete Row" org-shiftmetaup (org-at-table-p)]
18081 ["Insert Row" org-shiftmetadown (org-at-table-p)]
18082 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
18083 "--"
18084 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
18085 ("Rectangle"
18086 ["Copy Rectangle" org-copy-special (org-at-table-p)]
18087 ["Cut Rectangle" org-cut-special (org-at-table-p)]
18088 ["Paste Rectangle" org-paste-special (org-at-table-p)]
18089 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
18090 "--"
18091 ("Calculate"
18092 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
18093 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
18094 ["Edit Formulas" org-edit-special (org-at-table-p)]
18095 "--"
18096 ["Recalculate line" org-table-recalculate (org-at-table-p)]
18097 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
18098 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
18099 "--"
18100 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
18101 "--"
18102 ["Sum Column/Rectangle" org-table-sum
18103 (or (org-at-table-p) (org-region-active-p))]
18104 ["Which Column?" org-table-current-column (org-at-table-p)])
18105 ["Debug Formulas"
18106 org-table-toggle-formula-debugger
18107 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
18108 ["Show Col/Row Numbers"
18109 org-table-toggle-coordinate-overlays
18110 :style toggle
18111 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
18112 "--"
18113 ["Create" org-table-create (and (not (org-at-table-p))
18114 org-enable-table-editor)]
18115 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
18116 ["Import from File" org-table-import (not (org-at-table-p))]
18117 ["Export to File" org-table-export (org-at-table-p)]
18118 "--"
18119 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
18121 (easy-menu-define org-org-menu org-mode-map "Org menu"
18122 '("Org"
18123 ("Show/Hide"
18124 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
18125 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
18126 ["Sparse Tree..." org-sparse-tree t]
18127 ["Reveal Context" org-reveal t]
18128 ["Show All" show-all t]
18129 "--"
18130 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
18131 "--"
18132 ["New Heading" org-insert-heading t]
18133 ("Navigate Headings"
18134 ["Up" outline-up-heading t]
18135 ["Next" outline-next-visible-heading t]
18136 ["Previous" outline-previous-visible-heading t]
18137 ["Next Same Level" outline-forward-same-level t]
18138 ["Previous Same Level" outline-backward-same-level t]
18139 "--"
18140 ["Jump" org-goto t])
18141 ("Edit Structure"
18142 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
18143 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
18144 "--"
18145 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
18146 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
18147 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
18148 "--"
18149 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
18150 "--"
18151 ["Promote Heading" org-metaleft (not (org-at-table-p))]
18152 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
18153 ["Demote Heading" org-metaright (not (org-at-table-p))]
18154 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
18155 "--"
18156 ["Sort Region/Children" org-sort (not (org-at-table-p))]
18157 "--"
18158 ["Convert to odd levels" org-convert-to-odd-levels t]
18159 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
18160 ("Editing"
18161 ["Emphasis..." org-emphasize t]
18162 ["Edit Source Example" org-edit-special t]
18163 "--"
18164 ["Footnote new/jump" org-footnote-action t]
18165 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
18166 ("Archive"
18167 ["Archive (default method)" org-archive-subtree-default t]
18168 "--"
18169 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
18170 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
18171 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
18173 "--"
18174 ("Hyperlinks"
18175 ["Store Link (Global)" org-store-link t]
18176 ["Find existing link to here" org-occur-link-in-agenda-files t]
18177 ["Insert Link" org-insert-link t]
18178 ["Follow Link" org-open-at-point t]
18179 "--"
18180 ["Next link" org-next-link t]
18181 ["Previous link" org-previous-link t]
18182 "--"
18183 ["Descriptive Links"
18184 (progn (add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
18185 :style radio
18186 :selected (member '(org-link) buffer-invisibility-spec)]
18187 ["Literal Links"
18188 (progn
18189 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
18190 :style radio
18191 :selected (not (member '(org-link) buffer-invisibility-spec))])
18192 "--"
18193 ("TODO Lists"
18194 ["TODO/DONE/-" org-todo t]
18195 ("Select keyword"
18196 ["Next keyword" org-shiftright (org-on-heading-p)]
18197 ["Previous keyword" org-shiftleft (org-on-heading-p)]
18198 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
18199 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
18200 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
18201 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
18202 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
18203 "--"
18204 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
18205 :selected org-enforce-todo-dependencies :style toggle :active t]
18206 "Settings for tree at point"
18207 ["Do Children sequentially" org-toggle-ordered-property :style radio
18208 :selected (org-entry-get nil "ORDERED")
18209 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18210 ["Do Children parallel" org-toggle-ordered-property :style radio
18211 :selected (not (org-entry-get nil "ORDERED"))
18212 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18213 "--"
18214 ["Set Priority" org-priority t]
18215 ["Priority Up" org-shiftup t]
18216 ["Priority Down" org-shiftdown t]
18217 "--"
18218 ["Get news from all feeds" org-feed-update-all t]
18219 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
18220 ["Customize feeds" (customize-variable 'org-feed-alist) t])
18221 ("TAGS and Properties"
18222 ["Set Tags" org-set-tags-command t]
18223 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
18224 "--"
18225 ["Set property" org-set-property t]
18226 ["Column view of properties" org-columns t]
18227 ["Insert Column View DBlock" org-insert-columns-dblock t])
18228 ("Dates and Scheduling"
18229 ["Timestamp" org-time-stamp t]
18230 ["Timestamp (inactive)" org-time-stamp-inactive t]
18231 ("Change Date"
18232 ["1 Day Later" org-shiftright t]
18233 ["1 Day Earlier" org-shiftleft t]
18234 ["1 ... Later" org-shiftup t]
18235 ["1 ... Earlier" org-shiftdown t])
18236 ["Compute Time Range" org-evaluate-time-range t]
18237 ["Schedule Item" org-schedule t]
18238 ["Deadline" org-deadline t]
18239 "--"
18240 ["Custom time format" org-toggle-time-stamp-overlays
18241 :style radio :selected org-display-custom-times]
18242 "--"
18243 ["Goto Calendar" org-goto-calendar t]
18244 ["Date from Calendar" org-date-from-calendar t]
18245 "--"
18246 ["Start/Restart Timer" org-timer-start t]
18247 ["Pause/Continue Timer" org-timer-pause-or-continue t]
18248 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
18249 ["Insert Timer String" org-timer t]
18250 ["Insert Timer Item" org-timer-item t])
18251 ("Logging work"
18252 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
18253 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
18254 ["Clock out" org-clock-out t]
18255 ["Clock cancel" org-clock-cancel t]
18256 "--"
18257 ["Mark as default task" org-clock-mark-default-task t]
18258 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
18259 ["Goto running clock" org-clock-goto t]
18260 "--"
18261 ["Display times" org-clock-display t]
18262 ["Create clock table" org-clock-report t]
18263 "--"
18264 ["Record DONE time"
18265 (progn (setq org-log-done (not org-log-done))
18266 (message "Switching to %s will %s record a timestamp"
18267 (car org-done-keywords)
18268 (if org-log-done "automatically" "not")))
18269 :style toggle :selected org-log-done])
18270 "--"
18271 ["Agenda Command..." org-agenda t]
18272 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
18273 ("File List for Agenda")
18274 ("Special views current file"
18275 ["TODO Tree" org-show-todo-tree t]
18276 ["Check Deadlines" org-check-deadlines t]
18277 ["Timeline" org-timeline t]
18278 ["Tags/Property tree" org-match-sparse-tree t])
18279 "--"
18280 ["Export/Publish..." org-export t]
18281 ("LaTeX"
18282 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
18283 :selected org-cdlatex-mode]
18284 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
18285 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
18286 ["Modify math symbol" org-cdlatex-math-modify
18287 (org-inside-LaTeX-fragment-p)]
18288 ["Insert citation" org-reftex-citation t]
18289 "--"
18290 ["Template for BEAMER" org-insert-beamer-options-template t])
18291 "--"
18292 ("MobileOrg"
18293 ["Push Files and Views" org-mobile-push t]
18294 ["Get Captured and Flagged" org-mobile-pull t]
18295 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
18296 "--"
18297 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
18298 "--"
18299 ("Documentation"
18300 ["Show Version" org-version t]
18301 ["Info Documentation" org-info t])
18302 ("Customize"
18303 ["Browse Org Group" org-customize t]
18304 "--"
18305 ["Expand This Menu" org-create-customize-menu
18306 (fboundp 'customize-menu-create)])
18307 ["Send bug report" org-submit-bug-report t]
18308 "--"
18309 ("Refresh/Reload"
18310 ["Refresh setup current buffer" org-mode-restart t]
18311 ["Reload Org (after update)" org-reload t]
18312 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
18315 (defun org-info (&optional node)
18316 "Read documentation for Org-mode in the info system.
18317 With optional NODE, go directly to that node."
18318 (interactive)
18319 (info (format "(org)%s" (or node ""))))
18321 ;;;###autoload
18322 (defun org-submit-bug-report ()
18323 "Submit a bug report on Org-mode via mail.
18325 Don't hesitate to report any problems or inaccurate documentation.
18327 If you don't have setup sending mail from (X)Emacs, please copy the
18328 output buffer into your mail program, as it gives us important
18329 information about your Org-mode version and configuration."
18330 (interactive)
18331 (require 'reporter)
18332 (org-load-modules-maybe)
18333 (org-require-autoloaded-modules)
18334 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
18335 (reporter-submit-bug-report
18336 "emacs-orgmode@gnu.org"
18337 (org-version)
18338 (let (list)
18339 (save-window-excursion
18340 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
18341 (delete-other-windows)
18342 (erase-buffer)
18343 (insert "You are about to submit a bug report to the Org-mode mailing list.
18345 We would like to add your full Org-mode and Outline configuration to the
18346 bug report. This greatly simplifies the work of the maintainer and
18347 other experts on the mailing list.
18349 HOWEVER, some variables you have customized may contain private
18350 information. The names of customers, colleagues, or friends, might
18351 appear in the form of file names, tags, todo states, or search strings.
18352 If you answer yes to the prompt, you might want to check and remove
18353 such private information before sending the email.")
18354 (add-text-properties (point-min) (point-max) '(face org-warning))
18355 (when (yes-or-no-p "Include your Org-mode configuration ")
18356 (mapatoms
18357 (lambda (v)
18358 (and (boundp v)
18359 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
18360 (or (and (symbol-value v)
18361 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
18362 (and
18363 (get v 'custom-type) (get v 'standard-value)
18364 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
18365 (push v list)))))
18366 (kill-buffer (get-buffer "*Warn about privacy*"))
18367 list))
18368 nil nil
18369 "Remember to cover the basics, that is, what you expected to happen and
18370 what in fact did happen. You don't know how to make a good report? See
18372 http://orgmode.org/manual/Feedback.html#Feedback
18374 Your bug report will be posted to the Org-mode mailing list.
18375 ------------------------------------------------------------------------")
18376 (save-excursion
18377 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
18378 (replace-match "\\1Bug: \\3 [\\2]")))))
18381 (defun org-install-agenda-files-menu ()
18382 (let ((bl (buffer-list)))
18383 (save-excursion
18384 (while bl
18385 (set-buffer (pop bl))
18386 (if (org-mode-p) (setq bl nil)))
18387 (when (org-mode-p)
18388 (easy-menu-change
18389 '("Org") "File List for Agenda"
18390 (append
18391 (list
18392 ["Edit File List" (org-edit-agenda-file-list) t]
18393 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
18394 ["Remove Current File from List" org-remove-file t]
18395 ["Cycle through agenda files" org-cycle-agenda-files t]
18396 ["Occur in all agenda files" org-occur-in-agenda-files t]
18397 "--")
18398 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
18400 ;;;; Documentation
18402 ;;;###autoload
18403 (defun org-require-autoloaded-modules ()
18404 (interactive)
18405 (mapc 'require
18406 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
18407 org-docbook org-exp org-html org-icalendar
18408 org-id org-latex
18409 org-publish org-remember org-table
18410 org-timer org-xoxo)))
18412 ;;;###autoload
18413 (defun org-reload (&optional uncompiled)
18414 "Reload all org lisp files.
18415 With prefix arg UNCOMPILED, load the uncompiled versions."
18416 (interactive "P")
18417 (require 'find-func)
18418 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
18419 (dir-org (file-name-directory (org-find-library-name "org")))
18420 (dir-org-contrib (ignore-errors
18421 (file-name-directory
18422 (org-find-library-name "org-contribdir"))))
18423 (babel-files
18424 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
18425 (append (list nil "comint" "eval" "exp" "keys"
18426 "lob" "ref" "table" "tangle")
18427 (delq nil
18428 (mapcar
18429 (lambda (lang)
18430 (when (cdr lang) (symbol-name (car lang))))
18431 org-babel-load-languages)))))
18432 (files
18433 (append (directory-files dir-org t file-re)
18434 babel-files
18435 (and dir-org-contrib
18436 (directory-files dir-org-contrib t file-re))))
18437 (remove-re (concat (if (featurep 'xemacs)
18438 "org-colview" "org-colview-xemacs")
18439 "\\'")))
18440 (setq files (mapcar 'file-name-sans-extension files))
18441 (setq files (mapcar
18442 (lambda (x) (if (string-match remove-re x) nil x))
18443 files))
18444 (setq files (delq nil files))
18445 (mapc
18446 (lambda (f)
18447 (when (featurep (intern (file-name-nondirectory f)))
18448 (if (and (not uncompiled)
18449 (file-exists-p (concat f ".elc")))
18450 (load (concat f ".elc") nil nil t)
18451 (load (concat f ".el") nil nil t))))
18452 files))
18453 (org-version))
18455 ;;;###autoload
18456 (defun org-customize ()
18457 "Call the customize function with org as argument."
18458 (interactive)
18459 (org-load-modules-maybe)
18460 (org-require-autoloaded-modules)
18461 (customize-browse 'org))
18463 (defun org-create-customize-menu ()
18464 "Create a full customization menu for Org-mode, insert it into the menu."
18465 (interactive)
18466 (org-load-modules-maybe)
18467 (org-require-autoloaded-modules)
18468 (if (fboundp 'customize-menu-create)
18469 (progn
18470 (easy-menu-change
18471 '("Org") "Customize"
18472 `(["Browse Org group" org-customize t]
18473 "--"
18474 ,(customize-menu-create 'org)
18475 ["Set" Custom-set t]
18476 ["Save" Custom-save t]
18477 ["Reset to Current" Custom-reset-current t]
18478 ["Reset to Saved" Custom-reset-saved t]
18479 ["Reset to Standard Settings" Custom-reset-standard t]))
18480 (message "\"Org\"-menu now contains full customization menu"))
18481 (error "Cannot expand menu (outdated version of cus-edit.el)")))
18483 ;;;; Miscellaneous stuff
18485 ;;; Generally useful functions
18487 (defun org-get-at-bol (property)
18488 "Get text property PROPERTY at beginning of line."
18489 (get-text-property (point-at-bol) property))
18491 (defun org-find-text-property-in-string (prop s)
18492 "Return the first non-nil value of property PROP in string S."
18493 (or (get-text-property 0 prop s)
18494 (get-text-property (or (next-single-property-change 0 prop s) 0)
18495 prop s)))
18497 (defun org-display-warning (message) ;; Copied from Emacs-Muse
18498 "Display the given MESSAGE as a warning."
18499 (if (fboundp 'display-warning)
18500 (display-warning 'org message
18501 (if (featurep 'xemacs) 'warning :warning))
18502 (let ((buf (get-buffer-create "*Org warnings*")))
18503 (with-current-buffer buf
18504 (goto-char (point-max))
18505 (insert "Warning (Org): " message)
18506 (unless (bolp)
18507 (newline)))
18508 (display-buffer buf)
18509 (sit-for 0))))
18511 (defun org-eval (form)
18512 "Eval FORM and return result."
18513 (condition-case error
18514 (eval form)
18515 (error (format "%%![Error: %s]" error))))
18517 (defun org-in-commented-line ()
18518 "Is point in a line starting with `#'?"
18519 (equal (char-after (point-at-bol)) ?#))
18521 (defun org-in-indented-comment-line ()
18522 "Is point in a line starting with `#' after some white space?"
18523 (save-excursion
18524 (save-match-data
18525 (goto-char (point-at-bol))
18526 (looking-at "[ \t]*#"))))
18528 (defun org-in-verbatim-emphasis ()
18529 (save-match-data
18530 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
18532 (defun org-goto-marker-or-bmk (marker &optional bookmark)
18533 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
18534 (if (and marker (marker-buffer marker)
18535 (buffer-live-p (marker-buffer marker)))
18536 (progn
18537 (switch-to-buffer (marker-buffer marker))
18538 (if (or (> marker (point-max)) (< marker (point-min)))
18539 (widen))
18540 (goto-char marker)
18541 (org-show-context 'org-goto))
18542 (if bookmark
18543 (bookmark-jump bookmark)
18544 (error "Cannot find location"))))
18546 (defun org-quote-csv-field (s)
18547 "Quote field for inclusion in CSV material."
18548 (if (string-match "[\",]" s)
18549 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
18552 (defun org-force-self-insert (N)
18553 "Needed to enforce self-insert under remapping."
18554 (interactive "p")
18555 (self-insert-command N))
18557 (defun org-string-width (s)
18558 "Compute width of string, ignoring invisible characters.
18559 This ignores character with invisibility property `org-link', and also
18560 characters with property `org-cwidth', because these will become invisible
18561 upon the next fontification round."
18562 (let (b l)
18563 (when (or (eq t buffer-invisibility-spec)
18564 (assq 'org-link buffer-invisibility-spec))
18565 (while (setq b (text-property-any 0 (length s)
18566 'invisible 'org-link s))
18567 (setq s (concat (substring s 0 b)
18568 (substring s (or (next-single-property-change
18569 b 'invisible s) (length s)))))))
18570 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
18571 (setq s (concat (substring s 0 b)
18572 (substring s (or (next-single-property-change
18573 b 'org-cwidth s) (length s))))))
18574 (setq l (string-width s) b -1)
18575 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
18576 (setq l (- l (get-text-property b 'org-dwidth-n s))))
18579 (defun org-shorten-string (s maxlength)
18580 "Shorten string S so tht it is no longer than MAXLENGTH characters.
18581 If the string is shorter or has length MAXLENGTH, just return the
18582 original string. If it is longer, the functions finds a space in the
18583 string, breaks this string off at that locations and adds three dots
18584 as ellipsis. Including the ellipsis, the string will not be longer
18585 than MAXLENGTH. If finding a good breaking point in the string does
18586 not work, the string is just chopped off in the middle of a word
18587 if necessary."
18588 (if (<= (length s) maxlength)
18590 (let* ((n (max (- maxlength 4) 1))
18591 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
18592 (if (string-match re s)
18593 (concat (match-string 1 s) "...")
18594 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
18596 (defun org-get-indentation (&optional line)
18597 "Get the indentation of the current line, interpreting tabs.
18598 When LINE is given, assume it represents a line and compute its indentation."
18599 (if line
18600 (if (string-match "^ *" (org-remove-tabs line))
18601 (match-end 0))
18602 (save-excursion
18603 (beginning-of-line 1)
18604 (skip-chars-forward " \t")
18605 (current-column))))
18607 (defun org-get-string-indentation (s)
18608 "What indentation has S due to SPACE and TAB at the beginning of the string?"
18609 (let ((n -1) (i 0) (w tab-width) c)
18610 (catch 'exit
18611 (while (< (setq n (1+ n)) (length s))
18612 (setq c (aref s n))
18613 (cond ((= c ?\ ) (setq i (1+ i)))
18614 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
18615 (t (throw 'exit t)))))
18618 (defun org-remove-tabs (s &optional width)
18619 "Replace tabulators in S with spaces.
18620 Assumes that s is a single line, starting in column 0."
18621 (setq width (or width tab-width))
18622 (while (string-match "\t" s)
18623 (setq s (replace-match
18624 (make-string
18625 (- (* width (/ (+ (match-beginning 0) width) width))
18626 (match-beginning 0)) ?\ )
18627 t t s)))
18630 (defun org-fix-indentation (line ind)
18631 "Fix indentation in LINE.
18632 IND is a cons cell with target and minimum indentation.
18633 If the current indentation in LINE is smaller than the minimum,
18634 leave it alone. If it is larger than ind, set it to the target."
18635 (let* ((l (org-remove-tabs line))
18636 (i (org-get-indentation l))
18637 (i1 (car ind)) (i2 (cdr ind)))
18638 (if (>= i i2) (setq l (substring line i2)))
18639 (if (> i1 0)
18640 (concat (make-string i1 ?\ ) l)
18641 l)))
18643 (defun org-remove-indentation (code &optional n)
18644 "Remove the maximum common indentation from the lines in CODE.
18645 N may optionally be the number of spaces to remove."
18646 (with-temp-buffer
18647 (insert code)
18648 (org-do-remove-indentation n)
18649 (buffer-string)))
18651 (defun org-do-remove-indentation (&optional n)
18652 "Remove the maximum common indentation from the buffer."
18653 (untabify (point-min) (point-max))
18654 (let ((min 10000) re)
18655 (if n
18656 (setq min n)
18657 (goto-char (point-min))
18658 (while (re-search-forward "^ *[^ \n]" nil t)
18659 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
18660 (unless (or (= min 0) (= min 10000))
18661 (setq re (format "^ \\{%d\\}" min))
18662 (goto-char (point-min))
18663 (while (re-search-forward re nil t)
18664 (replace-match "")
18665 (end-of-line 1))
18666 min)))
18668 (defun org-fill-template (template alist)
18669 "Find each %key of ALIST in TEMPLATE and replace it."
18670 (let ((case-fold-search nil)
18671 entry key value)
18672 (setq alist (sort (copy-sequence alist)
18673 (lambda (a b) (< (length (car a)) (length (car b))))))
18674 (while (setq entry (pop alist))
18675 (setq template
18676 (replace-regexp-in-string
18677 (concat "%" (regexp-quote (car entry)))
18678 (cdr entry) template t t)))
18679 template))
18681 (defun org-base-buffer (buffer)
18682 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
18683 (if (not buffer)
18684 buffer
18685 (or (buffer-base-buffer buffer)
18686 buffer)))
18688 (defun org-trim (s)
18689 "Remove whitespace at beginning and end of string."
18690 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
18691 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
18694 (defun org-wrap (string &optional width lines)
18695 "Wrap string to either a number of lines, or a width in characters.
18696 If WIDTH is non-nil, the string is wrapped to that width, however many lines
18697 that costs. If there is a word longer than WIDTH, the text is actually
18698 wrapped to the length of that word.
18699 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
18700 many lines, whatever width that takes.
18701 The return value is a list of lines, without newlines at the end."
18702 (let* ((words (org-split-string string "[ \t\n]+"))
18703 (maxword (apply 'max (mapcar 'org-string-width words)))
18704 w ll)
18705 (cond (width
18706 (org-do-wrap words (max maxword width)))
18707 (lines
18708 (setq w maxword)
18709 (setq ll (org-do-wrap words maxword))
18710 (if (<= (length ll) lines)
18712 (setq ll words)
18713 (while (> (length ll) lines)
18714 (setq w (1+ w))
18715 (setq ll (org-do-wrap words w)))
18716 ll))
18717 (t (error "Cannot wrap this")))))
18719 (defun org-do-wrap (words width)
18720 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
18721 (let (lines line)
18722 (while words
18723 (setq line (pop words))
18724 (while (and words (< (+ (length line) (length (car words))) width))
18725 (setq line (concat line " " (pop words))))
18726 (setq lines (push line lines)))
18727 (nreverse lines)))
18729 (defun org-split-string (string &optional separators)
18730 "Splits STRING into substrings at SEPARATORS.
18731 No empty strings are returned if there are matches at the beginning
18732 and end of string."
18733 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
18734 (start 0)
18735 notfirst
18736 (list nil))
18737 (while (and (string-match rexp string
18738 (if (and notfirst
18739 (= start (match-beginning 0))
18740 (< start (length string)))
18741 (1+ start) start))
18742 (< (match-beginning 0) (length string)))
18743 (setq notfirst t)
18744 (or (eq (match-beginning 0) 0)
18745 (and (eq (match-beginning 0) (match-end 0))
18746 (eq (match-beginning 0) start))
18747 (setq list
18748 (cons (substring string start (match-beginning 0))
18749 list)))
18750 (setq start (match-end 0)))
18751 (or (eq start (length string))
18752 (setq list
18753 (cons (substring string start)
18754 list)))
18755 (nreverse list)))
18757 (defun org-quote-vert (s)
18758 "Replace \"|\" with \"\\vert\"."
18759 (while (string-match "|" s)
18760 (setq s (replace-match "\\vert" t t s)))
18763 (defun org-uuidgen-p (s)
18764 "Is S an ID created by UUIDGEN?"
18765 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
18767 (defun org-context ()
18768 "Return a list of contexts of the current cursor position.
18769 If several contexts apply, all are returned.
18770 Each context entry is a list with a symbol naming the context, and
18771 two positions indicating start and end of the context. Possible
18772 contexts are:
18774 :headline anywhere in a headline
18775 :headline-stars on the leading stars in a headline
18776 :todo-keyword on a TODO keyword (including DONE) in a headline
18777 :tags on the TAGS in a headline
18778 :priority on the priority cookie in a headline
18779 :item on the first line of a plain list item
18780 :item-bullet on the bullet/number of a plain list item
18781 :checkbox on the checkbox in a plain list item
18782 :table in an org-mode table
18783 :table-special on a special filed in a table
18784 :table-table in a table.el table
18785 :link on a hyperlink
18786 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
18787 :target on a <<target>>
18788 :radio-target on a <<<radio-target>>>
18789 :latex-fragment on a LaTeX fragment
18790 :latex-preview on a LaTeX fragment with overlayed preview image
18792 This function expects the position to be visible because it uses font-lock
18793 faces as a help to recognize the following contexts: :table-special, :link,
18794 and :keyword."
18795 (let* ((f (get-text-property (point) 'face))
18796 (faces (if (listp f) f (list f)))
18797 (p (point)) clist o)
18798 ;; First the large context
18799 (cond
18800 ((org-on-heading-p t)
18801 (push (list :headline (point-at-bol) (point-at-eol)) clist)
18802 (when (progn
18803 (beginning-of-line 1)
18804 (looking-at org-todo-line-tags-regexp))
18805 (push (org-point-in-group p 1 :headline-stars) clist)
18806 (push (org-point-in-group p 2 :todo-keyword) clist)
18807 (push (org-point-in-group p 4 :tags) clist))
18808 (goto-char p)
18809 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
18810 (if (looking-at "\\[#[A-Z0-9]\\]")
18811 (push (org-point-in-group p 0 :priority) clist)))
18813 ((org-at-item-p)
18814 (push (org-point-in-group p 2 :item-bullet) clist)
18815 (push (list :item (point-at-bol)
18816 (save-excursion (org-end-of-item) (point)))
18817 clist)
18818 (and (org-at-item-checkbox-p)
18819 (push (org-point-in-group p 0 :checkbox) clist)))
18821 ((org-at-table-p)
18822 (push (list :table (org-table-begin) (org-table-end)) clist)
18823 (if (memq 'org-formula faces)
18824 (push (list :table-special
18825 (previous-single-property-change p 'face)
18826 (next-single-property-change p 'face)) clist)))
18827 ((org-at-table-p 'any)
18828 (push (list :table-table) clist)))
18829 (goto-char p)
18831 ;; Now the small context
18832 (cond
18833 ((org-at-timestamp-p)
18834 (push (org-point-in-group p 0 :timestamp) clist))
18835 ((memq 'org-link faces)
18836 (push (list :link
18837 (previous-single-property-change p 'face)
18838 (next-single-property-change p 'face)) clist))
18839 ((memq 'org-special-keyword faces)
18840 (push (list :keyword
18841 (previous-single-property-change p 'face)
18842 (next-single-property-change p 'face)) clist))
18843 ((org-on-target-p)
18844 (push (org-point-in-group p 0 :target) clist)
18845 (goto-char (1- (match-beginning 0)))
18846 (if (looking-at org-radio-target-regexp)
18847 (push (org-point-in-group p 0 :radio-target) clist))
18848 (goto-char p))
18849 ((setq o (car (delq nil
18850 (mapcar
18851 (lambda (x)
18852 (if (memq x org-latex-fragment-image-overlays) x))
18853 (overlays-at (point))))))
18854 (push (list :latex-fragment
18855 (overlay-start o) (overlay-end o)) clist)
18856 (push (list :latex-preview
18857 (overlay-start o) (overlay-end o)) clist))
18858 ((org-inside-LaTeX-fragment-p)
18859 ;; FIXME: positions wrong.
18860 (push (list :latex-fragment (point) (point)) clist)))
18862 (setq clist (nreverse (delq nil clist)))
18863 clist))
18865 ;; FIXME: Compare with at-regexp-p Do we need both?
18866 (defun org-in-regexp (re &optional nlines visually)
18867 "Check if point is inside a match of regexp.
18868 Normally only the current line is checked, but you can include NLINES extra
18869 lines both before and after point into the search.
18870 If VISUALLY is set, require that the cursor is not after the match but
18871 really on, so that the block visually is on the match."
18872 (catch 'exit
18873 (let ((pos (point))
18874 (eol (point-at-eol (+ 1 (or nlines 0))))
18875 (inc (if visually 1 0)))
18876 (save-excursion
18877 (beginning-of-line (- 1 (or nlines 0)))
18878 (while (re-search-forward re eol t)
18879 (if (and (<= (match-beginning 0) pos)
18880 (>= (+ inc (match-end 0)) pos))
18881 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
18883 (defun org-at-regexp-p (regexp)
18884 "Is point inside a match of REGEXP in the current line?"
18885 (catch 'exit
18886 (save-excursion
18887 (let ((pos (point)) (end (point-at-eol)))
18888 (beginning-of-line 1)
18889 (while (re-search-forward regexp end t)
18890 (if (and (<= (match-beginning 0) pos)
18891 (>= (match-end 0) pos))
18892 (throw 'exit t)))
18893 nil))))
18895 (defun org-in-regexps-block-p (start-re end-re &optional bound)
18896 "Return t if the current point is between matches of START-RE and END-RE.
18897 This will also return t if point is on one of the two matches or
18898 in an unfinished block. END-RE can be a string or a form
18899 returning a string.
18901 An optional third argument bounds the search for START-RE. It
18902 defaults to previous heading or `point-min'."
18903 (let ((pos (point))
18904 (limit (or bound (save-excursion (outline-previous-heading)))))
18905 (save-excursion
18906 ;; we're on a block when point is on start-re...
18907 (or (org-at-regexp-p start-re)
18908 ;; ... or start-re can be found above...
18909 (and (re-search-backward start-re limit t)
18910 ;; ... but no end-re between start-re and point.
18911 (not (re-search-forward (eval end-re) pos t)))))))
18913 (defun org-occur-in-agenda-files (regexp &optional nlines)
18914 "Call `multi-occur' with buffers for all agenda files."
18915 (interactive "sOrg-files matching: \np")
18916 (let* ((files (org-agenda-files))
18917 (tnames (mapcar 'file-truename files))
18918 (extra org-agenda-text-search-extra-files)
18920 (when (eq (car extra) 'agenda-archives)
18921 (setq extra (cdr extra))
18922 (setq files (org-add-archive-files files)))
18923 (while (setq f (pop extra))
18924 (unless (member (file-truename f) tnames)
18925 (add-to-list 'files f 'append)
18926 (add-to-list 'tnames (file-truename f) 'append)))
18927 (multi-occur
18928 (mapcar (lambda (x)
18929 (with-current-buffer
18930 (or (get-file-buffer x) (find-file-noselect x))
18931 (widen)
18932 (current-buffer)))
18933 files)
18934 regexp)))
18936 (if (boundp 'occur-mode-find-occurrence-hook)
18937 ;; Emacs 23
18938 (add-hook 'occur-mode-find-occurrence-hook
18939 (lambda ()
18940 (when (org-mode-p)
18941 (org-reveal))))
18942 ;; Emacs 22
18943 (defadvice occur-mode-goto-occurrence
18944 (after org-occur-reveal activate)
18945 (and (org-mode-p) (org-reveal)))
18946 (defadvice occur-mode-goto-occurrence-other-window
18947 (after org-occur-reveal activate)
18948 (and (org-mode-p) (org-reveal)))
18949 (defadvice occur-mode-display-occurrence
18950 (after org-occur-reveal activate)
18951 (when (org-mode-p)
18952 (let ((pos (occur-mode-find-occurrence)))
18953 (with-current-buffer (marker-buffer pos)
18954 (save-excursion
18955 (goto-char pos)
18956 (org-reveal)))))))
18958 (defun org-occur-link-in-agenda-files ()
18959 "Create a link and search for it in the agendas.
18960 The link is not stored in `org-stored-links', it is just created
18961 for the search purpose."
18962 (interactive)
18963 (let ((link (condition-case nil
18964 (org-store-link nil)
18965 (error "Unable to create a link to here"))))
18966 (org-occur-in-agenda-files (regexp-quote link))))
18968 (defun org-uniquify (list)
18969 "Remove duplicate elements from LIST."
18970 (let (res)
18971 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
18972 res))
18974 (defun org-delete-all (elts list)
18975 "Remove all elements in ELTS from LIST."
18976 (while elts
18977 (setq list (delete (pop elts) list)))
18978 list)
18980 (defun org-count (cl-item cl-seq)
18981 "Count the number of occurrences of ITEM in SEQ.
18982 Taken from `count' in cl-seq.el with all keyword arguments removed."
18983 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
18984 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
18985 (while (< cl-start cl-end)
18986 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
18987 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
18988 (setq cl-start (1+ cl-start)))
18989 cl-count))
18991 (defun org-remove-if (predicate seq)
18992 "Remove everything from SEQ that fulfills PREDICATE."
18993 (let (res e)
18994 (while seq
18995 (setq e (pop seq))
18996 (if (not (funcall predicate e)) (push e res)))
18997 (nreverse res)))
18999 (defun org-remove-if-not (predicate seq)
19000 "Remove everything from SEQ that does not fulfill PREDICATE."
19001 (let (res e)
19002 (while seq
19003 (setq e (pop seq))
19004 (if (funcall predicate e) (push e res)))
19005 (nreverse res)))
19007 (defun org-back-over-empty-lines ()
19008 "Move backwards over whitespace, to the beginning of the first empty line.
19009 Returns the number of empty lines passed."
19010 (let ((pos (point)))
19011 (if (cdr (assoc 'heading org-blank-before-new-entry))
19012 (skip-chars-backward " \t\n\r")
19013 (forward-line -1))
19014 (beginning-of-line 2)
19015 (goto-char (min (point) pos))
19016 (count-lines (point) pos)))
19018 (defun org-skip-whitespace ()
19019 (skip-chars-forward " \t\n\r"))
19021 (defun org-point-in-group (point group &optional context)
19022 "Check if POINT is in match-group GROUP.
19023 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
19024 match. If the match group does not exist or point is not inside it,
19025 return nil."
19026 (and (match-beginning group)
19027 (>= point (match-beginning group))
19028 (<= point (match-end group))
19029 (if context
19030 (list context (match-beginning group) (match-end group))
19031 t)))
19033 (defun org-switch-to-buffer-other-window (&rest args)
19034 "Switch to buffer in a second window on the current frame.
19035 In particular, do not allow pop-up frames.
19036 Returns the newly created buffer."
19037 (let (pop-up-frames special-display-buffer-names special-display-regexps
19038 special-display-function)
19039 (apply 'switch-to-buffer-other-window args)))
19041 (defun org-combine-plists (&rest plists)
19042 "Create a single property list from all plists in PLISTS.
19043 The process starts by copying the first list, and then setting properties
19044 from the other lists. Settings in the last list are the most significant
19045 ones and overrule settings in the other lists."
19046 (let ((rtn (copy-sequence (pop plists)))
19047 p v ls)
19048 (while plists
19049 (setq ls (pop plists))
19050 (while ls
19051 (setq p (pop ls) v (pop ls))
19052 (setq rtn (plist-put rtn p v))))
19053 rtn))
19055 (defun org-move-line-down (arg)
19056 "Move the current line down. With prefix argument, move it past ARG lines."
19057 (interactive "p")
19058 (let ((col (current-column))
19059 beg end pos)
19060 (beginning-of-line 1) (setq beg (point))
19061 (beginning-of-line 2) (setq end (point))
19062 (beginning-of-line (+ 1 arg))
19063 (setq pos (move-marker (make-marker) (point)))
19064 (insert (delete-and-extract-region beg end))
19065 (goto-char pos)
19066 (org-move-to-column col)))
19068 (defun org-move-line-up (arg)
19069 "Move the current line up. With prefix argument, move it past ARG lines."
19070 (interactive "p")
19071 (let ((col (current-column))
19072 beg end pos)
19073 (beginning-of-line 1) (setq beg (point))
19074 (beginning-of-line 2) (setq end (point))
19075 (beginning-of-line (- arg))
19076 (setq pos (move-marker (make-marker) (point)))
19077 (insert (delete-and-extract-region beg end))
19078 (goto-char pos)
19079 (org-move-to-column col)))
19081 (defun org-replace-escapes (string table)
19082 "Replace %-escapes in STRING with values in TABLE.
19083 TABLE is an association list with keys like \"%a\" and string values.
19084 The sequences in STRING may contain normal field width and padding information,
19085 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
19086 so values can contain further %-escapes if they are define later in TABLE."
19087 (let ((tbl (copy-alist table))
19088 (case-fold-search nil)
19089 (pchg 0)
19090 e re rpl)
19091 (while (setq e (pop tbl))
19092 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
19093 (when (and (cdr e) (string-match re (cdr e)))
19094 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
19095 (safe "SREF"))
19096 (add-text-properties 0 3 (list 'sref sref) safe)
19097 (setcdr e (replace-match safe t t (cdr e)))))
19098 (while (string-match re string)
19099 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
19100 (cdr e)))
19101 (setq string (replace-match rpl t t string))))
19102 (while (setq pchg (next-property-change pchg string))
19103 (let ((sref (get-text-property pchg 'sref string)))
19104 (when (and sref (string-match "SREF" string pchg))
19105 (setq string (replace-match sref t t string)))))
19106 string))
19108 (defun org-sublist (list start end)
19109 "Return a section of LIST, from START to END.
19110 Counting starts at 1."
19111 (let (rtn (c start))
19112 (setq list (nthcdr (1- start) list))
19113 (while (and list (<= c end))
19114 (push (pop list) rtn)
19115 (setq c (1+ c)))
19116 (nreverse rtn)))
19118 (defun org-find-base-buffer-visiting (file)
19119 "Like `find-buffer-visiting' but always return the base buffer and
19120 not an indirect buffer."
19121 (let ((buf (or (get-file-buffer file)
19122 (find-buffer-visiting file))))
19123 (if buf
19124 (or (buffer-base-buffer buf) buf)
19125 nil)))
19127 (defun org-image-file-name-regexp (&optional extensions)
19128 "Return regexp matching the file names of images.
19129 If EXTENSIONS is given, only match these."
19130 (if (and (not extensions) (fboundp 'image-file-name-regexp))
19131 (image-file-name-regexp)
19132 (let ((image-file-name-extensions
19133 (or extensions
19134 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
19135 "xbm" "xpm" "pbm" "pgm" "ppm"))))
19136 (concat "\\."
19137 (regexp-opt (nconc (mapcar 'upcase
19138 image-file-name-extensions)
19139 image-file-name-extensions)
19141 "\\'"))))
19143 (defun org-file-image-p (file &optional extensions)
19144 "Return non-nil if FILE is an image."
19145 (save-match-data
19146 (string-match (org-image-file-name-regexp extensions) file)))
19148 (defun org-get-cursor-date ()
19149 "Return the date at cursor in as a time.
19150 This works in the calendar and in the agenda, anywhere else it just
19151 returns the current time."
19152 (let (date day defd)
19153 (cond
19154 ((eq major-mode 'calendar-mode)
19155 (setq date (calendar-cursor-to-date)
19156 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
19157 ((eq major-mode 'org-agenda-mode)
19158 (setq day (get-text-property (point) 'day))
19159 (if day
19160 (setq date (calendar-gregorian-from-absolute day)
19161 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
19162 (nth 2 date))))))
19163 (or defd (current-time))))
19165 (defvar org-agenda-action-marker (make-marker)
19166 "Marker pointing to the entry for the next agenda action.")
19168 (defun org-mark-entry-for-agenda-action ()
19169 "Mark the current entry as target of an agenda action.
19170 Agenda actions are actions executed from the agenda with the key `k',
19171 which make use of the date at the cursor."
19172 (interactive)
19173 (move-marker org-agenda-action-marker
19174 (save-excursion (org-back-to-heading t) (point))
19175 (current-buffer))
19176 (message
19177 "Entry marked for action; press `k' at desired date in agenda or calendar"))
19179 (defun org-mark-subtree ()
19180 "Mark the current subtree.
19181 This puts point at the start of the current subtree, and mark at the end.
19183 If point is in an inline task, mark that task instead."
19184 (interactive)
19185 (let ((inline-task-p
19186 (and (featurep 'org-inlinetask)
19187 (org-inlinetask-in-task-p)))
19188 (beg))
19189 ;; Get beginning of subtree
19190 (cond
19191 (inline-task-p (org-inlinetask-goto-beginning))
19192 ((org-at-heading-p) (beginning-of-line))
19193 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
19194 (setq beg (point))
19195 ;; Get end of it
19196 (if inline-task-p
19197 (org-inlinetask-goto-end)
19198 (org-end-of-subtree))
19199 ;; Mark zone
19200 (push-mark (point) nil t)
19201 (goto-char beg)))
19203 ;;; Paragraph filling stuff.
19204 ;; We want this to be just right, so use the full arsenal.
19206 (defun org-indent-line-function ()
19207 "Indent line depending on context."
19208 (interactive)
19209 (let* ((pos (point))
19210 (itemp (org-at-item-p))
19211 (case-fold-search t)
19212 (org-drawer-regexp (or org-drawer-regexp "\000"))
19213 (inline-task-p (and (featurep 'org-inlinetask)
19214 (org-inlinetask-in-task-p)))
19215 (inline-re (and inline-task-p
19216 (org-inlinetask-outline-regexp)))
19217 column)
19218 (beginning-of-line 1)
19219 (cond
19220 ;; Comments
19221 ((looking-at "# ") (setq column 0))
19222 ;; Headings
19223 ((looking-at "\\*+ ") (setq column 0))
19224 ;; Included files
19225 ((looking-at "#\\+include:") (setq column 0))
19226 ;; Footnote definition
19227 ((looking-at org-footnote-definition-re) (setq column 0))
19228 ;; Literal examples
19229 ((looking-at "[ \t]*:[ \t]")
19230 (setq column (org-get-indentation))) ; do nothing
19231 ;; Lists
19232 ((ignore-errors (goto-char (org-in-item-p)))
19233 (setq column (if itemp
19234 (org-get-indentation)
19235 (org-list-item-body-column (point))))
19236 (goto-char pos))
19237 ;; Drawers
19238 ((and (looking-at "[ \t]*:END:")
19239 (save-excursion (re-search-backward org-drawer-regexp nil t)))
19240 (save-excursion
19241 (goto-char (1- (match-beginning 1)))
19242 (setq column (current-column))))
19243 ;; Special blocks
19244 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
19245 (save-excursion
19246 (re-search-backward
19247 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
19248 (setq column (org-get-indentation (match-string 0))))
19249 ((and (not (looking-at "[ \t]*#\\+begin_"))
19250 (org-in-regexps-block-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
19251 (save-excursion
19252 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
19253 (setq column
19254 (if (equal (downcase (match-string 1)) "src")
19255 ;; src blocks: let `org-edit-src-exit' handle them
19256 (org-get-indentation)
19257 (org-get-indentation (match-string 0)))))
19258 ;; This line has nothing special, look at the previous relevant
19259 ;; line to compute indentation
19261 (beginning-of-line 0)
19262 (while (and (not (bobp))
19263 (not (looking-at org-drawer-regexp))
19264 ;; When point started in an inline task, do not move
19265 ;; above task starting line.
19266 (not (and inline-task-p (looking-at inline-re)))
19267 ;; Skip drawers, blocks, empty lines, verbatim,
19268 ;; comments, tables, footnotes definitions, lists,
19269 ;; inline tasks.
19270 (or (and (looking-at "[ \t]*:END:")
19271 (re-search-backward org-drawer-regexp nil t))
19272 (and (looking-at "[ \t]*#\\+end_")
19273 (re-search-backward "[ \t]*#\\+begin_"nil t))
19274 (looking-at "[ \t]*[\n:#|]")
19275 (looking-at org-footnote-definition-re)
19276 (and (ignore-errors (goto-char (org-in-item-p)))
19277 (goto-char
19278 (org-list-get-top-point (org-list-struct))))
19279 (and (not inline-task-p)
19280 (featurep 'org-inlinetask)
19281 (org-inlinetask-in-task-p)
19282 (or (org-inlinetask-goto-beginning) t))))
19283 (beginning-of-line 0))
19284 (cond
19285 ;; There was an heading above.
19286 ((looking-at "\\*+[ \t]+")
19287 (if (not org-adapt-indentation)
19288 (setq column 0)
19289 (goto-char (match-end 0))
19290 (setq column (current-column))))
19291 ;; A drawer had started and is unfinished
19292 ((looking-at org-drawer-regexp)
19293 (goto-char (1- (match-beginning 1)))
19294 (setq column (current-column)))
19295 ;; Else, nothing noticeable found: get indentation and go on.
19296 (t (setq column (org-get-indentation))))))
19297 ;; Now apply indentation and move cursor accordingly
19298 (goto-char pos)
19299 (if (<= (current-column) (current-indentation))
19300 (org-indent-line-to column)
19301 (save-excursion (org-indent-line-to column)))
19302 ;; Special polishing for properties, see `org-property-format'
19303 (setq column (current-column))
19304 (beginning-of-line 1)
19305 (if (looking-at
19306 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
19307 (replace-match (concat (match-string 1)
19308 (format org-property-format
19309 (match-string 2) (match-string 3)))
19310 t t))
19311 (org-move-to-column column)))
19313 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
19314 "Variable to store copy of `adaptive-fill-regexp'.
19315 Since `adaptive-fill-regexp' is set to never match, we need to
19316 store a backup of its value before entering `org-mode' so that
19317 the functionality can be provided as a fall-back.")
19319 (defun org-set-autofill-regexps ()
19320 (interactive)
19321 ;; In the paragraph separator we include headlines, because filling
19322 ;; text in a line directly attached to a headline would otherwise
19323 ;; fill the headline as well.
19324 (org-set-local 'comment-start-skip "^#+[ \t]*")
19325 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
19326 ;; The paragraph starter includes hand-formatted lists.
19327 (org-set-local
19328 'paragraph-start
19329 (concat
19330 "\f" "\\|"
19331 "[ ]*$" "\\|"
19332 "\\*+ " "\\|"
19333 "[ \t]*#" "\\|"
19334 (org-item-re) "\\|"
19335 "[ \t]*[:|]" "\\|"
19336 "\\$\\$" "\\|"
19337 "\\\\\\(begin\\|end\\|[][]\\)"))
19338 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
19339 ;; But only if the user has not turned off tables or fixed-width regions
19340 (org-set-local
19341 'auto-fill-inhibit-regexp
19342 (concat "\\*+ \\|#\\+"
19343 "\\|[ \t]*" org-keyword-time-regexp
19344 (if (or org-enable-table-editor org-enable-fixed-width-editor)
19345 (concat
19346 "\\|[ \t]*["
19347 (if org-enable-table-editor "|" "")
19348 (if org-enable-fixed-width-editor ":" "")
19349 "]"))))
19350 ;; We use our own fill-paragraph function, to make sure that tables
19351 ;; and fixed-width regions are not wrapped. That function will pass
19352 ;; through to `fill-paragraph' when appropriate.
19353 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
19354 ;; Prevent auto-fill from inserting unwanted new items.
19355 (org-set-local 'fill-nobreak-predicate
19356 (if (memq 'org-fill-item-nobreak-p fill-nobreak-predicate)
19357 fill-nobreak-predicate
19358 (cons 'org-fill-item-nobreak-p fill-nobreak-predicate)))
19359 ;; Adaptive filling: To get full control, first make sure that
19360 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
19361 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
19362 (org-set-local 'org-adaptive-fill-regexp-backup
19363 adaptive-fill-regexp))
19364 (org-set-local 'adaptive-fill-regexp "\000")
19365 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
19366 (org-set-local 'adaptive-fill-function
19367 'org-adaptive-fill-function)
19368 (org-set-local
19369 'align-mode-rules-list
19370 '((org-in-buffer-settings
19371 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
19372 (modes . '(org-mode))))))
19374 (defun org-fill-item-nobreak-p ()
19375 "Non-nil when a line break at point would insert a new item."
19376 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
19378 (defun org-fill-paragraph (&optional justify)
19379 "Re-align a table, pass through to fill-paragraph if no table."
19380 (let ((table-p (org-at-table-p))
19381 (table.el-p (org-at-table.el-p))
19382 (itemp (org-in-item-p)))
19383 (cond ((and (equal (char-after (point-at-bol)) ?*)
19384 (save-excursion (goto-char (point-at-bol))
19385 (looking-at outline-regexp)))
19386 t) ; skip headlines
19387 (table.el-p t) ; skip table.el tables
19388 (table-p (org-table-align) t) ; align Org tables
19389 (itemp ; align text in items
19390 (let* ((struct (save-excursion (goto-char itemp)
19391 (org-list-struct)))
19392 (parents (org-list-parents-alist struct))
19393 (children (org-list-get-children itemp struct parents))
19394 beg end prev next prefix)
19395 ;; Determine in which part of item point is: before
19396 ;; first child, after last child, between two
19397 ;; sub-lists, or simply in item if there's no child.
19398 (cond
19399 ((not children)
19400 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19401 beg itemp
19402 end (org-list-get-item-end itemp struct)))
19403 ((< (point) (setq next (car children)))
19404 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19405 beg itemp
19406 end next))
19407 ((> (point) (setq prev (car (last children))))
19408 (setq beg (org-list-get-item-end prev struct)
19409 end (org-list-get-item-end itemp struct)
19410 prefix (save-excursion
19411 (goto-char beg)
19412 (skip-chars-forward " \t")
19413 (make-string (current-column) ?\ ))))
19414 (t (catch 'exit
19415 (while (setq next (pop children))
19416 (if (> (point) next)
19417 (setq prev next)
19418 (setq beg (org-list-get-item-end prev struct)
19419 end next
19420 prefix (save-excursion
19421 (goto-char beg)
19422 (skip-chars-forward " \t")
19423 (make-string (current-column) ?\ )))
19424 (throw 'exit nil))))))
19425 ;; Use `fill-paragraph' with buffer narrowed to item
19426 ;; without any child, and with our computed PREFIX.
19427 (flet ((fill-context-prefix (from to &optional flr) prefix))
19428 (save-restriction
19429 (narrow-to-region beg end)
19430 (save-excursion (fill-paragraph justify)))) t))
19431 ;; Special case where point is not in a list but is on
19432 ;; a paragraph adjacent to a list: make sure this paragraph
19433 ;; doesn't get merged with the end of the list by narrowing
19434 ;; buffer first.
19435 ((save-excursion (forward-paragraph -1)
19436 (setq itemp (org-in-item-p)))
19437 (let ((struct (save-excursion (goto-char itemp)
19438 (org-list-struct))))
19439 (save-restriction
19440 (narrow-to-region (org-list-get-bottom-point struct)
19441 (save-excursion (forward-paragraph 1)
19442 (point)))
19443 (fill-paragraph justify) t)))
19444 ;; Else simply call `fill-paragraph'.
19445 (t nil))))
19447 ;; For reference, this is the default value of adaptive-fill-regexp
19448 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
19450 (defun org-adaptive-fill-function ()
19451 "Return a fill prefix for org-mode files."
19452 (let (itemp)
19453 (save-excursion
19454 (cond
19455 ;; Comment line
19456 ((looking-at "#[ \t]+")
19457 (match-string-no-properties 0))
19458 ;; Plain list item
19459 ((org-at-item-p)
19460 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
19461 ;; Point is in a list after `backward-paragraph': original
19462 ;; point wasn't in the list, or filling would have been taken
19463 ;; care of by `org-auto-fill-function', but the list and the
19464 ;; real paragraph are not separated by a blank line. Thus, move
19465 ;; point after the list to go back to real paragraph and
19466 ;; determine fill-prefix.
19467 ((setq itemp (org-in-item-p))
19468 (goto-char itemp)
19469 (let* ((struct (org-list-struct))
19470 (bottom (org-list-get-bottom-point struct)))
19471 (goto-char bottom)
19472 (make-string (org-get-indentation) ?\ )))
19473 ;; Other text
19474 ((looking-at org-adaptive-fill-regexp-backup)
19475 (match-string-no-properties 0))))))
19477 (defun org-auto-fill-function ()
19478 "Auto-fill function."
19479 (let (itemp prefix)
19480 ;; When in a list, compute an appropriate fill-prefix and make
19481 ;; sure it will be used by `do-auto-fill'.
19482 (if (setq itemp (org-in-item-p))
19483 (progn
19484 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
19485 (flet ((fill-context-prefix (from to &optional flr) prefix))
19486 (do-auto-fill)))
19487 ;; Else just use `do-auto-fill'.
19488 (do-auto-fill))))
19490 ;;; Other stuff.
19492 (defun org-toggle-fixed-width-section (arg)
19493 "Toggle the fixed-width export.
19494 If there is no active region, the QUOTE keyword at the current headline is
19495 inserted or removed. When present, it causes the text between this headline
19496 and the next to be exported as fixed-width text, and unmodified.
19497 If there is an active region, this command adds or removes a colon as the
19498 first character of this line. If the first character of a line is a colon,
19499 this line is also exported in fixed-width font."
19500 (interactive "P")
19501 (let* ((cc 0)
19502 (regionp (org-region-active-p))
19503 (beg (if regionp (region-beginning) (point)))
19504 (end (if regionp (region-end)))
19505 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
19506 (case-fold-search nil)
19507 (re "[ \t]*\\(: \\)")
19508 off)
19509 (if regionp
19510 (save-excursion
19511 (goto-char beg)
19512 (setq cc (current-column))
19513 (beginning-of-line 1)
19514 (setq off (looking-at re))
19515 (while (> nlines 0)
19516 (setq nlines (1- nlines))
19517 (beginning-of-line 1)
19518 (cond
19519 (arg
19520 (org-move-to-column cc t)
19521 (insert ": \n")
19522 (forward-line -1))
19523 ((and off (looking-at re))
19524 (replace-match "" t t nil 1))
19525 ((not off) (org-move-to-column cc t) (insert ": ")))
19526 (forward-line 1)))
19527 (save-excursion
19528 (org-back-to-heading)
19529 (if (looking-at (concat outline-regexp
19530 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
19531 (replace-match "" t t nil 1)
19532 (if (looking-at outline-regexp)
19533 (progn
19534 (goto-char (match-end 0))
19535 (insert org-quote-string " "))))))))
19537 (defun org-reftex-citation ()
19538 "Use reftex-citation to insert a citation into the buffer.
19539 This looks for a line like
19541 #+BIBLIOGRAPHY: foo plain option:-d
19543 and derives from it that foo.bib is the bibliography file relevant
19544 for this document. It then installs the necessary environment for RefTeX
19545 to work in this buffer and calls `reftex-citation' to insert a citation
19546 into the buffer.
19548 Export of such citations to both LaTeX and HTML is handled by the contributed
19549 package org-exp-bibtex by Taru Karttunen."
19550 (interactive)
19551 (let ((reftex-docstruct-symbol 'rds)
19552 (reftex-cite-format "\\cite{%l}")
19553 rds bib)
19554 (save-excursion
19555 (save-restriction
19556 (widen)
19557 (let ((case-fold-search t)
19558 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
19559 (if (not (save-excursion
19560 (or (re-search-forward re nil t)
19561 (re-search-backward re nil t))))
19562 (error "No bibliography defined in file")
19563 (setq bib (concat (match-string 1) ".bib")
19564 rds (list (list 'bib bib)))))))
19565 (call-interactively 'reftex-citation)))
19567 ;;;; Functions extending outline functionality
19569 (defun org-beginning-of-line (&optional arg)
19570 "Go to the beginning of the current line. If that is invisible, continue
19571 to a visible line beginning. This makes the function of C-a more intuitive.
19572 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
19573 first attempt, and only move to after the tags when the cursor is already
19574 beyond the end of the headline."
19575 (interactive "P")
19576 (let ((pos (point))
19577 (special (if (consp org-special-ctrl-a/e)
19578 (car org-special-ctrl-a/e)
19579 org-special-ctrl-a/e))
19580 refpos)
19581 (if (org-bound-and-true-p line-move-visual)
19582 (beginning-of-visual-line 1)
19583 (beginning-of-line 1))
19584 (if (and arg (fboundp 'move-beginning-of-line))
19585 (call-interactively 'move-beginning-of-line)
19586 (if (bobp)
19588 (backward-char 1)
19589 (if (org-truely-invisible-p)
19590 (while (and (not (bobp)) (org-truely-invisible-p))
19591 (backward-char 1)
19592 (beginning-of-line 1))
19593 (forward-char 1))))
19594 (when special
19595 (cond
19596 ((and (looking-at org-complex-heading-regexp)
19597 (= (char-after (match-end 1)) ?\ ))
19598 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
19599 (point-at-eol)))
19600 (goto-char
19601 (if (eq special t)
19602 (cond ((> pos refpos) refpos)
19603 ((= pos (point)) refpos)
19604 (t (point)))
19605 (cond ((> pos (point)) (point))
19606 ((not (eq last-command this-command)) (point))
19607 (t refpos)))))
19608 ((org-at-item-p)
19609 (goto-char
19610 (if (eq special t)
19611 (cond ((> pos (match-end 0)) (match-end 0))
19612 ((= pos (point)) (match-end 0))
19613 (t (point)))
19614 (cond ((> pos (point)) (point))
19615 ((not (eq last-command this-command)) (point))
19616 (t (match-end 0))))))))
19617 (org-no-warnings
19618 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
19620 (defun org-end-of-line (&optional arg)
19621 "Go to the end of the line.
19622 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
19623 first attempt, and only move to after the tags when the cursor is already
19624 beyond the end of the headline."
19625 (interactive "P")
19626 (let ((special (if (consp org-special-ctrl-a/e)
19627 (cdr org-special-ctrl-a/e)
19628 org-special-ctrl-a/e)))
19629 (if (or (not special)
19630 (not (org-on-heading-p))
19631 arg)
19632 (call-interactively
19633 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
19634 ((fboundp 'move-end-of-line) 'move-end-of-line)
19635 (t 'end-of-line)))
19636 (let ((pos (point)))
19637 (beginning-of-line 1)
19638 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
19639 (if (eq special t)
19640 (if (or (< pos (match-beginning 1))
19641 (= pos (match-end 0)))
19642 (goto-char (match-beginning 1))
19643 (goto-char (match-end 0)))
19644 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
19645 (goto-char (match-end 0))
19646 (goto-char (match-beginning 1))))
19647 (call-interactively (if (fboundp 'move-end-of-line)
19648 'move-end-of-line
19649 'end-of-line)))))
19650 (org-no-warnings
19651 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
19653 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
19654 (define-key org-mode-map "\C-e" 'org-end-of-line)
19656 (defun org-backward-sentence (&optional arg)
19657 "Go to beginning of sentence, or beginning of table field.
19658 This will call `backward-sentence' or `org-table-beginning-of-field',
19659 depending on context."
19660 (interactive "P")
19661 (cond
19662 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
19663 (t (call-interactively 'backward-sentence))))
19665 (defun org-forward-sentence (&optional arg)
19666 "Go to end of sentence, or end of table field.
19667 This will call `forward-sentence' or `org-table-end-of-field',
19668 depending on context."
19669 (interactive "P")
19670 (cond
19671 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
19672 (t (call-interactively 'forward-sentence))))
19674 (define-key org-mode-map "\M-a" 'org-backward-sentence)
19675 (define-key org-mode-map "\M-e" 'org-forward-sentence)
19677 (defun org-kill-line (&optional arg)
19678 "Kill line, to tags or end of line."
19679 (interactive "P")
19680 (cond
19681 ((or (not org-special-ctrl-k)
19682 (bolp)
19683 (not (org-on-heading-p)))
19684 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
19685 org-ctrl-k-protect-subtree)
19686 (if (or (eq org-ctrl-k-protect-subtree 'error)
19687 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
19688 (error "C-k aborted - would kill hidden subtree")))
19689 (call-interactively 'kill-line))
19690 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
19691 (kill-region (point) (match-beginning 1))
19692 (org-set-tags nil t))
19693 (t (kill-region (point) (point-at-eol)))))
19695 (define-key org-mode-map "\C-k" 'org-kill-line)
19697 (defun org-yank (&optional arg)
19698 "Yank. If the kill is a subtree, treat it specially.
19699 This command will look at the current kill and check if is a single
19700 subtree, or a series of subtrees[1]. If it passes the test, and if the
19701 cursor is at the beginning of a line or after the stars of a currently
19702 empty headline, then the yank is handled specially. How exactly depends
19703 on the value of the following variables, both set by default.
19705 org-yank-folded-subtrees
19706 When set, the subtree(s) will be folded after insertion, but only
19707 if doing so would now swallow text after the yanked text.
19709 org-yank-adjusted-subtrees
19710 When set, the subtree will be promoted or demoted in order to
19711 fit into the local outline tree structure, which means that the level
19712 will be adjusted so that it becomes the smaller one of the two
19713 *visible* surrounding headings.
19715 Any prefix to this command will cause `yank' to be called directly with
19716 no special treatment. In particular, a simple \\[universal-argument] prefix \
19717 will just
19718 plainly yank the text as it is.
19720 \[1] The test checks if the first non-white line is a heading
19721 and if there are no other headings with fewer stars."
19722 (interactive "P")
19723 (org-yank-generic 'yank arg))
19725 (defun org-yank-generic (command arg)
19726 "Perform some yank-like command.
19728 This function implements the behavior described in the `org-yank'
19729 documentation. However, it has been generalized to work for any
19730 interactive command with similar behavior."
19732 ;; pretend to be command COMMAND
19733 (setq this-command command)
19735 (if arg
19736 (call-interactively command)
19738 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
19739 (and (org-kill-is-subtree-p)
19740 (or (bolp)
19741 (and (looking-at "[ \t]*$")
19742 (string-match
19743 "\\`\\*+\\'"
19744 (buffer-substring (point-at-bol) (point)))))))
19745 swallowp)
19746 (cond
19747 ((and subtreep org-yank-folded-subtrees)
19748 (let ((beg (point))
19749 end)
19750 (if (and subtreep org-yank-adjusted-subtrees)
19751 (org-paste-subtree nil nil 'for-yank)
19752 (call-interactively command))
19754 (setq end (point))
19755 (goto-char beg)
19756 (when (and (bolp) subtreep
19757 (not (setq swallowp
19758 (org-yank-folding-would-swallow-text beg end))))
19759 (or (looking-at outline-regexp)
19760 (re-search-forward (concat "^" outline-regexp) end t))
19761 (while (and (< (point) end) (looking-at outline-regexp))
19762 (hide-subtree)
19763 (org-cycle-show-empty-lines 'folded)
19764 (condition-case nil
19765 (outline-forward-same-level 1)
19766 (error (goto-char end)))))
19767 (when swallowp
19768 (message
19769 "Inserted text not folded because that would swallow text"))
19771 (goto-char end)
19772 (skip-chars-forward " \t\n\r")
19773 (beginning-of-line 1)
19774 (push-mark beg 'nomsg)))
19775 ((and subtreep org-yank-adjusted-subtrees)
19776 (let ((beg (point-at-bol)))
19777 (org-paste-subtree nil nil 'for-yank)
19778 (push-mark beg 'nomsg)))
19780 (call-interactively command))))))
19782 (defun org-yank-folding-would-swallow-text (beg end)
19783 "Would hide-subtree at BEG swallow any text after END?"
19784 (let (level)
19785 (save-excursion
19786 (goto-char beg)
19787 (when (or (looking-at outline-regexp)
19788 (re-search-forward (concat "^" outline-regexp) end t))
19789 (setq level (org-outline-level)))
19790 (goto-char end)
19791 (skip-chars-forward " \t\r\n\v\f")
19792 (if (or (eobp)
19793 (and (bolp) (looking-at org-outline-regexp)
19794 (<= (org-outline-level) level)))
19795 nil ; Nothing would be swallowed
19796 t)))) ; something would swallow
19798 (define-key org-mode-map "\C-y" 'org-yank)
19800 (defun org-truely-invisible-p ()
19801 "Check if point is at a character currently not visible.
19802 This version does not only check the character property, but also
19803 `visible-mode'."
19804 ;; Early versions of noutline don't have `outline-invisible-p'.
19805 (if (org-bound-and-true-p visible-mode)
19807 (outline-invisible-p)))
19809 (defun org-invisible-p2 ()
19810 "Check if point is at a character currently not visible."
19811 (save-excursion
19812 (if (and (eolp) (not (bobp))) (backward-char 1))
19813 ;; Early versions of noutline don't have `outline-invisible-p'.
19814 (outline-invisible-p)))
19816 (defun org-back-to-heading (&optional invisible-ok)
19817 "Call `outline-back-to-heading', but provide a better error message."
19818 (condition-case nil
19819 (outline-back-to-heading invisible-ok)
19820 (error (error "Before first headline at position %d in buffer %s"
19821 (point) (current-buffer)))))
19823 (defun org-beginning-of-defun ()
19824 "Go to the beginning of the subtree, i.e. back to the heading."
19825 (org-back-to-heading))
19826 (defun org-end-of-defun ()
19827 "Go to the end of the subtree."
19828 (org-end-of-subtree nil t))
19830 (defun org-before-first-heading-p ()
19831 "Before first heading?"
19832 (save-excursion
19833 (end-of-line)
19834 (null (re-search-backward "^\\*+ " nil t))))
19836 (defun org-on-heading-p (&optional ignored)
19837 (outline-on-heading-p t))
19838 (defun org-at-heading-p (&optional ignored)
19839 (outline-on-heading-p t))
19841 (defun org-point-at-end-of-empty-headline ()
19842 "If point is at the end of an empty headline, return t, else nil.
19843 If the heading only contains a TODO keyword, it is still still considered
19844 empty."
19845 (and (looking-at "[ \t]*$")
19846 (save-excursion
19847 (beginning-of-line 1)
19848 (let ((case-fold-search nil))
19849 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
19850 "\\)?[ \t]*$"))))))
19851 (defun org-at-heading-or-item-p ()
19852 (or (org-on-heading-p) (org-at-item-p)))
19854 (defun org-on-target-p ()
19855 (or (org-in-regexp org-radio-target-regexp)
19856 (org-in-regexp org-target-regexp)))
19858 (defun org-up-heading-all (arg)
19859 "Move to the heading line of which the present line is a subheading.
19860 This function considers both visible and invisible heading lines.
19861 With argument, move up ARG levels."
19862 (if (fboundp 'outline-up-heading-all)
19863 (outline-up-heading-all arg) ; emacs 21 version of outline.el
19864 (outline-up-heading arg t))) ; emacs 22 version of outline.el
19866 (defun org-up-heading-safe ()
19867 "Move to the heading line of which the present line is a subheading.
19868 This version will not throw an error. It will return the level of the
19869 headline found, or nil if no higher level is found.
19871 Also, this function will be a lot faster than `outline-up-heading',
19872 because it relies on stars being the outline starters. This can really
19873 make a significant difference in outlines with very many siblings."
19874 (let (start-level re)
19875 (org-back-to-heading t)
19876 (setq start-level (funcall outline-level))
19877 (if (equal start-level 1)
19879 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
19880 (if (re-search-backward re nil t)
19881 (funcall outline-level)))))
19883 (defun org-first-sibling-p ()
19884 "Is this heading the first child of its parents?"
19885 (interactive)
19886 (let ((re (concat "^" outline-regexp))
19887 level l)
19888 (unless (org-at-heading-p t)
19889 (error "Not at a heading"))
19890 (setq level (funcall outline-level))
19891 (save-excursion
19892 (if (not (re-search-backward re nil t))
19894 (setq l (funcall outline-level))
19895 (< l level)))))
19897 (defun org-goto-sibling (&optional previous)
19898 "Goto the next sibling, even if it is invisible.
19899 When PREVIOUS is set, go to the previous sibling instead. Returns t
19900 when a sibling was found. When none is found, return nil and don't
19901 move point."
19902 (let ((fun (if previous 're-search-backward 're-search-forward))
19903 (pos (point))
19904 (re (concat "^" outline-regexp))
19905 level l)
19906 (when (condition-case nil (org-back-to-heading t) (error nil))
19907 (setq level (funcall outline-level))
19908 (catch 'exit
19909 (or previous (forward-char 1))
19910 (while (funcall fun re nil t)
19911 (setq l (funcall outline-level))
19912 (when (< l level) (goto-char pos) (throw 'exit nil))
19913 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
19914 (goto-char pos)
19915 nil))))
19917 (defun org-show-siblings ()
19918 "Show all siblings of the current headline."
19919 (save-excursion
19920 (while (org-goto-sibling) (org-flag-heading nil)))
19921 (save-excursion
19922 (while (org-goto-sibling 'previous)
19923 (org-flag-heading nil))))
19925 (defun org-goto-first-child ()
19926 "Goto the first child, even if it is invisible.
19927 Return t when a child was found. Otherwise don't move point and
19928 return nil."
19929 (let (level (pos (point)) (re (concat "^" outline-regexp)))
19930 (when (condition-case nil (org-back-to-heading t) (error nil))
19931 (setq level (outline-level))
19932 (forward-char 1)
19933 (if (and (re-search-forward re nil t) (> (outline-level) level))
19934 (progn (goto-char (match-beginning 0)) t)
19935 (goto-char pos) nil))))
19937 (defun org-show-hidden-entry ()
19938 "Show an entry where even the heading is hidden."
19939 (save-excursion
19940 (org-show-entry)))
19942 (defun org-flag-heading (flag &optional entry)
19943 "Flag the current heading. FLAG non-nil means make invisible.
19944 When ENTRY is non-nil, show the entire entry."
19945 (save-excursion
19946 (org-back-to-heading t)
19947 ;; Check if we should show the entire entry
19948 (if entry
19949 (progn
19950 (org-show-entry)
19951 (save-excursion
19952 (and (outline-next-heading)
19953 (org-flag-heading nil))))
19954 (outline-flag-region (max (point-min) (1- (point)))
19955 (save-excursion (outline-end-of-heading) (point))
19956 flag))))
19958 (defun org-get-next-sibling ()
19959 "Move to next heading of the same level, and return point.
19960 If there is no such heading, return nil.
19961 This is like outline-next-sibling, but invisible headings are ok."
19962 (let ((level (funcall outline-level)))
19963 (outline-next-heading)
19964 (while (and (not (eobp)) (> (funcall outline-level) level))
19965 (outline-next-heading))
19966 (if (or (eobp) (< (funcall outline-level) level))
19968 (point))))
19970 (defun org-get-last-sibling ()
19971 "Move to previous heading of the same level, and return point.
19972 If there is no such heading, return nil."
19973 (let ((opoint (point))
19974 (level (funcall outline-level)))
19975 (outline-previous-heading)
19976 (when (and (/= (point) opoint) (outline-on-heading-p t))
19977 (while (and (> (funcall outline-level) level)
19978 (not (bobp)))
19979 (outline-previous-heading))
19980 (if (< (funcall outline-level) level)
19982 (point)))))
19984 (defun org-end-of-subtree (&optional invisible-OK to-heading)
19985 ;; This contains an exact copy of the original function, but it uses
19986 ;; `org-back-to-heading', to make it work also in invisible
19987 ;; trees. And is uses an invisible-OK argument.
19988 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
19989 ;; Furthermore, when used inside Org, finding the end of a large subtree
19990 ;; with many children and grandchildren etc, this can be much faster
19991 ;; than the outline version.
19992 (org-back-to-heading invisible-OK)
19993 (let ((first t)
19994 (level (funcall outline-level)))
19995 (if (and (org-mode-p) (< level 1000))
19996 ;; A true heading (not a plain list item), in Org-mode
19997 ;; This means we can easily find the end by looking
19998 ;; only for the right number of stars. Using a regexp to do
19999 ;; this is so much faster than using a Lisp loop.
20000 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
20001 (forward-char 1)
20002 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
20003 ;; something else, do it the slow way
20004 (while (and (not (eobp))
20005 (or first (> (funcall outline-level) level)))
20006 (setq first nil)
20007 (outline-next-heading)))
20008 (unless to-heading
20009 (if (memq (preceding-char) '(?\n ?\^M))
20010 (progn
20011 ;; Go to end of line before heading
20012 (forward-char -1)
20013 (if (memq (preceding-char) '(?\n ?\^M))
20014 ;; leave blank line before heading
20015 (forward-char -1))))))
20016 (point))
20018 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
20019 "Use Org version in org-mode, for dramatic speed-up."
20020 (if (org-mode-p)
20021 (progn
20022 (org-end-of-subtree nil t)
20023 (unless (eobp) (backward-char 1)))
20024 ad-do-it))
20026 (defun org-end-of-meta-data-and-drawers ()
20027 "Jump to the first text after meta data and drawers in the current entry.
20028 This will move over empty lines, lines with planning time stamps,
20029 clocking lines, and drawers."
20030 (org-back-to-heading t)
20031 (let ((end (save-excursion (outline-next-heading) (point)))
20032 (re (concat "[ \t]*$"
20033 "\\|"
20034 "\\(" org-drawer-regexp "\\)" ; group 1 are drawers
20035 "\\|"
20036 "\\([ \t]*\\(" org-keyword-time-regexp "\\)\\)")))
20037 (forward-line 1)
20038 (while (looking-at (concat "[ \t]*\\(" org-keyword-time-regexp "\\)"))
20039 (if (not (match-end 1))
20040 ;; empty or planning line
20041 (forward-line 1)
20042 ;; a drawer, find the end
20043 (re-search-forward "^[ \t]*:END:" end 'move)
20044 (forward-line 1)))
20045 (point)))
20047 (defun org-forward-same-level (arg &optional invisible-ok)
20048 "Move forward to the arg'th subheading at same level as this one.
20049 Stop at the first and last subheadings of a superior heading.
20050 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
20051 it wil also look at invisible ones."
20052 (interactive "p")
20053 (org-back-to-heading invisible-ok)
20054 (org-on-heading-p)
20055 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20056 (re (format "^\\*\\{1,%d\\} " level))
20058 (forward-char 1)
20059 (while (> arg 0)
20060 (while (and (re-search-forward re nil 'move)
20061 (setq l (- (match-end 0) (match-beginning 0) 1))
20062 (= l level)
20063 (not invisible-ok)
20064 (progn (backward-char 1) (outline-invisible-p)))
20065 (if (< l level) (setq arg 1)))
20066 (setq arg (1- arg)))
20067 (beginning-of-line 1)))
20069 (defun org-backward-same-level (arg &optional invisible-ok)
20070 "Move backward to the arg'th subheading at same level as this one.
20071 Stop at the first and last subheadings of a superior heading."
20072 (interactive "p")
20073 (org-back-to-heading)
20074 (org-on-heading-p)
20075 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20076 (re (format "^\\*\\{1,%d\\} " level))
20078 (while (> arg 0)
20079 (while (and (re-search-backward re nil 'move)
20080 (setq l (- (match-end 0) (match-beginning 0) 1))
20081 (= l level)
20082 (not invisible-ok)
20083 (outline-invisible-p))
20084 (if (< l level) (setq arg 1)))
20085 (setq arg (1- arg)))))
20087 (defun org-show-subtree ()
20088 "Show everything after this heading at deeper levels."
20089 (outline-flag-region
20090 (point)
20091 (save-excursion
20092 (org-end-of-subtree t t))
20093 nil))
20095 (defun org-show-entry ()
20096 "Show the body directly following this heading.
20097 Show the heading too, if it is currently invisible."
20098 (interactive)
20099 (save-excursion
20100 (condition-case nil
20101 (progn
20102 (org-back-to-heading t)
20103 (outline-flag-region
20104 (max (point-min) (1- (point)))
20105 (save-excursion
20106 (if (re-search-forward
20107 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
20108 (match-beginning 1)
20109 (point-max)))
20110 nil)
20111 (org-cycle-hide-drawers 'children))
20112 (error nil))))
20114 (defun org-make-options-regexp (kwds &optional extra)
20115 "Make a regular expression for keyword lines."
20116 (concat
20118 "#?[ \t]*\\+\\("
20119 (mapconcat 'regexp-quote kwds "\\|")
20120 (if extra (concat "\\|" extra))
20121 "\\):[ \t]*"
20122 "\\(.*\\)"))
20124 ;; Make isearch reveal the necessary context
20125 (defun org-isearch-end ()
20126 "Reveal context after isearch exits."
20127 (when isearch-success ; only if search was successful
20128 (if (featurep 'xemacs)
20129 ;; Under XEmacs, the hook is run in the correct place,
20130 ;; we directly show the context.
20131 (org-show-context 'isearch)
20132 ;; In Emacs the hook runs *before* restoring the overlays.
20133 ;; So we have to use a one-time post-command-hook to do this.
20134 ;; (Emacs 22 has a special variable, see function `org-mode')
20135 (unless (and (boundp 'isearch-mode-end-hook-quit)
20136 isearch-mode-end-hook-quit)
20137 ;; Only when the isearch was not quitted.
20138 (org-add-hook 'post-command-hook 'org-isearch-post-command
20139 'append 'local)))))
20141 (defun org-isearch-post-command ()
20142 "Remove self from hook, and show context."
20143 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
20144 (org-show-context 'isearch))
20147 ;;;; Integration with and fixes for other packages
20149 ;;; Imenu support
20151 (defvar org-imenu-markers nil
20152 "All markers currently used by Imenu.")
20153 (make-variable-buffer-local 'org-imenu-markers)
20155 (defun org-imenu-new-marker (&optional pos)
20156 "Return a new marker for use by Imenu, and remember the marker."
20157 (let ((m (make-marker)))
20158 (move-marker m (or pos (point)))
20159 (push m org-imenu-markers)
20162 (defun org-imenu-get-tree ()
20163 "Produce the index for Imenu."
20164 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
20165 (setq org-imenu-markers nil)
20166 (let* ((n org-imenu-depth)
20167 (re (concat "^" outline-regexp))
20168 (subs (make-vector (1+ n) nil))
20169 (last-level 0)
20170 m level head)
20171 (save-excursion
20172 (save-restriction
20173 (widen)
20174 (goto-char (point-max))
20175 (while (re-search-backward re nil t)
20176 (setq level (org-reduced-level (funcall outline-level)))
20177 (when (<= level n)
20178 (looking-at org-complex-heading-regexp)
20179 (setq head (org-link-display-format
20180 (org-match-string-no-properties 4))
20181 m (org-imenu-new-marker))
20182 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
20183 (if (>= level last-level)
20184 (push (cons head m) (aref subs level))
20185 (push (cons head (aref subs (1+ level))) (aref subs level))
20186 (loop for i from (1+ level) to n do (aset subs i nil)))
20187 (setq last-level level)))))
20188 (aref subs 1)))
20190 (eval-after-load "imenu"
20191 '(progn
20192 (add-hook 'imenu-after-jump-hook
20193 (lambda ()
20194 (if (org-mode-p)
20195 (org-show-context 'org-goto))))))
20197 (defun org-link-display-format (link)
20198 "Replace a link with either the description, or the link target
20199 if no description is present"
20200 (save-match-data
20201 (if (string-match org-bracket-link-analytic-regexp link)
20202 (replace-match (if (match-end 5)
20203 (match-string 5 link)
20204 (concat (match-string 1 link)
20205 (match-string 3 link)))
20206 nil t link)
20207 link)))
20209 ;; Speedbar support
20211 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
20212 "Overlay marking the agenda restriction line in speedbar.")
20213 (overlay-put org-speedbar-restriction-lock-overlay
20214 'face 'org-agenda-restriction-lock)
20215 (overlay-put org-speedbar-restriction-lock-overlay
20216 'help-echo "Agendas are currently limited to this item.")
20217 (org-detach-overlay org-speedbar-restriction-lock-overlay)
20219 (defun org-speedbar-set-agenda-restriction ()
20220 "Restrict future agenda commands to the location at point in speedbar.
20221 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
20222 (interactive)
20223 (require 'org-agenda)
20224 (let (p m tp np dir txt)
20225 (cond
20226 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20227 'org-imenu t))
20228 (setq m (get-text-property p 'org-imenu-marker))
20229 (with-current-buffer (marker-buffer m)
20230 (goto-char m)
20231 (org-agenda-set-restriction-lock 'subtree)))
20232 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20233 'speedbar-function 'speedbar-find-file))
20234 (setq tp (previous-single-property-change
20235 (1+ p) 'speedbar-function)
20236 np (next-single-property-change
20237 tp 'speedbar-function)
20238 dir (speedbar-line-directory)
20239 txt (buffer-substring-no-properties (or tp (point-min))
20240 (or np (point-max))))
20241 (with-current-buffer (find-file-noselect
20242 (let ((default-directory dir))
20243 (expand-file-name txt)))
20244 (unless (org-mode-p)
20245 (error "Cannot restrict to non-Org-mode file"))
20246 (org-agenda-set-restriction-lock 'file)))
20247 (t (error "Don't know how to restrict Org-mode's agenda")))
20248 (move-overlay org-speedbar-restriction-lock-overlay
20249 (point-at-bol) (point-at-eol))
20250 (setq current-prefix-arg nil)
20251 (org-agenda-maybe-redo)))
20253 (eval-after-load "speedbar"
20254 '(progn
20255 (speedbar-add-supported-extension ".org")
20256 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
20257 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
20258 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
20259 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
20260 (add-hook 'speedbar-visiting-tag-hook
20261 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
20263 ;;; Fixes and Hacks for problems with other packages
20265 ;; Make flyspell not check words in links, to not mess up our keymap
20266 (defun org-mode-flyspell-verify ()
20267 "Don't let flyspell put overlays at active buttons, or on
20268 {todo,all-time,additional-option-like}-keywords."
20269 (let ((pos (max (1- (point)) (point-min)))
20270 (word (thing-at-point 'word)))
20271 (and (not (get-text-property pos 'keymap))
20272 (not (get-text-property pos 'org-no-flyspell))
20273 (not (member word org-todo-keywords-1))
20274 (not (member word org-all-time-keywords))
20275 (not (member word org-additional-option-like-keywords)))))
20277 (defun org-remove-flyspell-overlays-in (beg end)
20278 "Remove flyspell overlays in region."
20279 (and (org-bound-and-true-p flyspell-mode)
20280 (fboundp 'flyspell-delete-region-overlays)
20281 (flyspell-delete-region-overlays beg end))
20282 (add-text-properties beg end '(org-no-flyspell t)))
20284 ;; Make `bookmark-jump' shows the jump location if it was hidden.
20285 (eval-after-load "bookmark"
20286 '(if (boundp 'bookmark-after-jump-hook)
20287 ;; We can use the hook
20288 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
20289 ;; Hook not available, use advice
20290 (defadvice bookmark-jump (after org-make-visible activate)
20291 "Make the position visible."
20292 (org-bookmark-jump-unhide))))
20294 ;; Make sure saveplace shows the location if it was hidden
20295 (eval-after-load "saveplace"
20296 '(defadvice save-place-find-file-hook (after org-make-visible activate)
20297 "Make the position visible."
20298 (org-bookmark-jump-unhide)))
20300 ;; Make sure ecb shows the location if it was hidden
20301 (eval-after-load "ecb"
20302 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
20303 "Make hierarchy visible when jumping into location from ECB tree buffer."
20304 (if (org-mode-p)
20305 (org-show-context))))
20307 (defun org-bookmark-jump-unhide ()
20308 "Unhide the current position, to show the bookmark location."
20309 (and (org-mode-p)
20310 (or (outline-invisible-p)
20311 (save-excursion (goto-char (max (point-min) (1- (point))))
20312 (outline-invisible-p)))
20313 (org-show-context 'bookmark-jump)))
20315 ;; Make session.el ignore our circular variable
20316 (eval-after-load "session"
20317 '(add-to-list 'session-globals-exclude 'org-mark-ring))
20319 ;;;; Experimental code
20321 (defun org-closed-in-range ()
20322 "Sparse tree of items closed in a certain time range.
20323 Still experimental, may disappear in the future."
20324 (interactive)
20325 ;; Get the time interval from the user.
20326 (let* ((time1 (org-float-time
20327 (org-read-date nil 'to-time nil "Starting date: ")))
20328 (time2 (org-float-time
20329 (org-read-date nil 'to-time nil "End date:")))
20330 ;; callback function
20331 (callback (lambda ()
20332 (let ((time
20333 (org-float-time
20334 (apply 'encode-time
20335 (org-parse-time-string
20336 (match-string 1))))))
20337 ;; check if time in interval
20338 (and (>= time time1) (<= time time2))))))
20339 ;; make tree, check each match with the callback
20340 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
20342 ;;;; Finish up
20344 (provide 'org)
20346 (run-hooks 'org-load-hook)
20348 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
20350 ;;; org.el ends here