Adjust fontification of footnotes
[org-mode/org-jambu.git] / lisp / org.el
blob827008dc78d2129cf75d6377a7294f76f46b7d4f
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 (interactive-p)
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 (interactive-p)
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 (interactive-p) 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 (interactive-p)
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 (interactive-p))
8510 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
8511 (interactive-p)
8512 (not custom-id))
8513 (and org-link-to-org-use-id
8514 (org-entry-get nil "ID"))))
8515 ;; We can make a link using the ID.
8516 (setq link (condition-case nil
8517 (prog1 (org-id-store-link)
8518 (setq desc (plist-get org-store-link-plist
8519 :description)))
8520 (error
8521 ;; probably before first headline, link to file only
8522 (concat "file:"
8523 (abbreviate-file-name
8524 (buffer-file-name (buffer-base-buffer))))))))
8526 ;; Just link to current headline
8527 (setq cpltxt (concat "file:"
8528 (abbreviate-file-name
8529 (buffer-file-name (buffer-base-buffer)))))
8530 ;; Add a context search string
8531 (when (org-xor org-context-in-file-links arg)
8532 (setq txt (cond
8533 ((org-on-heading-p) nil)
8534 ((org-region-active-p)
8535 (buffer-substring (region-beginning) (region-end)))
8536 (t nil)))
8537 (when (or (null txt) (string-match "\\S-" txt))
8538 (setq cpltxt
8539 (concat cpltxt "::"
8540 (condition-case nil
8541 (org-make-org-heading-search-string txt)
8542 (error "")))
8543 desc (or (nth 4 (ignore-errors
8544 (org-heading-components))) "NONE"))))
8545 (if (string-match "::\\'" cpltxt)
8546 (setq cpltxt (substring cpltxt 0 -2)))
8547 (setq link (org-make-link cpltxt)))))
8549 ((buffer-file-name (buffer-base-buffer))
8550 ;; Just link to this file here.
8551 (setq cpltxt (concat "file:"
8552 (abbreviate-file-name
8553 (buffer-file-name (buffer-base-buffer)))))
8554 ;; Add a context string
8555 (when (org-xor org-context-in-file-links arg)
8556 (setq txt (if (org-region-active-p)
8557 (buffer-substring (region-beginning) (region-end))
8558 (buffer-substring (point-at-bol) (point-at-eol))))
8559 ;; Only use search option if there is some text.
8560 (when (string-match "\\S-" txt)
8561 (setq cpltxt
8562 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8563 desc "NONE")))
8564 (setq link (org-make-link cpltxt)))
8566 ((interactive-p)
8567 (error "Cannot link to a buffer which is not visiting a file"))
8569 (t (setq link nil)))
8571 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8572 (setq link (or link cpltxt)
8573 desc (or desc cpltxt))
8574 (if (equal desc "NONE") (setq desc nil))
8576 (if (and (or (interactive-p) executing-kbd-macro) link)
8577 (progn
8578 (setq org-stored-links
8579 (cons (list link desc) org-stored-links))
8580 (message "Stored: %s" (or desc link))
8581 (when custom-id
8582 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8583 "::#" custom-id))
8584 (setq org-stored-links
8585 (cons (list link desc) org-stored-links))))
8586 (or agenda-link (and link (org-make-link-string link desc)))))))
8588 (defun org-store-link-props (&rest plist)
8589 "Store link properties, extract names and addresses."
8590 (let (x adr)
8591 (when (setq x (plist-get plist :from))
8592 (setq adr (mail-extract-address-components x))
8593 (setq plist (plist-put plist :fromname (car adr)))
8594 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8595 (when (setq x (plist-get plist :to))
8596 (setq adr (mail-extract-address-components x))
8597 (setq plist (plist-put plist :toname (car adr)))
8598 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8599 (let ((from (plist-get plist :from))
8600 (to (plist-get plist :to)))
8601 (when (and from to org-from-is-user-regexp)
8602 (setq plist
8603 (plist-put plist :fromto
8604 (if (string-match org-from-is-user-regexp from)
8605 (concat "to %t")
8606 (concat "from %f"))))))
8607 (setq org-store-link-plist plist))
8609 (defun org-add-link-props (&rest plist)
8610 "Add these properties to the link property list."
8611 (let (key value)
8612 (while plist
8613 (setq key (pop plist) value (pop plist))
8614 (setq org-store-link-plist
8615 (plist-put org-store-link-plist key value)))))
8617 (defun org-email-link-description (&optional fmt)
8618 "Return the description part of an email link.
8619 This takes information from `org-store-link-plist' and formats it
8620 according to FMT (default from `org-email-link-description-format')."
8621 (setq fmt (or fmt org-email-link-description-format))
8622 (let* ((p org-store-link-plist)
8623 (to (plist-get p :toaddress))
8624 (from (plist-get p :fromaddress))
8625 (table
8626 (list
8627 (cons "%c" (plist-get p :fromto))
8628 (cons "%F" (plist-get p :from))
8629 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8630 (cons "%T" (plist-get p :to))
8631 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8632 (cons "%s" (plist-get p :subject))
8633 (cons "%d" (plist-get p :date))
8634 (cons "%m" (plist-get p :message-id)))))
8635 (when (string-match "%c" fmt)
8636 ;; Check if the user wrote this message
8637 (if (and org-from-is-user-regexp from to
8638 (save-match-data (string-match org-from-is-user-regexp from)))
8639 (setq fmt (replace-match "to %t" t t fmt))
8640 (setq fmt (replace-match "from %f" t t fmt))))
8641 (org-replace-escapes fmt table)))
8643 (defun org-make-org-heading-search-string (&optional string heading)
8644 "Make search string for STRING or current headline."
8645 (interactive)
8646 (let ((s (or string (org-get-heading)))
8647 (lines org-context-in-file-links))
8648 (unless (and string (not heading))
8649 ;; We are using a headline, clean up garbage in there.
8650 (if (string-match org-todo-regexp s)
8651 (setq s (replace-match "" t t s)))
8652 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
8653 (setq s (replace-match "" t t s)))
8654 (setq s (org-trim s))
8655 (if (string-match (concat "^\\(" org-quote-string "\\|"
8656 org-comment-string "\\)") s)
8657 (setq s (replace-match "" t t s)))
8658 (while (string-match org-ts-regexp s)
8659 (setq s (replace-match "" t t s))))
8660 (or string (setq s (concat "*" s))) ; Add * for headlines
8661 (when (and string (integerp lines) (> lines 0))
8662 (let ((slines (org-split-string s "\n")))
8663 (when (< lines (length slines))
8664 (setq s (mapconcat
8665 'identity
8666 (reverse (nthcdr (- (length slines) lines)
8667 (reverse slines))) "\n")))))
8668 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8670 (defun org-make-link (&rest strings)
8671 "Concatenate STRINGS."
8672 (apply 'concat strings))
8674 (defun org-make-link-string (link &optional description)
8675 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8676 (unless (string-match "\\S-" link)
8677 (error "Empty link"))
8678 (when (and description
8679 (stringp description)
8680 (not (string-match "\\S-" description)))
8681 (setq description nil))
8682 (when (stringp description)
8683 ;; Remove brackets from the description, they are fatal.
8684 (while (string-match "\\[" description)
8685 (setq description (replace-match "{" t t description)))
8686 (while (string-match "\\]" description)
8687 (setq description (replace-match "}" t t description))))
8688 (when (equal (org-link-escape link) description)
8689 ;; No description needed, it is identical
8690 (setq description nil))
8691 (when (and (not description)
8692 (not (equal link (org-link-escape link))))
8693 (setq description (org-extract-attributes link)))
8694 (setq link (if (string-match org-link-types-re link)
8695 (concat (match-string 1 link)
8696 (org-link-escape (substring link (match-end 1))))
8697 (org-link-escape link)))
8698 (concat "[[" link "]"
8699 (if description (concat "[" description "]") "")
8700 "]"))
8702 (defconst org-link-escape-chars
8703 '(?\ ?\[ ?\] ?\; ?\= ?\+)
8704 "List of characters that should be escaped in link.
8705 This is the list that is used for internal purposes.")
8707 (defvar org-url-encoding-use-url-hexify nil)
8709 (defconst org-link-escape-chars-browser
8710 '(?\ )
8711 "List of escapes for characters that are problematic in links.
8712 This is the list that is used before handing over to the browser.")
8714 (defun org-link-escape (text &optional table merge)
8715 "Return percent escaped representation of TEXT.
8716 TEXT is a string with the text to escape.
8717 Optional argument TABLE is a list with characters that should be
8718 escaped. When nil, `org-link-escape-chars' is used.
8719 If optional argument MERGE is set, merge TABLE into
8720 `org-link-escape-chars'."
8721 (if (and org-url-encoding-use-url-hexify (not table))
8722 (url-hexify-string text)
8723 (cond
8724 ((and table merge)
8725 (mapc (lambda (defchr)
8726 (unless (member defchr table)
8727 (setq table (cons defchr table)))) org-link-escape-chars))
8728 ((null table)
8729 (setq table org-link-escape-chars)))
8730 (mapconcat
8731 (lambda (char)
8732 (if (or (member char table)
8733 (< char 32) (= char 37) (> char 126))
8734 (mapconcat (lambda (sequence-element)
8735 (format "%%%.2X" sequence-element))
8736 (or (encode-coding-char char 'utf-8)
8737 (error "Unable to percent escape character: %s"
8738 (char-to-string char))) "")
8739 (char-to-string char))) text "")))
8741 (defun org-link-unescape (str)
8742 "Unhex hexified unicode strings as returned from the JavaScript function
8743 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
8744 (unless (and (null str) (string= "" str))
8745 (let ((pos 0) (case-fold-search t) unhexed)
8746 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
8747 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
8748 (setq str (replace-match unhexed t t str))
8749 (setq pos (+ pos (length unhexed))))))
8750 str)
8752 (defun org-link-unescape-compound (hex)
8753 "Unhexify unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
8754 Note: this function also decodes single byte encodings like
8755 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
8756 (save-match-data
8757 (let* ((bytes (cdr (split-string hex "%")))
8758 (ret "")
8759 (eat 0)
8760 (sum 0))
8761 (while bytes
8762 (let* ((val (string-to-number (pop bytes) 16))
8763 (shift-xor
8764 (if (= 0 eat)
8765 (cond
8766 ((>= val 252) (cons 6 252))
8767 ((>= val 248) (cons 5 248))
8768 ((>= val 240) (cons 4 240))
8769 ((>= val 224) (cons 3 224))
8770 ((>= val 192) (cons 2 192))
8771 (t (cons 0 0)))
8772 (cons 6 128))))
8773 (if (>= val 192) (setq eat (car shift-xor)))
8774 (setq val (logxor val (cdr shift-xor)))
8775 (setq sum (+ (lsh sum (car shift-xor)) val))
8776 (if (> eat 0) (setq eat (- eat 1)))
8777 (cond
8778 ((= 0 eat) ;multi byte
8779 (setq ret (concat ret (org-char-to-string sum)))
8780 (setq sum 0))
8781 ((not bytes) ; single byte(s)
8782 (setq ret (org-link-unescape-single-byte-sequence hex))))
8783 )) ;; end (while bytes
8784 ret )))
8786 (defun org-link-unescape-single-byte-sequence (hex)
8787 "Unhexify hex-encoded single byte character sequences."
8788 (mapconcat (lambda (byte)
8789 (char-to-string (string-to-number byte 16)))
8790 (cdr (split-string hex "%")) ""))
8792 (defun org-xor (a b)
8793 "Exclusive or."
8794 (if a (not b) b))
8796 (defun org-fixup-message-id-for-http (s)
8797 "Replace special characters in a message id, so it can be used in an http query."
8798 (when (string-match "%" s)
8799 (setq s (mapconcat (lambda (c)
8800 (if (eq c ?%)
8801 "%25"
8802 (char-to-string c)))
8803 s "")))
8804 (while (string-match "<" s)
8805 (setq s (replace-match "%3C" t t s)))
8806 (while (string-match ">" s)
8807 (setq s (replace-match "%3E" t t s)))
8808 (while (string-match "@" s)
8809 (setq s (replace-match "%40" t t s)))
8812 ;;;###autoload
8813 (defun org-insert-link-global ()
8814 "Insert a link like Org-mode does.
8815 This command can be called in any mode to insert a link in Org-mode syntax."
8816 (interactive)
8817 (org-load-modules-maybe)
8818 (org-run-like-in-org-mode 'org-insert-link))
8820 (defun org-insert-link (&optional complete-file link-location)
8821 "Insert a link. At the prompt, enter the link.
8823 Completion can be used to insert any of the link protocol prefixes like
8824 http or ftp in use.
8826 The history can be used to select a link previously stored with
8827 `org-store-link'. When the empty string is entered (i.e. if you just
8828 press RET at the prompt), the link defaults to the most recently
8829 stored link. As SPC triggers completion in the minibuffer, you need to
8830 use M-SPC or C-q SPC to force the insertion of a space character.
8832 You will also be prompted for a description, and if one is given, it will
8833 be displayed in the buffer instead of the link.
8835 If there is already a link at point, this command will allow you to edit link
8836 and description parts.
8838 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
8839 be selected using completion. The path to the file will be relative to the
8840 current directory if the file is in the current directory or a subdirectory.
8841 Otherwise, the link will be the absolute path as completed in the minibuffer
8842 \(i.e. normally ~/path/to/file). You can configure this behavior using the
8843 option `org-link-file-path-type'.
8845 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
8846 the current directory or below.
8848 With three \\[universal-argument] prefixes, negate the meaning of
8849 `org-keep-stored-link-after-insertion'.
8851 If `org-make-link-description-function' is non-nil, this function will be
8852 called with the link target, and the result will be the default
8853 link description.
8855 If the LINK-LOCATION parameter is non-nil, this value will be
8856 used as the link location instead of reading one interactively."
8857 (interactive "P")
8858 (let* ((wcf (current-window-configuration))
8859 (region (if (org-region-active-p)
8860 (buffer-substring (region-beginning) (region-end))))
8861 (remove (and region (list (region-beginning) (region-end))))
8862 (desc region)
8863 tmphist ; byte-compile incorrectly complains about this
8864 (link link-location)
8865 entry file all-prefixes)
8866 (cond
8867 (link-location) ; specified by arg, just use it.
8868 ((org-in-regexp org-bracket-link-regexp 1)
8869 ;; We do have a link at point, and we are going to edit it.
8870 (setq remove (list (match-beginning 0) (match-end 0)))
8871 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8872 (setq link (read-string "Link: "
8873 (org-link-unescape
8874 (org-match-string-no-properties 1)))))
8875 ((or (org-in-regexp org-angle-link-re)
8876 (org-in-regexp org-plain-link-re))
8877 ;; Convert to bracket link
8878 (setq remove (list (match-beginning 0) (match-end 0))
8879 link (read-string "Link: "
8880 (org-remove-angle-brackets (match-string 0)))))
8881 ((member complete-file '((4) (16)))
8882 ;; Completing read for file names.
8883 (setq link (org-file-complete-link complete-file)))
8885 ;; Read link, with completion for stored links.
8886 (with-output-to-temp-buffer "*Org Links*"
8887 (princ "Insert a link.
8888 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8889 (when org-stored-links
8890 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8891 (princ (mapconcat
8892 (lambda (x)
8893 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8894 (reverse org-stored-links) "\n"))))
8895 (let ((cw (selected-window)))
8896 (select-window (get-buffer-window "*Org Links*" 'visible))
8897 (with-current-buffer "*Org Links*" (setq truncate-lines) t)
8898 (unless (pos-visible-in-window-p (point-max))
8899 (org-fit-window-to-buffer))
8900 (and (window-live-p cw) (select-window cw)))
8901 ;; Fake a link history, containing the stored links.
8902 (setq tmphist (append (mapcar 'car org-stored-links)
8903 org-insert-link-history))
8904 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8905 (mapcar 'car org-link-abbrev-alist)
8906 org-link-types))
8907 (unwind-protect
8908 (progn
8909 (setq link
8910 (let ((org-completion-use-ido nil)
8911 (org-completion-use-iswitchb nil))
8912 (org-completing-read
8913 "Link: "
8914 (append
8915 (mapcar (lambda (x) (list (concat x ":")))
8916 all-prefixes)
8917 (mapcar 'car org-stored-links))
8918 nil nil nil
8919 'tmphist
8920 (car (car org-stored-links)))))
8921 (if (not (string-match "\\S-" link))
8922 (error "No link selected"))
8923 (if (or (member link all-prefixes)
8924 (and (equal ":" (substring link -1))
8925 (member (substring link 0 -1) all-prefixes)
8926 (setq link (substring link 0 -1))))
8927 (setq link (org-link-try-special-completion link))))
8928 (set-window-configuration wcf)
8929 (kill-buffer "*Org Links*"))
8930 (setq entry (assoc link org-stored-links))
8931 (or entry (push link org-insert-link-history))
8932 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8933 (not org-keep-stored-link-after-insertion))
8934 (setq org-stored-links (delq (assoc link org-stored-links)
8935 org-stored-links)))
8936 (setq desc (or desc (nth 1 entry)))))
8938 (if (string-match org-plain-link-re link)
8939 ;; URL-like link, normalize the use of angular brackets.
8940 (setq link (org-make-link (org-remove-angle-brackets link))))
8942 ;; Check if we are linking to the current file with a search option
8943 ;; If yes, simplify the link by using only the search option.
8944 (when (and buffer-file-name
8945 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8946 (let* ((path (match-string 1 link))
8947 (case-fold-search nil)
8948 (search (match-string 2 link)))
8949 (save-match-data
8950 (if (equal (file-truename buffer-file-name) (file-truename path))
8951 ;; We are linking to this same file, with a search option
8952 (setq link search)))))
8954 ;; Check if we can/should use a relative path. If yes, simplify the link
8955 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8956 (let* ((type (match-string 1 link))
8957 (path (match-string 2 link))
8958 (origpath path)
8959 (case-fold-search nil))
8960 (cond
8961 ((or (eq org-link-file-path-type 'absolute)
8962 (equal complete-file '(16)))
8963 (setq path (abbreviate-file-name (expand-file-name path))))
8964 ((eq org-link-file-path-type 'noabbrev)
8965 (setq path (expand-file-name path)))
8966 ((eq org-link-file-path-type 'relative)
8967 (setq path (file-relative-name path)))
8969 (save-match-data
8970 (if (string-match (concat "^" (regexp-quote
8971 (expand-file-name
8972 (file-name-as-directory
8973 default-directory))))
8974 (expand-file-name path))
8975 ;; We are linking a file with relative path name.
8976 (setq path (substring (expand-file-name path)
8977 (match-end 0)))
8978 (setq path (abbreviate-file-name (expand-file-name path)))))))
8979 (setq link (concat type path))
8980 (if (equal desc origpath)
8981 (setq desc path))))
8983 (if org-make-link-description-function
8984 (setq desc (funcall org-make-link-description-function link desc)))
8986 (setq desc (read-string "Description: " desc))
8987 (unless (string-match "\\S-" desc) (setq desc nil))
8988 (if remove (apply 'delete-region remove))
8989 (insert (org-make-link-string link desc))))
8991 (defun org-link-try-special-completion (type)
8992 "If there is completion support for link type TYPE, offer it."
8993 (let ((fun (intern (concat "org-" type "-complete-link"))))
8994 (if (functionp fun)
8995 (funcall fun)
8996 (read-string "Link (no completion support): " (concat type ":")))))
8998 (defun org-file-complete-link (&optional arg)
8999 "Create a file link using completion."
9000 (let (file link)
9001 (setq file (read-file-name "File: "))
9002 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9003 (pwd1 (file-name-as-directory (abbreviate-file-name
9004 (expand-file-name ".")))))
9005 (cond
9006 ((equal arg '(16))
9007 (setq link (org-make-link
9008 "file:"
9009 (abbreviate-file-name (expand-file-name file)))))
9010 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9011 (setq link (org-make-link "file:" (match-string 1 file))))
9012 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9013 (expand-file-name file))
9014 (setq link (org-make-link
9015 "file:" (match-string 1 (expand-file-name file)))))
9016 (t (setq link (org-make-link "file:" file)))))
9017 link))
9019 (defun org-completing-read (&rest args)
9020 "Completing-read with SPACE being a normal character."
9021 (let ((minibuffer-local-completion-map
9022 (copy-keymap minibuffer-local-completion-map)))
9023 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9024 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9025 (apply 'org-icompleting-read args)))
9027 (defun org-completing-read-no-i (&rest args)
9028 (let (org-completion-use-ido org-completion-use-iswitchb)
9029 (apply 'org-completing-read args)))
9031 (defun org-iswitchb-completing-read (prompt choices &rest args)
9032 "Use iswitch as a completing-read replacement to choose from choices.
9033 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9034 from."
9035 (let* ((iswitchb-use-virtual-buffers nil)
9036 (iswitchb-make-buflist-hook
9037 (lambda ()
9038 (setq iswitchb-temp-buflist choices))))
9039 (iswitchb-read-buffer prompt)))
9041 (defun org-icompleting-read (&rest args)
9042 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9043 (org-without-partial-completion
9044 (if (and org-completion-use-ido
9045 (fboundp 'ido-completing-read)
9046 (boundp 'ido-mode) ido-mode
9047 (listp (second args)))
9048 (let ((ido-enter-matching-directory nil))
9049 (apply 'ido-completing-read (concat (car args))
9050 (if (consp (car (nth 1 args)))
9051 (mapcar 'car (nth 1 args))
9052 (nth 1 args))
9053 (cddr args)))
9054 (if (and org-completion-use-iswitchb
9055 (boundp 'iswitchb-mode) iswitchb-mode
9056 (listp (second args)))
9057 (apply 'org-iswitchb-completing-read (concat (car args))
9058 (if (consp (car (nth 1 args)))
9059 (mapcar 'car (nth 1 args))
9060 (nth 1 args))
9061 (cddr args))
9062 (apply 'completing-read args)))))
9064 (defun org-extract-attributes (s)
9065 "Extract the attributes cookie from a string and set as text property."
9066 (let (a attr (start 0) key value)
9067 (save-match-data
9068 (when (string-match "{{\\([^}]+\\)}}$" s)
9069 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9070 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9071 (setq key (match-string 1 a) value (match-string 2 a)
9072 start (match-end 0)
9073 attr (plist-put attr (intern key) value))))
9074 (org-add-props s nil 'org-attr attr))
9077 (defun org-extract-attributes-from-string (tag)
9078 (let (key value attr)
9079 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9080 (setq key (match-string 1 tag) value (match-string 2 tag)
9081 tag (replace-match "" t t tag)
9082 attr (plist-put attr (intern key) value)))
9083 (cons tag attr)))
9085 (defun org-attributes-to-string (plist)
9086 "Format a property list into an HTML attribute list."
9087 (let ((s "") key value)
9088 (while plist
9089 (setq key (pop plist) value (pop plist))
9090 (and value
9091 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9094 ;;; Opening/following a link
9096 (defvar org-link-search-failed nil)
9098 (defvar org-open-link-functions nil
9099 "Hook for functions finding a plain text link.
9100 These functions must take a single argument, the link content.
9101 They will be called for links that look like [[link text][description]]
9102 when LINK TEXT does not have a protocol like \"http:\" and does not look
9103 like a filename (e.g. \"./blue.png\").
9105 These functions will be called *before* Org attempts to resolve the
9106 link by doing text searches in the current buffer - so if you want a
9107 link \"[[target]]\" to still find \"<<target>>\", your function should
9108 handle this as a special case.
9110 When the function does handle the link, it must return a non-nil value.
9111 If it decides that it is not responsible for this link, it must return
9112 nil to indicate that that Org-mode can continue with other options
9113 like exact and fuzzy text search.")
9115 (defun org-next-link ()
9116 "Move forward to the next link.
9117 If the link is in hidden text, expose it."
9118 (interactive)
9119 (when (and org-link-search-failed (eq this-command last-command))
9120 (goto-char (point-min))
9121 (message "Link search wrapped back to beginning of buffer"))
9122 (setq org-link-search-failed nil)
9123 (let* ((pos (point))
9124 (ct (org-context))
9125 (a (assoc :link ct)))
9126 (if a (goto-char (nth 2 a)))
9127 (if (re-search-forward org-any-link-re nil t)
9128 (progn
9129 (goto-char (match-beginning 0))
9130 (if (outline-invisible-p) (org-show-context)))
9131 (goto-char pos)
9132 (setq org-link-search-failed t)
9133 (error "No further link found"))))
9135 (defun org-previous-link ()
9136 "Move backward to the previous link.
9137 If the link is in hidden text, expose it."
9138 (interactive)
9139 (when (and org-link-search-failed (eq this-command last-command))
9140 (goto-char (point-max))
9141 (message "Link search wrapped back to end of buffer"))
9142 (setq org-link-search-failed nil)
9143 (let* ((pos (point))
9144 (ct (org-context))
9145 (a (assoc :link ct)))
9146 (if a (goto-char (nth 1 a)))
9147 (if (re-search-backward org-any-link-re nil t)
9148 (progn
9149 (goto-char (match-beginning 0))
9150 (if (outline-invisible-p) (org-show-context)))
9151 (goto-char pos)
9152 (setq org-link-search-failed t)
9153 (error "No further link found"))))
9155 (defun org-translate-link (s)
9156 "Translate a link string if a translation function has been defined."
9157 (if (and org-link-translation-function
9158 (fboundp org-link-translation-function)
9159 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9160 (progn
9161 (setq s (funcall org-link-translation-function
9162 (match-string 1) (match-string 2)))
9163 (concat (car s) ":" (cdr s)))
9166 (defun org-translate-link-from-planner (type path)
9167 "Translate a link from Emacs Planner syntax so that Org can follow it.
9168 This is still an experimental function, your mileage may vary."
9169 (cond
9170 ((member type '("http" "https" "news" "ftp"))
9171 ;; standard Internet links are the same.
9172 nil)
9173 ((and (equal type "irc") (string-match "^//" path))
9174 ;; Planner has two / at the beginning of an irc link, we have 1.
9175 ;; We should have zero, actually....
9176 (setq path (substring path 1)))
9177 ((and (equal type "lisp") (string-match "^/" path))
9178 ;; Planner has a slash, we do not.
9179 (setq type "elisp" path (substring path 1)))
9180 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9181 ;; A typical message link. Planner has the id after the final slash,
9182 ;; we separate it with a hash mark
9183 (setq path (concat (match-string 1 path) "#"
9184 (org-remove-angle-brackets (match-string 2 path)))))
9186 (cons type path))
9188 (defun org-find-file-at-mouse (ev)
9189 "Open file link or URL at mouse."
9190 (interactive "e")
9191 (mouse-set-point ev)
9192 (org-open-at-point 'in-emacs))
9194 (defun org-open-at-mouse (ev)
9195 "Open file link or URL at mouse."
9196 (interactive "e")
9197 (mouse-set-point ev)
9198 (if (eq major-mode 'org-agenda-mode)
9199 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9200 (org-open-at-point))
9202 (defvar org-window-config-before-follow-link nil
9203 "The window configuration before following a link.
9204 This is saved in case the need arises to restore it.")
9206 (defvar org-open-link-marker (make-marker)
9207 "Marker pointing to the location where `org-open-at-point; was called.")
9209 ;;;###autoload
9210 (defun org-open-at-point-global ()
9211 "Follow a link like Org-mode does.
9212 This command can be called in any mode to follow a link that has
9213 Org-mode syntax."
9214 (interactive)
9215 (org-run-like-in-org-mode 'org-open-at-point))
9217 ;;;###autoload
9218 (defun org-open-link-from-string (s &optional arg reference-buffer)
9219 "Open a link in the string S, as if it was in Org-mode."
9220 (interactive "sLink: \nP")
9221 (let ((reference-buffer (or reference-buffer (current-buffer))))
9222 (with-temp-buffer
9223 (let ((org-inhibit-startup t))
9224 (org-mode)
9225 (insert s)
9226 (goto-char (point-min))
9227 (when reference-buffer
9228 (setq org-link-abbrev-alist-local
9229 (with-current-buffer reference-buffer
9230 org-link-abbrev-alist-local)))
9231 (org-open-at-point arg reference-buffer)))))
9233 (defvar org-open-at-point-functions nil
9234 "Hook that is run when following a link at point.
9236 Functions in this hook must return t if they identify and follow
9237 a link at point. If they don't find anything interesting at point,
9238 they must return nil.")
9240 (defun org-open-at-point (&optional arg reference-buffer)
9241 "Open link at or after point.
9242 If there is no link at point, this function will search forward up to
9243 the end of the current line.
9244 Normally, files will be opened by an appropriate application. If the
9245 optional prefix argument ARG is non-nil, Emacs will visit the file.
9246 With a double prefix argument, try to open outside of Emacs, in the
9247 application the system uses for this file type."
9248 (interactive "P")
9249 ;; if in a code block, then open the block's results
9250 (unless (call-interactively #'org-babel-open-src-block-result)
9251 (org-load-modules-maybe)
9252 (move-marker org-open-link-marker (point))
9253 (setq org-window-config-before-follow-link (current-window-configuration))
9254 (org-remove-occur-highlights nil nil t)
9255 (cond
9256 ((and (org-on-heading-p)
9257 (not (org-in-regexp
9258 (concat org-plain-link-re "\\|"
9259 org-bracket-link-regexp "\\|"
9260 org-angle-link-re "\\|"
9261 "[ \t]:[^ \t\n]+:[ \t]*$")))
9262 (not (get-text-property (point) 'org-linked-text)))
9263 (or (org-offer-links-in-entry arg)
9264 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9265 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9266 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9267 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9268 (not (org-in-regexp org-bracket-link-regexp)))
9269 (org-footnote-action))
9271 (let (type path link line search (pos (point)))
9272 (catch 'match
9273 (save-excursion
9274 (skip-chars-forward "^]\n\r")
9275 (when (org-in-regexp org-bracket-link-regexp 1)
9276 (setq link (org-extract-attributes
9277 (org-link-unescape (org-match-string-no-properties 1))))
9278 (while (string-match " *\n *" link)
9279 (setq link (replace-match " " t t link)))
9280 (setq link (org-link-expand-abbrev link))
9281 (cond
9282 ((or (file-name-absolute-p link)
9283 (string-match "^\\.\\.?/" link))
9284 (setq type "file" path link))
9285 ((string-match org-link-re-with-space3 link)
9286 (setq type (match-string 1 link) path (match-string 2 link)))
9287 (t (setq type "thisfile" path link)))
9288 (throw 'match t)))
9290 (when (get-text-property (point) 'org-linked-text)
9291 (setq type "thisfile"
9292 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9293 (1+ (point)) (point))
9294 path (buffer-substring
9295 (or (previous-single-property-change pos 'org-linked-text)
9296 (point-min))
9297 (or (next-single-property-change pos 'org-linked-text)
9298 (point-max))))
9299 (throw 'match t))
9301 (save-excursion
9302 (when (or (org-in-regexp org-angle-link-re)
9303 (org-in-regexp org-plain-link-re))
9304 (setq type (match-string 1) path (match-string 2))
9305 (throw 'match t)))
9306 (save-excursion
9307 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9308 (setq type "tags"
9309 path (match-string 1))
9310 (while (string-match ":" path)
9311 (setq path (replace-match "+" t t path)))
9312 (throw 'match t)))
9313 (when (org-in-regexp "<\\([^><\n]+\\)>")
9314 (setq type "tree-match"
9315 path (match-string 1))
9316 (throw 'match t)))
9317 (unless path
9318 (error "No link found"))
9320 ;; switch back to reference buffer
9321 ;; needed when if called in a temporary buffer through
9322 ;; org-open-link-from-string
9323 (with-current-buffer (or reference-buffer (current-buffer))
9325 ;; Remove any trailing spaces in path
9326 (if (string-match " +\\'" path)
9327 (setq path (replace-match "" t t path)))
9328 (if (and org-link-translation-function
9329 (fboundp org-link-translation-function))
9330 ;; Check if we need to translate the link
9331 (let ((tmp (funcall org-link-translation-function type path)))
9332 (setq type (car tmp) path (cdr tmp))))
9334 (cond
9336 ((assoc type org-link-protocols)
9337 (funcall (nth 1 (assoc type org-link-protocols)) path))
9339 ((equal type "mailto")
9340 (let ((cmd (car org-link-mailto-program))
9341 (args (cdr org-link-mailto-program)) args1
9342 (address path) (subject "") a)
9343 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9344 (setq address (match-string 1 path)
9345 subject (org-link-escape (match-string 2 path))))
9346 (while args
9347 (cond
9348 ((not (stringp (car args))) (push (pop args) args1))
9349 (t (setq a (pop args))
9350 (if (string-match "%a" a)
9351 (setq a (replace-match address t t a)))
9352 (if (string-match "%s" a)
9353 (setq a (replace-match subject t t a)))
9354 (push a args1))))
9355 (apply cmd (nreverse args1))))
9357 ((member type '("http" "https" "ftp" "news"))
9358 (browse-url (concat type ":" (org-link-escape
9359 path org-link-escape-chars-browser))))
9361 ((string= type "doi")
9362 (browse-url (concat "http://dx.doi.org/"
9363 (org-link-escape
9364 path org-link-escape-chars-browser))))
9366 ((member type '("message"))
9367 (browse-url (concat type ":" path)))
9369 ((string= type "tags")
9370 (org-tags-view arg path))
9372 ((string= type "tree-match")
9373 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9375 ((string= type "file")
9376 (if (string-match "::\\([0-9]+\\)\\'" path)
9377 (setq line (string-to-number (match-string 1 path))
9378 path (substring path 0 (match-beginning 0)))
9379 (if (string-match "::\\(.+\\)\\'" path)
9380 (setq search (match-string 1 path)
9381 path (substring path 0 (match-beginning 0)))))
9382 (if (string-match "[*?{]" (file-name-nondirectory path))
9383 (dired path)
9384 (org-open-file path arg line search)))
9386 ((string= type "shell")
9387 (let ((cmd path))
9388 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9389 (string-match org-confirm-shell-link-not-regexp cmd))
9390 (not org-confirm-shell-link-function)
9391 (funcall org-confirm-shell-link-function
9392 (format "Execute \"%s\" in shell? "
9393 (org-add-props cmd nil
9394 'face 'org-warning))))
9395 (progn
9396 (message "Executing %s" cmd)
9397 (shell-command cmd))
9398 (error "Abort"))))
9400 ((string= type "elisp")
9401 (let ((cmd path))
9402 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9403 (string-match org-confirm-elisp-link-not-regexp cmd))
9404 (not org-confirm-elisp-link-function)
9405 (funcall org-confirm-elisp-link-function
9406 (format "Execute \"%s\" as elisp? "
9407 (org-add-props cmd nil
9408 'face 'org-warning))))
9409 (message "%s => %s" cmd
9410 (if (equal (string-to-char cmd) ?\()
9411 (eval (read cmd))
9412 (call-interactively (read cmd))))
9413 (error "Abort"))))
9415 ((and (string= type "thisfile")
9416 (run-hook-with-args-until-success
9417 'org-open-link-functions path)))
9419 ((string= type "thisfile")
9420 (if arg
9421 (switch-to-buffer-other-window
9422 (org-get-buffer-for-internal-link (current-buffer)))
9423 (org-mark-ring-push))
9424 (let ((cmd `(org-link-search
9425 ,path
9426 ,(cond ((equal arg '(4)) ''occur)
9427 ((equal arg '(16)) ''org-occur)
9428 (t nil))
9429 ,pos)))
9430 (condition-case nil (eval cmd)
9431 (error (progn (widen) (eval cmd))))))
9434 (browse-url-at-point)))))))
9435 (move-marker org-open-link-marker nil)
9436 (run-hook-with-args 'org-follow-link-hook)))
9438 (defun org-offer-links-in-entry (&optional nth zero)
9439 "Offer links in the current entry and follow the selected link.
9440 If there is only one link, follow it immediately as well.
9441 If NTH is an integer, immediately pick the NTH link found.
9442 If ZERO is a string, check also this string for a link, and if
9443 there is one, offer it as link number zero."
9444 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9445 "\\(" org-angle-link-re "\\)\\|"
9446 "\\(" org-plain-link-re "\\)"))
9447 (cnt ?0)
9448 (in-emacs (if (integerp nth) nil nth))
9449 have-zero end links link c)
9450 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9451 (push (match-string 0 zero) links)
9452 (setq cnt (1- cnt) have-zero t))
9453 (save-excursion
9454 (org-back-to-heading t)
9455 (setq end (save-excursion (outline-next-heading) (point)))
9456 (while (re-search-forward re end t)
9457 (push (match-string 0) links))
9458 (setq links (org-uniquify (reverse links))))
9460 (cond
9461 ((null links)
9462 (message "No links"))
9463 ((equal (length links) 1)
9464 (setq link (list (car links))))
9465 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9466 (setq link (nth (if have-zero nth (1- nth)) links)))
9467 (t ; we have to select a link
9468 (save-excursion
9469 (save-window-excursion
9470 (delete-other-windows)
9471 (with-output-to-temp-buffer "*Select Link*"
9472 (mapc (lambda (l)
9473 (if (not (string-match org-bracket-link-regexp l))
9474 (princ (format "[%c] %s\n" (incf cnt)
9475 (org-remove-angle-brackets l)))
9476 (if (match-end 3)
9477 (princ (format "[%c] %s (%s)\n" (incf cnt)
9478 (match-string 3 l) (match-string 1 l)))
9479 (princ (format "[%c] %s\n" (incf cnt)
9480 (match-string 1 l))))))
9481 links))
9482 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9483 (message "Select link to open, RET to open all:")
9484 (setq c (read-char-exclusive))
9485 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9486 (when (equal c ?q) (error "Abort"))
9487 (if (equal c ?\C-m)
9488 (setq link links)
9489 (setq nth (- c ?0))
9490 (if have-zero (setq nth (1+ nth)))
9491 (unless (and (integerp nth) (>= (length links) nth))
9492 (error "Invalid link selection"))
9493 (setq link (list (nth (1- nth) links))))))
9494 (if link
9495 (let ((buf (current-buffer)))
9496 (dolist (l link)
9497 (org-open-link-from-string l in-emacs buf))
9499 nil)))
9501 ;; Add special file links that specify the way of opening
9503 (org-add-link-type "file+sys" 'org-open-file-with-system)
9504 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9505 (defun org-open-file-with-system (path)
9506 "Open file at PATH using the system way of opening it."
9507 (org-open-file path 'system))
9508 (defun org-open-file-with-emacs (path)
9509 "Open file at PATH in Emacs."
9510 (org-open-file path 'emacs))
9511 (defun org-remove-file-link-modifiers ()
9512 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9513 (goto-char (point-min))
9514 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9515 (org-if-unprotected
9516 (replace-match "file:" t t))))
9517 (eval-after-load "org-exp"
9518 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9519 'org-remove-file-link-modifiers))
9521 ;;;; Time estimates
9523 (defun org-get-effort (&optional pom)
9524 "Get the effort estimate for the current entry."
9525 (org-entry-get pom org-effort-property))
9527 ;;; File search
9529 (defvar org-create-file-search-functions nil
9530 "List of functions to construct the right search string for a file link.
9531 These functions are called in turn with point at the location to
9532 which the link should point.
9534 A function in the hook should first test if it would like to
9535 handle this file type, for example by checking the `major-mode'
9536 or the file extension. If it decides not to handle this file, it
9537 should just return nil to give other functions a chance. If it
9538 does handle the file, it must return the search string to be used
9539 when following the link. The search string will be part of the
9540 file link, given after a double colon, and `org-open-at-point'
9541 will automatically search for it. If special measures must be
9542 taken to make the search successful, another function should be
9543 added to the companion hook `org-execute-file-search-functions',
9544 which see.
9546 A function in this hook may also use `setq' to set the variable
9547 `description' to provide a suggestion for the descriptive text to
9548 be used for this link when it gets inserted into an Org-mode
9549 buffer with \\[org-insert-link].")
9551 (defvar org-execute-file-search-functions nil
9552 "List of functions to execute a file search triggered by a link.
9554 Functions added to this hook must accept a single argument, the
9555 search string that was part of the file link, the part after the
9556 double colon. The function must first check if it would like to
9557 handle this search, for example by checking the `major-mode' or
9558 the file extension. If it decides not to handle this search, it
9559 should just return nil to give other functions a chance. If it
9560 does handle the search, it must return a non-nil value to keep
9561 other functions from trying.
9563 Each function can access the current prefix argument through the
9564 variable `current-prefix-argument'. Note that a single prefix is
9565 used to force opening a link in Emacs, so it may be good to only
9566 use a numeric or double prefix to guide the search function.
9568 In case this is needed, a function in this hook can also restore
9569 the window configuration before `org-open-at-point' was called using:
9571 (set-window-configuration org-window-config-before-follow-link)")
9573 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
9574 (defun org-link-search (s &optional type avoid-pos)
9575 "Search for a link search option.
9576 If S is surrounded by forward slashes, it is interpreted as a
9577 regular expression. In org-mode files, this will create an `org-occur'
9578 sparse tree. In ordinary files, `occur' will be used to list matches.
9579 If the current buffer is in `dired-mode', grep will be used to search
9580 in all files. If AVOID-POS is given, ignore matches near that position."
9581 (let ((case-fold-search t)
9582 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9583 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
9584 (append '(("") (" ") ("\t") ("\n"))
9585 org-emphasis-alist)
9586 "\\|") "\\)"))
9587 (pos (point))
9588 (pre nil) (post nil)
9589 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
9590 (cond
9591 ;; First check if there are any special search functions
9592 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9593 ;; Now try the builtin stuff
9594 ((and (equal (string-to-char s0) ?#)
9595 (> (length s0) 1)
9596 (save-excursion
9597 (goto-char (point-min))
9598 (and
9599 (re-search-forward
9600 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
9601 (setq type 'dedicated
9602 pos (match-beginning 0))))
9603 ;; There is an exact target for this
9604 (goto-char pos)
9605 (org-back-to-heading t)))
9606 ((save-excursion
9607 (goto-char (point-min))
9608 (and
9609 (re-search-forward
9610 (concat "<<" (regexp-quote s0) ">>") nil t)
9611 (setq type 'dedicated
9612 pos (match-beginning 0))))
9613 ;; There is an exact target for this
9614 (goto-char pos))
9615 ((and (string-match "^(\\(.*\\))$" s0)
9616 (save-excursion
9617 (goto-char (point-min))
9618 (and
9619 (re-search-forward
9620 (concat "[^[]" (regexp-quote
9621 (format org-coderef-label-format
9622 (match-string 1 s0))))
9623 nil t)
9624 (setq type 'dedicated
9625 pos (1+ (match-beginning 0))))))
9626 ;; There is a coderef target for this
9627 (goto-char pos))
9628 ((string-match "^/\\(.*\\)/$" s)
9629 ;; A regular expression
9630 (cond
9631 ((org-mode-p)
9632 (org-occur (match-string 1 s)))
9633 ;;((eq major-mode 'dired-mode)
9634 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9635 (t (org-do-occur (match-string 1 s)))))
9636 ((and (org-mode-p) org-link-search-must-match-exact-headline)
9637 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
9638 (goto-char (point-min))
9639 (cond
9640 ((let (case-fold-search)
9641 (re-search-forward (format org-complex-heading-regexp-format
9642 (regexp-quote s))
9643 nil t))
9644 ;; OK, found a match
9645 (setq type 'dedicated)
9646 (goto-char (match-beginning 0)))
9647 ((and (not org-link-search-inhibit-query)
9648 (eq org-link-search-must-match-exact-headline 'query-to-create)
9649 (y-or-n-p "No match - create this as a new heading? "))
9650 (goto-char (point-max))
9651 (or (bolp) (newline))
9652 (insert "* " s "\n")
9653 (beginning-of-line 0))
9655 (goto-char pos)
9656 (error "No match"))))
9658 ;; A normal search string
9659 (when (equal (string-to-char s) ?*)
9660 ;; Anchor on headlines, post may include tags.
9661 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
9662 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
9663 s (substring s 1)))
9664 (remove-text-properties
9665 0 (length s)
9666 '(face nil mouse-face nil keymap nil fontified nil) s)
9667 ;; Make a series of regular expressions to find a match
9668 (setq words (org-split-string s "[ \n\r\t]+")
9670 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9671 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
9672 "\\)" markers)
9673 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9674 re2a (concat "[ \t\r\n]" re2a_)
9675 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9676 re4 (concat "[^a-zA-Z_]" re4_)
9678 re1 (concat pre re2 post)
9679 re3 (concat pre (if pre re4_ re4) post)
9680 re5 (concat pre ".*" re4)
9681 re2 (concat pre re2)
9682 re2a (concat pre (if pre re2a_ re2a))
9683 re4 (concat pre (if pre re4_ re4))
9684 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9685 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9686 re5 "\\)"
9688 (cond
9689 ((eq type 'org-occur) (org-occur reall))
9690 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9691 (t (goto-char (point-min))
9692 (setq type 'fuzzy)
9693 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
9694 (org-search-not-self 1 re1 nil t)
9695 (org-search-not-self 1 re2 nil t)
9696 (org-search-not-self 1 re2a nil t)
9697 (org-search-not-self 1 re3 nil t)
9698 (org-search-not-self 1 re4 nil t)
9699 (org-search-not-self 1 re5 nil t)
9701 (goto-char (match-beginning 1))
9702 (goto-char pos)
9703 (error "No match"))))))
9704 (and (org-mode-p) (org-show-context 'link-search))
9705 type))
9707 (defun org-search-not-self (group &rest args)
9708 "Execute `re-search-forward', but only accept matches that do not
9709 enclose the position of `org-open-link-marker'."
9710 (let ((m org-open-link-marker))
9711 (catch 'exit
9712 (while (apply 're-search-forward args)
9713 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
9714 (goto-char (match-end group))
9715 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9716 (> (match-beginning 0) (marker-position m))
9717 (< (match-end 0) (marker-position m)))
9718 (save-match-data
9719 (or (not (org-in-regexp
9720 org-bracket-link-analytic-regexp 1))
9721 (not (match-end 4)) ; no description
9722 (and (<= (match-beginning 4) (point))
9723 (>= (match-end 4) (point))))))
9724 (throw 'exit (point))))))))
9726 (defun org-get-buffer-for-internal-link (buffer)
9727 "Return a buffer to be used for displaying the link target of internal links."
9728 (cond
9729 ((not org-display-internal-link-with-indirect-buffer)
9730 buffer)
9731 ((string-match "(Clone)$" (buffer-name buffer))
9732 (message "Buffer is already a clone, not making another one")
9733 ;; we also do not modify visibility in this case
9734 buffer)
9735 (t ; make a new indirect buffer for displaying the link
9736 (let* ((bn (buffer-name buffer))
9737 (ibn (concat bn "(Clone)"))
9738 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9739 (with-current-buffer ib (org-overview))
9740 ib))))
9742 (defun org-do-occur (regexp &optional cleanup)
9743 "Call the Emacs command `occur'.
9744 If CLEANUP is non-nil, remove the printout of the regular expression
9745 in the *Occur* buffer. This is useful if the regex is long and not useful
9746 to read."
9747 (occur regexp)
9748 (when cleanup
9749 (let ((cwin (selected-window)) win beg end)
9750 (when (setq win (get-buffer-window "*Occur*"))
9751 (select-window win))
9752 (goto-char (point-min))
9753 (when (re-search-forward "match[a-z]+" nil t)
9754 (setq beg (match-end 0))
9755 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9756 (setq end (1- (match-beginning 0)))))
9757 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9758 (goto-char (point-min))
9759 (select-window cwin))))
9761 ;;; The mark ring for links jumps
9763 (defvar org-mark-ring nil
9764 "Mark ring for positions before jumps in Org-mode.")
9765 (defvar org-mark-ring-last-goto nil
9766 "Last position in the mark ring used to go back.")
9767 ;; Fill and close the ring
9768 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9769 (loop for i from 1 to org-mark-ring-length do
9770 (push (make-marker) org-mark-ring))
9771 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9772 org-mark-ring)
9774 (defun org-mark-ring-push (&optional pos buffer)
9775 "Put the current position or POS into the mark ring and rotate it."
9776 (interactive)
9777 (setq pos (or pos (point)))
9778 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9779 (move-marker (car org-mark-ring)
9780 (or pos (point))
9781 (or buffer (current-buffer)))
9782 (message "%s"
9783 (substitute-command-keys
9784 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9786 (defun org-mark-ring-goto (&optional n)
9787 "Jump to the previous position in the mark ring.
9788 With prefix arg N, jump back that many stored positions. When
9789 called several times in succession, walk through the entire ring.
9790 Org-mode commands jumping to a different position in the current file,
9791 or to another Org-mode file, automatically push the old position
9792 onto the ring."
9793 (interactive "p")
9794 (let (p m)
9795 (if (eq last-command this-command)
9796 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9797 (setq p org-mark-ring))
9798 (setq org-mark-ring-last-goto p)
9799 (setq m (car p))
9800 (switch-to-buffer (marker-buffer m))
9801 (goto-char m)
9802 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9804 (defun org-remove-angle-brackets (s)
9805 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9806 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9808 (defun org-add-angle-brackets (s)
9809 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9810 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9812 (defun org-remove-double-quotes (s)
9813 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9814 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
9817 ;;; Following specific links
9819 (defun org-follow-timestamp-link ()
9820 (cond
9821 ((org-at-date-range-p t)
9822 (let ((org-agenda-start-on-weekday)
9823 (t1 (match-string 1))
9824 (t2 (match-string 2)))
9825 (setq t1 (time-to-days (org-time-string-to-time t1))
9826 t2 (time-to-days (org-time-string-to-time t2)))
9827 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9828 ((org-at-timestamp-p t)
9829 (org-agenda-list nil (time-to-days (org-time-string-to-time
9830 (substring (match-string 1) 0 10)))
9832 (t (error "This should not happen"))))
9835 ;;; Following file links
9836 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
9837 (declare-function mailcap-extension-to-mime "mailcap" (extn))
9838 (declare-function mailcap-mime-info
9839 "mailcap" (string &optional request no-decode))
9840 (defvar org-wait nil)
9841 (defun org-open-file (path &optional in-emacs line search)
9842 "Open the file at PATH.
9843 First, this expands any special file name abbreviations. Then the
9844 configuration variable `org-file-apps' is checked if it contains an
9845 entry for this file type, and if yes, the corresponding command is launched.
9847 If no application is found, Emacs simply visits the file.
9849 With optional prefix argument IN-EMACS, Emacs will visit the file.
9850 With a double \\[universal-argument] \\[universal-argument] \
9851 prefix arg, Org tries to avoid opening in Emacs
9852 and to use an external application to visit the file.
9854 Optional LINE specifies a line to go to, optional SEARCH a string
9855 to search for. If LINE or SEARCH is given, the file will be
9856 opened in Emacs, unless an entry from org-file-apps that makes
9857 use of groups in a regexp matches.
9858 If the file does not exist, an error is thrown."
9859 (let* ((file (if (equal path "")
9860 buffer-file-name
9861 (substitute-in-file-name (expand-file-name path))))
9862 (file-apps (append org-file-apps (org-default-apps)))
9863 (apps (org-remove-if
9864 'org-file-apps-entry-match-against-dlink-p file-apps))
9865 (apps-dlink (org-remove-if-not
9866 'org-file-apps-entry-match-against-dlink-p file-apps))
9867 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9868 (dirp (if remp nil (file-directory-p file)))
9869 (file (if (and dirp org-open-directory-means-index-dot-org)
9870 (concat (file-name-as-directory file) "index.org")
9871 file))
9872 (a-m-a-p (assq 'auto-mode apps))
9873 (dfile (downcase file))
9874 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
9875 (link (cond ((and (eq line nil)
9876 (eq search nil))
9877 file)
9878 (line
9879 (concat file "::" (number-to-string line)))
9880 (search
9881 (concat file "::" search))))
9882 (dlink (downcase link))
9883 (old-buffer (current-buffer))
9884 (old-pos (point))
9885 (old-mode major-mode)
9886 ext cmd link-match-data)
9887 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9888 (setq ext (match-string 1 dfile))
9889 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9890 (setq ext (match-string 1 dfile))))
9891 (cond
9892 ((member in-emacs '((16) system))
9893 (setq cmd (cdr (assoc 'system apps))))
9894 (in-emacs (setq cmd 'emacs))
9896 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9897 (and dirp (cdr (assoc 'directory apps)))
9898 ; first, try matching against apps-dlink
9899 ; if we get a match here, store the match data for later
9900 (let ((match (assoc-default dlink apps-dlink
9901 'string-match)))
9902 (if match
9903 (progn (setq link-match-data (match-data))
9904 match)
9905 (progn (setq in-emacs (or in-emacs line search))
9906 nil))) ; if we have no match in apps-dlink,
9907 ; always open the file in emacs if line or search
9908 ; is given (for backwards compatibility)
9909 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
9910 'string-match)
9911 (cdr (assoc ext apps))
9912 (cdr (assoc t apps))))))
9913 (when (eq cmd 'system)
9914 (setq cmd (cdr (assoc 'system apps))))
9915 (when (eq cmd 'default)
9916 (setq cmd (cdr (assoc t apps))))
9917 (when (eq cmd 'mailcap)
9918 (require 'mailcap)
9919 (mailcap-parse-mailcaps)
9920 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9921 (command (mailcap-mime-info mime-type)))
9922 (if (stringp command)
9923 (setq cmd command)
9924 (setq cmd 'emacs))))
9925 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
9926 (not (file-exists-p file))
9927 (not org-open-non-existing-files))
9928 (error "No such file: %s" file))
9929 (cond
9930 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9931 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9932 (while (string-match "['\"]%s['\"]" cmd)
9933 (setq cmd (replace-match "%s" t t cmd)))
9934 (while (string-match "%s" cmd)
9935 (setq cmd (replace-match
9936 (save-match-data
9937 (shell-quote-argument
9938 (convert-standard-filename file)))
9939 t t cmd)))
9941 ;; Replace "%1", "%2" etc. in command with group matches from regex
9942 (save-match-data
9943 (let ((match-index 1)
9944 (number-of-groups (- (/ (length link-match-data) 2) 1)))
9945 (set-match-data link-match-data)
9946 (while (<= match-index number-of-groups)
9947 (let ((regex (concat "%" (number-to-string match-index)))
9948 (replace-with (match-string match-index dlink)))
9949 (while (string-match regex cmd)
9950 (setq cmd (replace-match replace-with t t cmd))))
9951 (setq match-index (+ match-index 1)))))
9953 (save-window-excursion
9954 (start-process-shell-command cmd nil cmd)
9955 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9957 ((or (stringp cmd)
9958 (eq cmd 'emacs))
9959 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9960 (widen)
9961 (if line (org-goto-line line)
9962 (if search (org-link-search search))))
9963 ((consp cmd)
9964 (let ((file (convert-standard-filename file)))
9965 (save-match-data
9966 (set-match-data link-match-data)
9967 (eval cmd))))
9968 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9969 (and (org-mode-p) (eq old-mode 'org-mode)
9970 (or (not (equal old-buffer (current-buffer)))
9971 (not (equal old-pos (point))))
9972 (org-mark-ring-push old-pos old-buffer))))
9974 (defun org-file-apps-entry-match-against-dlink-p (entry)
9975 "This function returns non-nil if `entry' uses a regular
9976 expression which should be matched against the whole link by
9977 org-open-file.
9979 It assumes that is the case when the entry uses a regular
9980 expression which has at least one grouping construct and the
9981 action is either a lisp form or a command string containing
9982 '%1', i.e. using at least one subexpression match as a
9983 parameter."
9984 (let ((selector (car entry))
9985 (action (cdr entry)))
9986 (if (stringp selector)
9987 (and (> (regexp-opt-depth selector) 0)
9988 (or (and (stringp action)
9989 (string-match "%[0-9]" action))
9990 (consp action)))
9991 nil)))
9993 (defun org-default-apps ()
9994 "Return the default applications for this operating system."
9995 (cond
9996 ((eq system-type 'darwin)
9997 org-file-apps-defaults-macosx)
9998 ((eq system-type 'windows-nt)
9999 org-file-apps-defaults-windowsnt)
10000 (t org-file-apps-defaults-gnu)))
10002 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10003 "Convert extensions to regular expressions in the cars of LIST.
10004 Also, weed out any non-string entries, because the return value is used
10005 only for regexp matching.
10006 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10007 point to the symbol `emacs', indicating that the file should
10008 be opened in Emacs."
10009 (append
10010 (delq nil
10011 (mapcar (lambda (x)
10012 (if (not (stringp (car x)))
10014 (if (string-match "\\W" (car x))
10016 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10017 list))
10018 (if add-auto-mode
10019 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10021 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10022 (defun org-file-remote-p (file)
10023 "Test whether FILE specifies a location on a remote system.
10024 Return non-nil if the location is indeed remote.
10026 For example, the filename \"/user@host:/foo\" specifies a location
10027 on the system \"/user@host:\"."
10028 (cond ((fboundp 'file-remote-p)
10029 (file-remote-p file))
10030 ((fboundp 'tramp-handle-file-remote-p)
10031 (tramp-handle-file-remote-p file))
10032 ((and (boundp 'ange-ftp-name-format)
10033 (string-match (car ange-ftp-name-format) file))
10035 (t nil)))
10038 ;;;; Refiling
10040 (defun org-get-org-file ()
10041 "Read a filename, with default directory `org-directory'."
10042 (let ((default (or org-default-notes-file remember-data-file)))
10043 (read-file-name (format "File name [%s]: " default)
10044 (file-name-as-directory org-directory)
10045 default)))
10047 (defun org-notes-order-reversed-p ()
10048 "Check if the current file should receive notes in reversed order."
10049 (cond
10050 ((not org-reverse-note-order) nil)
10051 ((eq t org-reverse-note-order) t)
10052 ((not (listp org-reverse-note-order)) nil)
10053 (t (catch 'exit
10054 (let ((all org-reverse-note-order)
10055 entry)
10056 (while (setq entry (pop all))
10057 (if (string-match (car entry) buffer-file-name)
10058 (throw 'exit (cdr entry))))
10059 nil)))))
10061 (defvar org-refile-target-table nil
10062 "The list of refile targets, created by `org-refile'.")
10064 (defvar org-agenda-new-buffers nil
10065 "Buffers created to visit agenda files.")
10067 (defvar org-refile-cache nil
10068 "Cache for refile targets.")
10070 (defvar org-refile-markers nil
10071 "All the markers used for caching refile locations.")
10073 (defun org-refile-marker (pos)
10074 "Get a new refile marker, but only if caching is in use."
10075 (if (not org-refile-use-cache)
10077 (let ((m (make-marker)))
10078 (move-marker m pos)
10079 (push m org-refile-markers)
10080 m)))
10082 (defun org-refile-cache-clear ()
10083 "Clear the refile cache and disable all the markers."
10084 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10085 (setq org-refile-markers nil)
10086 (setq org-refile-cache nil)
10087 (message "Refile cache has been cleared"))
10089 (defun org-refile-cache-check-set (set)
10090 "Check if all the markers in the cache still have live buffers."
10091 (let (marker)
10092 (catch 'exit
10093 (while (and set (setq marker (nth 3 (pop set))))
10094 ;; if org-refile-use-outline-path is 'file, marker may be nil
10095 (when (and marker (null (marker-buffer marker)))
10096 (message "not found") (sit-for 3)
10097 (throw 'exit nil)))
10098 t)))
10100 (defun org-refile-cache-put (set &rest identifiers)
10101 "Push the refile targets SET into the cache, under IDENTIFIERS."
10102 (let* ((key (sha1 (prin1-to-string identifiers)))
10103 (entry (assoc key org-refile-cache)))
10104 (if entry
10105 (setcdr entry set)
10106 (push (cons key set) org-refile-cache))))
10108 (defun org-refile-cache-get (&rest identifiers)
10109 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10110 (cond
10111 ((not org-refile-cache) nil)
10112 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10114 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10115 org-refile-cache))))
10116 (and set (org-refile-cache-check-set set) set)))))
10118 (defun org-refile-get-targets (&optional default-buffer)
10119 "Produce a table with refile targets."
10120 (let ((case-fold-search nil)
10121 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10122 (entries (or org-refile-targets '((nil . (:level . 1)))))
10123 targets tgs txt re files f desc descre fast-path-p level pos0)
10124 (message "Getting targets...")
10125 (with-current-buffer (or default-buffer (current-buffer))
10126 (while (setq entry (pop entries))
10127 (setq files (car entry) desc (cdr entry))
10128 (setq fast-path-p nil)
10129 (cond
10130 ((null files) (setq files (list (current-buffer))))
10131 ((eq files 'org-agenda-files)
10132 (setq files (org-agenda-files 'unrestricted)))
10133 ((and (symbolp files) (fboundp files))
10134 (setq files (funcall files)))
10135 ((and (symbolp files) (boundp files))
10136 (setq files (symbol-value files))))
10137 (if (stringp files) (setq files (list files)))
10138 (cond
10139 ((eq (car desc) :tag)
10140 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10141 ((eq (car desc) :todo)
10142 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10143 ((eq (car desc) :regexp)
10144 (setq descre (cdr desc)))
10145 ((eq (car desc) :level)
10146 (setq descre (concat "^\\*\\{" (number-to-string
10147 (if org-odd-levels-only
10148 (1- (* 2 (cdr desc)))
10149 (cdr desc)))
10150 "\\}[ \t]")))
10151 ((eq (car desc) :maxlevel)
10152 (setq fast-path-p t)
10153 (setq descre (concat "^\\*\\{1," (number-to-string
10154 (if org-odd-levels-only
10155 (1- (* 2 (cdr desc)))
10156 (cdr desc)))
10157 "\\}[ \t]")))
10158 (t (error "Bad refiling target description %s" desc)))
10159 (while (setq f (pop files))
10160 (with-current-buffer
10161 (if (bufferp f) f (org-get-agenda-file-buffer f))
10163 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10164 (progn
10165 (if (bufferp f) (setq f (buffer-file-name
10166 (buffer-base-buffer f))))
10167 (setq f (and f (expand-file-name f)))
10168 (if (eq org-refile-use-outline-path 'file)
10169 (push (list (file-name-nondirectory f) f nil nil) tgs))
10170 (save-excursion
10171 (save-restriction
10172 (widen)
10173 (goto-char (point-min))
10174 (while (re-search-forward descre nil t)
10175 (goto-char (setq pos0 (point-at-bol)))
10176 (catch 'next
10177 (when org-refile-target-verify-function
10178 (save-match-data
10179 (or (funcall org-refile-target-verify-function)
10180 (throw 'next t))))
10181 (when (looking-at org-complex-heading-regexp)
10182 (setq level (org-reduced-level
10183 (- (match-end 1) (match-beginning 1)))
10184 txt (org-link-display-format (match-string 4))
10185 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10186 re (format org-complex-heading-regexp-format
10187 (regexp-quote (match-string 4))))
10188 (when org-refile-use-outline-path
10189 (setq txt (mapconcat
10190 'org-protect-slash
10191 (append
10192 (if (eq org-refile-use-outline-path
10193 'file)
10194 (list (file-name-nondirectory
10195 (buffer-file-name
10196 (buffer-base-buffer))))
10197 (if (eq org-refile-use-outline-path
10198 'full-file-path)
10199 (list (buffer-file-name
10200 (buffer-base-buffer)))))
10201 (org-get-outline-path fast-path-p
10202 level txt)
10203 (list txt))
10204 "/")))
10205 (push (list txt f re (org-refile-marker (point)))
10206 tgs)))
10207 (when (= (point) pos0)
10208 ;; verification function has not moved point
10209 (goto-char (point-at-eol))))))))
10210 (when org-refile-use-cache
10211 (org-refile-cache-put tgs (buffer-file-name) descre))
10212 (setq targets (append tgs targets))
10213 ))))
10214 (message "Getting targets...done")
10215 (nreverse targets)))
10217 (defun org-protect-slash (s)
10218 (while (string-match "/" s)
10219 (setq s (replace-match "\\" t t s)))
10222 (defvar org-olpa (make-vector 20 nil))
10224 (defun org-get-outline-path (&optional fastp level heading)
10225 "Return the outline path to the current entry, as a list.
10227 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10228 routine which makes outline path derivations for an entire file,
10229 avoiding backtracing. Refile target collection makes use of that."
10230 (if fastp
10231 (progn
10232 (if (> level 19)
10233 (error "Outline path failure, more than 19 levels"))
10234 (loop for i from level upto 19 do
10235 (aset org-olpa i nil))
10236 (prog1
10237 (delq nil (append org-olpa nil))
10238 (aset org-olpa level heading)))
10239 (let (rtn case-fold-search)
10240 (save-excursion
10241 (save-restriction
10242 (widen)
10243 (while (org-up-heading-safe)
10244 (when (looking-at org-complex-heading-regexp)
10245 (push (org-match-string-no-properties 4) rtn)))
10246 rtn)))))
10248 (defun org-format-outline-path (path &optional width prefix)
10249 "Format the outline path PATH for display.
10250 Width is the maximum number of characters that is available.
10251 Prefix is a prefix to be included in the returned string,
10252 such as the file name."
10253 (setq width (or width 79))
10254 (if prefix (setq width (- width (length prefix))))
10255 (if (not path)
10256 (or prefix "")
10257 (let* ((nsteps (length path))
10258 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10259 (maxwidth (if (<= total-width width)
10260 10000 ;; everything fits
10261 ;; we need to shorten the level headings
10262 (/ (- width nsteps) nsteps)))
10263 (org-odd-levels-only nil)
10264 (n 0)
10265 (total (1+ (length prefix))))
10266 (setq maxwidth (max maxwidth 10))
10267 (concat prefix
10268 (mapconcat
10269 (lambda (h)
10270 (setq n (1+ n))
10271 (if (and (= n nsteps) (< maxwidth 10000))
10272 (setq maxwidth (- total-width total)))
10273 (if (< (length h) maxwidth)
10274 (progn (setq total (+ total (length h) 1)) h)
10275 (setq h (substring h 0 (- maxwidth 2))
10276 total (+ total maxwidth 1))
10277 (if (string-match "[ \t]+\\'" h)
10278 (setq h (substring h 0 (match-beginning 0))))
10279 (setq h (concat h "..")))
10280 (org-add-props h nil 'face
10281 (nth (% (1- n) org-n-level-faces)
10282 org-level-faces))
10284 path "/")))))
10286 (defun org-display-outline-path (&optional file current)
10287 "Display the current outline path in the echo area."
10288 (interactive "P")
10289 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10290 (case-fold-search nil)
10291 (path (and (org-mode-p) (org-get-outline-path))))
10292 (if current (setq path (append path
10293 (save-excursion
10294 (org-back-to-heading t)
10295 (if (looking-at org-complex-heading-regexp)
10296 (list (match-string 4)))))))
10297 (message "%s"
10298 (org-format-outline-path
10299 path
10300 (1- (frame-width))
10301 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10303 (defvar org-refile-history nil
10304 "History for refiling operations.")
10306 (defvar org-after-refile-insert-hook nil
10307 "Hook run after `org-refile' has inserted its stuff at the new location.
10308 Note that this is still *before* the stuff will be removed from
10309 the *old* location.")
10311 (defvar org-capture-last-stored-marker)
10312 (defun org-refile (&optional goto default-buffer rfloc)
10313 "Move the entry at point to another heading.
10314 The list of target headings is compiled using the information in
10315 `org-refile-targets', which see. This list is created before each use
10316 and will therefore always be up-to-date.
10318 At the target location, the entry is filed as a subitem of the target heading.
10319 Depending on `org-reverse-note-order', the new subitem will either be the
10320 first or the last subitem.
10322 If there is an active region, all entries in that region will be moved.
10323 However, the region must fulfill the requirement that the first heading
10324 is the first one sets the top-level of the moved text - at most siblings
10325 below it are allowed.
10327 With prefix arg GOTO, the command will only visit the target location,
10328 not actually move anything.
10329 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10330 go to the location where the last refiling
10331 operation has put the subtree.
10332 With a prefix argument of `2', refile to the running clock.
10334 RFLOC can be a refile location obtained in a different way.
10336 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10338 If you are using target caching (see `org-refile-use-cache'),
10339 You have to clear the target cache in order to find new targets.
10340 This can be done with a 0 prefix: `C-0 C-c C-w'"
10341 (interactive "P")
10342 (if (member goto '(0 (64)))
10343 (org-refile-cache-clear)
10344 (let* ((cbuf (current-buffer))
10345 (regionp (org-region-active-p))
10346 (region-start (and regionp (region-beginning)))
10347 (region-end (and regionp (region-end)))
10348 (region-length (and regionp (- region-end region-start)))
10349 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10350 pos it nbuf file re level reversed)
10351 (setq last-command nil)
10352 (when regionp
10353 (goto-char region-start)
10354 (or (bolp) (goto-char (point-at-bol)))
10355 (setq region-start (point))
10356 (unless (org-kill-is-subtree-p
10357 (buffer-substring region-start region-end))
10358 (error "The region is not a (sequence of) subtree(s)")))
10359 (if (equal goto '(16))
10360 (org-refile-goto-last-stored)
10361 (when (or
10362 (and (equal goto 2)
10363 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10364 (prog1
10365 (setq it (list (or org-clock-heading "running clock")
10366 (buffer-file-name
10367 (marker-buffer org-clock-hd-marker))
10369 (marker-position org-clock-hd-marker)))
10370 (setq goto nil)))
10371 (setq it (or rfloc
10372 (save-excursion
10373 (org-refile-get-location
10374 (if goto "Goto" "Refile to") default-buffer
10375 org-refile-allow-creating-parent-nodes)))))
10376 (setq file (nth 1 it)
10377 re (nth 2 it)
10378 pos (nth 3 it))
10379 (if (and (not goto)
10381 (equal (buffer-file-name) file)
10382 (if regionp
10383 (and (>= pos region-start)
10384 (<= pos region-end))
10385 (and (>= pos (point))
10386 (< pos (save-excursion
10387 (org-end-of-subtree t t))))))
10388 (error "Cannot refile to position inside the tree or region"))
10390 (setq nbuf (or (find-buffer-visiting file)
10391 (find-file-noselect file)))
10392 (if goto
10393 (progn
10394 (switch-to-buffer nbuf)
10395 (goto-char pos)
10396 (org-show-context 'org-goto))
10397 (if regionp
10398 (progn
10399 (org-kill-new (buffer-substring region-start region-end))
10400 (org-save-markers-in-region region-start region-end))
10401 (org-copy-subtree 1 nil t))
10402 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10403 (find-file-noselect file)))
10404 (setq reversed (org-notes-order-reversed-p))
10405 (save-excursion
10406 (save-restriction
10407 (widen)
10408 (if pos
10409 (progn
10410 (goto-char pos)
10411 (looking-at outline-regexp)
10412 (setq level (org-get-valid-level (funcall outline-level) 1))
10413 (goto-char
10414 (if reversed
10415 (or (outline-next-heading) (point-max))
10416 (or (save-excursion (org-get-next-sibling))
10417 (org-end-of-subtree t t)
10418 (point-max)))))
10419 (setq level 1)
10420 (if (not reversed)
10421 (goto-char (point-max))
10422 (goto-char (point-min))
10423 (or (outline-next-heading) (goto-char (point-max)))))
10424 (if (not (bolp)) (newline))
10425 (org-paste-subtree level)
10426 (when org-log-refile
10427 (org-add-log-setup 'refile nil nil 'findpos
10428 org-log-refile)
10429 (unless (eq org-log-refile 'note)
10430 (save-excursion (org-add-log-note))))
10431 (and org-auto-align-tags (org-set-tags nil t))
10432 (bookmark-set "org-refile-last-stored")
10433 ;; If we are refiling for capture, make sure that the
10434 ;; last-capture pointers point here
10435 (when (org-bound-and-true-p org-refile-for-capture)
10436 (bookmark-set "org-capture-last-stored-marker")
10437 (move-marker org-capture-last-stored-marker (point)))
10438 (if (fboundp 'deactivate-mark) (deactivate-mark))
10439 (run-hooks 'org-after-refile-insert-hook))))
10440 (if regionp
10441 (delete-region (point) (+ (point) region-length))
10442 (org-cut-subtree))
10443 (when (featurep 'org-inlinetask)
10444 (org-inlinetask-remove-END-maybe))
10445 (setq org-markers-to-move nil)
10446 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
10448 (defun org-refile-goto-last-stored ()
10449 "Go to the location where the last refile was stored."
10450 (interactive)
10451 (bookmark-jump "org-refile-last-stored")
10452 (message "This is the location of the last refile"))
10454 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
10455 "Prompt the user for a refile location, using PROMPT.
10456 PROMPT should not be suffixed with a colon and a space, because
10457 this function appends the default value from
10458 `org-refile-history' automatically, if that is not empty."
10459 (let ((org-refile-targets org-refile-targets)
10460 (org-refile-use-outline-path org-refile-use-outline-path))
10461 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
10462 (unless org-refile-target-table
10463 (error "No refile targets"))
10464 (let* ((prompt (concat prompt
10465 (and (car org-refile-history)
10466 (concat " (default " (car org-refile-history) ")"))
10467 ": "))
10468 (cbuf (current-buffer))
10469 (partial-completion-mode nil)
10470 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
10471 (cfunc (if (and org-refile-use-outline-path
10472 org-outline-path-complete-in-steps)
10473 'org-olpath-completing-read
10474 'org-icompleting-read))
10475 (extra (if org-refile-use-outline-path "/" ""))
10476 (filename (and cfn (expand-file-name cfn)))
10477 (tbl (mapcar
10478 (lambda (x)
10479 (if (and (not (member org-refile-use-outline-path
10480 '(file full-file-path)))
10481 (not (equal filename (nth 1 x))))
10482 (cons (concat (car x) extra " ("
10483 (file-name-nondirectory (nth 1 x)) ")")
10484 (cdr x))
10485 (cons (concat (car x) extra) (cdr x))))
10486 org-refile-target-table))
10487 (completion-ignore-case t)
10488 pa answ parent-target child parent old-hist)
10489 (setq old-hist org-refile-history)
10490 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
10491 nil 'org-refile-history (car org-refile-history)))
10492 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
10493 (org-refile-check-position pa)
10494 (if pa
10495 (progn
10496 (when (or (not org-refile-history)
10497 (not (eq old-hist org-refile-history))
10498 (not (equal (car pa) (car org-refile-history))))
10499 (setq org-refile-history
10500 (cons (car pa) (if (assoc (car org-refile-history) tbl)
10501 org-refile-history
10502 (cdr org-refile-history))))
10503 (if (equal (car org-refile-history) (nth 1 org-refile-history))
10504 (pop org-refile-history)))
10506 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
10507 (progn
10508 (setq parent (match-string 1 answ)
10509 child (match-string 2 answ))
10510 (setq parent-target (or (assoc parent tbl)
10511 (assoc (concat parent "/") tbl)))
10512 (when (and parent-target
10513 (or (eq new-nodes t)
10514 (and (eq new-nodes 'confirm)
10515 (y-or-n-p (format "Create new node \"%s\"? "
10516 child)))))
10517 (org-refile-new-child parent-target child)))
10518 (error "Invalid target location")))))
10520 (defun org-refile-check-position (refile-pointer)
10521 "Check if the refile pointer matches the readline to which it points."
10522 (let* ((file (nth 1 refile-pointer))
10523 (re (nth 2 refile-pointer))
10524 (pos (nth 3 refile-pointer))
10525 buffer)
10526 (when (org-string-nw-p re)
10527 (setq buffer (if (markerp pos)
10528 (marker-buffer pos)
10529 (or (find-buffer-visiting file)
10530 (find-file-noselect file))))
10531 (with-current-buffer buffer
10532 (save-excursion
10533 (save-restriction
10534 (widen)
10535 (goto-char pos)
10536 (beginning-of-line 1)
10537 (unless (org-looking-at-p re)
10538 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
10540 (defun org-refile-new-child (parent-target child)
10541 "Use refile target PARENT-TARGET to add new CHILD below it."
10542 (unless parent-target
10543 (error "Cannot find parent for new node"))
10544 (let ((file (nth 1 parent-target))
10545 (pos (nth 3 parent-target))
10546 level)
10547 (with-current-buffer (or (find-buffer-visiting file)
10548 (find-file-noselect file))
10549 (save-excursion
10550 (save-restriction
10551 (widen)
10552 (if pos
10553 (goto-char pos)
10554 (goto-char (point-max))
10555 (if (not (bolp)) (newline)))
10556 (when (looking-at outline-regexp)
10557 (setq level (funcall outline-level))
10558 (org-end-of-subtree t t))
10559 (org-back-over-empty-lines)
10560 (insert "\n" (make-string
10561 (if pos (org-get-valid-level level 1) 1) ?*)
10562 " " child "\n")
10563 (beginning-of-line 0)
10564 (list (concat (car parent-target) "/" child) file "" (point)))))))
10566 (defun org-olpath-completing-read (prompt collection &rest args)
10567 "Read an outline path like a file name."
10568 (let ((thetable collection)
10569 (org-completion-use-ido nil) ; does not work with ido.
10570 (org-completion-use-iswitchb nil)) ; or iswitchb
10571 (apply
10572 'org-icompleting-read prompt
10573 (lambda (string predicate &optional flag)
10574 (let (rtn r f (l (length string)))
10575 (cond
10576 ((eq flag nil)
10577 ;; try completion
10578 (try-completion string thetable))
10579 ((eq flag t)
10580 ;; all-completions
10581 (setq rtn (all-completions string thetable predicate))
10582 (mapcar
10583 (lambda (x)
10584 (setq r (substring x l))
10585 (if (string-match " ([^)]*)$" x)
10586 (setq f (match-string 0 x))
10587 (setq f ""))
10588 (if (string-match "/" r)
10589 (concat string (substring r 0 (match-end 0)) f)
10591 rtn))
10592 ((eq flag 'lambda)
10593 ;; exact match?
10594 (assoc string thetable)))
10596 args)))
10598 ;;;; Dynamic blocks
10600 (defun org-find-dblock (name)
10601 "Find the first dynamic block with name NAME in the buffer.
10602 If not found, stay at current position and return nil."
10603 (let (pos)
10604 (save-excursion
10605 (goto-char (point-min))
10606 (setq pos (and (re-search-forward (concat "^[ \t]*#\\+BEGIN:[ \t]+" name "\\>")
10607 nil t)
10608 (match-beginning 0))))
10609 (if pos (goto-char pos))
10610 pos))
10612 (defconst org-dblock-start-re
10613 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10614 "Matches the start line of a dynamic block, with parameters.")
10616 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
10617 "Matches the end of a dynamic block.")
10619 (defun org-create-dblock (plist)
10620 "Create a dynamic block section, with parameters taken from PLIST.
10621 PLIST must contain a :name entry which is used as name of the block."
10622 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
10623 (end-of-line 1)
10624 (newline))
10625 (let ((col (current-column))
10626 (name (plist-get plist :name)))
10627 (insert "#+BEGIN: " name)
10628 (while plist
10629 (if (eq (car plist) :name)
10630 (setq plist (cddr plist))
10631 (insert " " (prin1-to-string (pop plist)))))
10632 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
10633 (beginning-of-line -2)))
10635 (defun org-prepare-dblock ()
10636 "Prepare dynamic block for refresh.
10637 This empties the block, puts the cursor at the insert position and returns
10638 the property list including an extra property :name with the block name."
10639 (unless (looking-at org-dblock-start-re)
10640 (error "Not at a dynamic block"))
10641 (let* ((begdel (1+ (match-end 0)))
10642 (name (org-no-properties (match-string 1)))
10643 (params (append (list :name name)
10644 (read (concat "(" (match-string 3) ")")))))
10645 (save-excursion
10646 (beginning-of-line 1)
10647 (skip-chars-forward " \t")
10648 (setq params (plist-put params :indentation-column (current-column))))
10649 (unless (re-search-forward org-dblock-end-re nil t)
10650 (error "Dynamic block not terminated"))
10651 (setq params
10652 (append params
10653 (list :content (buffer-substring
10654 begdel (match-beginning 0)))))
10655 (delete-region begdel (match-beginning 0))
10656 (goto-char begdel)
10657 (open-line 1)
10658 params))
10660 (defun org-map-dblocks (&optional command)
10661 "Apply COMMAND to all dynamic blocks in the current buffer.
10662 If COMMAND is not given, use `org-update-dblock'."
10663 (let ((cmd (or command 'org-update-dblock)))
10664 (save-excursion
10665 (goto-char (point-min))
10666 (while (re-search-forward org-dblock-start-re nil t)
10667 (goto-char (match-beginning 0))
10668 (save-excursion
10669 (condition-case nil
10670 (funcall cmd)
10671 (error (message "Error during update of dynamic block"))))
10672 (unless (re-search-forward org-dblock-end-re nil t)
10673 (error "Dynamic block not terminated"))))))
10675 (defun org-dblock-update (&optional arg)
10676 "User command for updating dynamic blocks.
10677 Update the dynamic block at point. With prefix ARG, update all dynamic
10678 blocks in the buffer."
10679 (interactive "P")
10680 (if arg
10681 (org-update-all-dblocks)
10682 (or (looking-at org-dblock-start-re)
10683 (org-beginning-of-dblock))
10684 (org-update-dblock)))
10686 (defun org-update-dblock ()
10687 "Update the dynamic block at point.
10688 This means to empty the block, parse for parameters and then call
10689 the correct writing function."
10690 (interactive)
10691 (save-window-excursion
10692 (let* ((pos (point))
10693 (line (org-current-line))
10694 (params (org-prepare-dblock))
10695 (name (plist-get params :name))
10696 (indent (plist-get params :indentation-column))
10697 (cmd (intern (concat "org-dblock-write:" name))))
10698 (message "Updating dynamic block `%s' at line %d..." name line)
10699 (funcall cmd params)
10700 (message "Updating dynamic block `%s' at line %d...done" name line)
10701 (goto-char pos)
10702 (when (and indent (> indent 0))
10703 (setq indent (make-string indent ?\ ))
10704 (save-excursion
10705 (org-beginning-of-dblock)
10706 (forward-line 1)
10707 (while (not (looking-at org-dblock-end-re))
10708 (insert indent)
10709 (beginning-of-line 2))
10710 (when (looking-at org-dblock-end-re)
10711 (and (looking-at "[ \t]+")
10712 (replace-match ""))
10713 (insert indent)))))))
10715 (defun org-beginning-of-dblock ()
10716 "Find the beginning of the dynamic block at point.
10717 Error if there is no such block at point."
10718 (let ((pos (point))
10719 beg)
10720 (end-of-line 1)
10721 (if (and (re-search-backward org-dblock-start-re nil t)
10722 (setq beg (match-beginning 0))
10723 (re-search-forward org-dblock-end-re nil t)
10724 (> (match-end 0) pos))
10725 (goto-char beg)
10726 (goto-char pos)
10727 (error "Not in a dynamic block"))))
10729 (defun org-update-all-dblocks ()
10730 "Update all dynamic blocks in the buffer.
10731 This function can be used in a hook."
10732 (interactive)
10733 (when (org-mode-p)
10734 (org-map-dblocks 'org-update-dblock)))
10737 ;;;; Completion
10739 (defconst org-additional-option-like-keywords
10740 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
10741 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
10742 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
10743 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
10744 "BEGIN:" "END:"
10745 "ORGTBL" "TBLFM:" "TBLNAME:"
10746 "BEGIN_EXAMPLE" "END_EXAMPLE"
10747 "BEGIN_QUOTE" "END_QUOTE"
10748 "BEGIN_VERSE" "END_VERSE"
10749 "BEGIN_CENTER" "END_CENTER"
10750 "BEGIN_SRC" "END_SRC"
10751 "BEGIN_RESULT" "END_RESULT"
10752 "SOURCE:" "SRCNAME:" "FUNCTION:"
10753 "RESULTS:"
10754 "HEADER:" "HEADERS:"
10755 "BABEL:"
10756 "CATEGORY:" "COLUMNS:" "PROPERTY:"
10757 "CAPTION:" "LABEL:"
10758 "SETUPFILE:"
10759 "INCLUDE:"
10760 "BIND:"
10761 "MACRO:"))
10763 (defcustom org-structure-template-alist
10765 ("s" "#+begin_src ?\n\n#+end_src"
10766 "<src lang=\"?\">\n\n</src>")
10767 ("e" "#+begin_example\n?\n#+end_example"
10768 "<example>\n?\n</example>")
10769 ("q" "#+begin_quote\n?\n#+end_quote"
10770 "<quote>\n?\n</quote>")
10771 ("v" "#+begin_verse\n?\n#+end_verse"
10772 "<verse>\n?\n/verse>")
10773 ("c" "#+begin_center\n?\n#+end_center"
10774 "<center>\n?\n/center>")
10775 ("l" "#+begin_latex\n?\n#+end_latex"
10776 "<literal style=\"latex\">\n?\n</literal>")
10777 ("L" "#+latex: "
10778 "<literal style=\"latex\">?</literal>")
10779 ("h" "#+begin_html\n?\n#+end_html"
10780 "<literal style=\"html\">\n?\n</literal>")
10781 ("H" "#+html: "
10782 "<literal style=\"html\">?</literal>")
10783 ("a" "#+begin_ascii\n?\n#+end_ascii")
10784 ("A" "#+ascii: ")
10785 ("i" "#+index: ?"
10786 "#+index: ?")
10787 ("I" "#+include %file ?"
10788 "<include file=%file markup=\"?\">")
10790 "Structure completion elements.
10791 This is a list of abbreviation keys and values. The value gets inserted
10792 if you type `<' followed by the key and then press the completion key,
10793 usually `M-TAB'. %file will be replaced by a file name after prompting
10794 for the file using completion. The cursor will be placed at the position
10795 of the `?` in the template.
10796 There are two templates for each key, the first uses the original Org syntax,
10797 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
10798 the default when the /org-mtags.el/ module has been loaded. See also the
10799 variable `org-mtags-prefer-muse-templates'.
10800 This is an experimental feature, it is undecided if it is going to stay in."
10801 :group 'org-completion
10802 :type '(repeat
10803 (string :tag "Key")
10804 (string :tag "Template")
10805 (string :tag "Muse Template")))
10807 (defun org-try-structure-completion ()
10808 "Try to complete a structure template before point.
10809 This looks for strings like \"<e\" on an otherwise empty line and
10810 expands them."
10811 (let ((l (buffer-substring (point-at-bol) (point)))
10813 (when (and (looking-at "[ \t]*$")
10814 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
10815 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
10816 (org-complete-expand-structure-template (+ -1 (point-at-bol)
10817 (match-beginning 1)) a)
10818 t)))
10820 (defun org-complete-expand-structure-template (start cell)
10821 "Expand a structure template."
10822 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
10823 (rpl (nth (if musep 2 1) cell))
10824 (ind ""))
10825 (delete-region start (point))
10826 (when (string-match "\\`#\\+" rpl)
10827 (cond
10828 ((bolp))
10829 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
10830 (setq ind (buffer-substring (point-at-bol) (point))))
10831 (t (newline))))
10832 (setq start (point))
10833 (if (string-match "%file" rpl)
10834 (setq rpl (replace-match
10835 (concat
10836 "\""
10837 (save-match-data
10838 (abbreviate-file-name (read-file-name "Include file: ")))
10839 "\"")
10840 t t rpl)))
10841 (setq rpl (mapconcat 'identity (split-string rpl "\n")
10842 (concat "\n" ind)))
10843 (insert rpl)
10844 (if (re-search-backward "\\?" start t) (delete-char 1))))
10846 ;;;; TODO, DEADLINE, Comments
10848 (defun org-toggle-comment ()
10849 "Change the COMMENT state of an entry."
10850 (interactive)
10851 (save-excursion
10852 (org-back-to-heading)
10853 (let (case-fold-search)
10854 (if (looking-at (concat outline-regexp
10855 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10856 (replace-match "" t t nil 1)
10857 (if (looking-at outline-regexp)
10858 (progn
10859 (goto-char (match-end 0))
10860 (insert org-comment-string " ")))))))
10862 (defvar org-last-todo-state-is-todo nil
10863 "This is non-nil when the last TODO state change led to a TODO state.
10864 If the last change removed the TODO tag or switched to DONE, then
10865 this is nil.")
10867 (defvar org-setting-tags nil) ; dynamically skipped
10869 (defvar org-todo-setup-filter-hook nil
10870 "Hook for functions that pre-filter todo specs.
10871 Each function takes a todo spec and returns either nil or the spec
10872 transformed into canonical form." )
10874 (defvar org-todo-get-default-hook nil
10875 "Hook for functions that get a default item for todo.
10876 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
10877 nil or a string to be used for the todo mark." )
10879 (defvar org-agenda-headline-snapshot-before-repeat)
10881 (defun org-todo (&optional arg)
10882 "Change the TODO state of an item.
10883 The state of an item is given by a keyword at the start of the heading,
10884 like
10885 *** TODO Write paper
10886 *** DONE Call mom
10888 The different keywords are specified in the variable `org-todo-keywords'.
10889 By default the available states are \"TODO\" and \"DONE\".
10890 So for this example: when the item starts with TODO, it is changed to DONE.
10891 When it starts with DONE, the DONE is removed. And when neither TODO nor
10892 DONE are present, add TODO at the beginning of the heading.
10894 With \\[universal-argument] prefix arg, use completion to determine the new \
10895 state.
10896 With numeric prefix arg, switch to that state.
10897 With a double \\[universal-argument] prefix, switch to the next set of TODO \
10898 keywords (nextset).
10899 With a triple \\[universal-argument] prefix, circumvent any state blocking.
10901 For calling through lisp, arg is also interpreted in the following way:
10902 'none -> empty state
10903 \"\"(empty string) -> switch to empty state
10904 'done -> switch to DONE
10905 'nextset -> switch to the next set of keywords
10906 'previousset -> switch to the previous set of keywords
10907 \"WAITING\" -> switch to the specified keyword, but only if it
10908 really is a member of `org-todo-keywords'."
10909 (interactive "P")
10910 (if (equal arg '(16)) (setq arg 'nextset))
10911 (let ((org-blocker-hook org-blocker-hook)
10912 (case-fold-search nil))
10913 (when (equal arg '(64))
10914 (setq arg nil org-blocker-hook nil))
10915 (when (and org-blocker-hook
10916 (or org-inhibit-blocking
10917 (org-entry-get nil "NOBLOCKING")))
10918 (setq org-blocker-hook nil))
10919 (save-excursion
10920 (catch 'exit
10921 (org-back-to-heading t)
10922 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
10923 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
10924 (looking-at " *"))
10925 (let* ((match-data (match-data))
10926 (startpos (point-at-bol))
10927 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
10928 (org-log-done org-log-done)
10929 (org-log-repeat org-log-repeat)
10930 (org-todo-log-states org-todo-log-states)
10931 (this (match-string 1))
10932 (hl-pos (match-beginning 0))
10933 (head (org-get-todo-sequence-head this))
10934 (ass (assoc head org-todo-kwd-alist))
10935 (interpret (nth 1 ass))
10936 (done-word (nth 3 ass))
10937 (final-done-word (nth 4 ass))
10938 (last-state (or this ""))
10939 (completion-ignore-case t)
10940 (member (member this org-todo-keywords-1))
10941 (tail (cdr member))
10942 (state (cond
10943 ((and org-todo-key-trigger
10944 (or (and (equal arg '(4))
10945 (eq org-use-fast-todo-selection 'prefix))
10946 (and (not arg) org-use-fast-todo-selection
10947 (not (eq org-use-fast-todo-selection
10948 'prefix)))))
10949 ;; Use fast selection
10950 (org-fast-todo-selection))
10951 ((and (equal arg '(4))
10952 (or (not org-use-fast-todo-selection)
10953 (not org-todo-key-trigger)))
10954 ;; Read a state with completion
10955 (org-icompleting-read
10956 "State: " (mapcar (lambda(x) (list x))
10957 org-todo-keywords-1)
10958 nil t))
10959 ((eq arg 'right)
10960 (if this
10961 (if tail (car tail) nil)
10962 (car org-todo-keywords-1)))
10963 ((eq arg 'left)
10964 (if (equal member org-todo-keywords-1)
10966 (if this
10967 (nth (- (length org-todo-keywords-1)
10968 (length tail) 2)
10969 org-todo-keywords-1)
10970 (org-last org-todo-keywords-1))))
10971 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10972 (setq arg nil))) ; hack to fall back to cycling
10973 (arg
10974 ;; user or caller requests a specific state
10975 (cond
10976 ((equal arg "") nil)
10977 ((eq arg 'none) nil)
10978 ((eq arg 'done) (or done-word (car org-done-keywords)))
10979 ((eq arg 'nextset)
10980 (or (car (cdr (member head org-todo-heads)))
10981 (car org-todo-heads)))
10982 ((eq arg 'previousset)
10983 (let ((org-todo-heads (reverse org-todo-heads)))
10984 (or (car (cdr (member head org-todo-heads)))
10985 (car org-todo-heads))))
10986 ((car (member arg org-todo-keywords-1)))
10987 ((stringp arg)
10988 (error "State `%s' not valid in this file" arg))
10989 ((nth (1- (prefix-numeric-value arg))
10990 org-todo-keywords-1))))
10991 ((null member) (or head (car org-todo-keywords-1)))
10992 ((equal this final-done-word) nil) ;; -> make empty
10993 ((null tail) nil) ;; -> first entry
10994 ((memq interpret '(type priority))
10995 (if (eq this-command last-command)
10996 (car tail)
10997 (if (> (length tail) 0)
10998 (or done-word (car org-done-keywords))
10999 nil)))
11001 (car tail))))
11002 (state (or
11003 (run-hook-with-args-until-success
11004 'org-todo-get-default-hook state last-state)
11005 state))
11006 (next (if state (concat " " state " ") " "))
11007 (change-plist (list :type 'todo-state-change :from this :to state
11008 :position startpos))
11009 dolog now-done-p)
11010 (when org-blocker-hook
11011 (setq org-last-todo-state-is-todo
11012 (not (member this org-done-keywords)))
11013 (unless (save-excursion
11014 (save-match-data
11015 (org-with-wide-buffer
11016 (run-hook-with-args-until-failure
11017 'org-blocker-hook change-plist))))
11018 (if (interactive-p)
11019 (error "TODO state change from %s to %s blocked" this state)
11020 ;; fail silently
11021 (message "TODO state change from %s to %s blocked" this state)
11022 (throw 'exit nil))))
11023 (store-match-data match-data)
11024 (replace-match next t t)
11025 (unless (pos-visible-in-window-p hl-pos)
11026 (message "TODO state changed to %s" (org-trim next)))
11027 (unless head
11028 (setq head (org-get-todo-sequence-head state)
11029 ass (assoc head org-todo-kwd-alist)
11030 interpret (nth 1 ass)
11031 done-word (nth 3 ass)
11032 final-done-word (nth 4 ass)))
11033 (when (memq arg '(nextset previousset))
11034 (message "Keyword-Set %d/%d: %s"
11035 (- (length org-todo-sets) -1
11036 (length (memq (assoc state org-todo-sets) org-todo-sets)))
11037 (length org-todo-sets)
11038 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11039 (setq org-last-todo-state-is-todo
11040 (not (member state org-done-keywords)))
11041 (setq now-done-p (and (member state org-done-keywords)
11042 (not (member this org-done-keywords))))
11043 (and logging (org-local-logging logging))
11044 (when (and (or org-todo-log-states org-log-done)
11045 (not (eq org-inhibit-logging t))
11046 (not (memq arg '(nextset previousset))))
11047 ;; we need to look at recording a time and note
11048 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
11049 (nth 2 (assoc this org-todo-log-states))))
11050 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11051 (setq dolog 'time))
11052 (when (and state
11053 (member state org-not-done-keywords)
11054 (not (member this org-not-done-keywords)))
11055 ;; This is now a todo state and was not one before
11056 ;; If there was a CLOSED time stamp, get rid of it.
11057 (org-add-planning-info nil nil 'closed))
11058 (when (and now-done-p org-log-done)
11059 ;; It is now done, and it was not done before
11060 (org-add-planning-info 'closed (org-current-time))
11061 (if (and (not dolog) (eq 'note org-log-done))
11062 (org-add-log-setup 'done state this 'findpos 'note)))
11063 (when (and state dolog)
11064 ;; This is a non-nil state, and we need to log it
11065 (org-add-log-setup 'state state this 'findpos dolog)))
11066 ;; Fixup tag positioning
11067 (org-todo-trigger-tag-changes state)
11068 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11069 (when org-provide-todo-statistics
11070 (org-update-parent-todo-statistics))
11071 (run-hooks 'org-after-todo-state-change-hook)
11072 (if (and arg (not (member state org-done-keywords)))
11073 (setq head (org-get-todo-sequence-head state)))
11074 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11075 ;; Do we need to trigger a repeat?
11076 (when now-done-p
11077 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11078 ;; This is for the agenda, take a snapshot of the headline.
11079 (save-match-data
11080 (setq org-agenda-headline-snapshot-before-repeat
11081 (org-get-heading))))
11082 (org-auto-repeat-maybe state))
11083 ;; Fixup cursor location if close to the keyword
11084 (if (and (outline-on-heading-p)
11085 (not (bolp))
11086 (save-excursion (beginning-of-line 1)
11087 (looking-at org-todo-line-regexp))
11088 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11089 (progn
11090 (goto-char (or (match-end 2) (match-end 1)))
11091 (and (looking-at " ") (just-one-space))))
11092 (when org-trigger-hook
11093 (save-excursion
11094 (run-hook-with-args 'org-trigger-hook change-plist))))))))
11096 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11097 "Block turning an entry into a TODO, using the hierarchy.
11098 This checks whether the current task should be blocked from state
11099 changes. Such blocking occurs when:
11101 1. The task has children which are not all in a completed state.
11103 2. A task has a parent with the property :ORDERED:, and there
11104 are siblings prior to the current task with incomplete
11105 status.
11107 3. The parent of the task is blocked because it has siblings that should
11108 be done first, or is child of a block grandparent TODO entry."
11110 (if (not org-enforce-todo-dependencies)
11111 t ; if locally turned off don't block
11112 (catch 'dont-block
11113 ;; If this is not a todo state change, or if this entry is already DONE,
11114 ;; do not block
11115 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11116 (member (plist-get change-plist :from)
11117 (cons 'done org-done-keywords))
11118 (member (plist-get change-plist :to)
11119 (cons 'todo org-not-done-keywords))
11120 (not (plist-get change-plist :to)))
11121 (throw 'dont-block t))
11122 ;; If this task has children, and any are undone, it's blocked
11123 (save-excursion
11124 (org-back-to-heading t)
11125 (let ((this-level (funcall outline-level)))
11126 (outline-next-heading)
11127 (let ((child-level (funcall outline-level)))
11128 (while (and (not (eobp))
11129 (> child-level this-level))
11130 ;; this todo has children, check whether they are all
11131 ;; completed
11132 (if (and (not (org-entry-is-done-p))
11133 (org-entry-is-todo-p))
11134 (throw 'dont-block nil))
11135 (outline-next-heading)
11136 (setq child-level (funcall outline-level))))))
11137 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11138 ;; any previous siblings are undone, it's blocked
11139 (save-excursion
11140 (org-back-to-heading t)
11141 (let* ((pos (point))
11142 (parent-pos (and (org-up-heading-safe) (point))))
11143 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11144 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11145 (forward-line 1)
11146 (re-search-forward org-not-done-heading-regexp pos t))
11147 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11148 ;; Search further up the hierarchy, to see if an anchestor is blocked
11149 (while t
11150 (goto-char parent-pos)
11151 (if (not (looking-at org-not-done-heading-regexp))
11152 (throw 'dont-block t)) ; do not block, parent is not a TODO
11153 (setq pos (point))
11154 (setq parent-pos (and (org-up-heading-safe) (point)))
11155 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11156 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11157 (forward-line 1)
11158 (re-search-forward org-not-done-heading-regexp pos t))
11159 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11161 (defcustom org-track-ordered-property-with-tag nil
11162 "Should the ORDERED property also be shown as a tag?
11163 The ORDERED property decides if an entry should require subtasks to be
11164 completed in sequence. Since a property is not very visible, setting
11165 this option means that toggling the ORDERED property with the command
11166 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11167 not relevant for the behavior, but it makes things more visible.
11169 Note that toggling the tag with tags commands will not change the property
11170 and therefore not influence behavior!
11172 This can be t, meaning the tag ORDERED should be used, It can also be a
11173 string to select a different tag for this task."
11174 :group 'org-todo
11175 :type '(choice
11176 (const :tag "No tracking" nil)
11177 (const :tag "Track with ORDERED tag" t)
11178 (string :tag "Use other tag")))
11180 (defun org-toggle-ordered-property ()
11181 "Toggle the ORDERED property of the current entry.
11182 For better visibility, you can track the value of this property with a tag.
11183 See variable `org-track-ordered-property-with-tag'."
11184 (interactive)
11185 (let* ((t1 org-track-ordered-property-with-tag)
11186 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11187 (save-excursion
11188 (org-back-to-heading)
11189 (if (org-entry-get nil "ORDERED")
11190 (progn
11191 (org-delete-property "ORDERED")
11192 (and tag (org-toggle-tag tag 'off))
11193 (message "Subtasks can be completed in arbitrary order"))
11194 (org-entry-put nil "ORDERED" "t")
11195 (and tag (org-toggle-tag tag 'on))
11196 (message "Subtasks must be completed in sequence")))))
11198 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11199 (defun org-block-todo-from-checkboxes (change-plist)
11200 "Block turning an entry into a TODO, using checkboxes.
11201 This checks whether the current task should be blocked from state
11202 changes because there are unchecked boxes in this entry."
11203 (if (not org-enforce-todo-checkbox-dependencies)
11204 t ; if locally turned off don't block
11205 (catch 'dont-block
11206 ;; If this is not a todo state change, or if this entry is already DONE,
11207 ;; do not block
11208 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11209 (member (plist-get change-plist :from)
11210 (cons 'done org-done-keywords))
11211 (member (plist-get change-plist :to)
11212 (cons 'todo org-not-done-keywords))
11213 (not (plist-get change-plist :to)))
11214 (throw 'dont-block t))
11215 ;; If this task has checkboxes that are not checked, it's blocked
11216 (save-excursion
11217 (org-back-to-heading t)
11218 (let ((beg (point)) end)
11219 (outline-next-heading)
11220 (setq end (point))
11221 (goto-char beg)
11222 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
11223 end t)
11224 (progn
11225 (if (boundp 'org-blocked-by-checkboxes)
11226 (setq org-blocked-by-checkboxes t))
11227 (throw 'dont-block nil)))))
11228 t))) ; do not block
11230 (defun org-entry-blocked-p ()
11231 "Is the current entry blocked?"
11232 (if (org-entry-get nil "NOBLOCKING")
11233 nil ;; Never block this entry
11234 (not
11235 (run-hook-with-args-until-failure
11236 'org-blocker-hook
11237 (list :type 'todo-state-change
11238 :position (point)
11239 :from 'todo
11240 :to 'done)))))
11242 (defun org-update-statistics-cookies (all)
11243 "Update the statistics cookie, either from TODO or from checkboxes.
11244 This should be called with the cursor in a line with a statistics cookie."
11245 (interactive "P")
11246 (if all
11247 (progn
11248 (org-update-checkbox-count 'all)
11249 (org-map-entries 'org-update-parent-todo-statistics))
11250 (if (not (org-on-heading-p))
11251 (org-update-checkbox-count)
11252 (let ((pos (move-marker (make-marker) (point)))
11253 end l1 l2)
11254 (ignore-errors (org-back-to-heading t))
11255 (if (not (org-on-heading-p))
11256 (org-update-checkbox-count)
11257 (setq l1 (org-outline-level))
11258 (setq end (save-excursion
11259 (outline-next-heading)
11260 (if (org-on-heading-p) (setq l2 (org-outline-level)))
11261 (point)))
11262 (if (and (save-excursion
11263 (re-search-forward
11264 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11265 (not (save-excursion (re-search-forward
11266 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11267 (org-update-checkbox-count)
11268 (if (and l2 (> l2 l1))
11269 (progn
11270 (goto-char end)
11271 (org-update-parent-todo-statistics))
11272 (goto-char pos)
11273 (beginning-of-line 1)
11274 (while (re-search-forward
11275 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11276 (point-at-eol) t)
11277 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11278 (goto-char pos)
11279 (move-marker pos nil)))))
11281 (defvar org-entry-property-inherited-from) ;; defined below
11282 (defun org-update-parent-todo-statistics ()
11283 "Update any statistics cookie in the parent of the current headline.
11284 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11285 the entire subtree and this will travel up the hierarchy and update
11286 statistics everywhere."
11287 (interactive)
11288 (let* ((lim 0) prop
11289 (recursive (or (not org-hierarchical-todo-statistics)
11290 (string-match
11291 "\\<recursive\\>"
11292 (or (setq prop (org-entry-get
11293 nil "COOKIE_DATA" 'inherit)) ""))))
11294 (lim (or (and prop (marker-position
11295 org-entry-property-inherited-from))
11296 lim))
11297 (first t)
11298 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11299 level ltoggle l1 new ndel
11300 (cnt-all 0) (cnt-done 0) is-percent kwd
11301 checkbox-beg ov ovs ove cookie-present)
11302 (catch 'exit
11303 (save-excursion
11304 (beginning-of-line 1)
11305 (if (org-at-heading-p)
11306 (setq ltoggle (funcall outline-level))
11307 (error "This should not happen"))
11308 (while (and (setq level (org-up-heading-safe))
11309 (or recursive first)
11310 (>= (point) lim))
11311 (setq first nil cookie-present nil)
11312 (unless (and level
11313 (not (string-match
11314 "\\<checkbox\\>"
11315 (downcase
11316 (or (org-entry-get
11317 nil "COOKIE_DATA")
11318 "")))))
11319 (throw 'exit nil))
11320 (while (re-search-forward box-re (point-at-eol) t)
11321 (setq cnt-all 0 cnt-done 0 cookie-present t)
11322 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11323 (save-match-data
11324 (unless (outline-next-heading) (throw 'exit nil))
11325 (while (and (looking-at org-complex-heading-regexp)
11326 (> (setq l1 (length (match-string 1))) level))
11327 (setq kwd (and (or recursive (= l1 ltoggle))
11328 (match-string 2)))
11329 (if (or (eq org-provide-todo-statistics 'all-headlines)
11330 (and (listp org-provide-todo-statistics)
11331 (or (member kwd org-provide-todo-statistics)
11332 (member kwd org-done-keywords))))
11333 (setq cnt-all (1+ cnt-all))
11334 (if (eq org-provide-todo-statistics t)
11335 (and kwd (setq cnt-all (1+ cnt-all)))))
11336 (and (member kwd org-done-keywords)
11337 (setq cnt-done (1+ cnt-done)))
11338 (outline-next-heading)))
11339 (setq new
11340 (if is-percent
11341 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11342 (format "[%d/%d]" cnt-done cnt-all))
11343 ndel (- (match-end 0) checkbox-beg))
11344 ;; handle overlays when updating cookie from column view
11345 (when (setq ov (car (overlays-at checkbox-beg)))
11346 (setq ovs (overlay-start ov) ove (overlay-end ov))
11347 (delete-overlay ov))
11348 (goto-char checkbox-beg)
11349 (insert new)
11350 (delete-region (point) (+ (point) ndel))
11351 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11352 (when ov (move-overlay ov ovs ove)))
11353 (when cookie-present
11354 (run-hook-with-args 'org-after-todo-statistics-hook
11355 cnt-done (- cnt-all cnt-done))))))
11356 (run-hooks 'org-todo-statistics-hook)))
11358 (defvar org-after-todo-statistics-hook nil
11359 "Hook that is called after a TODO statistics cookie has been updated.
11360 Each function is called with two arguments: the number of not-done entries
11361 and the number of done entries.
11363 For example, the following function, when added to this hook, will switch
11364 an entry to DONE when all children are done, and back to TODO when new
11365 entries are set to a TODO status. Note that this hook is only called
11366 when there is a statistics cookie in the headline!
11368 (defun org-summary-todo (n-done n-not-done)
11369 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11370 (let (org-log-done org-log-states) ; turn off logging
11371 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11374 (defvar org-todo-statistics-hook nil
11375 "Hook that is run whenever Org thinks TODO statistics should be updated.
11376 This hook runs even if there is no statistics cookie present, in which case
11377 `org-after-todo-statistics-hook' would not run.")
11379 (defun org-todo-trigger-tag-changes (state)
11380 "Apply the changes defined in `org-todo-state-tags-triggers'."
11381 (let ((l org-todo-state-tags-triggers)
11382 changes)
11383 (when (or (not state) (equal state ""))
11384 (setq changes (append changes (cdr (assoc "" l)))))
11385 (when (and (stringp state) (> (length state) 0))
11386 (setq changes (append changes (cdr (assoc state l)))))
11387 (when (member state org-not-done-keywords)
11388 (setq changes (append changes (cdr (assoc 'todo l)))))
11389 (when (member state org-done-keywords)
11390 (setq changes (append changes (cdr (assoc 'done l)))))
11391 (dolist (c changes)
11392 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11394 (defun org-local-logging (value)
11395 "Get logging settings from a property VALUE."
11396 (let* (words w a)
11397 ;; directly set the variables, they are already local.
11398 (setq org-log-done nil
11399 org-log-repeat nil
11400 org-todo-log-states nil)
11401 (setq words (org-split-string value))
11402 (while (setq w (pop words))
11403 (cond
11404 ((setq a (assoc w org-startup-options))
11405 (and (member (nth 1 a) '(org-log-done org-log-repeat))
11406 (set (nth 1 a) (nth 2 a))))
11407 ((setq a (org-extract-log-state-settings w))
11408 (and (member (car a) org-todo-keywords-1)
11409 (push a org-todo-log-states)))))))
11411 (defun org-get-todo-sequence-head (kwd)
11412 "Return the head of the TODO sequence to which KWD belongs.
11413 If KWD is not set, check if there is a text property remembering the
11414 right sequence."
11415 (let (p)
11416 (cond
11417 ((not kwd)
11418 (or (get-text-property (point-at-bol) 'org-todo-head)
11419 (progn
11420 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11421 nil (point-at-eol)))
11422 (get-text-property p 'org-todo-head))))
11423 ((not (member kwd org-todo-keywords-1))
11424 (car org-todo-keywords-1))
11425 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11427 (defun org-fast-todo-selection ()
11428 "Fast TODO keyword selection with single keys.
11429 Returns the new TODO keyword, or nil if no state change should occur."
11430 (let* ((fulltable org-todo-key-alist)
11431 (done-keywords org-done-keywords) ;; needed for the faces.
11432 (maxlen (apply 'max (mapcar
11433 (lambda (x)
11434 (if (stringp (car x)) (string-width (car x)) 0))
11435 fulltable)))
11436 (expert nil)
11437 (fwidth (+ maxlen 3 1 3))
11438 (ncol (/ (- (window-width) 4) fwidth))
11439 tg cnt e c tbl
11440 groups ingroup)
11441 (save-excursion
11442 (save-window-excursion
11443 (if expert
11444 (set-buffer (get-buffer-create " *Org todo*"))
11445 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
11446 (erase-buffer)
11447 (org-set-local 'org-done-keywords done-keywords)
11448 (setq tbl fulltable cnt 0)
11449 (while (setq e (pop tbl))
11450 (cond
11451 ((equal e '(:startgroup))
11452 (push '() groups) (setq ingroup t)
11453 (when (not (= cnt 0))
11454 (setq cnt 0)
11455 (insert "\n"))
11456 (insert "{ "))
11457 ((equal e '(:endgroup))
11458 (setq ingroup nil cnt 0)
11459 (insert "}\n"))
11460 ((equal e '(:newline))
11461 (when (not (= cnt 0))
11462 (setq cnt 0)
11463 (insert "\n")
11464 (setq e (car tbl))
11465 (while (equal (car tbl) '(:newline))
11466 (insert "\n")
11467 (setq tbl (cdr tbl)))))
11469 (setq tg (car e) c (cdr e))
11470 (if ingroup (push tg (car groups)))
11471 (setq tg (org-add-props tg nil 'face
11472 (org-get-todo-face tg)))
11473 (if (and (= cnt 0) (not ingroup)) (insert " "))
11474 (insert "[" c "] " tg (make-string
11475 (- fwidth 4 (length tg)) ?\ ))
11476 (when (= (setq cnt (1+ cnt)) ncol)
11477 (insert "\n")
11478 (if ingroup (insert " "))
11479 (setq cnt 0)))))
11480 (insert "\n")
11481 (goto-char (point-min))
11482 (if (not expert) (org-fit-window-to-buffer))
11483 (message "[a-z..]:Set [SPC]:clear")
11484 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11485 (cond
11486 ((or (= c ?\C-g)
11487 (and (= c ?q) (not (rassoc c fulltable))))
11488 (setq quit-flag t))
11489 ((= c ?\ ) nil)
11490 ((setq e (rassoc c fulltable) tg (car e))
11492 (t (setq quit-flag t)))))))
11494 (defun org-entry-is-todo-p ()
11495 (member (org-get-todo-state) org-not-done-keywords))
11497 (defun org-entry-is-done-p ()
11498 (member (org-get-todo-state) org-done-keywords))
11500 (defun org-get-todo-state ()
11501 (save-excursion
11502 (org-back-to-heading t)
11503 (and (looking-at org-todo-line-regexp)
11504 (match-end 2)
11505 (match-string 2))))
11507 (defun org-at-date-range-p (&optional inactive-ok)
11508 "Is the cursor inside a date range?"
11509 (interactive)
11510 (save-excursion
11511 (catch 'exit
11512 (let ((pos (point)))
11513 (skip-chars-backward "^[<\r\n")
11514 (skip-chars-backward "<[")
11515 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11516 (>= (match-end 0) pos)
11517 (throw 'exit t))
11518 (skip-chars-backward "^<[\r\n")
11519 (skip-chars-backward "<[")
11520 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
11521 (>= (match-end 0) pos)
11522 (throw 'exit t)))
11523 nil)))
11525 (defun org-get-repeat (&optional tagline)
11526 "Check if there is a deadline/schedule with repeater in this entry."
11527 (save-match-data
11528 (save-excursion
11529 (org-back-to-heading t)
11530 (and (re-search-forward (if tagline
11531 (concat tagline "\\s-*" org-repeat-re)
11532 org-repeat-re)
11533 (org-entry-end-position) t)
11534 (match-string-no-properties 1)))))
11536 (defvar org-last-changed-timestamp)
11537 (defvar org-last-inserted-timestamp)
11538 (defvar org-log-post-message)
11539 (defvar org-log-note-purpose)
11540 (defvar org-log-note-how)
11541 (defvar org-log-note-extra)
11542 (defun org-auto-repeat-maybe (done-word)
11543 "Check if the current headline contains a repeated deadline/schedule.
11544 If yes, set TODO state back to what it was and change the base date
11545 of repeating deadline/scheduled time stamps to new date.
11546 This function is run automatically after each state change to a DONE state."
11547 ;; last-state is dynamically scoped into this function
11548 (let* ((repeat (org-get-repeat))
11549 (aa (assoc last-state org-todo-kwd-alist))
11550 (interpret (nth 1 aa))
11551 (head (nth 2 aa))
11552 (whata '(("d" . day) ("m" . month) ("y" . year)))
11553 (msg "Entry repeats: ")
11554 (org-log-done nil)
11555 (org-todo-log-states nil)
11556 re type n what ts time to-state)
11557 (when repeat
11558 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
11559 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
11560 org-todo-repeat-to-state))
11561 (unless (and to-state (member to-state org-todo-keywords-1))
11562 (setq to-state (if (eq interpret 'type) last-state head)))
11563 (org-todo to-state)
11564 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
11565 (org-entry-put nil "LAST_REPEAT" (format-time-string
11566 (org-time-stamp-format t t))))
11567 (when org-log-repeat
11568 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
11569 (memq 'org-add-log-note post-command-hook))
11570 ;; OK, we are already setup for some record
11571 (if (eq org-log-repeat 'note)
11572 ;; make sure we take a note, not only a time stamp
11573 (setq org-log-note-how 'note))
11574 ;; Set up for taking a record
11575 (org-add-log-setup 'state (or done-word (car org-done-keywords))
11576 last-state
11577 'findpos org-log-repeat)))
11578 (org-back-to-heading t)
11579 (org-add-planning-info nil nil 'closed)
11580 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11581 org-deadline-time-regexp "\\)\\|\\("
11582 org-ts-regexp "\\)"))
11583 (while (re-search-forward
11584 re (save-excursion (outline-next-heading) (point)) t)
11585 (setq type (if (match-end 1) org-scheduled-string
11586 (if (match-end 3) org-deadline-string "Plain:"))
11587 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
11588 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
11589 (setq n (string-to-number (match-string 2 ts))
11590 what (match-string 3 ts))
11591 (if (equal what "w") (setq n (* n 7) what "d"))
11592 ;; Preparation, see if we need to modify the start date for the change
11593 (when (match-end 1)
11594 (setq time (save-match-data (org-time-string-to-time ts)))
11595 (cond
11596 ((equal (match-string 1 ts) ".")
11597 ;; Shift starting date to today
11598 (org-timestamp-change
11599 (- (time-to-days (current-time)) (time-to-days time))
11600 'day))
11601 ((equal (match-string 1 ts) "+")
11602 (let ((nshiftmax 10) (nshift 0))
11603 (while (or (= nshift 0)
11604 (<= (time-to-days time)
11605 (time-to-days (current-time))))
11606 (when (= (incf nshift) nshiftmax)
11607 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
11608 (error "Abort")))
11609 (org-timestamp-change n (cdr (assoc what whata)))
11610 (org-at-timestamp-p t)
11611 (setq ts (match-string 1))
11612 (setq time (save-match-data (org-time-string-to-time ts)))))
11613 (org-timestamp-change (- n) (cdr (assoc what whata)))
11614 ;; rematch, so that we have everything in place for the real shift
11615 (org-at-timestamp-p t)
11616 (setq ts (match-string 1))
11617 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
11618 (org-timestamp-change n (cdr (assoc what whata)))
11619 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
11620 (setq org-log-post-message msg)
11621 (message "%s" msg))))
11623 (defun org-show-todo-tree (arg)
11624 "Make a compact tree which shows all headlines marked with TODO.
11625 The tree will show the lines where the regexp matches, and all higher
11626 headlines above the match.
11627 With a \\[universal-argument] prefix, prompt for a regexp to match.
11628 With a numeric prefix N, construct a sparse tree for the Nth element
11629 of `org-todo-keywords-1'."
11630 (interactive "P")
11631 (let ((case-fold-search nil)
11632 (kwd-re
11633 (cond ((null arg) org-not-done-regexp)
11634 ((equal arg '(4))
11635 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
11636 (mapcar 'list org-todo-keywords-1))))
11637 (concat "\\("
11638 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11639 "\\)\\>")))
11640 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11641 (regexp-quote (nth (1- (prefix-numeric-value arg))
11642 org-todo-keywords-1)))
11643 (t (error "Invalid prefix argument: %s" arg)))))
11644 (message "%d TODO entries found"
11645 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
11647 (defun org-deadline (&optional remove time)
11648 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
11649 With argument REMOVE, remove any deadline from the item.
11650 When TIME is set, it should be an internal time specification, and the
11651 scheduling will use the corresponding date."
11652 (interactive "P")
11653 (let* ((old-date (org-entry-get nil "DEADLINE"))
11654 (repeater (and old-date
11655 (string-match
11656 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11657 old-date)
11658 (match-string 1 old-date))))
11659 (if remove
11660 (progn
11661 (when (and old-date org-log-redeadline)
11662 (org-add-log-setup 'deldeadline nil old-date 'findpos
11663 org-log-redeadline))
11664 (org-remove-timestamp-with-keyword org-deadline-string)
11665 (message "Item no longer has a deadline."))
11666 (org-add-planning-info 'deadline time 'closed)
11667 (when (and old-date org-log-redeadline
11668 (not (equal old-date
11669 (substring org-last-inserted-timestamp 1 -1))))
11670 (org-add-log-setup 'redeadline nil old-date 'findpos
11671 org-log-redeadline))
11672 (when repeater
11673 (save-excursion
11674 (org-back-to-heading t)
11675 (when (re-search-forward (concat org-deadline-string " "
11676 org-last-inserted-timestamp)
11677 (save-excursion
11678 (outline-next-heading) (point)) t)
11679 (goto-char (1- (match-end 0)))
11680 (insert " " repeater)
11681 (setq org-last-inserted-timestamp
11682 (concat (substring org-last-inserted-timestamp 0 -1)
11683 " " repeater
11684 (substring org-last-inserted-timestamp -1))))))
11685 (message "Deadline on %s" org-last-inserted-timestamp))))
11687 (defun org-schedule (&optional remove time)
11688 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
11689 With argument REMOVE, remove any scheduling date from the item.
11690 When TIME is set, it should be an internal time specification, and the
11691 scheduling will use the corresponding date."
11692 (interactive "P")
11693 (let* ((old-date (org-entry-get nil "SCHEDULED"))
11694 (repeater (and old-date
11695 (string-match
11696 "\\([.+-]+[0-9]+[dwmy]\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
11697 old-date)
11698 (match-string 1 old-date))))
11699 (if remove
11700 (progn
11701 (when (and old-date org-log-reschedule)
11702 (org-add-log-setup 'delschedule nil old-date 'findpos
11703 org-log-reschedule))
11704 (org-remove-timestamp-with-keyword org-scheduled-string)
11705 (message "Item is no longer scheduled."))
11706 (org-add-planning-info 'scheduled time 'closed)
11707 (when (and old-date org-log-reschedule
11708 (not (equal old-date
11709 (substring org-last-inserted-timestamp 1 -1))))
11710 (org-add-log-setup 'reschedule nil old-date 'findpos
11711 org-log-reschedule))
11712 (when repeater
11713 (save-excursion
11714 (org-back-to-heading t)
11715 (when (re-search-forward (concat org-scheduled-string " "
11716 org-last-inserted-timestamp)
11717 (save-excursion
11718 (outline-next-heading) (point)) t)
11719 (goto-char (1- (match-end 0)))
11720 (insert " " repeater)
11721 (setq org-last-inserted-timestamp
11722 (concat (substring org-last-inserted-timestamp 0 -1)
11723 " " repeater
11724 (substring org-last-inserted-timestamp -1))))))
11725 (message "Scheduled to %s" org-last-inserted-timestamp))))
11727 (defun org-get-scheduled-time (pom &optional inherit)
11728 "Get the scheduled time as a time tuple, of a format suitable
11729 for calling org-schedule with, or if there is no scheduling,
11730 returns nil."
11731 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
11732 (when time
11733 (apply 'encode-time (org-parse-time-string time)))))
11735 (defun org-get-deadline-time (pom &optional inherit)
11736 "Get the deadline as a time tuple, of a format suitable for
11737 calling org-deadline with, or if there is no scheduling, returns
11738 nil."
11739 (let ((time (org-entry-get pom "DEADLINE" inherit)))
11740 (when time
11741 (apply 'encode-time (org-parse-time-string time)))))
11743 (defun org-remove-timestamp-with-keyword (keyword)
11744 "Remove all time stamps with KEYWORD in the current entry."
11745 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
11746 beg)
11747 (save-excursion
11748 (org-back-to-heading t)
11749 (setq beg (point))
11750 (outline-next-heading)
11751 (while (re-search-backward re beg t)
11752 (replace-match "")
11753 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
11754 (equal (char-before) ?\ ))
11755 (backward-delete-char 1)
11756 (if (string-match "^[ \t]*$" (buffer-substring
11757 (point-at-bol) (point-at-eol)))
11758 (delete-region (point-at-bol)
11759 (min (point-max) (1+ (point-at-eol))))))))))
11761 (defun org-add-planning-info (what &optional time &rest remove)
11762 "Insert new timestamp with keyword in the line directly after the headline.
11763 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11764 If non is given, the user is prompted for a date.
11765 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11766 be removed."
11767 (interactive)
11768 (let (org-time-was-given org-end-time-was-given ts
11769 end default-time default-input)
11771 (catch 'exit
11772 (when (and (not time) (memq what '(scheduled deadline)))
11773 ;; Try to get a default date/time from existing timestamp
11774 (save-excursion
11775 (org-back-to-heading t)
11776 (setq end (save-excursion (outline-next-heading) (point)))
11777 (when (re-search-forward (if (eq what 'scheduled)
11778 org-scheduled-time-regexp
11779 org-deadline-time-regexp)
11780 end t)
11781 (setq ts (match-string 1)
11782 default-time
11783 (apply 'encode-time (org-parse-time-string ts))
11784 default-input (and ts (org-get-compact-tod ts))))))
11785 (when what
11786 ;; If necessary, get the time from the user
11787 (setq time (or time (org-read-date nil 'to-time nil nil
11788 default-time default-input))))
11790 (when (and org-insert-labeled-timestamps-at-point
11791 (member what '(scheduled deadline)))
11792 (insert
11793 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11794 (org-insert-time-stamp time org-time-was-given
11795 nil nil nil (list org-end-time-was-given))
11796 (setq what nil))
11797 (save-excursion
11798 (save-restriction
11799 (let (col list elt ts buffer-invisibility-spec)
11800 (org-back-to-heading t)
11801 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11802 (goto-char (match-end 1))
11803 (setq col (current-column))
11804 (goto-char (match-end 0))
11805 (if (eobp) (insert "\n") (forward-char 1))
11806 (when (and (not what)
11807 (not (looking-at
11808 (concat "[ \t]*"
11809 org-keyword-time-not-clock-regexp))))
11810 ;; Nothing to add, nothing to remove...... :-)
11811 (throw 'exit nil))
11812 (if (and (not (looking-at outline-regexp))
11813 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11814 "[^\r\n]*"))
11815 (not (equal (match-string 1) org-clock-string)))
11816 (narrow-to-region (match-beginning 0) (match-end 0))
11817 (insert-before-markers "\n")
11818 (backward-char 1)
11819 (narrow-to-region (point) (point))
11820 (and org-adapt-indentation (org-indent-to-column col)))
11821 ;; Check if we have to remove something.
11822 (setq list (cons what remove))
11823 (while list
11824 (setq elt (pop list))
11825 (goto-char (point-min))
11826 (when (or (and (eq elt 'scheduled)
11827 (re-search-forward org-scheduled-time-regexp nil t))
11828 (and (eq elt 'deadline)
11829 (re-search-forward org-deadline-time-regexp nil t))
11830 (and (eq elt 'closed)
11831 (re-search-forward org-closed-time-regexp nil t)))
11832 (replace-match "")
11833 (if (looking-at "--+<[^>]+>") (replace-match ""))
11834 (skip-chars-backward " ")
11835 (if (looking-at " +") (replace-match ""))))
11836 (goto-char (point-max))
11837 (and org-adapt-indentation (bolp) (org-indent-to-column col))
11838 (when what
11839 (insert
11840 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
11841 (cond ((eq what 'scheduled) org-scheduled-string)
11842 ((eq what 'deadline) org-deadline-string)
11843 ((eq what 'closed) org-closed-string))
11844 " ")
11845 (setq ts (org-insert-time-stamp
11846 time
11847 (or org-time-was-given
11848 (and (eq what 'closed) org-log-done-with-time))
11849 (eq what 'closed)
11850 nil nil (list org-end-time-was-given)))
11851 (end-of-line 1))
11852 (goto-char (point-min))
11853 (widen)
11854 (if (and (looking-at "[ \t]*\n")
11855 (equal (char-before) ?\n))
11856 (delete-region (1- (point)) (point-at-eol)))
11857 ts))))))
11859 (defvar org-log-note-marker (make-marker))
11860 (defvar org-log-note-purpose nil)
11861 (defvar org-log-note-state nil)
11862 (defvar org-log-note-previous-state nil)
11863 (defvar org-log-note-how nil)
11864 (defvar org-log-note-extra nil)
11865 (defvar org-log-note-window-configuration nil)
11866 (defvar org-log-note-return-to (make-marker))
11867 (defvar org-log-post-message nil
11868 "Message to be displayed after a log note has been stored.
11869 The auto-repeater uses this.")
11871 (defun org-add-note ()
11872 "Add a note to the current entry.
11873 This is done in the same way as adding a state change note."
11874 (interactive)
11875 (org-add-log-setup 'note nil nil 'findpos nil))
11877 (defvar org-property-end-re)
11878 (defun org-add-log-setup (&optional purpose state prev-state
11879 findpos how extra)
11880 "Set up the post command hook to take a note.
11881 If this is about to TODO state change, the new state is expected in STATE.
11882 When FINDPOS is non-nil, find the correct position for the note in
11883 the current entry. If not, assume that it can be inserted at point.
11884 HOW is an indicator what kind of note should be created.
11885 EXTRA is additional text that will be inserted into the notes buffer."
11886 (let* ((org-log-into-drawer (org-log-into-drawer))
11887 (drawer (cond ((stringp org-log-into-drawer)
11888 org-log-into-drawer)
11889 (org-log-into-drawer "LOGBOOK")
11890 (t nil))))
11891 (save-restriction
11892 (save-excursion
11893 (when findpos
11894 (org-back-to-heading t)
11895 (narrow-to-region (point) (save-excursion
11896 (outline-next-heading) (point)))
11897 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11898 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11899 "[^\r\n]*\\)?"))
11900 (goto-char (match-end 0))
11901 (cond
11902 (drawer
11903 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
11904 nil t)
11905 (progn
11906 (goto-char (match-end 0))
11907 (or org-log-states-order-reversed
11908 (and (re-search-forward org-property-end-re nil t)
11909 (goto-char (1- (match-beginning 0))))))
11910 (insert "\n:" drawer ":\n:END:")
11911 (beginning-of-line 0)
11912 (org-indent-line-function)
11913 (beginning-of-line 2)
11914 (org-indent-line-function)
11915 (end-of-line 0)))
11916 ((and org-log-state-notes-insert-after-drawers
11917 (save-excursion
11918 (forward-line) (looking-at org-drawer-regexp)))
11919 (forward-line)
11920 (while (looking-at org-drawer-regexp)
11921 (goto-char (match-end 0))
11922 (re-search-forward org-property-end-re (point-max) t)
11923 (forward-line))
11924 (forward-line -1)))
11925 (unless org-log-states-order-reversed
11926 (and (= (char-after) ?\n) (forward-char 1))
11927 (org-skip-over-state-notes)
11928 (skip-chars-backward " \t\n\r")))
11929 (move-marker org-log-note-marker (point))
11930 (setq org-log-note-purpose purpose
11931 org-log-note-state state
11932 org-log-note-previous-state prev-state
11933 org-log-note-how how
11934 org-log-note-extra extra)
11935 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
11937 (defun org-skip-over-state-notes ()
11938 "Skip past the list of State notes in an entry."
11939 (if (looking-at "\n[ \t]*- State") (forward-char 1))
11940 (when (ignore-errors (goto-char (org-in-item-p)))
11941 (let* ((struct (org-list-struct))
11942 (prevs (org-list-prevs-alist struct)))
11943 (while (looking-at "[ \t]*- State")
11944 (goto-char (or (org-list-get-next-item (point) struct prevs)
11945 (org-list-get-item-end (point) struct)))))))
11947 (defun org-add-log-note (&optional purpose)
11948 "Pop up a window for taking a note, and add this note later at point."
11949 (remove-hook 'post-command-hook 'org-add-log-note)
11950 (setq org-log-note-window-configuration (current-window-configuration))
11951 (delete-other-windows)
11952 (move-marker org-log-note-return-to (point))
11953 (switch-to-buffer (marker-buffer org-log-note-marker))
11954 (goto-char org-log-note-marker)
11955 (org-switch-to-buffer-other-window "*Org Note*")
11956 (erase-buffer)
11957 (if (memq org-log-note-how '(time state))
11958 (let (current-prefix-arg) (org-store-log-note))
11959 (let ((org-inhibit-startup t)) (org-mode))
11960 (insert (format "# Insert note for %s.
11961 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
11962 (cond
11963 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11964 ((eq org-log-note-purpose 'done) "closed todo item")
11965 ((eq org-log-note-purpose 'state)
11966 (format "state change from \"%s\" to \"%s\""
11967 (or org-log-note-previous-state "")
11968 (or org-log-note-state "")))
11969 ((eq org-log-note-purpose 'reschedule)
11970 "rescheduling")
11971 ((eq org-log-note-purpose 'delschedule)
11972 "no longer scheduled")
11973 ((eq org-log-note-purpose 'redeadline)
11974 "changing deadline")
11975 ((eq org-log-note-purpose 'deldeadline)
11976 "removing deadline")
11977 ((eq org-log-note-purpose 'refile)
11978 "refiling")
11979 ((eq org-log-note-purpose 'note)
11980 "this entry")
11981 (t (error "This should not happen")))))
11982 (if org-log-note-extra (insert org-log-note-extra))
11983 (org-set-local 'org-finish-function 'org-store-log-note)))
11985 (defvar org-note-abort nil) ; dynamically scoped
11986 (defun org-store-log-note ()
11987 "Finish taking a log note, and insert it to where it belongs."
11988 (let ((txt (buffer-string))
11989 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11990 lines ind bul)
11991 (kill-buffer (current-buffer))
11992 (while (string-match "\\`#.*\n[ \t\n]*" txt)
11993 (setq txt (replace-match "" t t txt)))
11994 (if (string-match "\\s-+\\'" txt)
11995 (setq txt (replace-match "" t t txt)))
11996 (setq lines (org-split-string txt "\n"))
11997 (when (and note (string-match "\\S-" note))
11998 (setq note
11999 (org-replace-escapes
12000 note
12001 (list (cons "%u" (user-login-name))
12002 (cons "%U" user-full-name)
12003 (cons "%t" (format-time-string
12004 (org-time-stamp-format 'long 'inactive)
12005 (current-time)))
12006 (cons "%T" (format-time-string
12007 (org-time-stamp-format 'long nil)
12008 (current-time)))
12009 (cons "%s" (if org-log-note-state
12010 (concat "\"" org-log-note-state "\"")
12011 ""))
12012 (cons "%S" (if org-log-note-previous-state
12013 (concat "\"" org-log-note-previous-state "\"")
12014 "\"\"")))))
12015 (if lines (setq note (concat note " \\\\")))
12016 (push note lines))
12017 (when (or current-prefix-arg org-note-abort)
12018 (when org-log-into-drawer
12019 (org-remove-empty-drawer-at
12020 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12021 org-log-note-marker))
12022 (setq lines nil))
12023 (when lines
12024 (with-current-buffer (marker-buffer org-log-note-marker)
12025 (save-excursion
12026 (goto-char org-log-note-marker)
12027 (move-marker org-log-note-marker nil)
12028 (end-of-line 1)
12029 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12030 (setq ind (save-excursion
12031 (if (ignore-errors (goto-char (org-in-item-p)))
12032 (let ((struct (org-list-struct)))
12033 (org-list-get-ind
12034 (org-list-get-top-point struct) struct))
12035 (skip-chars-backward " \r\t\n")
12036 (cond
12037 ((and (org-at-heading-p)
12038 org-adapt-indentation)
12039 (1+ (org-current-level)))
12040 ((org-at-heading-p) 0)
12041 (t (org-get-indentation))))))
12042 (setq bul (org-list-bullet-string "-"))
12043 (org-indent-line-to ind)
12044 (insert bul (pop lines))
12045 (let ((ind-body (+ (length bul) ind)))
12046 (while lines
12047 (insert "\n")
12048 (org-indent-line-to ind-body)
12049 (insert (pop lines))))
12050 (message "Note stored")
12051 (org-back-to-heading t)
12052 (org-cycle-hide-drawers 'children)))))
12053 (set-window-configuration org-log-note-window-configuration)
12054 (with-current-buffer (marker-buffer org-log-note-return-to)
12055 (goto-char org-log-note-return-to))
12056 (move-marker org-log-note-return-to nil)
12057 (and org-log-post-message (message "%s" org-log-post-message)))
12059 (defun org-remove-empty-drawer-at (drawer pos)
12060 "Remove an empty drawer DRAWER at position POS.
12061 POS may also be a marker."
12062 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12063 (save-excursion
12064 (save-restriction
12065 (widen)
12066 (goto-char pos)
12067 (if (org-in-regexp
12068 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12069 (replace-match ""))))))
12071 (defun org-sparse-tree (&optional arg)
12072 "Create a sparse tree, prompt for the details.
12073 This command can create sparse trees. You first need to select the type
12074 of match used to create the tree:
12076 t Show all TODO entries.
12077 T Show entries with a specific TODO keyword.
12078 m Show entries selected by a tags/property match.
12079 p Enter a property name and its value (both with completion on existing
12080 names/values) and show entries with that property.
12081 r Show entries matching a regular expression (`/' can be used as well)
12082 d Show deadlines due within `org-deadline-warning-days'.
12083 b Show deadlines and scheduled items before a date.
12084 a Show deadlines and scheduled items after a date."
12085 (interactive "P")
12086 (let (ans kwd value)
12087 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date")
12088 (setq ans (read-char-exclusive))
12089 (cond
12090 ((equal ans ?d)
12091 (call-interactively 'org-check-deadlines))
12092 ((equal ans ?b)
12093 (call-interactively 'org-check-before-date))
12094 ((equal ans ?a)
12095 (call-interactively 'org-check-after-date))
12096 ((equal ans ?t)
12097 (org-show-todo-tree nil))
12098 ((equal ans ?T)
12099 (org-show-todo-tree '(4)))
12100 ((member ans '(?T ?m))
12101 (call-interactively 'org-match-sparse-tree))
12102 ((member ans '(?p ?P))
12103 (setq kwd (org-icompleting-read "Property: "
12104 (mapcar 'list (org-buffer-property-keys))))
12105 (setq value (org-icompleting-read "Value: "
12106 (mapcar 'list (org-property-values kwd))))
12107 (unless (string-match "\\`{.*}\\'" value)
12108 (setq value (concat "\"" value "\"")))
12109 (org-match-sparse-tree arg (concat kwd "=" value)))
12110 ((member ans '(?r ?R ?/))
12111 (call-interactively 'org-occur))
12112 (t (error "No such sparse tree command \"%c\"" ans)))))
12114 (defvar org-occur-highlights nil
12115 "List of overlays used for occur matches.")
12116 (make-variable-buffer-local 'org-occur-highlights)
12117 (defvar org-occur-parameters nil
12118 "Parameters of the active org-occur calls.
12119 This is a list, each call to org-occur pushes as cons cell,
12120 containing the regular expression and the callback, onto the list.
12121 The list can contain several entries if `org-occur' has been called
12122 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12123 will only contain one set of parameters. When the highlights are
12124 removed (for example with `C-c C-c', or with the next edit (depending
12125 on `org-remove-highlights-with-change'), this variable is emptied
12126 as well.")
12127 (make-variable-buffer-local 'org-occur-parameters)
12129 (defun org-occur (regexp &optional keep-previous callback)
12130 "Make a compact tree which shows all matches of REGEXP.
12131 The tree will show the lines where the regexp matches, and all higher
12132 headlines above the match. It will also show the heading after the match,
12133 to make sure editing the matching entry is easy.
12134 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12135 call to `org-occur' will be kept, to allow stacking of calls to this
12136 command.
12137 If CALLBACK is non-nil, it is a function which is called to confirm
12138 that the match should indeed be shown."
12139 (interactive "sRegexp: \nP")
12140 (when (equal regexp "")
12141 (error "Regexp cannot be empty"))
12142 (unless keep-previous
12143 (org-remove-occur-highlights nil nil t))
12144 (push (cons regexp callback) org-occur-parameters)
12145 (let ((cnt 0))
12146 (save-excursion
12147 (goto-char (point-min))
12148 (if (or (not keep-previous) ; do not want to keep
12149 (not org-occur-highlights)) ; no previous matches
12150 ;; hide everything
12151 (org-overview))
12152 (while (re-search-forward regexp nil t)
12153 (when (or (not callback)
12154 (save-match-data (funcall callback)))
12155 (setq cnt (1+ cnt))
12156 (when org-highlight-sparse-tree-matches
12157 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12158 (org-show-context 'occur-tree))))
12159 (when org-remove-highlights-with-change
12160 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12161 nil 'local))
12162 (unless org-sparse-tree-open-archived-trees
12163 (org-hide-archived-subtrees (point-min) (point-max)))
12164 (run-hooks 'org-occur-hook)
12165 (if (interactive-p)
12166 (message "%d match(es) for regexp %s" cnt regexp))
12167 cnt))
12169 (defun org-occur-next-match (&optional n reset)
12170 "Function for `next-error-function' to find sparse tree matches.
12171 N is the number of matches to move, when negative move backwards.
12172 RESET is entirely ignored - this function always goes back to the
12173 starting point when no match is found."
12174 (let* ((limit (if (< n 0) (point-min) (point-max)))
12175 (search-func (if (< n 0)
12176 'previous-single-char-property-change
12177 'next-single-char-property-change))
12178 (n (abs n))
12179 (pos (point))
12181 (catch 'exit
12182 (while (setq p1 (funcall search-func (point) 'org-type))
12183 (when (equal p1 limit)
12184 (goto-char pos)
12185 (error "No more matches"))
12186 (when (equal (get-char-property p1 'org-type) 'org-occur)
12187 (setq n (1- n))
12188 (when (= n 0)
12189 (goto-char p1)
12190 (throw 'exit (point))))
12191 (goto-char p1))
12192 (goto-char p1)
12193 (error "No more matches"))))
12195 (defun org-show-context (&optional key)
12196 "Make sure point and context are visible.
12197 How much context is shown depends upon the variables
12198 `org-show-hierarchy-above', `org-show-following-heading'. and
12199 `org-show-siblings'."
12200 (let ((heading-p (org-on-heading-p t))
12201 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12202 (following-p (org-get-alist-option org-show-following-heading key))
12203 (entry-p (org-get-alist-option org-show-entry-below key))
12204 (siblings-p (org-get-alist-option org-show-siblings key)))
12205 (catch 'exit
12206 ;; Show heading or entry text
12207 (if (and heading-p (not entry-p))
12208 (org-flag-heading nil) ; only show the heading
12209 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12210 (org-show-hidden-entry))) ; show entire entry
12211 (when following-p
12212 ;; Show next sibling, or heading below text
12213 (save-excursion
12214 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12215 (org-flag-heading nil))))
12216 (when siblings-p (org-show-siblings))
12217 (when hierarchy-p
12218 ;; show all higher headings, possibly with siblings
12219 (save-excursion
12220 (while (and (condition-case nil
12221 (progn (org-up-heading-all 1) t)
12222 (error nil))
12223 (not (bobp)))
12224 (org-flag-heading nil)
12225 (when siblings-p (org-show-siblings))))))))
12227 (defvar org-reveal-start-hook nil
12228 "Hook run before revealing a location.")
12230 (defun org-reveal (&optional siblings)
12231 "Show current entry, hierarchy above it, and the following headline.
12232 This can be used to show a consistent set of context around locations
12233 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12234 not t for the search context.
12236 With optional argument SIBLINGS, on each level of the hierarchy all
12237 siblings are shown. This repairs the tree structure to what it would
12238 look like when opened with hierarchical calls to `org-cycle'.
12239 With double optional argument \\[universal-argument] \\[universal-argument], \
12240 go to the parent and show the
12241 entire tree."
12242 (interactive "P")
12243 (run-hooks 'org-reveal-start-hook)
12244 (let ((org-show-hierarchy-above t)
12245 (org-show-following-heading t)
12246 (org-show-siblings (if siblings t org-show-siblings)))
12247 (org-show-context nil))
12248 (when (equal siblings '(16))
12249 (save-excursion
12250 (when (org-up-heading-safe)
12251 (org-show-subtree)
12252 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12254 (defun org-highlight-new-match (beg end)
12255 "Highlight from BEG to END and mark the highlight is an occur headline."
12256 (let ((ov (make-overlay beg end)))
12257 (overlay-put ov 'face 'secondary-selection)
12258 (overlay-put ov 'org-type 'org-occur)
12259 (push ov org-occur-highlights)))
12261 (defun org-remove-occur-highlights (&optional beg end noremove)
12262 "Remove the occur highlights from the buffer.
12263 BEG and END are ignored. If NOREMOVE is nil, remove this function
12264 from the `before-change-functions' in the current buffer."
12265 (interactive)
12266 (unless org-inhibit-highlight-removal
12267 (mapc 'delete-overlay org-occur-highlights)
12268 (setq org-occur-highlights nil)
12269 (setq org-occur-parameters nil)
12270 (unless noremove
12271 (remove-hook 'before-change-functions
12272 'org-remove-occur-highlights 'local))))
12274 ;;;; Priorities
12276 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12277 "Regular expression matching the priority indicator.")
12279 (defvar org-remove-priority-next-time nil)
12281 (defun org-priority-up ()
12282 "Increase the priority of the current item."
12283 (interactive)
12284 (org-priority 'up))
12286 (defun org-priority-down ()
12287 "Decrease the priority of the current item."
12288 (interactive)
12289 (org-priority 'down))
12291 (defun org-priority (&optional action)
12292 "Change the priority of an item by ARG.
12293 ACTION can be `set', `up', `down', or a character."
12294 (interactive)
12295 (unless org-enable-priority-commands
12296 (error "Priority commands are disabled"))
12297 (setq action (or action 'set))
12298 (let (current new news have remove)
12299 (save-excursion
12300 (org-back-to-heading t)
12301 (if (looking-at org-priority-regexp)
12302 (setq current (string-to-char (match-string 2))
12303 have t))
12304 (cond
12305 ((eq action 'remove)
12306 (setq remove t new ?\ ))
12307 ((or (eq action 'set)
12308 (if (featurep 'xemacs) (characterp action) (integerp action)))
12309 (if (not (eq action 'set))
12310 (setq new action)
12311 (message "Priority %c-%c, SPC to remove: "
12312 org-highest-priority org-lowest-priority)
12313 (save-match-data
12314 (setq new (read-char-exclusive))))
12315 (if (and (= (upcase org-highest-priority) org-highest-priority)
12316 (= (upcase org-lowest-priority) org-lowest-priority))
12317 (setq new (upcase new)))
12318 (cond ((equal new ?\ ) (setq remove t))
12319 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12320 (error "Priority must be between `%c' and `%c'"
12321 org-highest-priority org-lowest-priority))))
12322 ((eq action 'up)
12323 (setq new (if have
12324 (1- current) ; normal cycling
12325 ;; last priority was empty
12326 (if (eq last-command this-command)
12327 org-lowest-priority ; wrap around empty to lowest
12328 ;; default
12329 (if org-priority-start-cycle-with-default
12330 org-default-priority
12331 (1- org-default-priority))))))
12332 ((eq action 'down)
12333 (setq new (if have
12334 (1+ current) ; normal cycling
12335 ;; last priority was empty
12336 (if (eq last-command this-command)
12337 org-highest-priority ; wrap around empty to highest
12338 ;; default
12339 (if org-priority-start-cycle-with-default
12340 org-default-priority
12341 (1+ org-default-priority))))))
12342 (t (error "Invalid action")))
12343 (if (or (< (upcase new) org-highest-priority)
12344 (> (upcase new) org-lowest-priority))
12345 (if (and (memq action '(up down))
12346 (not have) (not (eq last-command this-command)))
12347 ;; `new' is from default priority
12348 (error
12349 "The default can not be set, see `org-default-priority' why")
12350 ;; normal cycling: `new' is beyond highest/lowest priority
12351 ;; and is wrapped around to the empty priority
12352 (setq remove t)))
12353 (setq news (format "%c" new))
12354 (if have
12355 (if remove
12356 (replace-match "" t t nil 1)
12357 (replace-match news t t nil 2))
12358 (if remove
12359 (error "No priority cookie found in line")
12360 (let ((case-fold-search nil))
12361 (looking-at org-todo-line-regexp))
12362 (if (match-end 2)
12363 (progn
12364 (goto-char (match-end 2))
12365 (insert " [#" news "]"))
12366 (goto-char (match-beginning 3))
12367 (insert "[#" news "] "))))
12368 (org-preserve-lc (org-set-tags nil 'align)))
12369 (if remove
12370 (message "Priority removed")
12371 (message "Priority of current item set to %s" news))))
12373 (defun org-get-priority (s)
12374 "Find priority cookie and return priority."
12375 (if (functionp org-get-priority-function)
12376 (funcall org-get-priority-function)
12377 (save-match-data
12378 (if (not (string-match org-priority-regexp s))
12379 (* 1000 (- org-lowest-priority org-default-priority))
12380 (* 1000 (- org-lowest-priority
12381 (string-to-char (match-string 2 s))))))))
12383 ;;;; Tags
12385 (defvar org-agenda-archives-mode)
12386 (defvar org-map-continue-from nil
12387 "Position from where mapping should continue.
12388 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
12390 (defvar org-scanner-tags nil
12391 "The current tag list while the tags scanner is running.")
12392 (defvar org-trust-scanner-tags nil
12393 "Should `org-get-tags-at' use the tags for the scanner.
12394 This is for internal dynamical scoping only.
12395 When this is non-nil, the function `org-get-tags-at' will return the value
12396 of `org-scanner-tags' instead of building the list by itself. This
12397 can lead to large speed-ups when the tags scanner is used in a file with
12398 many entries, and when the list of tags is retrieved, for example to
12399 obtain a list of properties. Building the tags list for each entry in such
12400 a file becomes an N^2 operation - but with this variable set, it scales
12401 as N.")
12403 (defun org-scan-tags (action matcher &optional todo-only)
12404 "Scan headline tags with inheritance and produce output ACTION.
12406 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
12407 or `agenda' to produce an entry list for an agenda view. It can also be
12408 a Lisp form or a function that should be called at each matched headline, in
12409 this case the return value is a list of all return values from these calls.
12411 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
12412 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
12413 only lines with a TODO keyword are included in the output."
12414 (require 'org-agenda)
12415 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
12416 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12417 (org-re
12418 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
12419 (props (list 'face 'default
12420 'done-face 'org-agenda-done
12421 'undone-face 'default
12422 'mouse-face 'highlight
12423 'org-not-done-regexp org-not-done-regexp
12424 'org-todo-regexp org-todo-regexp
12425 'help-echo
12426 (format "mouse-2 or RET jump to org file %s"
12427 (abbreviate-file-name
12428 (or (buffer-file-name (buffer-base-buffer))
12429 (buffer-name (buffer-base-buffer)))))))
12430 (case-fold-search nil)
12431 (org-map-continue-from nil)
12432 lspos tags tags-list
12433 (tags-alist (list (cons 0 org-file-tags)))
12434 (llast 0) rtn rtn1 level category i txt
12435 todo marker entry priority)
12436 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
12437 (setq action (list 'lambda nil action)))
12438 (save-excursion
12439 (goto-char (point-min))
12440 (when (eq action 'sparse-tree)
12441 (org-overview)
12442 (org-remove-occur-highlights))
12443 (while (re-search-forward re nil t)
12444 (catch :skip
12445 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
12446 tags (if (match-end 4) (org-match-string-no-properties 4)))
12447 (goto-char (setq lspos (match-beginning 0)))
12448 (setq level (org-reduced-level (funcall outline-level))
12449 category (org-get-category))
12450 (setq i llast llast level)
12451 ;; remove tag lists from same and sublevels
12452 (while (>= i level)
12453 (when (setq entry (assoc i tags-alist))
12454 (setq tags-alist (delete entry tags-alist)))
12455 (setq i (1- i)))
12456 ;; add the next tags
12457 (when tags
12458 (setq tags (org-split-string tags ":")
12459 tags-alist
12460 (cons (cons level tags) tags-alist)))
12461 ;; compile tags for current headline
12462 (setq tags-list
12463 (if org-use-tag-inheritance
12464 (apply 'append (mapcar 'cdr (reverse tags-alist)))
12465 tags)
12466 org-scanner-tags tags-list)
12467 (when org-use-tag-inheritance
12468 (setcdr (car tags-alist)
12469 (mapcar (lambda (x)
12470 (setq x (copy-sequence x))
12471 (org-add-prop-inherited x))
12472 (cdar tags-alist))))
12473 (when (and tags org-use-tag-inheritance
12474 (or (not (eq t org-use-tag-inheritance))
12475 org-tags-exclude-from-inheritance))
12476 ;; selective inheritance, remove uninherited ones
12477 (setcdr (car tags-alist)
12478 (org-remove-uninherited-tags (cdar tags-alist))))
12479 (when (and
12481 ;; eval matcher only when the todo condition is OK
12482 (and (or (not todo-only) (member todo org-not-done-keywords))
12483 (let ((case-fold-search t)) (eval matcher)))
12485 ;; Call the skipper, but return t if it does not skip,
12486 ;; so that the `and' form continues evaluating
12487 (progn
12488 (unless (eq action 'sparse-tree) (org-agenda-skip))
12491 ;; Check if timestamps are deselecting this entry
12492 (or (not todo-only)
12493 (and (member todo org-not-done-keywords)
12494 (or (not org-agenda-tags-todo-honor-ignore-options)
12495 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
12497 ;; Extra check for the archive tag
12498 ;; FIXME: Does the skipper already do this????
12500 (not (member org-archive-tag tags-list))
12501 ;; we have an archive tag, should we use this anyway?
12502 (or (not org-agenda-skip-archived-trees)
12503 (and (eq action 'agenda) org-agenda-archives-mode))))
12505 ;; select this headline
12507 (cond
12508 ((eq action 'sparse-tree)
12509 (and org-highlight-sparse-tree-matches
12510 (org-get-heading) (match-end 0)
12511 (org-highlight-new-match
12512 (match-beginning 0) (match-beginning 1)))
12513 (org-show-context 'tags-tree))
12514 ((eq action 'agenda)
12515 (setq txt (org-format-agenda-item
12517 (concat
12518 (if (eq org-tags-match-list-sublevels 'indented)
12519 (make-string (1- level) ?.) "")
12520 (org-get-heading))
12521 category
12522 tags-list
12524 priority (org-get-priority txt))
12525 (goto-char lspos)
12526 (setq marker (org-agenda-new-marker))
12527 (org-add-props txt props
12528 'org-marker marker 'org-hd-marker marker 'org-category category
12529 'todo-state todo
12530 'priority priority 'type "tagsmatch")
12531 (push txt rtn))
12532 ((functionp action)
12533 (setq org-map-continue-from nil)
12534 (save-excursion
12535 (setq rtn1 (funcall action))
12536 (push rtn1 rtn)))
12537 (t (error "Invalid action")))
12539 ;; if we are to skip sublevels, jump to end of subtree
12540 (unless org-tags-match-list-sublevels
12541 (org-end-of-subtree t)
12542 (backward-char 1))))
12543 ;; Get the correct position from where to continue
12544 (if org-map-continue-from
12545 (goto-char org-map-continue-from)
12546 (and (= (point) lspos) (end-of-line 1)))))
12547 (when (and (eq action 'sparse-tree)
12548 (not org-sparse-tree-open-archived-trees))
12549 (org-hide-archived-subtrees (point-min) (point-max)))
12550 (nreverse rtn)))
12552 (defun org-remove-uninherited-tags (tags)
12553 "Remove all tags that are not inherited from the list TAGS."
12554 (cond
12555 ((eq org-use-tag-inheritance t)
12556 (if org-tags-exclude-from-inheritance
12557 (org-delete-all org-tags-exclude-from-inheritance tags)
12558 tags))
12559 ((not org-use-tag-inheritance) nil)
12560 ((stringp org-use-tag-inheritance)
12561 (delq nil (mapcar
12562 (lambda (x)
12563 (if (and (string-match org-use-tag-inheritance x)
12564 (not (member x org-tags-exclude-from-inheritance)))
12565 x nil))
12566 tags)))
12567 ((listp org-use-tag-inheritance)
12568 (delq nil (mapcar
12569 (lambda (x)
12570 (if (member x org-use-tag-inheritance) x nil))
12571 tags)))))
12573 (defvar todo-only) ;; dynamically scoped
12575 (defun org-match-sparse-tree (&optional todo-only match)
12576 "Create a sparse tree according to tags string MATCH.
12577 MATCH can contain positive and negative selection of tags, like
12578 \"+WORK+URGENT-WITHBOSS\".
12579 If optional argument TODO-ONLY is non-nil, only select lines that are
12580 also TODO lines."
12581 (interactive "P")
12582 (org-prepare-agenda-buffers (list (current-buffer)))
12583 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12585 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
12587 (defvar org-cached-props nil)
12588 (defun org-cached-entry-get (pom property)
12589 (if (or (eq t org-use-property-inheritance)
12590 (and (stringp org-use-property-inheritance)
12591 (string-match org-use-property-inheritance property))
12592 (and (listp org-use-property-inheritance)
12593 (member property org-use-property-inheritance)))
12594 ;; Caching is not possible, check it directly
12595 (org-entry-get pom property 'inherit)
12596 ;; Get all properties, so that we can do complicated checks easily
12597 (cdr (assoc property (or org-cached-props
12598 (setq org-cached-props
12599 (org-entry-properties pom)))))))
12601 (defun org-global-tags-completion-table (&optional files)
12602 "Return the list of all tags in all agenda buffer/files.
12603 Optional FILES argument is a list of files to which can be used
12604 instead of the agenda files."
12605 (save-excursion
12606 (org-uniquify
12607 (delq nil
12608 (apply 'append
12609 (mapcar
12610 (lambda (file)
12611 (set-buffer (find-file-noselect file))
12612 (append (org-get-buffer-tags)
12613 (mapcar (lambda (x) (if (stringp (car-safe x))
12614 (list (car-safe x)) nil))
12615 org-tag-alist)))
12616 (if (and files (car files))
12617 files
12618 (org-agenda-files))))))))
12620 (defun org-make-tags-matcher (match)
12621 "Create the TAGS/TODO matcher form for the selection string MATCH."
12622 ;; todo-only is scoped dynamically into this function, and the function
12623 ;; may change it if the matcher asks for it.
12624 (unless match
12625 ;; Get a new match request, with completion
12626 (let ((org-last-tags-completion-table
12627 (org-global-tags-completion-table)))
12628 (setq match (org-completing-read-no-i
12629 "Match: " 'org-tags-completion-function nil nil nil
12630 'org-tags-history))))
12632 ;; Parse the string and create a lisp form
12633 (let ((match0 match)
12634 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
12635 minus tag mm
12636 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12637 orterms term orlist re-p str-p level-p level-op time-p
12638 prop-p pn pv po gv rest)
12639 (if (string-match "/+" match)
12640 ;; match contains also a todo-matching request
12641 (progn
12642 (setq tagsmatch (substring match 0 (match-beginning 0))
12643 todomatch (substring match (match-end 0)))
12644 (if (string-match "^!" todomatch)
12645 (setq todo-only t todomatch (substring todomatch 1)))
12646 (if (string-match "^\\s-*$" todomatch)
12647 (setq todomatch nil)))
12648 ;; only matching tags
12649 (setq tagsmatch match todomatch nil))
12651 ;; Make the tags matcher
12652 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12653 (setq tagsmatcher t)
12654 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12655 (while (setq term (pop orterms))
12656 (while (and (equal (substring term -1) "\\") orterms)
12657 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12658 (while (string-match re term)
12659 (setq rest (substring term (match-end 0))
12660 minus (and (match-end 1)
12661 (equal (match-string 1 term) "-"))
12662 tag (save-match-data (replace-regexp-in-string
12663 "\\\\-" "-"
12664 (match-string 2 term)))
12665 re-p (equal (string-to-char tag) ?{)
12666 level-p (match-end 4)
12667 prop-p (match-end 5)
12668 mm (cond
12669 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12670 (level-p
12671 (setq level-op (org-op-to-function (match-string 3 term)))
12672 `(,level-op level ,(string-to-number
12673 (match-string 4 term))))
12674 (prop-p
12675 (setq pn (match-string 5 term)
12676 po (match-string 6 term)
12677 pv (match-string 7 term)
12678 re-p (equal (string-to-char pv) ?{)
12679 str-p (equal (string-to-char pv) ?\")
12680 time-p (save-match-data
12681 (string-match "^\"[[<].*[]>]\"$" pv))
12682 pv (if (or re-p str-p) (substring pv 1 -1) pv))
12683 (if time-p (setq pv (org-matcher-time pv)))
12684 (setq po (org-op-to-function po (if time-p 'time str-p)))
12685 (cond
12686 ((equal pn "CATEGORY")
12687 (setq gv '(get-text-property (point) 'org-category)))
12688 ((equal pn "TODO")
12689 (setq gv 'todo))
12691 (setq gv `(org-cached-entry-get nil ,pn))))
12692 (if re-p
12693 (if (eq po 'org<>)
12694 `(not (string-match ,pv (or ,gv "")))
12695 `(string-match ,pv (or ,gv "")))
12696 (if str-p
12697 `(,po (or ,gv "") ,pv)
12698 `(,po (string-to-number (or ,gv ""))
12699 ,(string-to-number pv) ))))
12700 (t `(member ,tag tags-list)))
12701 mm (if minus (list 'not mm) mm)
12702 term rest)
12703 (push mm tagsmatcher))
12704 (push (if (> (length tagsmatcher) 1)
12705 (cons 'and tagsmatcher)
12706 (car tagsmatcher))
12707 orlist)
12708 (setq tagsmatcher nil))
12709 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
12710 (setq tagsmatcher
12711 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
12712 ;; Make the todo matcher
12713 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
12714 (setq todomatcher t)
12715 (setq orterms (org-split-string todomatch "|") orlist nil)
12716 (while (setq term (pop orterms))
12717 (while (string-match re term)
12718 (setq minus (and (match-end 1)
12719 (equal (match-string 1 term) "-"))
12720 kwd (match-string 2 term)
12721 re-p (equal (string-to-char kwd) ?{)
12722 term (substring term (match-end 0))
12723 mm (if re-p
12724 `(string-match ,(substring kwd 1 -1) todo)
12725 (list 'equal 'todo kwd))
12726 mm (if minus (list 'not mm) mm))
12727 (push mm todomatcher))
12728 (push (if (> (length todomatcher) 1)
12729 (cons 'and todomatcher)
12730 (car todomatcher))
12731 orlist)
12732 (setq todomatcher nil))
12733 (setq todomatcher (if (> (length orlist) 1)
12734 (cons 'or orlist) (car orlist))))
12736 ;; Return the string and lisp forms of the matcher
12737 (setq matcher (if todomatcher
12738 (list 'and tagsmatcher todomatcher)
12739 tagsmatcher))
12740 (cons match0 matcher)))
12742 (defun org-op-to-function (op &optional stringp)
12743 "Turn an operator into the appropriate function."
12744 (setq op
12745 (cond
12746 ((equal op "<" ) '(< string< org-time<))
12747 ((equal op ">" ) '(> org-string> org-time>))
12748 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
12749 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
12750 ((member op '("=" "==")) '(= string= org-time=))
12751 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
12752 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
12754 (defun org<> (a b) (not (= a b)))
12755 (defun org-string<= (a b) (or (string= a b) (string< a b)))
12756 (defun org-string>= (a b) (not (string< a b)))
12757 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
12758 (defun org-string<> (a b) (not (string= a b)))
12759 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
12760 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< 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) (org<> a b)))
12765 (defun org-2ft (s)
12766 "Convert S to a floating point time.
12767 If S is already a number, just return it. If it is a string, parse
12768 it as a time string and apply `float-time' to it. If S is nil, just return 0."
12769 (cond
12770 ((numberp s) s)
12771 ((stringp s)
12772 (condition-case nil
12773 (float-time (apply 'encode-time (org-parse-time-string s)))
12774 (error 0.)))
12775 (t 0.)))
12777 (defun org-time-today ()
12778 "Time in seconds today at 0:00.
12779 Returns the float number of seconds since the beginning of the
12780 epoch to the beginning of today (00:00)."
12781 (float-time (apply 'encode-time
12782 (append '(0 0 0) (nthcdr 3 (decode-time))))))
12784 (defun org-matcher-time (s)
12785 "Interpret a time comparison value."
12786 (save-match-data
12787 (cond
12788 ((string= s "<now>") (float-time))
12789 ((string= s "<today>") (org-time-today))
12790 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
12791 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
12792 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
12793 (+ (org-time-today)
12794 (* (string-to-number (match-string 1 s))
12795 (cdr (assoc (match-string 2 s)
12796 '(("d" . 86400.0) ("w" . 604800.0)
12797 ("m" . 2678400.0) ("y" . 31557600.0)))))))
12798 (t (org-2ft s)))))
12800 (defun org-match-any-p (re list)
12801 "Does re match any element of list?"
12802 (setq list (mapcar (lambda (x) (string-match re x)) list))
12803 (delq nil list))
12805 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
12806 (defvar org-tags-overlay (make-overlay 1 1))
12807 (org-detach-overlay org-tags-overlay)
12809 (defun org-get-local-tags-at (&optional pos)
12810 "Get a list of tags defined in the current headline."
12811 (org-get-tags-at pos 'local))
12813 (defun org-get-local-tags ()
12814 "Get a list of tags defined in the current headline."
12815 (org-get-tags-at nil 'local))
12817 (defun org-get-tags-at (&optional pos local)
12818 "Get a list of all headline tags applicable at POS.
12819 POS defaults to point. If tags are inherited, the list contains
12820 the targets in the same sequence as the headlines appear, i.e.
12821 the tags of the current headline come last.
12822 When LOCAL is non-nil, only return tags from the current headline,
12823 ignore inherited ones."
12824 (interactive)
12825 (if (and org-trust-scanner-tags
12826 (or (not pos) (equal pos (point)))
12827 (not local))
12828 org-scanner-tags
12829 (let (tags ltags lastpos parent)
12830 (save-excursion
12831 (save-restriction
12832 (widen)
12833 (goto-char (or pos (point)))
12834 (save-match-data
12835 (catch 'done
12836 (condition-case nil
12837 (progn
12838 (org-back-to-heading t)
12839 (while (not (equal lastpos (point)))
12840 (setq lastpos (point))
12841 (when (looking-at
12842 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
12843 (setq ltags (org-split-string
12844 (org-match-string-no-properties 1) ":"))
12845 (when parent
12846 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
12847 (setq tags (append
12848 (if parent
12849 (org-remove-uninherited-tags ltags)
12850 ltags)
12851 tags)))
12852 (or org-use-tag-inheritance (throw 'done t))
12853 (if local (throw 'done t))
12854 (or (org-up-heading-safe) (error nil))
12855 (setq parent t)))
12856 (error nil)))))
12857 (if local
12858 tags
12859 (append (org-remove-uninherited-tags org-file-tags) tags))))))
12861 (defun org-add-prop-inherited (s)
12862 (add-text-properties 0 (length s) '(inherited t) s)
12865 (defun org-toggle-tag (tag &optional onoff)
12866 "Toggle the tag TAG for the current line.
12867 If ONOFF is `on' or `off', don't toggle but set to this state."
12868 (let (res current)
12869 (save-excursion
12870 (org-back-to-heading t)
12871 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
12872 (point-at-eol) t)
12873 (progn
12874 (setq current (match-string 1))
12875 (replace-match ""))
12876 (setq current ""))
12877 (setq current (nreverse (org-split-string current ":")))
12878 (cond
12879 ((eq onoff 'on)
12880 (setq res t)
12881 (or (member tag current) (push tag current)))
12882 ((eq onoff 'off)
12883 (or (not (member tag current)) (setq current (delete tag current))))
12884 (t (if (member tag current)
12885 (setq current (delete tag current))
12886 (setq res t)
12887 (push tag current))))
12888 (end-of-line 1)
12889 (if current
12890 (progn
12891 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
12892 (org-set-tags nil t))
12893 (delete-horizontal-space))
12894 (run-hooks 'org-after-tags-change-hook))
12895 res))
12897 (defun org-align-tags-here (to-col)
12898 ;; Assumes that this is a headline
12899 (let ((pos (point)) (col (current-column)) ncol tags-l p)
12900 (beginning-of-line 1)
12901 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
12902 (< pos (match-beginning 2)))
12903 (progn
12904 (setq tags-l (- (match-end 2) (match-beginning 2)))
12905 (goto-char (match-beginning 1))
12906 (insert " ")
12907 (delete-region (point) (1+ (match-beginning 2)))
12908 (setq ncol (max (1+ (current-column))
12909 (1+ col)
12910 (if (> to-col 0)
12911 to-col
12912 (- (abs to-col) tags-l))))
12913 (setq p (point))
12914 (insert (make-string (- ncol (current-column)) ?\ ))
12915 (setq ncol (current-column))
12916 (when indent-tabs-mode (tabify p (point-at-eol)))
12917 (org-move-to-column (min ncol col) t))
12918 (goto-char pos))))
12920 (defun org-set-tags-command (&optional arg just-align)
12921 "Call the set-tags command for the current entry."
12922 (interactive "P")
12923 (if (org-on-heading-p)
12924 (org-set-tags arg just-align)
12925 (save-excursion
12926 (org-back-to-heading t)
12927 (org-set-tags arg just-align))))
12929 (defun org-set-tags-to (data)
12930 "Set the tags of the current entry to DATA, replacing the current tags.
12931 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
12932 If DATA is nil or the empty string, any tags will be removed."
12933 (interactive "sTags: ")
12934 (setq data
12935 (cond
12936 ((eq data nil) "")
12937 ((equal data "") "")
12938 ((stringp data)
12939 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
12940 ":"))
12941 ((listp data)
12942 (concat ":" (mapconcat 'identity data ":") ":"))
12943 (t nil)))
12944 (when data
12945 (save-excursion
12946 (org-back-to-heading t)
12947 (when (looking-at org-complex-heading-regexp)
12948 (if (match-end 5)
12949 (progn
12950 (goto-char (match-beginning 5))
12951 (insert data)
12952 (delete-region (point) (point-at-eol))
12953 (org-set-tags nil 'align))
12954 (goto-char (point-at-eol))
12955 (insert " " data)
12956 (org-set-tags nil 'align)))
12957 (beginning-of-line 1)
12958 (if (looking-at ".*?\\([ \t]+\\)$")
12959 (delete-region (match-beginning 1) (match-end 1))))))
12961 (defun org-align-all-tags ()
12962 "Align the tags i all headings."
12963 (interactive)
12964 (save-excursion
12965 (or (ignore-errors (org-back-to-heading t))
12966 (outline-next-heading))
12967 (if (org-on-heading-p)
12968 (org-set-tags t)
12969 (message "No headings"))))
12971 (defvar org-indent-indentation-per-level)
12972 (defun org-set-tags (&optional arg just-align)
12973 "Set the tags for the current headline.
12974 With prefix ARG, realign all tags in headings in the current buffer."
12975 (interactive "P")
12976 (let* ((re (concat "^" outline-regexp))
12977 (current (org-get-tags-string))
12978 (col (current-column))
12979 (org-setting-tags t)
12980 table current-tags inherited-tags ; computed below when needed
12981 tags p0 c0 c1 rpl di tc level)
12982 (if arg
12983 (save-excursion
12984 (goto-char (point-min))
12985 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12986 (while (re-search-forward re nil t)
12987 (org-set-tags nil t)
12988 (end-of-line 1)))
12989 (message "All tags realigned to column %d" org-tags-column))
12990 (if just-align
12991 (setq tags current)
12992 ;; Get a new set of tags from the user
12993 (save-excursion
12994 (setq table (append org-tag-persistent-alist
12995 (or org-tag-alist (org-get-buffer-tags))
12996 (and
12997 org-complete-tags-always-offer-all-agenda-tags
12998 (org-global-tags-completion-table
12999 (org-agenda-files))))
13000 org-last-tags-completion-table table
13001 current-tags (org-split-string current ":")
13002 inherited-tags (nreverse
13003 (nthcdr (length current-tags)
13004 (nreverse (org-get-tags-at))))
13005 tags
13006 (if (or (eq t org-use-fast-tag-selection)
13007 (and org-use-fast-tag-selection
13008 (delq nil (mapcar 'cdr table))))
13009 (org-fast-tag-selection
13010 current-tags inherited-tags table
13011 (if org-fast-tag-selection-include-todo
13012 org-todo-key-alist))
13013 (let ((org-add-colon-after-tag-completion t))
13014 (org-trim
13015 (org-without-partial-completion
13016 (org-icompleting-read "Tags: "
13017 'org-tags-completion-function
13018 nil nil current 'org-tags-history)))))))
13019 (while (string-match "[-+&]+" tags)
13020 ;; No boolean logic, just a list
13021 (setq tags (replace-match ":" t t tags))))
13023 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13025 (if org-tags-sort-function
13026 (setq tags (mapconcat 'identity
13027 (sort (org-split-string
13028 tags (org-re "[^[:alnum:]_@#%]+"))
13029 org-tags-sort-function) ":")))
13031 (if (string-match "\\`[\t ]*\\'" tags)
13032 (setq tags "")
13033 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13034 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13036 ;; Insert new tags at the correct column
13037 (beginning-of-line 1)
13038 (setq level (or (and (looking-at org-outline-regexp)
13039 (- (match-end 0) (point) 1))
13041 (cond
13042 ((and (equal current "") (equal tags "")))
13043 ((re-search-forward
13044 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13045 (point-at-eol) t)
13046 (if (equal tags "")
13047 (setq rpl "")
13048 (goto-char (match-beginning 0))
13049 (setq c0 (current-column)
13050 ;; compute offset for the case of org-indent-mode active
13051 di (if org-indent-mode
13052 (* (1- org-indent-indentation-per-level) (1- level))
13054 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13055 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13056 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13057 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13058 (replace-match rpl t t)
13059 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13060 tags)
13061 (t (error "Tags alignment failed")))
13062 (org-move-to-column col)
13063 (unless just-align
13064 (run-hooks 'org-after-tags-change-hook)))))
13066 (defun org-change-tag-in-region (beg end tag off)
13067 "Add or remove TAG for each entry in the region.
13068 This works in the agenda, and also in an org-mode buffer."
13069 (interactive
13070 (list (region-beginning) (region-end)
13071 (let ((org-last-tags-completion-table
13072 (if (org-mode-p)
13073 (org-get-buffer-tags)
13074 (org-global-tags-completion-table))))
13075 (org-icompleting-read
13076 "Tag: " 'org-tags-completion-function nil nil nil
13077 'org-tags-history))
13078 (progn
13079 (message "[s]et or [r]emove? ")
13080 (equal (read-char-exclusive) ?r))))
13081 (if (fboundp 'deactivate-mark) (deactivate-mark))
13082 (let ((agendap (equal major-mode 'org-agenda-mode))
13083 l1 l2 m buf pos newhead (cnt 0))
13084 (goto-char end)
13085 (setq l2 (1- (org-current-line)))
13086 (goto-char beg)
13087 (setq l1 (org-current-line))
13088 (loop for l from l1 to l2 do
13089 (org-goto-line l)
13090 (setq m (get-text-property (point) 'org-hd-marker))
13091 (when (or (and (org-mode-p) (org-on-heading-p))
13092 (and agendap m))
13093 (setq buf (if agendap (marker-buffer m) (current-buffer))
13094 pos (if agendap m (point)))
13095 (with-current-buffer buf
13096 (save-excursion
13097 (save-restriction
13098 (goto-char pos)
13099 (setq cnt (1+ cnt))
13100 (org-toggle-tag tag (if off 'off 'on))
13101 (setq newhead (org-get-heading)))))
13102 (and agendap (org-agenda-change-all-lines newhead m))))
13103 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13105 (defun org-tags-completion-function (string predicate &optional flag)
13106 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13107 (confirm (lambda (x) (stringp (car x)))))
13108 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13109 (setq s1 (match-string 1 string)
13110 s2 (match-string 2 string))
13111 (setq s1 "" s2 string))
13112 (cond
13113 ((eq flag nil)
13114 ;; try completion
13115 (setq rtn (try-completion s2 ctable confirm))
13116 (if (stringp rtn)
13117 (setq rtn
13118 (concat s1 s2 (substring rtn (length s2))
13119 (if (and org-add-colon-after-tag-completion
13120 (assoc rtn ctable))
13121 ":" ""))))
13122 rtn)
13123 ((eq flag t)
13124 ;; all-completions
13125 (all-completions s2 ctable confirm)
13127 ((eq flag 'lambda)
13128 ;; exact match?
13129 (assoc s2 ctable)))
13132 (defun org-fast-tag-insert (kwd tags face &optional end)
13133 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13134 (insert (format "%-12s" (concat kwd ":"))
13135 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13136 (or end "")))
13138 (defun org-fast-tag-show-exit (flag)
13139 (save-excursion
13140 (org-goto-line 3)
13141 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13142 (replace-match ""))
13143 (when flag
13144 (end-of-line 1)
13145 (org-move-to-column (- (window-width) 19) t)
13146 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13148 (defun org-set-current-tags-overlay (current prefix)
13149 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13150 (if (featurep 'xemacs)
13151 (org-overlay-display org-tags-overlay (concat prefix s)
13152 'secondary-selection)
13153 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13154 (org-overlay-display org-tags-overlay (concat prefix s)))))
13156 (defvar org-last-tag-selection-key nil)
13157 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13158 "Fast tag selection with single keys.
13159 CURRENT is the current list of tags in the headline, INHERITED is the
13160 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13161 possibly with grouping information. TODO-TABLE is a similar table with
13162 TODO keywords, should these have keys assigned to them.
13163 If the keys are nil, a-z are automatically assigned.
13164 Returns the new tags string, or nil to not change the current settings."
13165 (let* ((fulltable (append table todo-table))
13166 (maxlen (apply 'max (mapcar
13167 (lambda (x)
13168 (if (stringp (car x)) (string-width (car x)) 0))
13169 fulltable)))
13170 (buf (current-buffer))
13171 (expert (eq org-fast-tag-selection-single-key 'expert))
13172 (buffer-tags nil)
13173 (fwidth (+ maxlen 3 1 3))
13174 (ncol (/ (- (window-width) 4) fwidth))
13175 (i-face 'org-done)
13176 (c-face 'org-todo)
13177 tg cnt e c char c1 c2 ntable tbl rtn
13178 ov-start ov-end ov-prefix
13179 (exit-after-next org-fast-tag-selection-single-key)
13180 (done-keywords org-done-keywords)
13181 groups ingroup)
13182 (save-excursion
13183 (beginning-of-line 1)
13184 (if (looking-at
13185 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13186 (setq ov-start (match-beginning 1)
13187 ov-end (match-end 1)
13188 ov-prefix "")
13189 (setq ov-start (1- (point-at-eol))
13190 ov-end (1+ ov-start))
13191 (skip-chars-forward "^\n\r")
13192 (setq ov-prefix
13193 (concat
13194 (buffer-substring (1- (point)) (point))
13195 (if (> (current-column) org-tags-column)
13197 (make-string (- org-tags-column (current-column)) ?\ ))))))
13198 (move-overlay org-tags-overlay ov-start ov-end)
13199 (save-window-excursion
13200 (if expert
13201 (set-buffer (get-buffer-create " *Org tags*"))
13202 (delete-other-windows)
13203 (split-window-vertically)
13204 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13205 (erase-buffer)
13206 (org-set-local 'org-done-keywords done-keywords)
13207 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13208 (org-fast-tag-insert "Current" current c-face "\n\n")
13209 (org-fast-tag-show-exit exit-after-next)
13210 (org-set-current-tags-overlay current ov-prefix)
13211 (setq tbl fulltable char ?a cnt 0)
13212 (while (setq e (pop tbl))
13213 (cond
13214 ((equal (car e) :startgroup)
13215 (push '() groups) (setq ingroup t)
13216 (when (not (= cnt 0))
13217 (setq cnt 0)
13218 (insert "\n"))
13219 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13220 ((equal (car e) :endgroup)
13221 (setq ingroup nil cnt 0)
13222 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13223 ((equal e '(:newline))
13224 (when (not (= cnt 0))
13225 (setq cnt 0)
13226 (insert "\n")
13227 (setq e (car tbl))
13228 (while (equal (car tbl) '(:newline))
13229 (insert "\n")
13230 (setq tbl (cdr tbl)))))
13232 (setq tg (copy-sequence (car e)) c2 nil)
13233 (if (cdr e)
13234 (setq c (cdr e))
13235 ;; automatically assign a character.
13236 (setq c1 (string-to-char
13237 (downcase (substring
13238 tg (if (= (string-to-char tg) ?@) 1 0)))))
13239 (if (or (rassoc c1 ntable) (rassoc c1 table))
13240 (while (or (rassoc char ntable) (rassoc char table))
13241 (setq char (1+ char)))
13242 (setq c2 c1))
13243 (setq c (or c2 char)))
13244 (if ingroup (push tg (car groups)))
13245 (setq tg (org-add-props tg nil 'face
13246 (cond
13247 ((not (assoc tg table))
13248 (org-get-todo-face tg))
13249 ((member tg current) c-face)
13250 ((member tg inherited) i-face)
13251 (t nil))))
13252 (if (and (= cnt 0) (not ingroup)) (insert " "))
13253 (insert "[" c "] " tg (make-string
13254 (- fwidth 4 (length tg)) ?\ ))
13255 (push (cons tg c) ntable)
13256 (when (= (setq cnt (1+ cnt)) ncol)
13257 (insert "\n")
13258 (if ingroup (insert " "))
13259 (setq cnt 0)))))
13260 (setq ntable (nreverse ntable))
13261 (insert "\n")
13262 (goto-char (point-min))
13263 (if (not expert) (org-fit-window-to-buffer))
13264 (setq rtn
13265 (catch 'exit
13266 (while t
13267 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13268 (if (not groups) "no " "")
13269 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13270 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13271 (setq org-last-tag-selection-key c)
13272 (cond
13273 ((= c ?\r) (throw 'exit t))
13274 ((= c ?!)
13275 (setq groups (not groups))
13276 (goto-char (point-min))
13277 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13278 ((= c ?\C-c)
13279 (if (not expert)
13280 (org-fast-tag-show-exit
13281 (setq exit-after-next (not exit-after-next)))
13282 (setq expert nil)
13283 (delete-other-windows)
13284 (set-window-buffer (split-window-vertically) " *Org tags*")
13285 (org-switch-to-buffer-other-window " *Org tags*")
13286 (org-fit-window-to-buffer)))
13287 ((or (= c ?\C-g)
13288 (and (= c ?q) (not (rassoc c ntable))))
13289 (org-detach-overlay org-tags-overlay)
13290 (setq quit-flag t))
13291 ((= c ?\ )
13292 (setq current nil)
13293 (if exit-after-next (setq exit-after-next 'now)))
13294 ((= c ?\t)
13295 (condition-case nil
13296 (setq tg (org-icompleting-read
13297 "Tag: "
13298 (or buffer-tags
13299 (with-current-buffer buf
13300 (org-get-buffer-tags)))))
13301 (quit (setq tg "")))
13302 (when (string-match "\\S-" tg)
13303 (add-to-list 'buffer-tags (list tg))
13304 (if (member tg current)
13305 (setq current (delete tg current))
13306 (push tg current)))
13307 (if exit-after-next (setq exit-after-next 'now)))
13308 ((setq e (rassoc c todo-table) tg (car e))
13309 (with-current-buffer buf
13310 (save-excursion (org-todo tg)))
13311 (if exit-after-next (setq exit-after-next 'now)))
13312 ((setq e (rassoc c ntable) tg (car e))
13313 (if (member tg current)
13314 (setq current (delete tg current))
13315 (loop for g in groups do
13316 (if (member tg g)
13317 (mapc (lambda (x)
13318 (setq current (delete x current)))
13319 g)))
13320 (push tg current))
13321 (if exit-after-next (setq exit-after-next 'now))))
13323 ;; Create a sorted list
13324 (setq current
13325 (sort current
13326 (lambda (a b)
13327 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13328 (if (eq exit-after-next 'now) (throw 'exit t))
13329 (goto-char (point-min))
13330 (beginning-of-line 2)
13331 (delete-region (point) (point-at-eol))
13332 (org-fast-tag-insert "Current" current c-face)
13333 (org-set-current-tags-overlay current ov-prefix)
13334 (while (re-search-forward
13335 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
13336 (setq tg (match-string 1))
13337 (add-text-properties
13338 (match-beginning 1) (match-end 1)
13339 (list 'face
13340 (cond
13341 ((member tg current) c-face)
13342 ((member tg inherited) i-face)
13343 (t (get-text-property (match-beginning 1) 'face))))))
13344 (goto-char (point-min)))))
13345 (org-detach-overlay org-tags-overlay)
13346 (if rtn
13347 (mapconcat 'identity current ":")
13348 nil))))
13350 (defun org-get-tags-string ()
13351 "Get the TAGS string in the current headline."
13352 (unless (org-on-heading-p t)
13353 (error "Not on a heading"))
13354 (save-excursion
13355 (beginning-of-line 1)
13356 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13357 (org-match-string-no-properties 1)
13358 "")))
13360 (defun org-get-tags ()
13361 "Get the list of tags specified in the current headline."
13362 (org-split-string (org-get-tags-string) ":"))
13364 (defun org-get-buffer-tags ()
13365 "Get a table of all tags used in the buffer, for completion."
13366 (let (tags)
13367 (save-excursion
13368 (goto-char (point-min))
13369 (while (re-search-forward
13370 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
13371 (when (equal (char-after (point-at-bol 0)) ?*)
13372 (mapc (lambda (x) (add-to-list 'tags x))
13373 (org-split-string (org-match-string-no-properties 1) ":")))))
13374 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
13375 (mapcar 'list tags)))
13377 ;;;; The mapping API
13379 ;;;###autoload
13380 (defun org-map-entries (func &optional match scope &rest skip)
13381 "Call FUNC at each headline selected by MATCH in SCOPE.
13383 FUNC is a function or a lisp form. The function will be called without
13384 arguments, with the cursor positioned at the beginning of the headline.
13385 The return values of all calls to the function will be collected and
13386 returned as a list.
13388 The call to FUNC will be wrapped into a save-excursion form, so FUNC
13389 does not need to preserve point. After evaluation, the cursor will be
13390 moved to the end of the line (presumably of the headline of the
13391 processed entry) and search continues from there. Under some
13392 circumstances, this may not produce the wanted results. For example,
13393 if you have removed (e.g. archived) the current (sub)tree it could
13394 mean that the next entry will be skipped entirely. In such cases, you
13395 can specify the position from where search should continue by making
13396 FUNC set the variable `org-map-continue-from' to the desired buffer
13397 position.
13399 MATCH is a tags/property/todo match as it is used in the agenda tags view.
13400 Only headlines that are matched by this query will be considered during
13401 the iteration. When MATCH is nil or t, all headlines will be
13402 visited by the iteration.
13404 SCOPE determines the scope of this command. It can be any of:
13406 nil The current buffer, respecting the restriction if any
13407 tree The subtree started with the entry at point
13408 file The current buffer, without restriction
13409 file-with-archives
13410 The current buffer, and any archives associated with it
13411 agenda All agenda files
13412 agenda-with-archives
13413 All agenda files with any archive files associated with them
13414 \(file1 file2 ...)
13415 If this is a list, all files in the list will be scanned
13417 The remaining args are treated as settings for the skipping facilities of
13418 the scanner. The following items can be given here:
13420 archive skip trees with the archive tag.
13421 comment skip trees with the COMMENT keyword
13422 function or Emacs Lisp form:
13423 will be used as value for `org-agenda-skip-function', so whenever
13424 the function returns t, FUNC will not be called for that
13425 entry and search will continue from the point where the
13426 function leaves it.
13428 If your function needs to retrieve the tags including inherited tags
13429 at the *current* entry, you can use the value of the variable
13430 `org-scanner-tags' which will be much faster than getting the value
13431 with `org-get-tags-at'. If your function gets properties with
13432 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
13433 to t around the call to `org-entry-properties' to get the same speedup.
13434 Note that if your function moves around to retrieve tags and properties at
13435 a *different* entry, you cannot use these techniques."
13436 (let* ((org-agenda-archives-mode nil) ; just to make sure
13437 (org-agenda-skip-archived-trees (memq 'archive skip))
13438 (org-agenda-skip-comment-trees (memq 'comment skip))
13439 (org-agenda-skip-function
13440 (car (org-delete-all '(comment archive) skip)))
13441 (org-tags-match-list-sublevels t)
13442 matcher file res
13443 org-todo-keywords-for-agenda
13444 org-done-keywords-for-agenda
13445 org-todo-keyword-alist-for-agenda
13446 org-drawers-for-agenda
13447 org-tag-alist-for-agenda)
13449 (cond
13450 ((eq match t) (setq matcher t))
13451 ((eq match nil) (setq matcher t))
13452 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
13454 (save-excursion
13455 (save-restriction
13456 (when (eq scope 'tree)
13457 (org-back-to-heading t)
13458 (org-narrow-to-subtree)
13459 (setq scope nil))
13461 (if (not scope)
13462 (progn
13463 (org-prepare-agenda-buffers
13464 (list (buffer-file-name (current-buffer))))
13465 (setq res (org-scan-tags func matcher)))
13466 ;; Get the right scope
13467 (cond
13468 ((and scope (listp scope) (symbolp (car scope)))
13469 (setq scope (eval scope)))
13470 ((eq scope 'agenda)
13471 (setq scope (org-agenda-files t)))
13472 ((eq scope 'agenda-with-archives)
13473 (setq scope (org-agenda-files t))
13474 (setq scope (org-add-archive-files scope)))
13475 ((eq scope 'file)
13476 (setq scope (list (buffer-file-name))))
13477 ((eq scope 'file-with-archives)
13478 (setq scope (org-add-archive-files (list (buffer-file-name))))))
13479 (org-prepare-agenda-buffers scope)
13480 (while (setq file (pop scope))
13481 (with-current-buffer (org-find-base-buffer-visiting file)
13482 (save-excursion
13483 (save-restriction
13484 (widen)
13485 (goto-char (point-min))
13486 (setq res (append res (org-scan-tags func matcher))))))))))
13487 res))
13489 ;;;; Properties
13491 ;;; Setting and retrieving properties
13493 (defconst org-special-properties
13494 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
13495 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM")
13496 "The special properties valid in Org-mode.
13498 These are properties that are not defined in the property drawer,
13499 but in some other way.")
13501 (defconst org-default-properties
13502 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
13503 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
13504 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
13505 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
13506 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
13507 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
13508 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
13509 "Some properties that are used by Org-mode for various purposes.
13510 Being in this list makes sure that they are offered for completion.")
13512 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13513 "Regular expression matching the first line of a property drawer.")
13515 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13516 "Regular expression matching the last line of a property drawer.")
13518 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
13519 "Regular expression matching the first line of a property drawer.")
13521 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
13522 "Regular expression matching the first line of a property drawer.")
13524 (defconst org-property-drawer-re
13525 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
13526 org-property-end-re "\\)\n?")
13527 "Matches an entire property drawer.")
13529 (defconst org-clock-drawer-re
13530 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
13531 org-property-end-re "\\)\n?")
13532 "Matches an entire clock drawer.")
13534 (defsubst org-re-property (property)
13535 "Return a regexp matching PROPERTY.
13536 Match group 1 will be set to the value "
13537 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
13539 (defun org-property-action ()
13540 "Do an action on properties."
13541 (interactive)
13542 (let (c)
13543 (org-at-property-p)
13544 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13545 (setq c (read-char-exclusive))
13546 (cond
13547 ((equal c ?s)
13548 (call-interactively 'org-set-property))
13549 ((equal c ?d)
13550 (call-interactively 'org-delete-property))
13551 ((equal c ?D)
13552 (call-interactively 'org-delete-property-globally))
13553 ((equal c ?c)
13554 (call-interactively 'org-compute-property-at-point))
13555 (t (error "No such property action %c" c)))))
13557 (defun org-set-effort (&optional value)
13558 "Set the effort property of the current entry.
13559 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
13560 allowed value."
13561 (interactive "P")
13562 (if (equal value 0) (setq value 10))
13563 (let* ((completion-ignore-case t)
13564 (prop org-effort-property)
13565 (cur (org-entry-get nil prop))
13566 (allowed (org-property-get-allowed-values nil prop 'table))
13567 (existing (mapcar 'list (org-property-values prop)))
13569 (val (cond
13570 ((stringp value) value)
13571 ((and allowed (integerp value))
13572 (or (car (nth (1- value) allowed))
13573 (car (org-last allowed))))
13574 (allowed
13575 (message "Select 1-9,0, [RET%s]: %s"
13576 (if cur (concat "=" cur) "")
13577 (mapconcat 'car allowed " "))
13578 (setq rpl (read-char-exclusive))
13579 (if (equal rpl ?\r)
13581 (setq rpl (- rpl ?0))
13582 (if (equal rpl 0) (setq rpl 10))
13583 (if (and (> rpl 0) (<= rpl (length allowed)))
13584 (car (nth (1- rpl) allowed))
13585 (org-completing-read "Effort: " allowed nil))))
13587 (let (org-completion-use-ido org-completion-use-iswitchb)
13588 (org-completing-read
13589 (concat "Effort " (if (and cur (string-match "\\S-" cur))
13590 (concat "[" cur "]") "")
13591 ": ")
13592 existing nil nil "" nil cur))))))
13593 (unless (equal (org-entry-get nil prop) val)
13594 (org-entry-put nil prop val))
13595 (message "%s is now %s" prop val)))
13597 (defun org-at-property-p ()
13598 "Is cursor inside a property drawer?"
13599 (save-excursion
13600 (beginning-of-line 1)
13601 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
13602 (save-match-data ;; Used by calling procedures
13603 (let ((p (point))
13604 (range (unless (org-before-first-heading-p)
13605 (org-get-property-block))))
13606 (and range (<= (car range) p) (< p (cdr range))))))))
13608 (defun org-get-property-block (&optional beg end force)
13609 "Return the (beg . end) range of the body of the property drawer.
13610 BEG and END can be beginning and end of subtree, if not given
13611 they will be found.
13612 If the drawer does not exist and FORCE is non-nil, create the drawer."
13613 (catch 'exit
13614 (save-excursion
13615 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13616 (end (or end (progn (outline-next-heading) (point)))))
13617 (goto-char beg)
13618 (if (re-search-forward org-property-start-re end t)
13619 (setq beg (1+ (match-end 0)))
13620 (if force
13621 (save-excursion
13622 (org-insert-property-drawer)
13623 (setq end (progn (outline-next-heading) (point))))
13624 (throw 'exit nil))
13625 (goto-char beg)
13626 (if (re-search-forward org-property-start-re end t)
13627 (setq beg (1+ (match-end 0)))))
13628 (if (re-search-forward org-property-end-re end t)
13629 (setq end (match-beginning 0))
13630 (or force (throw 'exit nil))
13631 (goto-char beg)
13632 (setq end beg)
13633 (org-indent-line-function)
13634 (insert ":END:\n"))
13635 (cons beg end)))))
13637 (defun org-entry-properties (&optional pom which specific)
13638 "Get all properties of the entry at point-or-marker POM.
13639 This includes the TODO keyword, the tags, time strings for deadline,
13640 scheduled, and clocking, and any additional properties defined in the
13641 entry. The return value is an alist, keys may occur multiple times
13642 if the property key was used several times.
13643 POM may also be nil, in which case the current entry is used.
13644 If WHICH is nil or `all', get all properties. If WHICH is
13645 `special' or `standard', only get that subclass. If WHICH
13646 is a string only get exactly this property. SPECIFIC can be a string, the
13647 specific property we are interested in. Specifying it can speed
13648 things up because then unnecessary parsing is avoided."
13649 (setq which (or which 'all))
13650 (org-with-point-at pom
13651 (let ((clockstr (substring org-clock-string 0 -1))
13652 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
13653 (case-fold-search nil)
13654 beg end range props sum-props key key1 value string clocksum)
13655 (save-excursion
13656 (when (condition-case nil
13657 (and (org-mode-p) (org-back-to-heading t))
13658 (error nil))
13659 (setq beg (point))
13660 (setq sum-props (get-text-property (point) 'org-summaries))
13661 (setq clocksum (get-text-property (point) :org-clock-minutes))
13662 (outline-next-heading)
13663 (setq end (point))
13664 (when (memq which '(all special))
13665 ;; Get the special properties, like TODO and tags
13666 (goto-char beg)
13667 (when (and (or (not specific) (string= specific "TODO"))
13668 (looking-at org-todo-line-regexp) (match-end 2))
13669 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13670 (when (and (or (not specific) (string= specific "PRIORITY"))
13671 (looking-at org-priority-regexp))
13672 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13673 (when (or (not specific) (string= specific "FILE"))
13674 (push (cons "FILE" buffer-file-name) props))
13675 (when (and (or (not specific) (string= specific "TAGS"))
13676 (setq value (org-get-tags-string))
13677 (string-match "\\S-" value))
13678 (push (cons "TAGS" value) props))
13679 (when (and (or (not specific) (string= specific "ALLTAGS"))
13680 (setq value (org-get-tags-at)))
13681 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
13682 ":"))
13683 props))
13684 (when (or (not specific) (string= specific "BLOCKED"))
13685 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
13686 (when (or (not specific)
13687 (member specific
13688 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
13689 "TIMESTAMP" "TIMESTAMP_IA")))
13690 (catch 'match
13691 (while (re-search-forward org-maybe-keyword-time-regexp end t)
13692 (setq key (if (match-end 1)
13693 (substring (org-match-string-no-properties 1)
13694 0 -1))
13695 string (if (equal key clockstr)
13696 (org-no-properties
13697 (org-trim
13698 (buffer-substring
13699 (match-beginning 3) (goto-char
13700 (point-at-eol)))))
13701 (substring (org-match-string-no-properties 3)
13702 1 -1)))
13703 ;; Get the correct property name from the key. This is
13704 ;; necessary if the user has configured time keywords.
13705 (setq key1 (concat key ":"))
13706 (cond
13707 ((not key)
13708 (setq key
13709 (if (= (char-after (match-beginning 3)) ?\[)
13710 "TIMESTAMP_IA" "TIMESTAMP")))
13711 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
13712 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
13713 ((equal key1 org-closed-string) (setq key "CLOSED"))
13714 ((equal key1 org-clock-string) (setq key "CLOCK")))
13715 (if (and specific (equal key specific) (not (equal key "CLOCK")))
13716 (progn
13717 (push (cons key string) props)
13718 ;; no need to search further if match is found
13719 (throw 'match t))
13720 (when (or (equal key "CLOCK") (not (assoc key props)))
13721 (push (cons key string) props))))))
13724 (when (memq which '(all standard))
13725 ;; Get the standard properties, like :PROP: ...
13726 (setq range (org-get-property-block beg end))
13727 (when range
13728 (goto-char (car range))
13729 (while (re-search-forward
13730 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
13731 (cdr range) t)
13732 (setq key (org-match-string-no-properties 1)
13733 value (org-trim (or (org-match-string-no-properties 2) "")))
13734 (unless (member key excluded)
13735 (push (cons key (or value "")) props)))))
13736 (if clocksum
13737 (push (cons "CLOCKSUM"
13738 (org-columns-number-to-string (/ (float clocksum) 60.)
13739 'add_times))
13740 props))
13741 (unless (assoc "CATEGORY" props)
13742 (push (cons "CATEGORY" (org-get-category)) props))
13743 (append sum-props (nreverse props)))))))
13745 (defun org-entry-get (pom property &optional inherit literal-nil)
13746 "Get value of PROPERTY for entry at point-or-marker POM.
13747 If INHERIT is non-nil and the entry does not have the property,
13748 then also check higher levels of the hierarchy.
13749 If INHERIT is the symbol `selective', use inheritance only if the setting
13750 in `org-use-property-inheritance' selects PROPERTY for inheritance.
13751 If the property is present but empty, the return value is the empty string.
13752 If the property is not present at all, nil is returned.
13754 If LITERAL-NIL is set, return the string value \"nil\" as a string,
13755 do not interpret it as the list atom nil. This is used for inheritance
13756 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
13757 (org-with-point-at pom
13758 (if (and inherit (if (eq inherit 'selective)
13759 (org-property-inherit-p property)
13761 (org-entry-get-with-inheritance property literal-nil)
13762 (if (member property org-special-properties)
13763 ;; We need a special property. Use `org-entry-properties' to
13764 ;; retrieve it, but specify the wanted property
13765 (cdr (assoc property (org-entry-properties nil 'special property)))
13766 (let ((range (unless (org-before-first-heading-p)
13767 (org-get-property-block))))
13768 (if (and range
13769 (goto-char (car range))
13770 (re-search-forward
13771 (org-re-property property)
13772 (cdr range) t))
13773 ;; Found the property, return it.
13774 (if (match-end 1)
13775 (if literal-nil
13776 (org-match-string-no-properties 1)
13777 (org-not-nil (org-match-string-no-properties 1)))
13778 "")))))))
13780 (defun org-property-or-variable-value (var &optional inherit)
13781 "Check if there is a property fixing the value of VAR.
13782 If yes, return this value. If not, return the current value of the variable."
13783 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13784 (if (and prop (stringp prop) (string-match "\\S-" prop))
13785 (read prop)
13786 (symbol-value var))))
13788 (defun org-entry-delete (pom property)
13789 "Delete the property PROPERTY from entry at point-or-marker POM."
13790 (org-with-point-at pom
13791 (if (member property org-special-properties)
13792 nil ; cannot delete these properties.
13793 (let ((range (org-get-property-block)))
13794 (if (and range
13795 (goto-char (car range))
13796 (re-search-forward
13797 (org-re-property property)
13798 (cdr range) t))
13799 (progn
13800 (delete-region (match-beginning 0) (1+ (point-at-eol)))
13802 nil)))))
13804 ;; Multi-values properties are properties that contain multiple values
13805 ;; These values are assumed to be single words, separated by whitespace.
13806 (defun org-entry-add-to-multivalued-property (pom property value)
13807 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
13808 (let* ((old (org-entry-get pom property))
13809 (values (and old (org-split-string old "[ \t]"))))
13810 (setq value (org-entry-protect-space value))
13811 (unless (member value values)
13812 (setq values (cons value values))
13813 (org-entry-put pom property
13814 (mapconcat 'identity values " ")))))
13816 (defun org-entry-remove-from-multivalued-property (pom property value)
13817 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
13818 (let* ((old (org-entry-get pom property))
13819 (values (and old (org-split-string old "[ \t]"))))
13820 (setq value (org-entry-protect-space value))
13821 (when (member value values)
13822 (setq values (delete value values))
13823 (org-entry-put pom property
13824 (mapconcat 'identity values " ")))))
13826 (defun org-entry-member-in-multivalued-property (pom property value)
13827 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
13828 (let* ((old (org-entry-get pom property))
13829 (values (and old (org-split-string old "[ \t]"))))
13830 (setq value (org-entry-protect-space value))
13831 (member value values)))
13833 (defun org-entry-get-multivalued-property (pom property)
13834 "Return a list of values in a multivalued property."
13835 (let* ((value (org-entry-get pom property))
13836 (values (and value (org-split-string value "[ \t]"))))
13837 (mapcar 'org-entry-restore-space values)))
13839 (defun org-entry-put-multivalued-property (pom property &rest values)
13840 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
13841 VALUES should be a list of strings. Spaces will be protected."
13842 (org-entry-put pom property
13843 (mapconcat 'org-entry-protect-space values " "))
13844 (let* ((value (org-entry-get pom property))
13845 (values (and value (org-split-string value "[ \t]"))))
13846 (mapcar 'org-entry-restore-space values)))
13848 (defun org-entry-protect-space (s)
13849 "Protect spaces and newline in string S."
13850 (while (string-match " " s)
13851 (setq s (replace-match "%20" t t s)))
13852 (while (string-match "\n" s)
13853 (setq s (replace-match "%0A" t t s)))
13856 (defun org-entry-restore-space (s)
13857 "Restore spaces and newline in string S."
13858 (while (string-match "%20" s)
13859 (setq s (replace-match " " t t s)))
13860 (while (string-match "%0A" s)
13861 (setq s (replace-match "\n" t t s)))
13864 (defvar org-entry-property-inherited-from (make-marker)
13865 "Marker pointing to the entry from where a property was inherited.
13866 Each call to `org-entry-get-with-inheritance' will set this marker to the
13867 location of the entry where the inheritance search matched. If there was
13868 no match, the marker will point nowhere.
13869 Note that also `org-entry-get' calls this function, if the INHERIT flag
13870 is set.")
13872 (defun org-entry-get-with-inheritance (property &optional literal-nil)
13873 "Get entry property, and search higher levels if not present.
13874 The search will stop at the first ancestor which has the property defined.
13875 If the value found is \"nil\", return nil to show that the property
13876 should be considered as undefined (this is the meaning of nil here).
13877 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
13878 (move-marker org-entry-property-inherited-from nil)
13879 (let (tmp)
13880 (unless (org-before-first-heading-p)
13881 (save-excursion
13882 (save-restriction
13883 (widen)
13884 (catch 'ex
13885 (while t
13886 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
13887 (org-back-to-heading t)
13888 (move-marker org-entry-property-inherited-from (point))
13889 (throw 'ex tmp))
13890 (or (org-up-heading-safe) (throw 'ex nil)))))))
13891 (setq tmp (or tmp
13892 (cdr (assoc property org-file-properties))
13893 (cdr (assoc property org-global-properties))
13894 (cdr (assoc property org-global-properties-fixed))))
13895 (if literal-nil tmp (org-not-nil tmp))))
13897 (defvar org-property-changed-functions nil
13898 "Hook called when the value of a property has changed.
13899 Each hook function should accept two arguments, the name of the property
13900 and the new value.")
13902 (defun org-entry-put (pom property value)
13903 "Set PROPERTY to VALUE for entry at point-or-marker POM."
13904 (org-with-point-at pom
13905 (org-back-to-heading t)
13906 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
13907 range)
13908 (cond
13909 ((equal property "TODO")
13910 (when (and (stringp value) (string-match "\\S-" value)
13911 (not (member value org-todo-keywords-1)))
13912 (error "\"%s\" is not a valid TODO state" value))
13913 (if (or (not value)
13914 (not (string-match "\\S-" value)))
13915 (setq value 'none))
13916 (org-todo value)
13917 (org-set-tags nil 'align))
13918 ((equal property "PRIORITY")
13919 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
13920 (string-to-char value) ?\ ))
13921 (org-set-tags nil 'align))
13922 ((equal property "SCHEDULED")
13923 (if (re-search-forward org-scheduled-time-regexp end t)
13924 (cond
13925 ((eq value 'earlier) (org-timestamp-change -1 'day))
13926 ((eq value 'later) (org-timestamp-change 1 'day))
13927 (t (call-interactively 'org-schedule)))
13928 (call-interactively 'org-schedule)))
13929 ((equal property "DEADLINE")
13930 (if (re-search-forward org-deadline-time-regexp end t)
13931 (cond
13932 ((eq value 'earlier) (org-timestamp-change -1 'day))
13933 ((eq value 'later) (org-timestamp-change 1 'day))
13934 (t (call-interactively 'org-deadline)))
13935 (call-interactively 'org-deadline)))
13936 ((member property org-special-properties)
13937 (error "The %s property can not yet be set with `org-entry-put'"
13938 property))
13939 (t ; a non-special property
13940 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
13941 (setq range (org-get-property-block beg end 'force))
13942 (goto-char (car range))
13943 (if (re-search-forward
13944 (org-re-property property) (cdr range) t)
13945 (progn
13946 (delete-region (match-beginning 0) (match-end 0))
13947 (goto-char (match-beginning 0)))
13948 (goto-char (cdr range))
13949 (insert "\n")
13950 (backward-char 1)
13951 (org-indent-line-function))
13952 (insert ":" property ":")
13953 (and value (insert " " value))
13954 (org-indent-line-function)))))
13955 (run-hook-with-args 'org-property-changed-functions property value)))
13957 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
13958 "Get all property keys in the current buffer.
13959 With INCLUDE-SPECIALS, also list the special properties that reflect things
13960 like tags and TODO state.
13961 With INCLUDE-DEFAULTS, also include properties that has special meaning
13962 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
13963 and others.
13964 With INCLUDE-COLUMNS, also include property names given in COLUMN
13965 formats in the current buffer."
13966 (let (rtn range cfmt s p)
13967 (save-excursion
13968 (save-restriction
13969 (widen)
13970 (goto-char (point-min))
13971 (while (re-search-forward org-property-start-re nil t)
13972 (setq range (org-get-property-block))
13973 (goto-char (car range))
13974 (while (re-search-forward
13975 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
13976 (cdr range) t)
13977 (add-to-list 'rtn (org-match-string-no-properties 1)))
13978 (outline-next-heading))))
13980 (when include-specials
13981 (setq rtn (append org-special-properties rtn)))
13983 (when include-defaults
13984 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
13985 (add-to-list 'rtn org-effort-property))
13987 (when include-columns
13988 (save-excursion
13989 (save-restriction
13990 (widen)
13991 (goto-char (point-min))
13992 (while (re-search-forward
13993 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
13994 nil t)
13995 (setq cfmt (match-string 2) s 0)
13996 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
13997 cfmt s)
13998 (setq s (match-end 0)
13999 p (match-string 1 cfmt))
14000 (unless (or (equal p "ITEM")
14001 (member p org-special-properties))
14002 (add-to-list 'rtn (match-string 1 cfmt))))))))
14004 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14006 (defun org-property-values (key)
14007 "Return a list of all values of property KEY in the current buffer."
14008 (save-excursion
14009 (save-restriction
14010 (widen)
14011 (goto-char (point-min))
14012 (let ((re (org-re-property key))
14013 values)
14014 (while (re-search-forward re nil t)
14015 (add-to-list 'values (org-trim (match-string 1))))
14016 (delete "" values)))))
14018 (defun org-insert-property-drawer ()
14019 "Insert a property drawer into the current entry."
14020 (interactive)
14021 (org-back-to-heading t)
14022 (looking-at outline-regexp)
14023 (let ((indent (if org-adapt-indentation
14024 (- (match-end 0)(match-beginning 0))
14026 (beg (point))
14027 (re (concat "^[ \t]*" org-keyword-time-regexp))
14028 end hiddenp)
14029 (outline-next-heading)
14030 (setq end (point))
14031 (goto-char beg)
14032 (while (re-search-forward re end t))
14033 (setq hiddenp (outline-invisible-p))
14034 (end-of-line 1)
14035 (and (equal (char-after) ?\n) (forward-char 1))
14036 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14037 (if (member (match-string 1) '("CLOCK:" ":END:"))
14038 ;; just skip this line
14039 (beginning-of-line 2)
14040 ;; Drawer start, find the end
14041 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14042 (beginning-of-line 1)))
14043 (org-skip-over-state-notes)
14044 (skip-chars-backward " \t\n\r")
14045 (if (eq (char-before) ?*) (forward-char 1))
14046 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14047 (beginning-of-line 0)
14048 (org-indent-to-column indent)
14049 (beginning-of-line 2)
14050 (org-indent-to-column indent)
14051 (beginning-of-line 0)
14052 (if hiddenp
14053 (save-excursion
14054 (org-back-to-heading t)
14055 (hide-entry))
14056 (org-flag-drawer t))))
14058 (defvar org-property-set-functions-alist nil
14059 "Property set function alist.
14060 Each entry should have the following format:
14062 (PROPERTY . READ-FUNCTION)
14064 The read function will be called with the same argument as
14065 `org-completing-read'.")
14067 (defun org-set-property-function (property)
14068 "Get the function that should be used to set PROPERTY.
14069 This is computed according to `org-property-set-functions-alist'."
14070 (or (cdr (assoc property org-property-set-functions-alist))
14071 'org-completing-read))
14073 (defun org-read-property-value (property)
14074 "Read PROPERTY value from user."
14075 (let* ((completion-ignore-case t)
14076 (allowed (org-property-get-allowed-values nil property 'table))
14077 (cur (org-entry-get nil property))
14078 (prompt (concat property " value"
14079 (if (and cur (string-match "\\S-" cur))
14080 (concat " [" cur "]") "") ": "))
14081 (set-function (org-set-property-function property))
14082 (val (if allowed
14083 (funcall set-function prompt allowed nil
14084 (not (get-text-property 0 'org-unrestricted
14085 (caar allowed))))
14086 (let (org-completion-use-ido org-completion-use-iswitchb)
14087 (funcall set-function prompt
14088 (mapcar 'list (org-property-values property))
14089 nil nil "" nil cur)))))
14090 (if (equal val "")
14092 val)))
14094 (defun org-read-property-name ()
14095 "Read a property name."
14096 (let* ((completion-ignore-case t)
14097 (keys (org-buffer-property-keys nil t t))
14098 (default-prop (save-excursion
14099 (save-match-data
14100 (beginning-of-line)
14101 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14102 (null (string= (match-string 1) "END"))
14103 (match-string 1)))))
14104 (property (org-icompleting-read
14105 (concat "Property"
14106 (if default-prop (concat " [" default-prop "]") "")
14107 ": ")
14108 (mapcar 'list keys)
14109 nil nil nil nil
14110 default-prop
14112 (if (member property keys)
14113 property
14114 (or (cdr (assoc (downcase property)
14115 (mapcar (lambda (x) (cons (downcase x) x))
14116 keys)))
14117 property))))
14119 (defun org-set-property (property value)
14120 "In the current entry, set PROPERTY to VALUE.
14121 When called interactively, this will prompt for a property name, offering
14122 completion on existing and default properties. And then it will prompt
14123 for a value, offering completion either on allowed values (via an inherited
14124 xxx_ALL property) or on existing values in other instances of this property
14125 in the current file."
14126 (interactive (list nil nil))
14127 (let* ((property (or property (org-read-property-name)))
14128 (value (or value (org-read-property-value property))))
14129 (unless (equal (org-entry-get nil property) value)
14130 (org-entry-put nil property value))))
14132 (defun org-delete-property (property)
14133 "In the current entry, delete PROPERTY."
14134 (interactive
14135 (let* ((completion-ignore-case t)
14136 (prop (org-icompleting-read "Property: "
14137 (org-entry-properties nil 'standard))))
14138 (list prop)))
14139 (message "Property %s %s" property
14140 (if (org-entry-delete nil property)
14141 "deleted"
14142 "was not present in the entry")))
14144 (defun org-delete-property-globally (property)
14145 "Remove PROPERTY globally, from all entries."
14146 (interactive
14147 (let* ((completion-ignore-case t)
14148 (prop (org-icompleting-read
14149 "Globally remove property: "
14150 (mapcar 'list (org-buffer-property-keys)))))
14151 (list prop)))
14152 (save-excursion
14153 (save-restriction
14154 (widen)
14155 (goto-char (point-min))
14156 (let ((cnt 0))
14157 (while (re-search-forward
14158 (org-re-property property)
14159 nil t)
14160 (setq cnt (1+ cnt))
14161 (replace-match ""))
14162 (message "Property \"%s\" removed from %d entries" property cnt)))))
14164 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
14166 (defun org-compute-property-at-point ()
14167 "Compute the property at point.
14168 This looks for an enclosing column format, extracts the operator and
14169 then applies it to the property in the column format's scope."
14170 (interactive)
14171 (unless (org-at-property-p)
14172 (error "Not at a property"))
14173 (let ((prop (org-match-string-no-properties 2)))
14174 (org-columns-get-format-and-top-level)
14175 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14176 (error "No operator defined for property %s" prop))
14177 (org-columns-compute prop)))
14179 (defvar org-property-allowed-value-functions nil
14180 "Hook for functions supplying allowed values for a specific property.
14181 The functions must take a single argument, the name of the property, and
14182 return a flat list of allowed values. If \":ETC\" is one of
14183 the values, this means that these values are intended as defaults for
14184 completion, but that other values should be allowed too.
14185 The functions must return nil if they are not responsible for this
14186 property.")
14188 (defun org-property-get-allowed-values (pom property &optional table)
14189 "Get allowed values for the property PROPERTY.
14190 When TABLE is non-nil, return an alist that can directly be used for
14191 completion."
14192 (let (vals)
14193 (cond
14194 ((equal property "TODO")
14195 (setq vals (org-with-point-at pom
14196 (append org-todo-keywords-1 '("")))))
14197 ((equal property "PRIORITY")
14198 (let ((n org-lowest-priority))
14199 (while (>= n org-highest-priority)
14200 (push (char-to-string n) vals)
14201 (setq n (1- n)))))
14202 ((member property org-special-properties))
14203 ((setq vals (run-hook-with-args-until-success
14204 'org-property-allowed-value-functions property)))
14206 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14207 (when (and vals (string-match "\\S-" vals))
14208 (setq vals (car (read-from-string (concat "(" vals ")"))))
14209 (setq vals (mapcar (lambda (x)
14210 (cond ((stringp x) x)
14211 ((numberp x) (number-to-string x))
14212 ((symbolp x) (symbol-name x))
14213 (t "???")))
14214 vals)))))
14215 (when (member ":ETC" vals)
14216 (setq vals (remove ":ETC" vals))
14217 (org-add-props (car vals) '(org-unrestricted t)))
14218 (if table (mapcar 'list vals) vals)))
14220 (defun org-property-previous-allowed-value (&optional previous)
14221 "Switch to the next allowed value for this property."
14222 (interactive)
14223 (org-property-next-allowed-value t))
14225 (defun org-property-next-allowed-value (&optional previous)
14226 "Switch to the next allowed value for this property."
14227 (interactive)
14228 (unless (org-at-property-p)
14229 (error "Not at a property"))
14230 (let* ((key (match-string 2))
14231 (value (match-string 3))
14232 (allowed (or (org-property-get-allowed-values (point) key)
14233 (and (member value '("[ ]" "[-]" "[X]"))
14234 '("[ ]" "[X]"))))
14235 nval)
14236 (unless allowed
14237 (error "Allowed values for this property have not been defined"))
14238 (if previous (setq allowed (reverse allowed)))
14239 (if (member value allowed)
14240 (setq nval (car (cdr (member value allowed)))))
14241 (setq nval (or nval (car allowed)))
14242 (if (equal nval value)
14243 (error "Only one allowed value for this property"))
14244 (org-at-property-p)
14245 (replace-match (concat " :" key ": " nval) t t)
14246 (org-indent-line-function)
14247 (beginning-of-line 1)
14248 (skip-chars-forward " \t")
14249 (run-hook-with-args 'org-property-changed-functions key nval)))
14251 (defun org-find-olp (path &optional this-buffer)
14252 "Return a marker pointing to the entry at outline path OLP.
14253 If anything goes wrong, throw an error.
14254 You can wrap this call to catch the error like this:
14256 (condition-case msg
14257 (org-mobile-locate-entry (match-string 4))
14258 (error (nth 1 msg)))
14260 The return value will then be either a string with the error message,
14261 or a marker if everything is OK.
14263 If THIS-BUFFER is set, the outline path does not contain a file,
14264 only headings."
14265 (let* ((file (if this-buffer buffer-file-name (pop path)))
14266 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
14267 (level 1)
14268 (lmin 1)
14269 (lmax 1)
14270 limit re end found pos heading cnt flevel)
14271 (unless buffer (error "File not found :%s" file))
14272 (with-current-buffer buffer
14273 (save-excursion
14274 (save-restriction
14275 (widen)
14276 (setq limit (point-max))
14277 (goto-char (point-min))
14278 (while (setq heading (pop path))
14279 (setq re (format org-complex-heading-regexp-format
14280 (regexp-quote heading)))
14281 (setq cnt 0 pos (point))
14282 (while (re-search-forward re end t)
14283 (setq level (- (match-end 1) (match-beginning 1)))
14284 (if (and (>= level lmin) (<= level lmax))
14285 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
14286 (when (= cnt 0) (error "Heading not found on level %d: %s"
14287 lmax heading))
14288 (when (> cnt 1) (error "Heading not unique on level %d: %s"
14289 lmax heading))
14290 (goto-char found)
14291 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
14292 (setq end (save-excursion (org-end-of-subtree t t))))
14293 (when (org-on-heading-p)
14294 (move-marker (make-marker) (point))))))))
14296 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
14297 "Find node HEADING in BUFFER.
14298 Return a marker to the heading if it was found, or nil if not.
14299 If POS-ONLY is set, return just the position instead of a marker.
14301 The heading text must match exact, but it may have a TODO keyword,
14302 a priority cookie and tags in the standard locations."
14303 (with-current-buffer (or buffer (current-buffer))
14304 (save-excursion
14305 (save-restriction
14306 (widen)
14307 (goto-char (point-min))
14308 (let (case-fold-search)
14309 (if (re-search-forward
14310 (format org-complex-heading-regexp-format
14311 (regexp-quote heading)) nil t)
14312 (if pos-only
14313 (match-beginning 0)
14314 (move-marker (make-marker) (match-beginning 0)))))))))
14316 (defun org-find-exact-heading-in-directory (heading &optional dir)
14317 "Find Org node headline HEADING in all .org files in directory DIR.
14318 When the target headline is found, return a marker to this location."
14319 (let ((files (directory-files (or dir default-directory)
14320 nil "\\`[^.#].*\\.org\\'"))
14321 file visiting m buffer)
14322 (catch 'found
14323 (while (setq file (pop files))
14324 (message "trying %s" file)
14325 (setq visiting (org-find-base-buffer-visiting file))
14326 (setq buffer (or visiting (find-file-noselect file)))
14327 (setq m (org-find-exact-headline-in-buffer
14328 heading buffer))
14329 (when (and (not m) (not visiting)) (kill-buffer buffer))
14330 (and m (throw 'found m))))))
14332 (defun org-find-entry-with-id (ident)
14333 "Locate the entry that contains the ID property with exact value IDENT.
14334 IDENT can be a string, a symbol or a number, this function will search for
14335 the string representation of it.
14336 Return the position where this entry starts, or nil if there is no such entry."
14337 (interactive "sID: ")
14338 (let ((id (cond
14339 ((stringp ident) ident)
14340 ((symbol-name ident) (symbol-name ident))
14341 ((numberp ident) (number-to-string ident))
14342 (t (error "IDENT %s must be a string, symbol or number" ident))))
14343 (case-fold-search nil))
14344 (save-excursion
14345 (save-restriction
14346 (widen)
14347 (goto-char (point-min))
14348 (when (re-search-forward
14349 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
14350 nil t)
14351 (org-back-to-heading t)
14352 (point))))))
14354 ;;;; Timestamps
14356 (defvar org-last-changed-timestamp nil)
14357 (defvar org-last-inserted-timestamp nil
14358 "The last time stamp inserted with `org-insert-time-stamp'.")
14359 (defvar org-time-was-given) ; dynamically scoped parameter
14360 (defvar org-end-time-was-given) ; dynamically scoped parameter
14361 (defvar org-ts-what) ; dynamically scoped parameter
14363 (defun org-time-stamp (arg &optional inactive)
14364 "Prompt for a date/time and insert a time stamp.
14365 If the user specifies a time like HH:MM, or if this command is called
14366 with a prefix argument, the time stamp will contain date and time.
14367 Otherwise, only the date will be included. All parts of a date not
14368 specified by the user will be filled in from the current date/time.
14369 So if you press just return without typing anything, the time stamp
14370 will represent the current date/time. If there is already a timestamp
14371 at the cursor, it will be modified."
14372 (interactive "P")
14373 (let* ((ts nil)
14374 (default-time
14375 ;; Default time is either today, or, when entering a range,
14376 ;; the range start.
14377 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
14378 (save-excursion
14379 (re-search-backward
14380 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14381 (- (point) 20) t)))
14382 (apply 'encode-time (org-parse-time-string (match-string 1)))
14383 (current-time)))
14384 (default-input (and ts (org-get-compact-tod ts)))
14385 (repeater (save-excursion
14386 (save-match-data
14387 (beginning-of-line)
14388 (when (re-search-forward
14389 "\\([.+-]+[0-9]+[dwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[dwmy]\\)?\\) ?"
14390 (save-excursion (progn (end-of-line) (point))) t)
14391 (match-string 0)))))
14392 org-time-was-given org-end-time-was-given time)
14393 (cond
14394 ((and (org-at-timestamp-p t)
14395 (memq last-command '(org-time-stamp org-time-stamp-inactive))
14396 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
14397 (insert "--")
14398 (setq time (let ((this-command this-command))
14399 (org-read-date arg 'totime nil nil
14400 default-time default-input)))
14401 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
14402 ((org-at-timestamp-p t)
14403 (setq time (let ((this-command this-command))
14404 (org-read-date arg 'totime nil nil default-time default-input)))
14405 (when (org-at-timestamp-p t) ; just to get the match data
14406 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
14407 (replace-match "")
14408 (setq org-last-changed-timestamp
14409 (org-insert-time-stamp
14410 time (or org-time-was-given arg)
14411 inactive nil nil (list org-end-time-was-given)))
14412 (when repeater (goto-char (1- (point))) (insert " " repeater)
14413 (setq org-last-changed-timestamp
14414 (concat (substring org-last-inserted-timestamp 0 -1)
14415 " " repeater ">"))))
14416 (message "Timestamp updated"))
14418 (setq time (let ((this-command this-command))
14419 (org-read-date arg 'totime nil nil default-time default-input)))
14420 (org-insert-time-stamp time (or org-time-was-given arg) inactive
14421 nil nil (list org-end-time-was-given))))))
14423 ;; FIXME: can we use this for something else, like computing time differences?
14424 (defun org-get-compact-tod (s)
14425 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
14426 (let* ((t1 (match-string 1 s))
14427 (h1 (string-to-number (match-string 2 s)))
14428 (m1 (string-to-number (match-string 3 s)))
14429 (t2 (and (match-end 4) (match-string 5 s)))
14430 (h2 (and t2 (string-to-number (match-string 6 s))))
14431 (m2 (and t2 (string-to-number (match-string 7 s))))
14432 dh dm)
14433 (if (not t2)
14435 (setq dh (- h2 h1) dm (- m2 m1))
14436 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
14437 (concat t1 "+" (number-to-string dh)
14438 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
14440 (defun org-time-stamp-inactive (&optional arg)
14441 "Insert an inactive time stamp.
14442 An inactive time stamp is enclosed in square brackets instead of angle
14443 brackets. It is inactive in the sense that it does not trigger agenda entries,
14444 does not link to the calendar and cannot be changed with the S-cursor keys.
14445 So these are more for recording a certain time/date."
14446 (interactive "P")
14447 (org-time-stamp arg 'inactive))
14449 (defvar org-date-ovl (make-overlay 1 1))
14450 (overlay-put org-date-ovl 'face 'org-warning)
14451 (org-detach-overlay org-date-ovl)
14453 (defvar org-ans1) ; dynamically scoped parameter
14454 (defvar org-ans2) ; dynamically scoped parameter
14456 (defvar org-plain-time-of-day-regexp) ; defined below
14458 (defvar org-overriding-default-time nil) ; dynamically scoped
14459 (defvar org-read-date-overlay nil)
14460 (defvar org-dcst nil) ; dynamically scoped
14461 (defvar org-read-date-history nil)
14462 (defvar org-read-date-final-answer nil)
14463 (defvar org-read-date-analyze-futurep nil)
14464 (defvar org-read-date-analyze-forced-year nil)
14466 (defun org-read-date (&optional with-time to-time from-string prompt
14467 default-time default-input)
14468 "Read a date, possibly a time, and make things smooth for the user.
14469 The prompt will suggest to enter an ISO date, but you can also enter anything
14470 which will at least partially be understood by `parse-time-string'.
14471 Unrecognized parts of the date will default to the current day, month, year,
14472 hour and minute. If this command is called to replace a timestamp at point,
14473 of to enter the second timestamp of a range, the default time is taken
14474 from the existing stamp. Furthermore, the command prefers the future,
14475 so if you are giving a date where the year is not given, and the day-month
14476 combination is already past in the current year, it will assume you
14477 mean next year. For details, see the manual. A few examples:
14479 3-2-5 --> 2003-02-05
14480 feb 15 --> currentyear-02-15
14481 2/15 --> currentyear-02-15
14482 sep 12 9 --> 2009-09-12
14483 12:45 --> today 12:45
14484 22 sept 0:34 --> currentyear-09-22 0:34
14485 12 --> currentyear-currentmonth-12
14486 Fri --> nearest Friday (today or later)
14487 etc.
14489 Furthermore you can specify a relative date by giving, as the *first* thing
14490 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
14491 change in days weeks, months, years.
14492 With a single plus or minus, the date is relative to today. With a double
14493 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
14494 +4d --> four days from today
14495 +4 --> same as above
14496 +2w --> two weeks from today
14497 ++5 --> five days from default date
14499 The function understands only English month and weekday abbreviations,
14500 but this can be configured with the variables `parse-time-months' and
14501 `parse-time-weekdays'.
14503 While prompting, a calendar is popped up - you can also select the
14504 date with the mouse (button 1). The calendar shows a period of three
14505 months. To scroll it to other months, use the keys `>' and `<'.
14506 If you don't like the calendar, turn it off with
14507 \(setq org-read-date-popup-calendar nil)
14509 With optional argument TO-TIME, the date will immediately be converted
14510 to an internal time.
14511 With an optional argument WITH-TIME, the prompt will suggest to also
14512 insert a time. Note that when WITH-TIME is not set, you can still
14513 enter a time, and this function will inform the calling routine about
14514 this change. The calling routine may then choose to change the format
14515 used to insert the time stamp into the buffer to include the time.
14516 With optional argument FROM-STRING, read from this string instead from
14517 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
14518 the time/date that is used for everything that is not specified by the
14519 user."
14520 (require 'parse-time)
14521 (let* ((org-time-stamp-rounding-minutes
14522 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
14523 (org-dcst org-display-custom-times)
14524 (ct (org-current-time))
14525 (def (or org-overriding-default-time default-time ct))
14526 (defdecode (decode-time def))
14527 (dummy (progn
14528 (when (< (nth 2 defdecode) org-extend-today-until)
14529 (setcar (nthcdr 2 defdecode) -1)
14530 (setcar (nthcdr 1 defdecode) 59)
14531 (setq def (apply 'encode-time defdecode)
14532 defdecode (decode-time def)))))
14533 (calendar-frame-setup nil)
14534 (calendar-setup nil)
14535 (calendar-move-hook nil)
14536 (calendar-view-diary-initially-flag nil)
14537 (calendar-view-holidays-initially-flag nil)
14538 (timestr (format-time-string
14539 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
14540 (prompt (concat (if prompt (concat prompt " ") "")
14541 (format "Date+time [%s]: " timestr)))
14542 ans (org-ans0 "") org-ans1 org-ans2 final)
14544 (cond
14545 (from-string (setq ans from-string))
14546 (org-read-date-popup-calendar
14547 (save-excursion
14548 (save-window-excursion
14549 (calendar)
14550 (unwind-protect
14551 (progn
14552 (calendar-forward-day (- (time-to-days def)
14553 (calendar-absolute-from-gregorian
14554 (calendar-current-date))))
14555 (org-eval-in-calendar nil t)
14556 (let* ((old-map (current-local-map))
14557 (map (copy-keymap calendar-mode-map))
14558 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14559 (org-defkey map (kbd "RET") 'org-calendar-select)
14560 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
14561 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
14562 (org-defkey minibuffer-local-map [(meta shift left)]
14563 (lambda () (interactive)
14564 (org-eval-in-calendar '(calendar-backward-month 1))))
14565 (org-defkey minibuffer-local-map [(meta shift right)]
14566 (lambda () (interactive)
14567 (org-eval-in-calendar '(calendar-forward-month 1))))
14568 (org-defkey minibuffer-local-map [(meta shift up)]
14569 (lambda () (interactive)
14570 (org-eval-in-calendar '(calendar-backward-year 1))))
14571 (org-defkey minibuffer-local-map [(meta shift down)]
14572 (lambda () (interactive)
14573 (org-eval-in-calendar '(calendar-forward-year 1))))
14574 (org-defkey minibuffer-local-map [?\e (shift left)]
14575 (lambda () (interactive)
14576 (org-eval-in-calendar '(calendar-backward-month 1))))
14577 (org-defkey minibuffer-local-map [?\e (shift right)]
14578 (lambda () (interactive)
14579 (org-eval-in-calendar '(calendar-forward-month 1))))
14580 (org-defkey minibuffer-local-map [?\e (shift up)]
14581 (lambda () (interactive)
14582 (org-eval-in-calendar '(calendar-backward-year 1))))
14583 (org-defkey minibuffer-local-map [?\e (shift down)]
14584 (lambda () (interactive)
14585 (org-eval-in-calendar '(calendar-forward-year 1))))
14586 (org-defkey minibuffer-local-map [(shift up)]
14587 (lambda () (interactive)
14588 (org-eval-in-calendar '(calendar-backward-week 1))))
14589 (org-defkey minibuffer-local-map [(shift down)]
14590 (lambda () (interactive)
14591 (org-eval-in-calendar '(calendar-forward-week 1))))
14592 (org-defkey minibuffer-local-map [(shift left)]
14593 (lambda () (interactive)
14594 (org-eval-in-calendar '(calendar-backward-day 1))))
14595 (org-defkey minibuffer-local-map [(shift right)]
14596 (lambda () (interactive)
14597 (org-eval-in-calendar '(calendar-forward-day 1))))
14598 (org-defkey minibuffer-local-map ">"
14599 (lambda () (interactive)
14600 (org-eval-in-calendar '(scroll-calendar-left 1))))
14601 (org-defkey minibuffer-local-map "<"
14602 (lambda () (interactive)
14603 (org-eval-in-calendar '(scroll-calendar-right 1))))
14604 (org-defkey minibuffer-local-map "\C-v"
14605 (lambda () (interactive)
14606 (org-eval-in-calendar
14607 '(calendar-scroll-left-three-months 1))))
14608 (org-defkey minibuffer-local-map "\M-v"
14609 (lambda () (interactive)
14610 (org-eval-in-calendar
14611 '(calendar-scroll-right-three-months 1))))
14612 (run-hooks 'org-read-date-minibuffer-setup-hook)
14613 (unwind-protect
14614 (progn
14615 (use-local-map map)
14616 (add-hook 'post-command-hook 'org-read-date-display)
14617 (setq org-ans0 (read-string prompt default-input
14618 'org-read-date-history nil))
14619 ;; org-ans0: from prompt
14620 ;; org-ans1: from mouse click
14621 ;; org-ans2: from calendar motion
14622 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14623 (remove-hook 'post-command-hook 'org-read-date-display)
14624 (use-local-map old-map)
14625 (when org-read-date-overlay
14626 (delete-overlay org-read-date-overlay)
14627 (setq org-read-date-overlay nil)))))
14628 (bury-buffer "*Calendar*")))))
14630 (t ; Naked prompt only
14631 (unwind-protect
14632 (setq ans (read-string prompt default-input
14633 'org-read-date-history timestr))
14634 (when org-read-date-overlay
14635 (delete-overlay org-read-date-overlay)
14636 (setq org-read-date-overlay nil)))))
14638 (setq final (org-read-date-analyze ans def defdecode))
14640 (when org-read-date-analyze-forced-year
14641 (message "Year was forced into %s"
14642 (if org-read-date-force-compatible-dates
14643 "compatible range (1970-2037)"
14644 "range representable on this machine"))
14645 (ding))
14647 ;; One round trip to get rid of 34th of August and stuff like that....
14648 (setq final (decode-time (apply 'encode-time final)))
14650 (setq org-read-date-final-answer ans)
14652 (if to-time
14653 (apply 'encode-time final)
14654 (if (and (boundp 'org-time-was-given) org-time-was-given)
14655 (format "%04d-%02d-%02d %02d:%02d"
14656 (nth 5 final) (nth 4 final) (nth 3 final)
14657 (nth 2 final) (nth 1 final))
14658 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
14660 (defvar def)
14661 (defvar defdecode)
14662 (defvar with-time)
14663 (defun org-read-date-display ()
14664 "Display the current date prompt interpretation in the minibuffer."
14665 (when org-read-date-display-live
14666 (when org-read-date-overlay
14667 (delete-overlay org-read-date-overlay))
14668 (let ((p (point)))
14669 (end-of-line 1)
14670 (while (not (equal (buffer-substring
14671 (max (point-min) (- (point) 4)) (point))
14672 " "))
14673 (insert " "))
14674 (goto-char p))
14675 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
14676 " " (or org-ans1 org-ans2)))
14677 (org-end-time-was-given nil)
14678 (f (org-read-date-analyze ans def defdecode))
14679 (fmts (if org-dcst
14680 org-time-stamp-custom-formats
14681 org-time-stamp-formats))
14682 (fmt (if (or with-time
14683 (and (boundp 'org-time-was-given) org-time-was-given))
14684 (cdr fmts)
14685 (car fmts)))
14686 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
14687 (when (and org-end-time-was-given
14688 (string-match org-plain-time-of-day-regexp txt))
14689 (setq txt (concat (substring txt 0 (match-end 0)) "-"
14690 org-end-time-was-given
14691 (substring txt (match-end 0)))))
14692 (when org-read-date-analyze-futurep
14693 (setq txt (concat txt " (=>F)")))
14694 (setq org-read-date-overlay
14695 (make-overlay (1- (point-at-eol)) (point-at-eol)))
14696 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
14698 (defun org-read-date-analyze (ans def defdecode)
14699 "Analyze the combined answer of the date prompt."
14700 ;; FIXME: cleanup and comment
14701 (let ((nowdecode (decode-time (current-time)))
14702 delta deltan deltaw deltadef year month day
14703 hour minute second wday pm h2 m2 tl wday1
14704 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
14705 (setq org-read-date-analyze-futurep nil
14706 org-read-date-analyze-forced-year nil)
14707 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
14708 (setq ans "+0"))
14710 (when (setq delta (org-read-date-get-relative ans (current-time) def))
14711 (setq ans (replace-match "" t t ans)
14712 deltan (car delta)
14713 deltaw (nth 1 delta)
14714 deltadef (nth 2 delta)))
14716 ;; Check if there is an iso week date in there
14717 ;; If yes, store the info and postpone interpreting it until the rest
14718 ;; of the parsing is done
14719 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
14720 (setq iso-year (if (match-end 1)
14721 (org-small-year-to-year
14722 (string-to-number (match-string 1 ans))))
14723 iso-weekday (if (match-end 3)
14724 (string-to-number (match-string 3 ans)))
14725 iso-week (string-to-number (match-string 2 ans)))
14726 (setq ans (replace-match "" t t ans)))
14728 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
14729 (when (string-match
14730 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
14731 (setq year (if (match-end 2)
14732 (string-to-number (match-string 2 ans))
14733 (progn (setq kill-year t)
14734 (string-to-number (format-time-string "%Y"))))
14735 month (string-to-number (match-string 3 ans))
14736 day (string-to-number (match-string 4 ans)))
14737 (if (< year 100) (setq year (+ 2000 year)))
14738 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14739 t nil ans)))
14741 ;; Help matching dottet european dates
14742 (when (string-match
14743 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
14744 (setq year (if (match-end 3)
14745 (string-to-number (match-string 3 ans))
14746 (progn (setq kill-year t)
14747 (string-to-number (format-time-string "%Y"))))
14748 day (string-to-number (match-string 1 ans))
14749 month (string-to-number (match-string 2 ans))
14750 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14751 t nil ans)))
14753 ;; Help matching american dates, like 5/30 or 5/30/7
14754 (when (string-match
14755 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
14756 (setq year (if (match-end 4)
14757 (string-to-number (match-string 4 ans))
14758 (progn (setq kill-year t)
14759 (string-to-number (format-time-string "%Y"))))
14760 month (string-to-number (match-string 1 ans))
14761 day (string-to-number (match-string 2 ans)))
14762 (if (< year 100) (setq year (+ 2000 year)))
14763 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14764 t nil ans)))
14765 ;; Help matching am/pm times, because `parse-time-string' does not do that.
14766 ;; If there is a time with am/pm, and *no* time without it, we convert
14767 ;; so that matching will be successful.
14768 (loop for i from 1 to 2 do ; twice, for end time as well
14769 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
14770 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
14771 (setq hour (string-to-number (match-string 1 ans))
14772 minute (if (match-end 3)
14773 (string-to-number (match-string 3 ans))
14775 pm (equal ?p
14776 (string-to-char (downcase (match-string 4 ans)))))
14777 (if (and (= hour 12) (not pm))
14778 (setq hour 0)
14779 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
14780 (setq ans (replace-match (format "%02d:%02d" hour minute)
14781 t t ans))))
14783 ;; Check if a time range is given as a duration
14784 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
14785 (setq hour (string-to-number (match-string 1 ans))
14786 h2 (+ hour (string-to-number (match-string 3 ans)))
14787 minute (string-to-number (match-string 2 ans))
14788 m2 (+ minute (if (match-end 5) (string-to-number
14789 (match-string 5 ans))0)))
14790 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
14791 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
14792 t t ans)))
14794 ;; Check if there is a time range
14795 (when (boundp 'org-end-time-was-given)
14796 (setq org-time-was-given nil)
14797 (when (and (string-match org-plain-time-of-day-regexp ans)
14798 (match-end 8))
14799 (setq org-end-time-was-given (match-string 8 ans))
14800 (setq ans (concat (substring ans 0 (match-beginning 7))
14801 (substring ans (match-end 7))))))
14803 (setq tl (parse-time-string ans)
14804 day (or (nth 3 tl) (nth 3 defdecode))
14805 month (or (nth 4 tl)
14806 (if (and org-read-date-prefer-future
14807 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
14808 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
14809 (nth 4 defdecode)))
14810 year (or (and (not kill-year) (nth 5 tl))
14811 (if (and org-read-date-prefer-future
14812 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
14813 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
14814 (nth 5 defdecode)))
14815 hour (or (nth 2 tl) (nth 2 defdecode))
14816 minute (or (nth 1 tl) (nth 1 defdecode))
14817 second (or (nth 0 tl) 0)
14818 wday (nth 6 tl))
14820 (when (and (eq org-read-date-prefer-future 'time)
14821 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
14822 (equal day (nth 3 nowdecode))
14823 (equal month (nth 4 nowdecode))
14824 (equal year (nth 5 nowdecode))
14825 (nth 2 tl)
14826 (or (< (nth 2 tl) (nth 2 nowdecode))
14827 (and (= (nth 2 tl) (nth 2 nowdecode))
14828 (nth 1 tl)
14829 (< (nth 1 tl) (nth 1 nowdecode)))))
14830 (setq day (1+ day)
14831 futurep t))
14833 ;; Special date definitions below
14834 (cond
14835 (iso-week
14836 ;; There was an iso week
14837 (require 'cal-iso)
14838 (setq futurep nil)
14839 (setq year (or iso-year year)
14840 day (or iso-weekday wday 1)
14841 wday nil ; to make sure that the trigger below does not match
14842 iso-date (calendar-gregorian-from-absolute
14843 (calendar-absolute-from-iso
14844 (list iso-week day year))))
14845 ; FIXME: Should we also push ISO weeks into the future?
14846 ; (when (and org-read-date-prefer-future
14847 ; (not iso-year)
14848 ; (< (calendar-absolute-from-gregorian iso-date)
14849 ; (time-to-days (current-time))))
14850 ; (setq year (1+ year)
14851 ; iso-date (calendar-gregorian-from-absolute
14852 ; (calendar-absolute-from-iso
14853 ; (list iso-week day year)))))
14854 (setq month (car iso-date)
14855 year (nth 2 iso-date)
14856 day (nth 1 iso-date)))
14857 (deltan
14858 (setq futurep nil)
14859 (unless deltadef
14860 (let ((now (decode-time (current-time))))
14861 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
14862 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
14863 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
14864 ((equal deltaw "m") (setq month (+ month deltan)))
14865 ((equal deltaw "y") (setq year (+ year deltan)))))
14866 ((and wday (not (nth 3 tl)))
14867 (setq futurep nil)
14868 ;; Weekday was given, but no day, so pick that day in the week
14869 ;; on or after the derived date.
14870 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
14871 (unless (equal wday wday1)
14872 (setq day (+ day (% (- wday wday1 -7) 7))))))
14873 (if (and (boundp 'org-time-was-given)
14874 (nth 2 tl))
14875 (setq org-time-was-given t))
14876 (if (< year 100) (setq year (+ 2000 year)))
14877 ;; Check of the date is representable
14878 (if org-read-date-force-compatible-dates
14879 (progn
14880 (if (< year 1970)
14881 (setq year 1970 org-read-date-analyze-forced-year t))
14882 (if (> year 2037)
14883 (setq year 2037 org-read-date-analyze-forced-year t)))
14884 (condition-case nil
14885 (ignore (encode-time second minute hour day month year))
14886 (error
14887 (setq year (nth 5 defdecode))
14888 (setq org-read-date-analyze-forced-year t))))
14889 (setq org-read-date-analyze-futurep futurep)
14890 (list second minute hour day month year)))
14892 (defvar parse-time-weekdays)
14894 (defun org-read-date-get-relative (s today default)
14895 "Check string S for special relative date string.
14896 TODAY and DEFAULT are internal times, for today and for a default.
14897 Return shift list (N what def-flag)
14898 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
14899 N is the number of WHATs to shift.
14900 DEF-FLAG is t when a double ++ or -- indicates shift relative to
14901 the DEFAULT date rather than TODAY."
14902 (when (and
14903 (string-match
14904 (concat
14905 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
14906 "\\([0-9]+\\)?"
14907 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
14908 "\\([ \t]\\|$\\)") s)
14909 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
14910 (let* ((dir (if (> (match-end 1) (match-beginning 1))
14911 (string-to-char (substring (match-string 1 s) -1))
14912 ?+))
14913 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
14914 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
14915 (what (if (match-end 3) (match-string 3 s) "d"))
14916 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
14917 (date (if rel default today))
14918 (wday (nth 6 (decode-time date)))
14919 delta)
14920 (if wday1
14921 (progn
14922 (setq delta (mod (+ 7 (- wday1 wday)) 7))
14923 (if (= dir ?-) (setq delta (- delta 7)))
14924 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
14925 (list delta "d" rel))
14926 (list (* n (if (= dir ?-) -1 1)) what rel)))))
14928 (defun org-order-calendar-date-args (arg1 arg2 arg3)
14929 "Turn a user-specified date into the internal representation.
14930 The internal representation needed by the calendar is (month day year).
14931 This is a wrapper to handle the brain-dead convention in calendar that
14932 user function argument order change dependent on argument order."
14933 (if (boundp 'calendar-date-style)
14934 (cond
14935 ((eq calendar-date-style 'american)
14936 (list arg1 arg2 arg3))
14937 ((eq calendar-date-style 'european)
14938 (list arg2 arg1 arg3))
14939 ((eq calendar-date-style 'iso)
14940 (list arg2 arg3 arg1)))
14941 (with-no-warnings ;; european-calendar-style is obsolete as of version 23.1
14942 (if (org-bound-and-true-p european-calendar-style)
14943 (list arg2 arg1 arg3)
14944 (list arg1 arg2 arg3)))))
14946 (defun org-eval-in-calendar (form &optional keepdate)
14947 "Eval FORM in the calendar window and return to current window.
14948 Also, store the cursor date in variable org-ans2."
14949 (let ((sf (selected-frame))
14950 (sw (selected-window)))
14951 (select-window (get-buffer-window "*Calendar*" t))
14952 (eval form)
14953 (when (and (not keepdate) (calendar-cursor-to-date))
14954 (let* ((date (calendar-cursor-to-date))
14955 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14956 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
14957 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
14958 (select-window sw)
14959 (org-select-frame-set-input-focus sf)))
14961 (defun org-calendar-select ()
14962 "Return to `org-read-date' with the date currently selected.
14963 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14964 (interactive)
14965 (when (calendar-cursor-to-date)
14966 (let* ((date (calendar-cursor-to-date))
14967 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14968 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14969 (if (active-minibuffer-window) (exit-minibuffer))))
14971 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
14972 "Insert a date stamp for the date given by the internal TIME.
14973 WITH-HM means use the stamp format that includes the time of the day.
14974 INACTIVE means use square brackets instead of angular ones, so that the
14975 stamp will not contribute to the agenda.
14976 PRE and POST are optional strings to be inserted before and after the
14977 stamp.
14978 The command returns the inserted time stamp."
14979 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
14980 stamp)
14981 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
14982 (insert-before-markers (or pre ""))
14983 (when (listp extra)
14984 (setq extra (car extra))
14985 (if (and (stringp extra)
14986 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
14987 (setq extra (format "-%02d:%02d"
14988 (string-to-number (match-string 1 extra))
14989 (string-to-number (match-string 2 extra))))
14990 (setq extra nil)))
14991 (when extra
14992 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
14993 (insert-before-markers (setq stamp (format-time-string fmt time)))
14994 (insert-before-markers (or post ""))
14995 (setq org-last-inserted-timestamp stamp)))
14997 (defun org-toggle-time-stamp-overlays ()
14998 "Toggle the use of custom time stamp formats."
14999 (interactive)
15000 (setq org-display-custom-times (not org-display-custom-times))
15001 (unless org-display-custom-times
15002 (let ((p (point-min)) (bmp (buffer-modified-p)))
15003 (while (setq p (next-single-property-change p 'display))
15004 (if (and (get-text-property p 'display)
15005 (eq (get-text-property p 'face) 'org-date))
15006 (remove-text-properties
15007 p (setq p (next-single-property-change p 'display))
15008 '(display t))))
15009 (set-buffer-modified-p bmp)))
15010 (if (featurep 'xemacs)
15011 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15012 (org-restart-font-lock)
15013 (setq org-table-may-need-update t)
15014 (if org-display-custom-times
15015 (message "Time stamps are overlayed with custom format")
15016 (message "Time stamp overlays removed")))
15018 (defun org-display-custom-time (beg end)
15019 "Overlay modified time stamp format over timestamp between BEG and END."
15020 (let* ((ts (buffer-substring beg end))
15021 t1 w1 with-hm tf time str w2 (off 0))
15022 (save-match-data
15023 (setq t1 (org-parse-time-string ts t))
15024 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
15025 (setq off (- (match-end 0) (match-beginning 0)))))
15026 (setq end (- end off))
15027 (setq w1 (- end beg)
15028 with-hm (and (nth 1 t1) (nth 2 t1))
15029 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15030 time (org-fix-decoded-time t1)
15031 str (org-add-props
15032 (format-time-string
15033 (substring tf 1 -1) (apply 'encode-time time))
15034 nil 'mouse-face 'highlight)
15035 w2 (length str))
15036 (if (not (= w2 w1))
15037 (add-text-properties (1+ beg) (+ 2 beg)
15038 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15039 (if (featurep 'xemacs)
15040 (progn
15041 (put-text-property beg end 'invisible t)
15042 (put-text-property beg end 'end-glyph (make-glyph str)))
15043 (put-text-property beg end 'display str))))
15045 (defun org-translate-time (string)
15046 "Translate all timestamps in STRING to custom format.
15047 But do this only if the variable `org-display-custom-times' is set."
15048 (when org-display-custom-times
15049 (save-match-data
15050 (let* ((start 0)
15051 (re org-ts-regexp-both)
15052 t1 with-hm inactive tf time str beg end)
15053 (while (setq start (string-match re string start))
15054 (setq beg (match-beginning 0)
15055 end (match-end 0)
15056 t1 (save-match-data
15057 (org-parse-time-string (substring string beg end) t))
15058 with-hm (and (nth 1 t1) (nth 2 t1))
15059 inactive (equal (substring string beg (1+ beg)) "[")
15060 tf (funcall (if with-hm 'cdr 'car)
15061 org-time-stamp-custom-formats)
15062 time (org-fix-decoded-time t1)
15063 str (format-time-string
15064 (concat
15065 (if inactive "[" "<") (substring tf 1 -1)
15066 (if inactive "]" ">"))
15067 (apply 'encode-time time))
15068 string (replace-match str t t string)
15069 start (+ start (length str)))))))
15070 string)
15072 (defun org-fix-decoded-time (time)
15073 "Set 0 instead of nil for the first 6 elements of time.
15074 Don't touch the rest."
15075 (let ((n 0))
15076 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15078 (defun org-days-to-time (timestamp-string)
15079 "Difference between TIMESTAMP-STRING and now in days."
15080 (- (time-to-days (org-time-string-to-time timestamp-string))
15081 (time-to-days (current-time))))
15083 (defun org-deadline-close (timestamp-string &optional ndays)
15084 "Is the time in TIMESTAMP-STRING close to the current date?"
15085 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15086 (and (< (org-days-to-time timestamp-string) ndays)
15087 (not (org-entry-is-done-p))))
15089 (defun org-get-wdays (ts)
15090 "Get the deadline lead time appropriate for timestring TS."
15091 (cond
15092 ((<= org-deadline-warning-days 0)
15093 ;; 0 or negative, enforce this value no matter what
15094 (- org-deadline-warning-days))
15095 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
15096 ;; lead time is specified.
15097 (floor (* (string-to-number (match-string 1 ts))
15098 (cdr (assoc (match-string 2 ts)
15099 '(("d" . 1) ("w" . 7)
15100 ("m" . 30.4) ("y" . 365.25)))))))
15101 ;; go for the default.
15102 (t org-deadline-warning-days)))
15104 (defun org-calendar-select-mouse (ev)
15105 "Return to `org-read-date' with the date currently selected.
15106 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15107 (interactive "e")
15108 (mouse-set-point ev)
15109 (when (calendar-cursor-to-date)
15110 (let* ((date (calendar-cursor-to-date))
15111 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15112 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15113 (if (active-minibuffer-window) (exit-minibuffer))))
15115 (defun org-check-deadlines (ndays)
15116 "Check if there are any deadlines due or past due.
15117 A deadline is considered due if it happens within `org-deadline-warning-days'
15118 days from today's date. If the deadline appears in an entry marked DONE,
15119 it is not shown. The prefix arg NDAYS can be used to test that many
15120 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15121 (interactive "P")
15122 (let* ((org-warn-days
15123 (cond
15124 ((equal ndays '(4)) 100000)
15125 (ndays (prefix-numeric-value ndays))
15126 (t (abs org-deadline-warning-days))))
15127 (case-fold-search nil)
15128 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15129 (callback
15130 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15132 (message "%d deadlines past-due or due within %d days"
15133 (org-occur regexp nil callback)
15134 org-warn-days)))
15136 (defun org-check-before-date (date)
15137 "Check if there are deadlines or scheduled entries before DATE."
15138 (interactive (list (org-read-date)))
15139 (let ((case-fold-search nil)
15140 (regexp (concat "\\<\\(" org-deadline-string
15141 "\\|" org-scheduled-string
15142 "\\) *<\\([^>]+\\)>"))
15143 (callback
15144 (lambda () (time-less-p
15145 (org-time-string-to-time (match-string 2))
15146 (org-time-string-to-time date)))))
15147 (message "%d entries before %s"
15148 (org-occur regexp nil callback) date)))
15150 (defun org-check-after-date (date)
15151 "Check if there are deadlines or scheduled entries after DATE."
15152 (interactive (list (org-read-date)))
15153 (let ((case-fold-search nil)
15154 (regexp (concat "\\<\\(" org-deadline-string
15155 "\\|" org-scheduled-string
15156 "\\) *<\\([^>]+\\)>"))
15157 (callback
15158 (lambda () (not
15159 (time-less-p
15160 (org-time-string-to-time (match-string 2))
15161 (org-time-string-to-time date))))))
15162 (message "%d entries after %s"
15163 (org-occur regexp nil callback) date)))
15165 (defun org-evaluate-time-range (&optional to-buffer)
15166 "Evaluate a time range by computing the difference between start and end.
15167 Normally the result is just printed in the echo area, but with prefix arg
15168 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15169 If the time range is actually in a table, the result is inserted into the
15170 next column.
15171 For time difference computation, a year is assumed to be exactly 365
15172 days in order to avoid rounding problems."
15173 (interactive "P")
15175 (org-clock-update-time-maybe)
15176 (save-excursion
15177 (unless (org-at-date-range-p t)
15178 (goto-char (point-at-bol))
15179 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15180 (if (not (org-at-date-range-p t))
15181 (error "Not at a time-stamp range, and none found in current line")))
15182 (let* ((ts1 (match-string 1))
15183 (ts2 (match-string 2))
15184 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15185 (match-end (match-end 0))
15186 (time1 (org-time-string-to-time ts1))
15187 (time2 (org-time-string-to-time ts2))
15188 (t1 (org-float-time time1))
15189 (t2 (org-float-time time2))
15190 (diff (abs (- t2 t1)))
15191 (negative (< (- t2 t1) 0))
15192 ;; (ys (floor (* 365 24 60 60)))
15193 (ds (* 24 60 60))
15194 (hs (* 60 60))
15195 (fy "%dy %dd %02d:%02d")
15196 (fy1 "%dy %dd")
15197 (fd "%dd %02d:%02d")
15198 (fd1 "%dd")
15199 (fh "%02d:%02d")
15200 y d h m align)
15201 (if havetime
15202 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15204 d (floor (/ diff ds)) diff (mod diff ds)
15205 h (floor (/ diff hs)) diff (mod diff hs)
15206 m (floor (/ diff 60)))
15207 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15209 d (floor (+ (/ diff ds) 0.5))
15210 h 0 m 0))
15211 (if (not to-buffer)
15212 (message "%s" (org-make-tdiff-string y d h m))
15213 (if (org-at-table-p)
15214 (progn
15215 (goto-char match-end)
15216 (setq align t)
15217 (and (looking-at " *|") (goto-char (match-end 0))))
15218 (goto-char match-end))
15219 (if (looking-at
15220 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15221 (replace-match ""))
15222 (if negative (insert " -"))
15223 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15224 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15225 (insert " " (format fh h m))))
15226 (if align (org-table-align))
15227 (message "Time difference inserted")))))
15229 (defun org-make-tdiff-string (y d h m)
15230 (let ((fmt "")
15231 (l nil))
15232 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15233 l (push y l)))
15234 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15235 l (push d l)))
15236 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15237 l (push h l)))
15238 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15239 l (push m l)))
15240 (apply 'format fmt (nreverse l))))
15242 (defun org-time-string-to-time (s)
15243 (apply 'encode-time (org-parse-time-string s)))
15244 (defun org-time-string-to-seconds (s)
15245 (org-float-time (org-time-string-to-time s)))
15247 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
15248 "Convert a time stamp to an absolute day number.
15249 If there is a specifier for a cyclic time stamp, get the closest date to
15250 DAYNR.
15251 PREFER and SHOW-ALL are passed through to `org-closest-date'.
15252 The variable date is bound by the calendar when this is called."
15253 (cond
15254 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15255 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15256 daynr
15257 (+ daynr 1000)))
15258 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15259 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15260 (time-to-days (current-time))) (match-string 0 s)
15261 prefer show-all))
15262 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
15264 (defun org-days-to-iso-week (days)
15265 "Return the iso week number."
15266 (require 'cal-iso)
15267 (car (calendar-iso-from-absolute days)))
15269 (defun org-small-year-to-year (year)
15270 "Convert 2-digit years into 4-digit years.
15271 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15272 The year 2000 cannot be abbreviated. Any year larger than 99
15273 is returned unchanged."
15274 (if (< year 38)
15275 (setq year (+ 2000 year))
15276 (if (< year 100)
15277 (setq year (+ 1900 year))))
15278 year)
15280 (defun org-time-from-absolute (d)
15281 "Return the time corresponding to date D.
15282 D may be an absolute day number, or a calendar-type list (month day year)."
15283 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
15284 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
15286 (defun org-calendar-holiday ()
15287 "List of holidays, for Diary display in Org-mode."
15288 (require 'holidays)
15289 (let ((hl (funcall
15290 (if (fboundp 'calendar-check-holidays)
15291 'calendar-check-holidays 'check-calendar-holidays) date)))
15292 (if hl (mapconcat 'identity hl "; "))))
15294 (defun org-diary-sexp-entry (sexp entry date)
15295 "Process a SEXP diary ENTRY for DATE."
15296 (require 'diary-lib)
15297 (let ((result (if calendar-debug-sexp
15298 (let ((stack-trace-on-error t))
15299 (eval (car (read-from-string sexp))))
15300 (condition-case nil
15301 (eval (car (read-from-string sexp)))
15302 (error
15303 (beep)
15304 (message "Bad sexp at line %d in %s: %s"
15305 (org-current-line)
15306 (buffer-file-name) sexp)
15307 (sleep-for 2))))))
15308 (cond ((stringp result) (split-string result "; "))
15309 ((and (consp result)
15310 (not (consp (cdr result)))
15311 (stringp (cdr result))) (cdr result))
15312 ((and (consp result)
15313 (stringp (car result))) result)
15314 (result entry)
15315 (t nil))))
15317 (defun org-diary-to-ical-string (frombuf)
15318 "Get iCalendar entries from diary entries in buffer FROMBUF.
15319 This uses the icalendar.el library."
15320 (let* ((tmpdir (if (featurep 'xemacs)
15321 (temp-directory)
15322 temporary-file-directory))
15323 (tmpfile (make-temp-name
15324 (expand-file-name "orgics" tmpdir)))
15325 buf rtn b e)
15326 (with-current-buffer frombuf
15327 (icalendar-export-region (point-min) (point-max) tmpfile)
15328 (setq buf (find-buffer-visiting tmpfile))
15329 (set-buffer buf)
15330 (goto-char (point-min))
15331 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15332 (setq b (match-beginning 0)))
15333 (goto-char (point-max))
15334 (if (re-search-backward "^END:VEVENT" nil t)
15335 (setq e (match-end 0)))
15336 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15337 (kill-buffer buf)
15338 (delete-file tmpfile)
15339 rtn))
15341 (defun org-closest-date (start current change prefer show-all)
15342 "Find the date closest to CURRENT that is consistent with START and CHANGE.
15343 When PREFER is `past', return a date that is either CURRENT or past.
15344 When PREFER is `future', return a date that is either CURRENT or future.
15345 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
15346 ;; Make the proper lists from the dates
15347 (catch 'exit
15348 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15349 dn dw sday cday n1 n2 n0
15350 d m y y1 y2 date1 date2 nmonths nm ny m2)
15352 (setq start (org-date-to-gregorian start)
15353 current (org-date-to-gregorian
15354 (if show-all
15355 current
15356 (time-to-days (current-time))))
15357 sday (calendar-absolute-from-gregorian start)
15358 cday (calendar-absolute-from-gregorian current))
15360 (if (<= cday sday) (throw 'exit sday))
15362 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15363 (setq dn (string-to-number (match-string 1 change))
15364 dw (cdr (assoc (match-string 2 change) a1)))
15365 (error "Invalid change specifier: %s" change))
15366 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15367 (cond
15368 ((eq dw 'day)
15369 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15370 n2 (+ n1 dn)))
15371 ((eq dw 'year)
15372 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15373 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15374 (setq date1 (list m d y1)
15375 n1 (calendar-absolute-from-gregorian date1)
15376 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15377 n2 (calendar-absolute-from-gregorian date2)))
15378 ((eq dw 'month)
15379 ;; approx number of month between the two dates
15380 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15381 ;; How often does dn fit in there?
15382 (setq d (nth 1 start) m (car start) y (nth 2 start)
15383 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15384 m (+ m nm)
15385 ny (floor (/ m 12))
15386 y (+ y ny)
15387 m (- m (* ny 12)))
15388 (while (> m 12) (setq m (- m 12) y (1+ y)))
15389 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15390 (setq m2 (+ m dn) y2 y)
15391 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15392 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15393 (while (<= n2 cday)
15394 (setq n1 n2 m m2 y y2)
15395 (setq m2 (+ m dn) y2 y)
15396 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15397 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15398 ;; Make sure n1 is the earlier date
15399 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
15400 (if show-all
15401 (cond
15402 ((eq prefer 'past) (if (= cday n2) n2 n1))
15403 ((eq prefer 'future) (if (= cday n1) n1 n2))
15404 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
15405 (cond
15406 ((eq prefer 'past) (if (= cday n2) n2 n1))
15407 ((eq prefer 'future) (if (= cday n1) n1 n2))
15408 (t (if (= cday n1) n1 n2)))))))
15410 (defun org-date-to-gregorian (date)
15411 "Turn any specification of DATE into a Gregorian date for the calendar."
15412 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15413 ((and (listp date) (= (length date) 3)) date)
15414 ((stringp date)
15415 (setq date (org-parse-time-string date))
15416 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15417 ((listp date)
15418 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15420 (defun org-parse-time-string (s &optional nodefault)
15421 "Parse the standard Org-mode time string.
15422 This should be a lot faster than the normal `parse-time-string'.
15423 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15424 hour and minute fields will be nil if not given."
15425 (if (string-match org-ts-regexp0 s)
15426 (list 0
15427 (if (or (match-beginning 8) (not nodefault))
15428 (string-to-number (or (match-string 8 s) "0")))
15429 (if (or (match-beginning 7) (not nodefault))
15430 (string-to-number (or (match-string 7 s) "0")))
15431 (string-to-number (match-string 4 s))
15432 (string-to-number (match-string 3 s))
15433 (string-to-number (match-string 2 s))
15434 nil nil nil)
15435 (error "Not a standard Org-mode time string: %s" s)))
15437 (defun org-timestamp-up (&optional arg)
15438 "Increase the date item at the cursor by one.
15439 If the cursor is on the year, change the year. If it is on the month or
15440 the day, change that.
15441 With prefix ARG, change by that many units."
15442 (interactive "p")
15443 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
15445 (defun org-timestamp-down (&optional arg)
15446 "Decrease the date item at the cursor by one.
15447 If the cursor is on the year, change the year. If it is on the month or
15448 the day, change that.
15449 With prefix ARG, change by that many units."
15450 (interactive "p")
15451 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
15453 (defun org-timestamp-up-day (&optional arg)
15454 "Increase the date in the time stamp by one day.
15455 With prefix ARG, change that many days."
15456 (interactive "p")
15457 (if (and (not (org-at-timestamp-p t))
15458 (org-on-heading-p))
15459 (org-todo 'up)
15460 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
15462 (defun org-timestamp-down-day (&optional arg)
15463 "Decrease the date in the time stamp by one day.
15464 With prefix ARG, change that many days."
15465 (interactive "p")
15466 (if (and (not (org-at-timestamp-p t))
15467 (org-on-heading-p))
15468 (org-todo 'down)
15469 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
15471 (defun org-at-timestamp-p (&optional inactive-ok)
15472 "Determine if the cursor is in or at a timestamp."
15473 (interactive)
15474 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15475 (pos (point))
15476 (ans (or (looking-at tsr)
15477 (save-excursion
15478 (skip-chars-backward "^[<\n\r\t")
15479 (if (> (point) (point-min)) (backward-char 1))
15480 (and (looking-at tsr)
15481 (> (- (match-end 0) pos) -1))))))
15482 (and ans
15483 (boundp 'org-ts-what)
15484 (setq org-ts-what
15485 (cond
15486 ((= pos (match-beginning 0)) 'bracket)
15487 ((= pos (1- (match-end 0))) 'bracket)
15488 ((org-pos-in-match-range pos 2) 'year)
15489 ((org-pos-in-match-range pos 3) 'month)
15490 ((org-pos-in-match-range pos 7) 'hour)
15491 ((org-pos-in-match-range pos 8) 'minute)
15492 ((or (org-pos-in-match-range pos 4)
15493 (org-pos-in-match-range pos 5)) 'day)
15494 ((and (> pos (or (match-end 8) (match-end 5)))
15495 (< pos (match-end 0)))
15496 (- pos (or (match-end 8) (match-end 5))))
15497 (t 'day))))
15498 ans))
15500 (defun org-toggle-timestamp-type ()
15501 "Toggle the type (<active> or [inactive]) of a time stamp."
15502 (interactive)
15503 (when (org-at-timestamp-p t)
15504 (let ((beg (match-beginning 0)) (end (match-end 0))
15505 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
15506 (save-excursion
15507 (goto-char beg)
15508 (while (re-search-forward "[][<>]" end t)
15509 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
15510 t t)))
15511 (message "Timestamp is now %sactive"
15512 (if (equal (char-after beg) ?<) "" "in")))))
15514 (defun org-timestamp-change (n &optional what updown)
15515 "Change the date in the time stamp at point.
15516 The date will be changed by N times WHAT. WHAT can be `day', `month',
15517 `year', `minute', `second'. If WHAT is not given, the cursor position
15518 in the timestamp determines what will be changed."
15519 (let ((pos (point))
15520 with-hm inactive
15521 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
15522 org-ts-what
15523 extra rem
15524 ts time time0)
15525 (if (not (org-at-timestamp-p t))
15526 (error "Not at a timestamp"))
15527 (if (and (not what) (eq org-ts-what 'bracket))
15528 (org-toggle-timestamp-type)
15529 (if (and (not what) (not (eq org-ts-what 'day))
15530 org-display-custom-times
15531 (get-text-property (point) 'display)
15532 (not (get-text-property (1- (point)) 'display)))
15533 (setq org-ts-what 'day))
15534 (setq org-ts-what (or what org-ts-what)
15535 inactive (= (char-after (match-beginning 0)) ?\[)
15536 ts (match-string 0))
15537 (replace-match "")
15538 (if (string-match
15539 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
15541 (setq extra (match-string 1 ts)))
15542 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15543 (setq with-hm t))
15544 (setq time0 (org-parse-time-string ts))
15545 (when (and updown
15546 (eq org-ts-what 'minute)
15547 (not current-prefix-arg))
15548 ;; This looks like s-up and s-down. Change by one rounding step.
15549 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
15550 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
15551 (setcar (cdr time0) (+ (nth 1 time0)
15552 (if (> n 0) (- rem) (- dm rem))))))
15553 (setq time
15554 (encode-time (or (car time0) 0)
15555 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
15556 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
15557 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
15558 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
15559 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
15560 (nthcdr 6 time0)))
15561 (when (and (member org-ts-what '(hour minute))
15562 extra
15563 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
15564 (setq extra (org-modify-ts-extra
15565 extra
15566 (if (eq org-ts-what 'hour) 2 5)
15567 n dm)))
15568 (when (integerp org-ts-what)
15569 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
15570 (if (eq what 'calendar)
15571 (let ((cal-date (org-get-date-from-calendar)))
15572 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15573 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15574 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15575 (setcar time0 (or (car time0) 0))
15576 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15577 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
15578 (setq time (apply 'encode-time time0))))
15579 (setq org-last-changed-timestamp
15580 (org-insert-time-stamp time with-hm inactive nil nil extra))
15581 (org-clock-update-time-maybe)
15582 (goto-char pos)
15583 ;; Try to recenter the calendar window, if any
15584 (if (and org-calendar-follow-timestamp-change
15585 (get-buffer-window "*Calendar*" t)
15586 (memq org-ts-what '(day month year)))
15587 (org-recenter-calendar (time-to-days time))))))
15589 (defun org-modify-ts-extra (s pos n dm)
15590 "Change the different parts of the lead-time and repeat fields in timestamp."
15591 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15592 ng h m new rem)
15593 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15594 (cond
15595 ((or (org-pos-in-match-range pos 2)
15596 (org-pos-in-match-range pos 3))
15597 (setq m (string-to-number (match-string 3 s))
15598 h (string-to-number (match-string 2 s)))
15599 (if (org-pos-in-match-range pos 2)
15600 (setq h (+ h n))
15601 (setq n (* dm (org-no-warnings (signum n))))
15602 (when (not (= 0 (setq rem (% m dm))))
15603 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
15604 (setq m (+ m n)))
15605 (if (< m 0) (setq m (+ m 60) h (1- h)))
15606 (if (> m 59) (setq m (- m 60) h (1+ h)))
15607 (setq h (min 24 (max 0 h)))
15608 (setq ng 1 new (format "-%02d:%02d" h m)))
15609 ((org-pos-in-match-range pos 6)
15610 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15611 ((org-pos-in-match-range pos 5)
15612 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
15614 ((org-pos-in-match-range pos 9)
15615 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
15616 ((org-pos-in-match-range pos 8)
15617 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
15619 (when ng
15620 (setq s (concat
15621 (substring s 0 (match-beginning ng))
15623 (substring s (match-end ng))))))
15626 (defun org-recenter-calendar (date)
15627 "If the calendar is visible, recenter it to DATE."
15628 (let* ((win (selected-window))
15629 (cwin (get-buffer-window "*Calendar*" t))
15630 (calendar-move-hook nil))
15631 (when cwin
15632 (select-window cwin)
15633 (calendar-goto-date (if (listp date) date
15634 (calendar-gregorian-from-absolute date)))
15635 (select-window win))))
15637 (defun org-goto-calendar (&optional arg)
15638 "Go to the Emacs calendar at the current date.
15639 If there is a time stamp in the current line, go to that date.
15640 A prefix ARG can be used to force the current date."
15641 (interactive "P")
15642 (let ((tsr org-ts-regexp) diff
15643 (calendar-move-hook nil)
15644 (calendar-view-holidays-initially-flag nil)
15645 (calendar-view-diary-initially-flag nil))
15646 (if (or (org-at-timestamp-p)
15647 (save-excursion
15648 (beginning-of-line 1)
15649 (looking-at (concat ".*" tsr))))
15650 (let ((d1 (time-to-days (current-time)))
15651 (d2 (time-to-days
15652 (org-time-string-to-time (match-string 1)))))
15653 (setq diff (- d2 d1))))
15654 (calendar)
15655 (calendar-goto-today)
15656 (if (and diff (not arg)) (calendar-forward-day diff))))
15658 (defun org-get-date-from-calendar ()
15659 "Return a list (month day year) of date at point in calendar."
15660 (with-current-buffer "*Calendar*"
15661 (save-match-data
15662 (calendar-cursor-to-date))))
15664 (defun org-date-from-calendar ()
15665 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
15666 If there is already a time stamp at the cursor position, update it."
15667 (interactive)
15668 (if (org-at-timestamp-p t)
15669 (org-timestamp-change 0 'calendar)
15670 (let ((cal-date (org-get-date-from-calendar)))
15671 (org-insert-time-stamp
15672 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
15674 (defun org-minutes-to-hh:mm-string (m)
15675 "Compute H:MM from a number of minutes."
15676 (let ((h (/ m 60)))
15677 (setq m (- m (* 60 h)))
15678 (format org-time-clocksum-format h m)))
15680 (defun org-hh:mm-string-to-minutes (s)
15681 "Convert a string H:MM to a number of minutes.
15682 If the string is just a number, interpret it as minutes.
15683 In fact, the first hh:mm or number in the string will be taken,
15684 there can be extra stuff in the string.
15685 If no number is found, the return value is 0."
15686 (cond
15687 ((integerp s) s)
15688 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
15689 (+ (* (string-to-number (match-string 1 s)) 60)
15690 (string-to-number (match-string 2 s))))
15691 ((string-match "\\([0-9]+\\)" s)
15692 (string-to-number (match-string 1 s)))
15693 (t 0)))
15695 (defcustom org-effort-durations
15696 `(("h" . 60)
15697 ("d" . ,(* 60 8))
15698 ("w" . ,(* 60 8 5))
15699 ("m" . ,(* 60 8 5 4))
15700 ("y" . ,(* 60 8 5 40)))
15701 "Conversion factor to minutes for an effort modifier.
15703 Each entry has the form (MODIFIER . MINUTES).
15705 In an effort string, a number followed by MODIFIER is multiplied
15706 by the specified number of MINUTES to obtain an effort in
15707 minutes.
15709 For example, if the value of this variable is ((\"hours\" . 60)), then an
15710 effort string \"2hours\" is equivalent to 120 minutes."
15711 :group 'org-agenda
15712 :type '(alist :key-type (string :tag "Modifier")
15713 :value-type (number :tag "Minutes")))
15715 (defun org-duration-string-to-minutes (s)
15716 "Convert a duration string S to minutes.
15718 A bare number is interpreted as minutes, modifiers can be set by
15719 customizing `org-effort-durations' (which see).
15721 Entries containing a colon are interpreted as H:MM by
15722 `org-hh:mm-string-to-minutes'."
15723 (let ((result 0)
15724 (re (concat "\\([0-9]+\\) *\\("
15725 (regexp-opt (mapcar 'car org-effort-durations))
15726 "\\)")))
15727 (while (string-match re s)
15728 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
15729 (string-to-number (match-string 1 s))))
15730 (setq s (replace-match "" nil t s)))
15731 (incf result (org-hh:mm-string-to-minutes s))
15732 result))
15734 ;;;; Files
15736 (defun org-save-all-org-buffers ()
15737 "Save all Org-mode buffers without user confirmation."
15738 (interactive)
15739 (message "Saving all Org-mode buffers...")
15740 (save-some-buffers t 'org-mode-p)
15741 (when (featurep 'org-id) (org-id-locations-save))
15742 (message "Saving all Org-mode buffers... done"))
15744 (defun org-revert-all-org-buffers ()
15745 "Revert all Org-mode buffers.
15746 Prompt for confirmation when there are unsaved changes.
15747 Be sure you know what you are doing before letting this function
15748 overwrite your changes.
15750 This function is useful in a setup where one tracks org files
15751 with a version control system, to revert on one machine after pulling
15752 changes from another. I believe the procedure must be like this:
15754 1. M-x org-save-all-org-buffers
15755 2. Pull changes from the other machine, resolve conflicts
15756 3. M-x org-revert-all-org-buffers"
15757 (interactive)
15758 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
15759 (error "Abort"))
15760 (save-excursion
15761 (save-window-excursion
15762 (mapc
15763 (lambda (b)
15764 (when (and (with-current-buffer b (org-mode-p))
15765 (with-current-buffer b buffer-file-name))
15766 (switch-to-buffer b)
15767 (revert-buffer t 'no-confirm)))
15768 (buffer-list))
15769 (when (and (featurep 'org-id) org-id-track-globally)
15770 (org-id-locations-load)))))
15772 ;;;; Agenda files
15774 ;;;###autoload
15775 (defun org-switchb (&optional arg)
15776 "Switch between Org buffers.
15777 With a prefix argument, restrict available to files.
15778 With two prefix arguments, restrict available buffers to agenda files.
15780 Defaults to `iswitchb' for buffer name completion.
15781 Set `org-completion-use-ido' to make it use ido instead."
15782 (interactive "P")
15783 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
15784 ((equal arg '(16)) (org-buffer-list 'agenda))
15785 (t (org-buffer-list))))
15786 (org-completion-use-iswitchb org-completion-use-iswitchb)
15787 (org-completion-use-ido org-completion-use-ido))
15788 (unless (or org-completion-use-ido org-completion-use-iswitchb)
15789 (setq org-completion-use-iswitchb t))
15790 (switch-to-buffer
15791 (org-icompleting-read "Org buffer: "
15792 (mapcar 'list (mapcar 'buffer-name blist))
15793 nil t))))
15795 ;;; Define some older names previously used for this functionality
15796 ;;;###autoload
15797 (defalias 'org-ido-switchb 'org-switchb)
15798 ;;;###autoload
15799 (defalias 'org-iswitchb 'org-switchb)
15801 (defun org-buffer-list (&optional predicate exclude-tmp)
15802 "Return a list of Org buffers.
15803 PREDICATE can be `export', `files' or `agenda'.
15805 export restrict the list to Export buffers.
15806 files restrict the list to buffers visiting Org files.
15807 agenda restrict the list to buffers visiting agenda files.
15809 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
15810 (let* ((bfn nil)
15811 (agenda-files (and (eq predicate 'agenda)
15812 (mapcar 'file-truename (org-agenda-files t))))
15813 (filter
15814 (cond
15815 ((eq predicate 'files)
15816 (lambda (b) (with-current-buffer b (org-mode-p))))
15817 ((eq predicate 'export)
15818 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
15819 ((eq predicate 'agenda)
15820 (lambda (b)
15821 (with-current-buffer b
15822 (and (org-mode-p)
15823 (setq bfn (buffer-file-name b))
15824 (member (file-truename bfn) agenda-files)))))
15825 (t (lambda (b) (with-current-buffer b
15826 (or (org-mode-p)
15827 (string-match "\*Org .*Export"
15828 (buffer-name b)))))))))
15829 (delq nil
15830 (mapcar
15831 (lambda(b)
15832 (if (and (funcall filter b)
15833 (or (not exclude-tmp)
15834 (not (string-match "tmp" (buffer-name b)))))
15836 nil))
15837 (buffer-list)))))
15839 (defun org-agenda-files (&optional unrestricted archives)
15840 "Get the list of agenda files.
15841 Optional UNRESTRICTED means return the full list even if a restriction
15842 is currently in place.
15843 When ARCHIVES is t, include all archive files that are really being
15844 used by the agenda files. If ARCHIVE is `ifmode', do this only if
15845 `org-agenda-archives-mode' is t."
15846 (let ((files
15847 (cond
15848 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
15849 ((stringp org-agenda-files) (org-read-agenda-file-list))
15850 ((listp org-agenda-files) org-agenda-files)
15851 (t (error "Invalid value of `org-agenda-files'")))))
15852 (setq files (apply 'append
15853 (mapcar (lambda (f)
15854 (if (file-directory-p f)
15855 (directory-files
15856 f t org-agenda-file-regexp)
15857 (list f)))
15858 files)))
15859 (when org-agenda-skip-unavailable-files
15860 (setq files (delq nil
15861 (mapcar (function
15862 (lambda (file)
15863 (and (file-readable-p file) file)))
15864 files))))
15865 (when (or (eq archives t)
15866 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
15867 (setq files (org-add-archive-files files)))
15868 files))
15870 (defun org-agenda-file-p (&optional file)
15871 "Return non-nil, if FILE is an agenda file.
15872 If FILE is omitted, use the file associated with the current
15873 buffer."
15874 (member (or file (buffer-file-name))
15875 (org-agenda-files t)))
15877 (defun org-edit-agenda-file-list ()
15878 "Edit the list of agenda files.
15879 Depending on setup, this either uses customize to edit the variable
15880 `org-agenda-files', or it visits the file that is holding the list. In the
15881 latter case, the buffer is set up in a way that saving it automatically kills
15882 the buffer and restores the previous window configuration."
15883 (interactive)
15884 (if (stringp org-agenda-files)
15885 (let ((cw (current-window-configuration)))
15886 (find-file org-agenda-files)
15887 (org-set-local 'org-window-configuration cw)
15888 (org-add-hook 'after-save-hook
15889 (lambda ()
15890 (set-window-configuration
15891 (prog1 org-window-configuration
15892 (kill-buffer (current-buffer))))
15893 (org-install-agenda-files-menu)
15894 (message "New agenda file list installed"))
15895 nil 'local)
15896 (message "%s" (substitute-command-keys
15897 "Edit list and finish with \\[save-buffer]")))
15898 (customize-variable 'org-agenda-files)))
15900 (defun org-store-new-agenda-file-list (list)
15901 "Set new value for the agenda file list and save it correctly."
15902 (if (stringp org-agenda-files)
15903 (let ((fe (org-read-agenda-file-list t)) b u)
15904 (while (setq b (find-buffer-visiting org-agenda-files))
15905 (kill-buffer b))
15906 (with-temp-file org-agenda-files
15907 (insert
15908 (mapconcat
15909 (lambda (f) ;; Keep un-expanded entries.
15910 (if (setq u (assoc f fe))
15911 (cdr u)
15913 list "\n")
15914 "\n")))
15915 (let ((org-mode-hook nil) (org-inhibit-startup t)
15916 (org-insert-mode-line-in-empty-file nil))
15917 (setq org-agenda-files list)
15918 (customize-save-variable 'org-agenda-files org-agenda-files))))
15920 (defun org-read-agenda-file-list (&optional pair-with-expansion)
15921 "Read the list of agenda files from a file.
15922 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
15923 filenames, used by `org-store-new-agenda-file-list' to write back
15924 un-expanded file names."
15925 (when (file-directory-p org-agenda-files)
15926 (error "`org-agenda-files' cannot be a single directory"))
15927 (when (stringp org-agenda-files)
15928 (with-temp-buffer
15929 (insert-file-contents org-agenda-files)
15930 (mapcar
15931 (lambda (f)
15932 (let ((e (expand-file-name (substitute-in-file-name f)
15933 org-directory)))
15934 (if pair-with-expansion
15935 (cons e f)
15936 e)))
15937 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
15939 ;;;###autoload
15940 (defun org-cycle-agenda-files ()
15941 "Cycle through the files in `org-agenda-files'.
15942 If the current buffer visits an agenda file, find the next one in the list.
15943 If the current buffer does not, find the first agenda file."
15944 (interactive)
15945 (let* ((fs (org-agenda-files t))
15946 (files (append fs (list (car fs))))
15947 (tcf (if buffer-file-name (file-truename buffer-file-name)))
15948 file)
15949 (unless files (error "No agenda files"))
15950 (catch 'exit
15951 (while (setq file (pop files))
15952 (if (equal (file-truename file) tcf)
15953 (when (car files)
15954 (find-file (car files))
15955 (throw 'exit t))))
15956 (find-file (car fs)))
15957 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
15959 (defun org-agenda-file-to-front (&optional to-end)
15960 "Move/add the current file to the top of the agenda file list.
15961 If the file is not present in the list, it is added to the front. If it is
15962 present, it is moved there. With optional argument TO-END, add/move to the
15963 end of the list."
15964 (interactive "P")
15965 (let ((org-agenda-skip-unavailable-files nil)
15966 (file-alist (mapcar (lambda (x)
15967 (cons (file-truename x) x))
15968 (org-agenda-files t)))
15969 (ctf (file-truename buffer-file-name))
15970 x had)
15971 (setq x (assoc ctf file-alist) had x)
15973 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
15974 (if to-end
15975 (setq file-alist (append (delq x file-alist) (list x)))
15976 (setq file-alist (cons x (delq x file-alist))))
15977 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
15978 (org-install-agenda-files-menu)
15979 (message "File %s to %s of agenda file list"
15980 (if had "moved" "added") (if to-end "end" "front"))))
15982 (defun org-remove-file (&optional file)
15983 "Remove current file from the list of files in variable `org-agenda-files'.
15984 These are the files which are being checked for agenda entries.
15985 Optional argument FILE means use this file instead of the current."
15986 (interactive)
15987 (let* ((org-agenda-skip-unavailable-files nil)
15988 (file (or file buffer-file-name))
15989 (true-file (file-truename file))
15990 (afile (abbreviate-file-name file))
15991 (files (delq nil (mapcar
15992 (lambda (x)
15993 (if (equal true-file
15994 (file-truename x))
15995 nil x))
15996 (org-agenda-files t)))))
15997 (if (not (= (length files) (length (org-agenda-files t))))
15998 (progn
15999 (org-store-new-agenda-file-list files)
16000 (org-install-agenda-files-menu)
16001 (message "Removed file: %s" afile))
16002 (message "File was not in list: %s (not removed)" afile))))
16004 (defun org-file-menu-entry (file)
16005 (vector file (list 'find-file file) t))
16007 (defun org-check-agenda-file (file)
16008 "Make sure FILE exists. If not, ask user what to do."
16009 (when (not (file-exists-p file))
16010 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
16011 (abbreviate-file-name file))
16012 (let ((r (downcase (read-char-exclusive))))
16013 (cond
16014 ((equal r ?r)
16015 (org-remove-file file)
16016 (throw 'nextfile t))
16017 (t (error "Abort"))))))
16019 (defun org-get-agenda-file-buffer (file)
16020 "Get a buffer visiting FILE. If the buffer needs to be created, add
16021 it to the list of buffers which might be released later."
16022 (let ((buf (org-find-base-buffer-visiting file)))
16023 (if buf
16024 buf ; just return it
16025 ;; Make a new buffer and remember it
16026 (setq buf (find-file-noselect file))
16027 (if buf (push buf org-agenda-new-buffers))
16028 buf)))
16030 (defun org-release-buffers (blist)
16031 "Release all buffers in list, asking the user for confirmation when needed.
16032 When a buffer is unmodified, it is just killed. When modified, it is saved
16033 \(if the user agrees) and then killed."
16034 (let (buf file)
16035 (while (setq buf (pop blist))
16036 (setq file (buffer-file-name buf))
16037 (when (and (buffer-modified-p buf)
16038 file
16039 (y-or-n-p (format "Save file %s? " file)))
16040 (with-current-buffer buf (save-buffer)))
16041 (kill-buffer buf))))
16043 (defun org-prepare-agenda-buffers (files)
16044 "Create buffers for all agenda files, protect archived trees and comments."
16045 (interactive)
16046 (let ((pa '(:org-archived t))
16047 (pc '(:org-comment t))
16048 (pall '(:org-archived t :org-comment t))
16049 (inhibit-read-only t)
16050 (rea (concat ":" org-archive-tag ":"))
16051 bmp file re)
16052 (save-excursion
16053 (save-restriction
16054 (while (setq file (pop files))
16055 (catch 'nextfile
16056 (if (bufferp file)
16057 (set-buffer file)
16058 (org-check-agenda-file file)
16059 (set-buffer (org-get-agenda-file-buffer file)))
16060 (widen)
16061 (setq bmp (buffer-modified-p))
16062 (org-refresh-category-properties)
16063 (setq org-todo-keywords-for-agenda
16064 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16065 (setq org-done-keywords-for-agenda
16066 (append org-done-keywords-for-agenda org-done-keywords))
16067 (setq org-todo-keyword-alist-for-agenda
16068 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
16069 (setq org-drawers-for-agenda
16070 (append org-drawers-for-agenda org-drawers))
16071 (setq org-tag-alist-for-agenda
16072 (append org-tag-alist-for-agenda org-tag-alist))
16074 (save-excursion
16075 (remove-text-properties (point-min) (point-max) pall)
16076 (when org-agenda-skip-archived-trees
16077 (goto-char (point-min))
16078 (while (re-search-forward rea nil t)
16079 (if (org-on-heading-p t)
16080 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16081 (goto-char (point-min))
16082 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
16083 (while (re-search-forward re nil t)
16084 (add-text-properties
16085 (match-beginning 0) (org-end-of-subtree t) pc)))
16086 (set-buffer-modified-p bmp)))))
16087 (setq org-todo-keywords-for-agenda
16088 (org-uniquify org-todo-keywords-for-agenda))
16089 (setq org-todo-keyword-alist-for-agenda
16090 (org-uniquify org-todo-keyword-alist-for-agenda)
16091 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
16093 ;;;; Embedded LaTeX
16095 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16096 "Keymap for the minor `org-cdlatex-mode'.")
16098 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16099 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16100 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16101 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16102 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16104 (defvar org-cdlatex-texmathp-advice-is-done nil
16105 "Flag remembering if we have applied the advice to texmathp already.")
16107 (define-minor-mode org-cdlatex-mode
16108 "Toggle the minor `org-cdlatex-mode'.
16109 This mode supports entering LaTeX environment and math in LaTeX fragments
16110 in Org-mode.
16111 \\{org-cdlatex-mode-map}"
16112 nil " OCDL" nil
16113 (when org-cdlatex-mode (require 'cdlatex))
16114 (unless org-cdlatex-texmathp-advice-is-done
16115 (setq org-cdlatex-texmathp-advice-is-done t)
16116 (defadvice texmathp (around org-math-always-on activate)
16117 "Always return t in org-mode buffers.
16118 This is because we want to insert math symbols without dollars even outside
16119 the LaTeX math segments. If Orgmode thinks that point is actually inside
16120 an embedded LaTeX fragment, let texmathp do its job.
16121 \\[org-cdlatex-mode-map]"
16122 (interactive)
16123 (let (p)
16124 (cond
16125 ((not (org-mode-p)) ad-do-it)
16126 ((eq this-command 'cdlatex-math-symbol)
16127 (setq ad-return-value t
16128 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16130 (let ((p (org-inside-LaTeX-fragment-p)))
16131 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16132 (setq ad-return-value t
16133 texmathp-why '("Org-mode embedded math" . 0))
16134 (if p ad-do-it)))))))))
16136 (defun turn-on-org-cdlatex ()
16137 "Unconditionally turn on `org-cdlatex-mode'."
16138 (org-cdlatex-mode 1))
16140 (defun org-inside-LaTeX-fragment-p ()
16141 "Test if point is inside a LaTeX fragment.
16142 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16143 sequence appearing also before point.
16144 Even though the matchers for math are configurable, this function assumes
16145 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16146 delimiters are skipped when they have been removed by customization.
16147 The return value is nil, or a cons cell with the delimiter and the
16148 position of this delimiter.
16150 This function does a reasonably good job, but can locally be fooled by
16151 for example currency specifications. For example it will assume being in
16152 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16153 fragments that are properly closed, but during editing, we have to live
16154 with the uncertainty caused by missing closing delimiters. This function
16155 looks only before point, not after."
16156 (catch 'exit
16157 (let ((pos (point))
16158 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16159 (lim (progn
16160 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16161 (point)))
16162 dd-on str (start 0) m re)
16163 (goto-char pos)
16164 (when dodollar
16165 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16166 re (nth 1 (assoc "$" org-latex-regexps)))
16167 (while (string-match re str start)
16168 (cond
16169 ((= (match-end 0) (length str))
16170 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16171 ((= (match-end 0) (- (length str) 5))
16172 (throw 'exit nil))
16173 (t (setq start (match-end 0))))))
16174 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16175 (goto-char pos)
16176 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16177 (and (match-beginning 2) (throw 'exit nil))
16178 ;; count $$
16179 (while (re-search-backward "\\$\\$" lim t)
16180 (setq dd-on (not dd-on)))
16181 (goto-char pos)
16182 (if dd-on (cons "$$" m))))))
16184 (defun org-inside-latex-macro-p ()
16185 "Is point inside a LaTeX macro or its arguments?"
16186 (save-match-data
16187 (org-in-regexp
16188 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
16190 (defun org-try-cdlatex-tab ()
16191 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16192 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16193 - inside a LaTeX fragment, or
16194 - after the first word in a line, where an abbreviation expansion could
16195 insert a LaTeX environment."
16196 (when org-cdlatex-mode
16197 (cond
16198 ((save-excursion
16199 (skip-chars-backward "a-zA-Z0-9*")
16200 (skip-chars-backward " \t")
16201 (bolp))
16202 (cdlatex-tab) t)
16203 ((org-inside-LaTeX-fragment-p)
16204 (cdlatex-tab) t)
16205 (t nil))))
16207 (defun org-cdlatex-underscore-caret (&optional arg)
16208 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16209 Revert to the normal definition outside of these fragments."
16210 (interactive "P")
16211 (if (org-inside-LaTeX-fragment-p)
16212 (call-interactively 'cdlatex-sub-superscript)
16213 (let (org-cdlatex-mode)
16214 (call-interactively (key-binding (vector last-input-event))))))
16216 (defun org-cdlatex-math-modify (&optional arg)
16217 "Execute `cdlatex-math-modify' in LaTeX fragments.
16218 Revert to the normal definition outside of these fragments."
16219 (interactive "P")
16220 (if (org-inside-LaTeX-fragment-p)
16221 (call-interactively 'cdlatex-math-modify)
16222 (let (org-cdlatex-mode)
16223 (call-interactively (key-binding (vector last-input-event))))))
16225 (defvar org-latex-fragment-image-overlays nil
16226 "List of overlays carrying the images of latex fragments.")
16227 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16229 (defun org-remove-latex-fragment-image-overlays ()
16230 "Remove all overlays with LaTeX fragment images in current buffer."
16231 (mapc 'delete-overlay org-latex-fragment-image-overlays)
16232 (setq org-latex-fragment-image-overlays nil))
16234 (defun org-preview-latex-fragment (&optional subtree)
16235 "Preview the LaTeX fragment at point, or all locally or globally.
16236 If the cursor is in a LaTeX fragment, create the image and overlay
16237 it over the source code. If there is no fragment at point, display
16238 all fragments in the current text, from one headline to the next. With
16239 prefix SUBTREE, display all fragments in the current subtree. With a
16240 double prefix arg \\[universal-argument] \\[universal-argument], or when \
16241 the cursor is before the first headline,
16242 display all fragments in the buffer.
16243 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16244 (interactive "P")
16245 (org-remove-latex-fragment-image-overlays)
16246 (save-excursion
16247 (save-restriction
16248 (let (beg end at msg)
16249 (cond
16250 ((or (equal subtree '(16))
16251 (not (save-excursion
16252 (re-search-backward (concat "^" outline-regexp) nil t))))
16253 (setq beg (point-min) end (point-max)
16254 msg "Creating images for buffer...%s"))
16255 ((equal subtree '(4))
16256 (org-back-to-heading)
16257 (setq beg (point) end (org-end-of-subtree t)
16258 msg "Creating images for subtree...%s"))
16260 (if (setq at (org-inside-LaTeX-fragment-p))
16261 (goto-char (max (point-min) (- (cdr at) 2)))
16262 (org-back-to-heading))
16263 (setq beg (point) end (progn (outline-next-heading) (point))
16264 msg (if at "Creating image...%s"
16265 "Creating images for entry...%s"))))
16266 (message msg "")
16267 (narrow-to-region beg end)
16268 (goto-char beg)
16269 (org-format-latex
16270 (concat "ltxpng/" (file-name-sans-extension
16271 (file-name-nondirectory
16272 buffer-file-name)))
16273 default-directory 'overlays msg at 'forbuffer 'dvipng)
16274 (message msg "done. Use `C-c C-c' to remove images.")))))
16276 (defvar org-latex-regexps
16277 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16278 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16279 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16280 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16281 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
16282 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16283 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
16284 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
16285 "Regular expressions for matching embedded LaTeX.")
16287 (defvar org-export-have-math nil) ;; dynamic scoping
16288 (defun org-format-latex (prefix &optional dir overlays msg at
16289 forbuffer processing-type)
16290 "Replace LaTeX fragments with links to an image, and produce images.
16291 Some of the options can be changed using the variable
16292 `org-format-latex-options'."
16293 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16294 (let* ((prefixnodir (file-name-nondirectory prefix))
16295 (absprefix (expand-file-name prefix dir))
16296 (todir (file-name-directory absprefix))
16297 (opt org-format-latex-options)
16298 (matchers (plist-get opt :matchers))
16299 (re-list org-latex-regexps)
16300 (org-format-latex-header-extra
16301 (plist-get (org-infile-export-plist) :latex-header-extra))
16302 (cnt 0) txt hash link beg end re e checkdir
16303 executables-checked string
16304 m n block linkfile movefile ov)
16305 ;; Check the different regular expressions
16306 (while (setq e (pop re-list))
16307 (setq m (car e) re (nth 1 e) n (nth 2 e)
16308 block (if (nth 3 e) "\n\n" ""))
16309 (when (member m matchers)
16310 (goto-char (point-min))
16311 (while (re-search-forward re nil t)
16312 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
16313 (not (get-text-property (match-beginning n)
16314 'org-protected))
16315 (or (not overlays)
16316 (not (eq (get-char-property (match-beginning n)
16317 'org-overlay-type)
16318 'org-latex-overlay))))
16319 (setq org-export-have-math t)
16320 (cond
16321 ((eq processing-type 'verbatim)
16322 ;; Leave the text verbatim, just protect it
16323 (add-text-properties (match-beginning n) (match-end n)
16324 '(org-protected t)))
16325 ((eq processing-type 'mathjax)
16326 ;; Prepare for MathJax processing
16327 (setq string (match-string n))
16328 (if (member m '("$" "$1"))
16329 (save-excursion
16330 (delete-region (match-beginning n) (match-end n))
16331 (goto-char (match-beginning n))
16332 (insert (org-add-props (concat "\\(" (substring string 1 -1)
16333 "\\)")
16334 '(org-protected t))))
16335 (add-text-properties (match-beginning n) (match-end n)
16336 '(org-protected t))))
16337 ((or (eq processing-type 'dvipng) t)
16338 ;; Process to an image
16339 (setq txt (match-string n)
16340 beg (match-beginning n) end (match-end n)
16341 cnt (1+ cnt))
16342 (let (print-length print-level) ; make sure full list is printed
16343 (setq hash (sha1 (prin1-to-string
16344 (list org-format-latex-header
16345 org-format-latex-header-extra
16346 org-export-latex-default-packages-alist
16347 org-export-latex-packages-alist
16348 org-format-latex-options
16349 forbuffer txt)))
16350 linkfile (format "%s_%s.png" prefix hash)
16351 movefile (format "%s_%s.png" absprefix hash)))
16352 (setq link (concat block "[[file:" linkfile "]]" block))
16353 (if msg (message msg cnt))
16354 (goto-char beg)
16355 (unless checkdir ; make sure the directory exists
16356 (setq checkdir t)
16357 (or (file-directory-p todir) (make-directory todir t)))
16359 (unless executables-checked
16360 (org-check-external-command
16361 "latex" "needed to convert LaTeX fragments to images")
16362 (org-check-external-command
16363 "dvipng" "needed to convert LaTeX fragments to images")
16364 (setq executables-checked t))
16366 (unless (file-exists-p movefile)
16367 (org-create-formula-image
16368 txt movefile opt forbuffer))
16369 (if overlays
16370 (progn
16371 (mapc (lambda (o)
16372 (if (eq (overlay-get o 'org-overlay-type)
16373 'org-latex-overlay)
16374 (delete-overlay o)))
16375 (overlays-in beg end))
16376 (setq ov (make-overlay beg end))
16377 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
16378 (if (featurep 'xemacs)
16379 (progn
16380 (overlay-put ov 'invisible t)
16381 (overlay-put
16382 ov 'end-glyph
16383 (make-glyph (vector 'png :file movefile))))
16384 (overlay-put
16385 ov 'display
16386 (list 'image :type 'png :file movefile :ascent 'center)))
16387 (push ov org-latex-fragment-image-overlays)
16388 (goto-char end))
16389 (delete-region beg end)
16390 (insert (org-add-props link
16391 (list 'org-latex-src
16392 (replace-regexp-in-string
16393 "\"" "" txt)))))))))))))
16395 ;; This function borrows from Ganesh Swami's latex2png.el
16396 (defun org-create-formula-image (string tofile options buffer)
16397 "This calls dvipng."
16398 (require 'org-latex)
16399 (let* ((tmpdir (if (featurep 'xemacs)
16400 (temp-directory)
16401 temporary-file-directory))
16402 (texfilebase (make-temp-name
16403 (expand-file-name "orgtex" tmpdir)))
16404 (texfile (concat texfilebase ".tex"))
16405 (dvifile (concat texfilebase ".dvi"))
16406 (pngfile (concat texfilebase ".png"))
16407 (fnh (if (featurep 'xemacs)
16408 (font-height (get-face-font 'default))
16409 (face-attribute 'default :height nil)))
16410 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
16411 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
16412 (fg (or (plist-get options (if buffer :foreground :html-foreground))
16413 "Black"))
16414 (bg (or (plist-get options (if buffer :background :html-background))
16415 "Transparent")))
16416 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
16417 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
16418 (with-temp-file texfile
16419 (insert (org-splice-latex-header
16420 org-format-latex-header
16421 org-export-latex-default-packages-alist
16422 org-export-latex-packages-alist t
16423 org-format-latex-header-extra))
16424 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
16425 (require 'org-latex)
16426 (org-export-latex-fix-inputenc))
16427 (let ((dir default-directory))
16428 (condition-case nil
16429 (progn
16430 (cd tmpdir)
16431 (call-process "latex" nil nil nil texfile))
16432 (error nil))
16433 (cd dir))
16434 (if (not (file-exists-p dvifile))
16435 (progn (message "Failed to create dvi file from %s" texfile) nil)
16436 (condition-case nil
16437 (call-process "dvipng" nil nil nil
16438 "-fg" fg "-bg" bg
16439 "-D" dpi
16440 ;;"-x" scale "-y" scale
16441 "-T" "tight"
16442 "-o" pngfile
16443 dvifile)
16444 (error nil))
16445 (if (not (file-exists-p pngfile))
16446 (if org-format-latex-signal-error
16447 (error "Failed to create png file from %s" texfile)
16448 (message "Failed to create png file from %s" texfile)
16449 nil)
16450 ;; Use the requested file name and clean up
16451 (copy-file pngfile tofile 'replace)
16452 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16453 (delete-file (concat texfilebase e)))
16454 pngfile))))
16456 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
16457 "Fill a LaTeX header template TPL.
16458 In the template, the following place holders will be recognized:
16460 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
16461 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
16462 [PACKAGES] \\usepackage statements for PKG
16463 [NO-PACKAGES] do not include PKG
16464 [EXTRA] the string EXTRA
16465 [NO-EXTRA] do not include EXTRA
16467 For backward compatibility, if both the positive and the negative place
16468 holder is missing, the positive one (without the \"NO-\") will be
16469 assumed to be present at the end of the template.
16470 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
16471 EXTRA is a string.
16472 SNIPPETS-P indicates if this is run to create snippet images for HTML."
16473 (let (rpl (end ""))
16474 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
16475 (setq rpl (if (or (match-end 1) (not def-pkg))
16476 "" (org-latex-packages-to-string def-pkg snippets-p t))
16477 tpl (replace-match rpl t t tpl))
16478 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
16480 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
16481 (setq rpl (if (or (match-end 1) (not pkg))
16482 "" (org-latex-packages-to-string pkg snippets-p t))
16483 tpl (replace-match rpl t t tpl))
16484 (if pkg (setq end
16485 (concat end "\n"
16486 (org-latex-packages-to-string pkg snippets-p)))))
16488 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
16489 (setq rpl (if (or (match-end 1) (not extra))
16490 "" (concat extra "\n"))
16491 tpl (replace-match rpl t t tpl))
16492 (if (and extra (string-match "\\S-" extra))
16493 (setq end (concat end "\n" extra))))
16495 (if (string-match "\\S-" end)
16496 (concat tpl "\n" end)
16497 tpl)))
16499 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
16500 "Turn an alist of packages into a string with the \\usepackage macros."
16501 (setq pkg (mapconcat (lambda(p)
16502 (cond
16503 ((stringp p) p)
16504 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
16505 (format "%% Package %s omitted" (cadr p)))
16506 ((equal "" (car p))
16507 (format "\\usepackage{%s}" (cadr p)))
16509 (format "\\usepackage[%s]{%s}"
16510 (car p) (cadr p)))))
16512 "\n"))
16513 (if newline (concat pkg "\n") pkg))
16515 (defun org-dvipng-color (attr)
16516 "Return an rgb color specification for dvipng."
16517 (apply 'format "rgb %s %s %s"
16518 (mapcar 'org-normalize-color
16519 (color-values (face-attribute 'default attr nil)))))
16521 (defun org-normalize-color (value)
16522 "Return string to be used as color value for an RGB component."
16523 (format "%g" (/ value 65535.0)))
16525 ;; Image display
16528 (defvar org-inline-image-overlays nil)
16529 (make-variable-buffer-local 'org-inline-image-overlays)
16531 (defun org-toggle-inline-images (&optional include-linked)
16532 "Toggle the display of inline images.
16533 INCLUDE-LINKED is passed to `org-display-inline-images'."
16534 (interactive "P")
16535 (if org-inline-image-overlays
16536 (progn
16537 (org-remove-inline-images)
16538 (message "Inline image display turned off"))
16539 (org-display-inline-images include-linked)
16540 (if org-inline-image-overlays
16541 (message "%d images displayed inline"
16542 (length org-inline-image-overlays))
16543 (message "No images to display inline"))))
16545 (defun org-display-inline-images (&optional include-linked refresh beg end)
16546 "Display inline images.
16547 Normally only links without a description part are inlined, because this
16548 is how it will work for export. When INCLUDE-LINKED is set, also links
16549 with a description part will be inlined. This can be nice for a quick
16550 look at those images, but it does not reflect what exported files will look
16551 like.
16552 When REFRESH is set, refresh existing images between BEG and END.
16553 This will create new image displays only if necessary.
16554 BEG and END default to the buffer boundaries."
16555 (interactive "P")
16556 (unless refresh
16557 (org-remove-inline-images)
16558 (if (fboundp 'clear-image-cache) (clear-image-cache)))
16559 (save-excursion
16560 (save-restriction
16561 (widen)
16562 (setq beg (or beg (point-min)) end (or end (point-max)))
16563 (goto-char (point-min))
16564 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
16565 (substring (org-image-file-name-regexp) 0 -2)
16566 "\\)\\]" (if include-linked "" "\\]")))
16567 old file ov img)
16568 (while (re-search-forward re end t)
16569 (setq old (get-char-property-and-overlay (match-beginning 1)
16570 'org-image-overlay))
16571 (setq file (expand-file-name
16572 (concat (or (match-string 3) "") (match-string 4))))
16573 (when (file-exists-p file)
16574 (if (and (car-safe old) refresh)
16575 (image-refresh (overlay-get (cdr old) 'display))
16576 (setq img (save-match-data (create-image file)))
16577 (when img
16578 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
16579 (overlay-put ov 'display img)
16580 (overlay-put ov 'face 'default)
16581 (overlay-put ov 'org-image-overlay t)
16582 (overlay-put ov 'modification-hooks
16583 (list 'org-display-inline-modification-hook))
16584 (push ov org-inline-image-overlays)))))))))
16586 (defun org-display-inline-modification-hook (ov after beg end &optional len)
16587 "Remove inline-display overlay if a corresponding region is modified."
16588 (let ((inhibit-modification-hooks t))
16589 (when (and ov after)
16590 (delete ov org-inline-image-overlays)
16591 (delete-overlay ov))))
16593 (defun org-remove-inline-images ()
16594 "Remove inline display of images."
16595 (interactive)
16596 (mapc 'delete-overlay org-inline-image-overlays)
16597 (setq org-inline-image-overlays nil))
16599 ;;;; Key bindings
16601 ;; Make `C-c C-x' a prefix key
16602 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
16604 ;; TAB key with modifiers
16605 (org-defkey org-mode-map "\C-i" 'org-cycle)
16606 (org-defkey org-mode-map [(tab)] 'org-cycle)
16607 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
16608 (org-defkey org-mode-map [(meta tab)] 'pcomplete)
16609 (org-defkey org-mode-map "\M-\t" 'pcomplete)
16610 (org-defkey org-mode-map "\M-\C-i" 'pcomplete)
16611 ;; The following line is necessary under Suse GNU/Linux
16612 (unless (featurep 'xemacs)
16613 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
16614 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
16615 (define-key org-mode-map [backtab] 'org-shifttab)
16617 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
16618 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
16619 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
16621 ;; Cursor keys with modifiers
16622 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
16623 (org-defkey org-mode-map [(meta right)] 'org-metaright)
16624 (org-defkey org-mode-map [(meta up)] 'org-metaup)
16625 (org-defkey org-mode-map [(meta down)] 'org-metadown)
16627 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
16628 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
16629 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
16630 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
16632 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
16633 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
16634 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
16635 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
16637 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
16638 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
16640 ;; Babel keys
16641 (define-key org-mode-map org-babel-key-prefix org-babel-map)
16642 (mapc (lambda (pair)
16643 (define-key org-babel-map (car pair) (cdr pair)))
16644 org-babel-key-bindings)
16646 ;;; Extra keys for tty access.
16647 ;; We only set them when really needed because otherwise the
16648 ;; menus don't show the simple keys
16650 (when (or org-use-extra-keys
16651 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
16652 (not window-system))
16653 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
16654 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
16655 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
16656 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
16657 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
16658 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
16659 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
16660 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
16661 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
16662 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
16663 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
16664 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
16665 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
16666 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
16667 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
16668 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
16669 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
16670 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
16671 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
16672 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
16673 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
16674 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
16675 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
16676 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
16677 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
16678 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
16679 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
16680 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
16682 ;; All the other keys
16684 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
16685 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
16686 (if (boundp 'narrow-map)
16687 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
16688 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
16689 (if (boundp 'narrow-map)
16690 (org-defkey narrow-map "b" 'org-narrow-to-block)
16691 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
16692 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
16693 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
16694 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
16695 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
16696 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
16697 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
16698 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
16699 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
16700 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
16701 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
16702 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
16703 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
16704 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
16705 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
16706 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
16707 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
16708 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
16709 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
16710 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
16711 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
16712 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
16713 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
16714 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
16715 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
16716 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
16717 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
16718 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
16719 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
16720 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
16721 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
16722 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
16723 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
16724 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
16725 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
16726 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
16727 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
16728 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
16729 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
16730 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
16731 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
16732 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16733 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
16734 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
16735 (org-defkey org-mode-map "\C-c^" 'org-sort)
16736 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
16737 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
16738 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
16739 (org-defkey org-mode-map "\C-m" 'org-return)
16740 (org-defkey org-mode-map "\C-j" 'org-return-indent)
16741 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
16742 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
16743 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
16744 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
16745 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
16746 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
16747 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
16748 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
16749 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
16750 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
16751 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
16752 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
16753 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
16754 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
16755 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
16756 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
16757 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
16758 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
16759 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
16760 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
16761 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
16763 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
16764 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
16765 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
16766 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
16768 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
16769 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
16770 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
16771 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
16772 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
16773 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
16774 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
16775 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
16776 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
16777 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
16778 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
16779 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
16780 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
16781 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
16782 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
16783 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
16784 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
16785 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
16787 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
16788 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
16789 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
16790 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
16791 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
16793 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
16795 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
16797 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
16798 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
16800 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
16803 (when (featurep 'xemacs)
16804 (org-defkey org-mode-map 'button3 'popup-mode-menu))
16807 (defconst org-speed-commands-default
16809 ("Outline Navigation")
16810 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
16811 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
16812 ("f" . (org-speed-move-safe 'org-forward-same-level))
16813 ("b" . (org-speed-move-safe 'org-backward-same-level))
16814 ("u" . (org-speed-move-safe 'outline-up-heading))
16815 ("j" . org-goto)
16816 ("g" . (org-refile t))
16817 ("Outline Visibility")
16818 ("c" . org-cycle)
16819 ("C" . org-shifttab)
16820 (" " . org-display-outline-path)
16821 ("Outline Structure Editing")
16822 ("U" . org-shiftmetaup)
16823 ("D" . org-shiftmetadown)
16824 ("r" . org-metaright)
16825 ("l" . org-metaleft)
16826 ("R" . org-shiftmetaright)
16827 ("L" . org-shiftmetaleft)
16828 ("i" . (progn (forward-char 1) (call-interactively
16829 'org-insert-heading-respect-content)))
16830 ("^" . org-sort)
16831 ("w" . org-refile)
16832 ("a" . org-archive-subtree-default-with-confirmation)
16833 ("." . org-mark-subtree)
16834 ("Clock Commands")
16835 ("I" . org-clock-in)
16836 ("O" . org-clock-out)
16837 ("Meta Data Editing")
16838 ("t" . org-todo)
16839 ("0" . (org-priority ?\ ))
16840 ("1" . (org-priority ?A))
16841 ("2" . (org-priority ?B))
16842 ("3" . (org-priority ?C))
16843 (";" . org-set-tags-command)
16844 ("e" . org-set-effort)
16845 ("Agenda Views etc")
16846 ("v" . org-agenda)
16847 ("/" . org-sparse-tree)
16848 ("Misc")
16849 ("o" . org-open-at-point)
16850 ("?" . org-speed-command-help)
16851 ("<" . (org-agenda-set-restriction-lock 'subtree))
16852 (">" . (org-agenda-remove-restriction-lock))
16854 "The default speed commands.")
16856 (defun org-print-speed-command (e)
16857 (if (> (length (car e)) 1)
16858 (progn
16859 (princ "\n")
16860 (princ (car e))
16861 (princ "\n")
16862 (princ (make-string (length (car e)) ?-))
16863 (princ "\n"))
16864 (princ (car e))
16865 (princ " ")
16866 (if (symbolp (cdr e))
16867 (princ (symbol-name (cdr e)))
16868 (prin1 (cdr e)))
16869 (princ "\n")))
16871 (defun org-speed-command-help ()
16872 "Show the available speed commands."
16873 (interactive)
16874 (if (not org-use-speed-commands)
16875 (error "Speed commands are not activated, customize `org-use-speed-commands'")
16876 (with-output-to-temp-buffer "*Help*"
16877 (princ "User-defined Speed commands\n===========================\n")
16878 (mapc 'org-print-speed-command org-speed-commands-user)
16879 (princ "\n")
16880 (princ "Built-in Speed commands\n=======================\n")
16881 (mapc 'org-print-speed-command org-speed-commands-default))
16882 (with-current-buffer "*Help*"
16883 (setq truncate-lines t))))
16885 (defun org-speed-move-safe (cmd)
16886 "Execute CMD, but make sure that the cursor always ends up in a headline.
16887 If not, return to the original position and throw an error."
16888 (interactive)
16889 (let ((pos (point)))
16890 (call-interactively cmd)
16891 (unless (and (bolp) (org-on-heading-p))
16892 (goto-char pos)
16893 (error "Boundary reached while executing %s" cmd))))
16895 (defvar org-self-insert-command-undo-counter 0)
16897 (defvar org-table-auto-blank-field) ; defined in org-table.el
16898 (defvar org-speed-command nil)
16900 (defun org-speed-command-default-hook (keys)
16901 "Hook for activating single-letter speed commands.
16902 `org-speed-commands-default' specifies a minimal command set. Use
16903 `org-speed-commands-user' for further customization."
16904 (when (or (and (bolp) (looking-at outline-regexp))
16905 (and (functionp org-use-speed-commands)
16906 (funcall org-use-speed-commands)))
16907 (cdr (assoc keys (append org-speed-commands-user
16908 org-speed-commands-default)))))
16910 (defun org-babel-speed-command-hook (keys)
16911 "Hook for activating single-letter code block commands."
16912 (when (and (bolp) (looking-at org-babel-src-block-regexp))
16913 (cdr (assoc keys org-babel-key-bindings))))
16915 (defcustom org-speed-command-hook
16916 '(org-speed-command-default-hook org-babel-speed-command-hook)
16917 "Hook for activating speed commands at strategic locations.
16918 Hook functions are called in sequence until a valid handler is
16919 found.
16921 Each hook takes a single argument, a user-pressed command key
16922 which is also a `self-insert-command' from the global map.
16924 Within the hook, examine the cursor position and the command key
16925 and return nil or a valid handler as appropriate. Handler could
16926 be one of an interactive command, a function, or a form.
16928 Set `org-use-speed-commands' to non-nil value to enable this
16929 hook. The default setting is `org-speed-command-default-hook'."
16930 :group 'org-structure
16931 :type 'hook)
16933 (defun org-self-insert-command (N)
16934 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
16935 If the cursor is in a table looking at whitespace, the whitespace is
16936 overwritten, and the table is not marked as requiring realignment."
16937 (interactive "p")
16938 (cond
16939 ((and org-use-speed-commands
16940 (setq org-speed-command
16941 (run-hook-with-args-until-success
16942 'org-speed-command-hook (this-command-keys))))
16943 (cond
16944 ((commandp org-speed-command)
16945 (setq this-command org-speed-command)
16946 (call-interactively org-speed-command))
16947 ((functionp org-speed-command)
16948 (funcall org-speed-command))
16949 ((and org-speed-command (listp org-speed-command))
16950 (eval org-speed-command))
16951 (t (let (org-use-speed-commands)
16952 (call-interactively 'org-self-insert-command)))))
16953 ((and
16954 (org-table-p)
16955 (progn
16956 ;; check if we blank the field, and if that triggers align
16957 (and (featurep 'org-table) org-table-auto-blank-field
16958 (member last-command
16959 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
16960 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
16961 ;; got extra space, this field does not determine column width
16962 (let (org-table-may-need-update) (org-table-blank-field))
16963 ;; no extra space, this field may determine column width
16964 (org-table-blank-field)))
16966 (eq N 1)
16967 (looking-at "[^|\n]* |"))
16968 (let (org-table-may-need-update)
16969 (goto-char (1- (match-end 0)))
16970 (delete-char -1)
16971 (goto-char (match-beginning 0))
16972 (self-insert-command N)))
16974 (setq org-table-may-need-update t)
16975 (self-insert-command N)
16976 (org-fix-tags-on-the-fly)
16977 (if org-self-insert-cluster-for-undo
16978 (if (not (eq last-command 'org-self-insert-command))
16979 (setq org-self-insert-command-undo-counter 1)
16980 (if (>= org-self-insert-command-undo-counter 20)
16981 (setq org-self-insert-command-undo-counter 1)
16982 (and (> org-self-insert-command-undo-counter 0)
16983 buffer-undo-list (listp buffer-undo-list)
16984 (not (cadr buffer-undo-list)) ; remove nil entry
16985 (setcdr buffer-undo-list (cddr buffer-undo-list)))
16986 (setq org-self-insert-command-undo-counter
16987 (1+ org-self-insert-command-undo-counter))))))))
16989 (defun org-fix-tags-on-the-fly ()
16990 (when (and (equal (char-after (point-at-bol)) ?*)
16991 (org-on-heading-p))
16992 (org-align-tags-here org-tags-column)))
16994 (defun org-delete-backward-char (N)
16995 "Like `delete-backward-char', insert whitespace at field end in tables.
16996 When deleting backwards, in tables this function will insert whitespace in
16997 front of the next \"|\" separator, to keep the table aligned. The table will
16998 still be marked for re-alignment if the field did fill the entire column,
16999 because, in this case the deletion might narrow the column."
17000 (interactive "p")
17001 (if (and (org-table-p)
17002 (eq N 1)
17003 (string-match "|" (buffer-substring (point-at-bol) (point)))
17004 (looking-at ".*?|"))
17005 (let ((pos (point))
17006 (noalign (looking-at "[^|\n\r]* |"))
17007 (c org-table-may-need-update))
17008 (backward-delete-char N)
17009 (if (not overwrite-mode)
17010 (progn
17011 (skip-chars-forward "^|")
17012 (insert " ")
17013 (goto-char (1- pos))))
17014 ;; noalign: if there were two spaces at the end, this field
17015 ;; does not determine the width of the column.
17016 (if noalign (setq org-table-may-need-update c)))
17017 (backward-delete-char N)
17018 (org-fix-tags-on-the-fly)))
17020 (defun org-delete-char (N)
17021 "Like `delete-char', but insert whitespace at field end in tables.
17022 When deleting characters, in tables this function will insert whitespace in
17023 front of the next \"|\" separator, to keep the table aligned. The table will
17024 still be marked for re-alignment if the field did fill the entire column,
17025 because, in this case the deletion might narrow the column."
17026 (interactive "p")
17027 (if (and (org-table-p)
17028 (not (bolp))
17029 (not (= (char-after) ?|))
17030 (eq N 1))
17031 (if (looking-at ".*?|")
17032 (let ((pos (point))
17033 (noalign (looking-at "[^|\n\r]* |"))
17034 (c org-table-may-need-update))
17035 (replace-match (concat
17036 (substring (match-string 0) 1 -1)
17037 " |"))
17038 (goto-char pos)
17039 ;; noalign: if there were two spaces at the end, this field
17040 ;; does not determine the width of the column.
17041 (if noalign (setq org-table-may-need-update c)))
17042 (delete-char N))
17043 (delete-char N)
17044 (org-fix-tags-on-the-fly)))
17046 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17047 (put 'org-self-insert-command 'delete-selection t)
17048 (put 'orgtbl-self-insert-command 'delete-selection t)
17049 (put 'org-delete-char 'delete-selection 'supersede)
17050 (put 'org-delete-backward-char 'delete-selection 'supersede)
17051 (put 'org-yank 'delete-selection 'yank)
17053 ;; Make `flyspell-mode' delay after some commands
17054 (put 'org-self-insert-command 'flyspell-delayed t)
17055 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
17056 (put 'org-delete-char 'flyspell-delayed t)
17057 (put 'org-delete-backward-char 'flyspell-delayed t)
17059 ;; Make pabbrev-mode expand after org-mode commands
17060 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
17061 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
17063 ;; How to do this: Measure non-white length of current string
17064 ;; If equal to column width, we should realign.
17066 (defun org-remap (map &rest commands)
17067 "In MAP, remap the functions given in COMMANDS.
17068 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17069 (let (new old)
17070 (while commands
17071 (setq old (pop commands) new (pop commands))
17072 (if (fboundp 'command-remapping)
17073 (org-defkey map (vector 'remap old) new)
17074 (substitute-key-definition old new map global-map)))))
17076 (when (eq org-enable-table-editor 'optimized)
17077 ;; If the user wants maximum table support, we need to hijack
17078 ;; some standard editing functions
17079 (org-remap org-mode-map
17080 'self-insert-command 'org-self-insert-command
17081 'delete-char 'org-delete-char
17082 'delete-backward-char 'org-delete-backward-char)
17083 (org-defkey org-mode-map "|" 'org-force-self-insert))
17085 (defvar org-ctrl-c-ctrl-c-hook nil
17086 "Hook for functions attaching themselves to `C-c C-c'.
17087 This can be used to add additional functionality to the C-c C-c key which
17088 executes context-dependent commands.
17089 Each function will be called with no arguments. The function must check
17090 if the context is appropriate for it to act. If yes, it should do its
17091 thing and then return a non-nil value. If the context is wrong,
17092 just do nothing and return nil.")
17094 (defvar org-tab-first-hook nil
17095 "Hook for functions to attach themselves to TAB.
17096 See `org-ctrl-c-ctrl-c-hook' for more information.
17097 This hook runs as the first action when TAB is pressed, even before
17098 `org-cycle' messes around with the `outline-regexp' to cater for
17099 inline tasks and plain list item folding.
17100 If any function in this hook returns t, any other actions that
17101 would have been caused by TAB (such as table field motion or visibility
17102 cycling) will not occur.")
17104 (defvar org-tab-after-check-for-table-hook nil
17105 "Hook for functions to attach themselves to TAB.
17106 See `org-ctrl-c-ctrl-c-hook' for more information.
17107 This hook runs after it has been established that the cursor is not in a
17108 table, but before checking if the cursor is in a headline or if global cycling
17109 should be done.
17110 If any function in this hook returns t, not other actions like visibility
17111 cycling will be done.")
17113 (defvar org-tab-after-check-for-cycling-hook nil
17114 "Hook for functions to attach themselves to TAB.
17115 See `org-ctrl-c-ctrl-c-hook' for more information.
17116 This hook runs after it has been established that not table field motion and
17117 not visibility should be done because of current context. This is probably
17118 the place where a package like yasnippets can hook in.")
17120 (defvar org-tab-before-tab-emulation-hook nil
17121 "Hook for functions to attach themselves to TAB.
17122 See `org-ctrl-c-ctrl-c-hook' for more information.
17123 This hook runs after every other options for TAB have been exhausted, but
17124 before indentation and \t insertion takes place.")
17126 (defvar org-metaleft-hook nil
17127 "Hook for functions attaching themselves to `M-left'.
17128 See `org-ctrl-c-ctrl-c-hook' for more information.")
17129 (defvar org-metaright-hook nil
17130 "Hook for functions attaching themselves to `M-right'.
17131 See `org-ctrl-c-ctrl-c-hook' for more information.")
17132 (defvar org-metaup-hook nil
17133 "Hook for functions attaching themselves to `M-up'.
17134 See `org-ctrl-c-ctrl-c-hook' for more information.")
17135 (defvar org-metadown-hook nil
17136 "Hook for functions attaching themselves to `M-down'.
17137 See `org-ctrl-c-ctrl-c-hook' for more information.")
17138 (defvar org-shiftmetaleft-hook nil
17139 "Hook for functions attaching themselves to `M-S-left'.
17140 See `org-ctrl-c-ctrl-c-hook' for more information.")
17141 (defvar org-shiftmetaright-hook nil
17142 "Hook for functions attaching themselves to `M-S-right'.
17143 See `org-ctrl-c-ctrl-c-hook' for more information.")
17144 (defvar org-shiftmetaup-hook nil
17145 "Hook for functions attaching themselves to `M-S-up'.
17146 See `org-ctrl-c-ctrl-c-hook' for more information.")
17147 (defvar org-shiftmetadown-hook nil
17148 "Hook for functions attaching themselves to `M-S-down'.
17149 See `org-ctrl-c-ctrl-c-hook' for more information.")
17150 (defvar org-metareturn-hook nil
17151 "Hook for functions attaching themselves to `M-RET'.
17152 See `org-ctrl-c-ctrl-c-hook' for more information.")
17153 (defvar org-shiftup-hook nil
17154 "Hook for functions attaching themselves to `S-up'.
17155 See `org-ctrl-c-ctrl-c-hook' for more information.")
17156 (defvar org-shiftup-final-hook nil
17157 "Hook for functions attaching themselves to `S-up'.
17158 This one runs after all other options except shift-select have been excluded.
17159 See `org-ctrl-c-ctrl-c-hook' for more information.")
17160 (defvar org-shiftdown-hook nil
17161 "Hook for functions attaching themselves to `S-down'.
17162 See `org-ctrl-c-ctrl-c-hook' for more information.")
17163 (defvar org-shiftdown-final-hook nil
17164 "Hook for functions attaching themselves to `S-down'.
17165 This one runs after all other options except shift-select have been excluded.
17166 See `org-ctrl-c-ctrl-c-hook' for more information.")
17167 (defvar org-shiftleft-hook nil
17168 "Hook for functions attaching themselves to `S-left'.
17169 See `org-ctrl-c-ctrl-c-hook' for more information.")
17170 (defvar org-shiftleft-final-hook nil
17171 "Hook for functions attaching themselves to `S-left'.
17172 This one runs after all other options except shift-select have been excluded.
17173 See `org-ctrl-c-ctrl-c-hook' for more information.")
17174 (defvar org-shiftright-hook nil
17175 "Hook for functions attaching themselves to `S-right'.
17176 See `org-ctrl-c-ctrl-c-hook' for more information.")
17177 (defvar org-shiftright-final-hook nil
17178 "Hook for functions attaching themselves to `S-right'.
17179 This one runs after all other options except shift-select have been excluded.
17180 See `org-ctrl-c-ctrl-c-hook' for more information.")
17182 (defun org-modifier-cursor-error ()
17183 "Throw an error, a modified cursor command was applied in wrong context."
17184 (error "This command is active in special context like tables, headlines or items"))
17186 (defun org-shiftselect-error ()
17187 "Throw an error because Shift-Cursor command was applied in wrong context."
17188 (if (and (boundp 'shift-select-mode) shift-select-mode)
17189 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
17190 (error "This command works only in special context like headlines or timestamps")))
17192 (defun org-call-for-shift-select (cmd)
17193 (let ((this-command-keys-shift-translated t))
17194 (call-interactively cmd)))
17196 (defun org-shifttab (&optional arg)
17197 "Global visibility cycling or move to previous table field.
17198 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17199 on context.
17200 See the individual commands for more information."
17201 (interactive "P")
17202 (cond
17203 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17204 ((integerp arg)
17205 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
17206 (message "Content view to level: %d" arg)
17207 (org-content (prefix-numeric-value arg2))
17208 (setq org-cycle-global-status 'overview)))
17209 (t (call-interactively 'org-global-cycle))))
17211 (defun org-shiftmetaleft ()
17212 "Promote subtree or delete table column.
17213 Calls `org-promote-subtree', `org-outdent-item',
17214 or `org-table-delete-column', depending on context.
17215 See the individual commands for more information."
17216 (interactive)
17217 (cond
17218 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
17219 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17220 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
17221 ((org-at-item-p) (call-interactively 'org-outdent-item-tree))
17222 (t (org-modifier-cursor-error))))
17224 (defun org-shiftmetaright ()
17225 "Demote subtree or insert table column.
17226 Calls `org-demote-subtree', `org-indent-item',
17227 or `org-table-insert-column', depending on context.
17228 See the individual commands for more information."
17229 (interactive)
17230 (cond
17231 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
17232 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17233 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
17234 ((org-at-item-p) (call-interactively 'org-indent-item-tree))
17235 (t (org-modifier-cursor-error))))
17237 (defun org-shiftmetaup (&optional arg)
17238 "Move subtree up or kill table row.
17239 Calls `org-move-subtree-up' or `org-table-kill-row' or
17240 `org-move-item-up' depending on context. See the individual commands
17241 for more information."
17242 (interactive "P")
17243 (cond
17244 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
17245 ((org-at-table-p) (call-interactively 'org-table-kill-row))
17246 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17247 ((org-at-item-p) (call-interactively 'org-move-item-up))
17248 (t (org-modifier-cursor-error))))
17250 (defun org-shiftmetadown (&optional arg)
17251 "Move subtree down or insert table row.
17252 Calls `org-move-subtree-down' or `org-table-insert-row' or
17253 `org-move-item-down', depending on context. See the individual
17254 commands for more information."
17255 (interactive "P")
17256 (cond
17257 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
17258 ((org-at-table-p) (call-interactively 'org-table-insert-row))
17259 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17260 ((org-at-item-p) (call-interactively 'org-move-item-down))
17261 (t (org-modifier-cursor-error))))
17263 (defsubst org-hidden-tree-error ()
17264 (error
17265 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
17267 (defun org-metaleft (&optional arg)
17268 "Promote heading or move table column to left.
17269 Calls `org-do-promote' or `org-table-move-column', depending on context.
17270 With no specific context, calls the Emacs default `backward-word'.
17271 See the individual commands for more information."
17272 (interactive "P")
17273 (cond
17274 ((run-hook-with-args-until-success 'org-metaleft-hook))
17275 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
17276 ((org-with-limited-levels
17277 (or (org-on-heading-p)
17278 (and (org-region-active-p)
17279 (save-excursion
17280 (goto-char (region-beginning))
17281 (org-on-heading-p)))))
17282 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17283 (call-interactively 'org-do-promote))
17284 ;; At an inline task.
17285 ((org-on-heading-p)
17286 (call-interactively 'org-inlinetask-promote))
17287 ((or (org-at-item-p)
17288 (and (org-region-active-p)
17289 (save-excursion
17290 (goto-char (region-beginning))
17291 (org-at-item-p))))
17292 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17293 (call-interactively 'org-outdent-item))
17294 (t (call-interactively 'backward-word))))
17296 (defun org-metaright (&optional arg)
17297 "Demote subtree or move table column to right.
17298 Calls `org-do-demote' or `org-table-move-column', depending on context.
17299 With no specific context, calls the Emacs default `forward-word'.
17300 See the individual commands for more information."
17301 (interactive "P")
17302 (cond
17303 ((run-hook-with-args-until-success 'org-metaright-hook))
17304 ((org-at-table-p) (call-interactively 'org-table-move-column))
17305 ((org-with-limited-levels
17306 (or (org-on-heading-p)
17307 (and (org-region-active-p)
17308 (save-excursion
17309 (goto-char (region-beginning))
17310 (org-on-heading-p)))))
17311 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
17312 (call-interactively 'org-do-demote))
17313 ;; At an inline task.
17314 ((org-on-heading-p)
17315 (call-interactively 'org-inlinetask-demote))
17316 ((or (org-at-item-p)
17317 (and (org-region-active-p)
17318 (save-excursion
17319 (goto-char (region-beginning))
17320 (org-at-item-p))))
17321 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
17322 (call-interactively 'org-indent-item))
17323 (t (call-interactively 'forward-word))))
17325 (defun org-check-for-hidden (what)
17326 "Check if there are hidden headlines/items in the current visual line.
17327 WHAT can be either `headlines' or `items'. If the current line is
17328 an outline or item heading and it has a folded subtree below it,
17329 this function returns t, nil otherwise."
17330 (let ((re (cond
17331 ((eq what 'headlines) (concat "^" org-outline-regexp))
17332 ((eq what 'items) (org-item-beginning-re))
17333 (t (error "This should not happen"))))
17334 beg end)
17335 (save-excursion
17336 (catch 'exit
17337 (unless (org-region-active-p)
17338 (setq beg (point-at-bol))
17339 (beginning-of-line 2)
17340 (while (and (not (eobp)) ;; this is like `next-line'
17341 (get-char-property (1- (point)) 'invisible))
17342 (beginning-of-line 2))
17343 (setq end (point))
17344 (goto-char beg)
17345 (goto-char (point-at-eol))
17346 (setq end (max end (point)))
17347 (while (re-search-forward re end t)
17348 (if (get-char-property (match-beginning 0) 'invisible)
17349 (throw 'exit t))))
17350 nil))))
17352 (defun org-metaup (&optional arg)
17353 "Move subtree up or move table row up.
17354 Calls `org-move-subtree-up' or `org-table-move-row' or
17355 `org-move-item-up', depending on context. See the individual commands
17356 for more information."
17357 (interactive "P")
17358 (cond
17359 ((run-hook-with-args-until-success 'org-metaup-hook))
17360 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
17361 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17362 ((org-at-item-p) (call-interactively 'org-move-item-up))
17363 (t (transpose-lines 1) (beginning-of-line -1))))
17365 (defun org-metadown (&optional arg)
17366 "Move subtree down or move table row down.
17367 Calls `org-move-subtree-down' or `org-table-move-row' or
17368 `org-move-item-down', depending on context. See the individual
17369 commands for more information."
17370 (interactive "P")
17371 (cond
17372 ((run-hook-with-args-until-success 'org-metadown-hook))
17373 ((org-at-table-p) (call-interactively 'org-table-move-row))
17374 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17375 ((org-at-item-p) (call-interactively 'org-move-item-down))
17376 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
17378 (defun org-shiftup (&optional arg)
17379 "Increase item in timestamp or increase priority of current headline.
17380 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
17381 depending on context. See the individual commands for more information."
17382 (interactive "P")
17383 (cond
17384 ((run-hook-with-args-until-success 'org-shiftup-hook))
17385 ((and org-support-shift-select (org-region-active-p))
17386 (org-call-for-shift-select 'previous-line))
17387 ((org-at-timestamp-p t)
17388 (call-interactively (if org-edit-timestamp-down-means-later
17389 'org-timestamp-down 'org-timestamp-up)))
17390 ((and (not (eq org-support-shift-select 'always))
17391 org-enable-priority-commands
17392 (org-on-heading-p))
17393 (call-interactively 'org-priority-up))
17394 ((and (not org-support-shift-select) (org-at-item-p))
17395 (call-interactively 'org-previous-item))
17396 ((org-clocktable-try-shift 'up arg))
17397 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
17398 (org-support-shift-select
17399 (org-call-for-shift-select 'previous-line))
17400 (t (org-shiftselect-error))))
17402 (defun org-shiftdown (&optional arg)
17403 "Decrease item in timestamp or decrease priority of current headline.
17404 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
17405 depending on context. See the individual commands for more information."
17406 (interactive "P")
17407 (cond
17408 ((run-hook-with-args-until-success 'org-shiftdown-hook))
17409 ((and org-support-shift-select (org-region-active-p))
17410 (org-call-for-shift-select 'next-line))
17411 ((org-at-timestamp-p t)
17412 (call-interactively (if org-edit-timestamp-down-means-later
17413 'org-timestamp-up 'org-timestamp-down)))
17414 ((and (not (eq org-support-shift-select 'always))
17415 org-enable-priority-commands
17416 (org-on-heading-p))
17417 (call-interactively 'org-priority-down))
17418 ((and (not org-support-shift-select) (org-at-item-p))
17419 (call-interactively 'org-next-item))
17420 ((org-clocktable-try-shift 'down arg))
17421 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
17422 (org-support-shift-select
17423 (org-call-for-shift-select 'next-line))
17424 (t (org-shiftselect-error))))
17426 (defun org-shiftright (&optional arg)
17427 "Cycle the thing at point or in the current line, depending on context.
17428 Depending on context, this does one of the following:
17430 - switch a timestamp at point one day into the future
17431 - on a headline, switch to the next TODO keyword.
17432 - on an item, switch entire list to the next bullet type
17433 - on a property line, switch to the next allowed value
17434 - on a clocktable definition line, move time block into the future"
17435 (interactive "P")
17436 (cond
17437 ((run-hook-with-args-until-success 'org-shiftright-hook))
17438 ((and org-support-shift-select (org-region-active-p))
17439 (org-call-for-shift-select 'forward-char))
17440 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
17441 ((and (not (eq org-support-shift-select 'always))
17442 (org-on-heading-p))
17443 (let ((org-inhibit-logging
17444 (not org-treat-S-cursor-todo-selection-as-state-change))
17445 (org-inhibit-blocking
17446 (not org-treat-S-cursor-todo-selection-as-state-change)))
17447 (org-call-with-arg 'org-todo 'right)))
17448 ((or (and org-support-shift-select
17449 (not (eq org-support-shift-select 'always))
17450 (org-at-item-bullet-p))
17451 (and (not org-support-shift-select) (org-at-item-p)))
17452 (org-call-with-arg 'org-cycle-list-bullet nil))
17453 ((and (not (eq org-support-shift-select 'always))
17454 (org-at-property-p))
17455 (call-interactively 'org-property-next-allowed-value))
17456 ((org-clocktable-try-shift 'right arg))
17457 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
17458 (org-support-shift-select
17459 (org-call-for-shift-select 'forward-char))
17460 (t (org-shiftselect-error))))
17462 (defun org-shiftleft (&optional arg)
17463 "Cycle the thing at point or in the current line, depending on context.
17464 Depending on context, this does one of the following:
17466 - switch a timestamp at point one day into the past
17467 - on a headline, switch to the previous TODO keyword.
17468 - on an item, switch entire list to the previous bullet type
17469 - on a property line, switch to the previous allowed value
17470 - on a clocktable definition line, move time block into the past"
17471 (interactive "P")
17472 (cond
17473 ((run-hook-with-args-until-success 'org-shiftleft-hook))
17474 ((and org-support-shift-select (org-region-active-p))
17475 (org-call-for-shift-select 'backward-char))
17476 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
17477 ((and (not (eq org-support-shift-select 'always))
17478 (org-on-heading-p))
17479 (let ((org-inhibit-logging
17480 (not org-treat-S-cursor-todo-selection-as-state-change))
17481 (org-inhibit-blocking
17482 (not org-treat-S-cursor-todo-selection-as-state-change)))
17483 (org-call-with-arg 'org-todo 'left)))
17484 ((or (and org-support-shift-select
17485 (not (eq org-support-shift-select 'always))
17486 (org-at-item-bullet-p))
17487 (and (not org-support-shift-select) (org-at-item-p)))
17488 (org-call-with-arg 'org-cycle-list-bullet 'previous))
17489 ((and (not (eq org-support-shift-select 'always))
17490 (org-at-property-p))
17491 (call-interactively 'org-property-previous-allowed-value))
17492 ((org-clocktable-try-shift 'left arg))
17493 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
17494 (org-support-shift-select
17495 (org-call-for-shift-select 'backward-char))
17496 (t (org-shiftselect-error))))
17498 (defun org-shiftcontrolright ()
17499 "Switch to next TODO set."
17500 (interactive)
17501 (cond
17502 ((and org-support-shift-select (org-region-active-p))
17503 (org-call-for-shift-select 'forward-word))
17504 ((and (not (eq org-support-shift-select 'always))
17505 (org-on-heading-p))
17506 (org-call-with-arg 'org-todo 'nextset))
17507 (org-support-shift-select
17508 (org-call-for-shift-select 'forward-word))
17509 (t (org-shiftselect-error))))
17511 (defun org-shiftcontrolleft ()
17512 "Switch to previous TODO set."
17513 (interactive)
17514 (cond
17515 ((and org-support-shift-select (org-region-active-p))
17516 (org-call-for-shift-select 'backward-word))
17517 ((and (not (eq org-support-shift-select 'always))
17518 (org-on-heading-p))
17519 (org-call-with-arg 'org-todo 'previousset))
17520 (org-support-shift-select
17521 (org-call-for-shift-select 'backward-word))
17522 (t (org-shiftselect-error))))
17524 (defun org-ctrl-c-ret ()
17525 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
17526 (interactive)
17527 (cond
17528 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
17529 (t (call-interactively 'org-insert-heading))))
17531 (defun org-copy-special ()
17532 "Copy region in table or copy current subtree.
17533 Calls `org-table-copy' or `org-copy-subtree', depending on context.
17534 See the individual commands for more information."
17535 (interactive)
17536 (call-interactively
17537 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
17539 (defun org-cut-special ()
17540 "Cut region in table or cut current subtree.
17541 Calls `org-table-copy' or `org-cut-subtree', depending on context.
17542 See the individual commands for more information."
17543 (interactive)
17544 (call-interactively
17545 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
17547 (defun org-paste-special (arg)
17548 "Paste rectangular region into table, or past subtree relative to level.
17549 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
17550 See the individual commands for more information."
17551 (interactive "P")
17552 (if (org-at-table-p)
17553 (org-table-paste-rectangle)
17554 (org-paste-subtree arg)))
17556 (defun org-edit-special (&optional arg)
17557 "Call a special editor for the stuff at point.
17558 When at a table, call the formula editor with `org-table-edit-formulas'.
17559 When at the first line of an src example, call `org-edit-src-code'.
17560 When in an #+include line, visit the include file. Otherwise call
17561 `ffap' to visit the file at point."
17562 (interactive)
17563 ;; possibly prep session before editing source
17564 (when arg
17565 (let* ((info (org-babel-get-src-block-info))
17566 (lang (nth 0 info))
17567 (params (nth 2 info))
17568 (session (cdr (assoc :session params))))
17569 (when (and info session) ;; we are in a source-code block with a session
17570 (funcall
17571 (intern (concat "org-babel-prep-session:" lang)) session params))))
17572 (cond ;; proceed with `org-edit-special'
17573 ((save-excursion
17574 (beginning-of-line 1)
17575 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
17576 (find-file (org-trim (match-string 1))))
17577 ((org-edit-src-code))
17578 ((org-edit-fixed-width-region))
17579 ((org-at-table.el-p)
17580 (org-edit-src-code))
17581 ((or (org-at-table-p)
17582 (save-excursion
17583 (beginning-of-line 1)
17584 (looking-at "[ \t]*#\\+TBLFM:")))
17585 (call-interactively 'org-table-edit-formulas))
17586 (t (call-interactively 'ffap))))
17588 (defun org-ctrl-c-ctrl-c (&optional arg)
17589 "Set tags in headline, or update according to changed information at point.
17591 This command does many different things, depending on context:
17593 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
17594 this is what we do.
17596 - If the cursor is on a statistics cookie, update it.
17598 - If the cursor is in a headline, prompt for tags and insert them
17599 into the current line, aligned to `org-tags-column'. When called
17600 with prefix arg, realign all tags in the current buffer.
17602 - If the cursor is in one of the special #+KEYWORD lines, this
17603 triggers scanning the buffer for these lines and updating the
17604 information.
17606 - If the cursor is inside a table, realign the table. This command
17607 works even if the automatic table editor has been turned off.
17609 - If the cursor is on a #+TBLFM line, re-apply the formulas to
17610 the entire table.
17612 - If the cursor is at a footnote reference or definition, jump to
17613 the corresponding definition or references, respectively.
17615 - If the cursor is a the beginning of a dynamic block, update it.
17617 - If the current buffer is a capture buffer, close note and file it.
17619 - If the cursor is on a <<<target>>>, update radio targets and
17620 corresponding links in this buffer.
17622 - If the cursor is on a numbered item in a plain list, renumber the
17623 ordered list.
17625 - If the cursor is on a checkbox, toggle it.
17627 - If the cursor is on a code block, evaluate it. The variable
17628 `org-confirm-babel-evaluate' can be used to control prompting
17629 before code block evaluation, by default every code block
17630 evaluation requires confirmation. Code block evaluation can be
17631 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
17632 (interactive "P")
17633 (let ((org-enable-table-editor t))
17634 (cond
17635 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
17636 org-occur-highlights
17637 org-latex-fragment-image-overlays)
17638 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
17639 (org-remove-occur-highlights)
17640 (org-remove-latex-fragment-image-overlays)
17641 (message "Temporary highlights/overlays removed from current buffer"))
17642 ((and (local-variable-p 'org-finish-function (current-buffer))
17643 (fboundp org-finish-function))
17644 (funcall org-finish-function))
17645 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
17646 ((or (looking-at org-property-start-re)
17647 (org-at-property-p))
17648 (call-interactively 'org-property-action))
17649 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
17650 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
17651 (or (org-on-heading-p) (org-at-item-p)))
17652 (call-interactively 'org-update-statistics-cookies))
17653 ((org-on-heading-p) (call-interactively 'org-set-tags))
17654 ((org-at-table.el-p)
17655 (message "Use C-c ' to edit table.el tables"))
17656 ((org-at-table-p)
17657 (org-table-maybe-eval-formula)
17658 (if arg
17659 (call-interactively 'org-table-recalculate)
17660 (org-table-maybe-recalculate-line))
17661 (call-interactively 'org-table-align)
17662 (orgtbl-send-table 'maybe))
17663 ((or (org-footnote-at-reference-p)
17664 (org-footnote-at-definition-p))
17665 (call-interactively 'org-footnote-action))
17666 ((org-at-item-checkbox-p)
17667 ;; Cursor at a checkbox: repair list and update checkboxes. Send
17668 ;; list only if at top item.
17669 (let* ((cbox (match-string 1))
17670 (struct (org-list-struct))
17671 (old-struct (copy-tree struct))
17672 (parents (org-list-parents-alist struct))
17673 (prevs (org-list-prevs-alist struct))
17674 (orderedp (org-entry-get nil "ORDERED"))
17675 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
17676 block-item)
17677 ;; Use a light version of `org-toggle-checkbox' to avoid
17678 ;; computing list structure twice.
17679 (org-list-set-checkbox (point-at-bol) struct
17680 (cond
17681 ((equal arg '(16)) "[-]")
17682 ((equal arg '(4)) nil)
17683 ((equal "[X]" cbox) "[ ]")
17684 (t "[X]")))
17685 (org-list-struct-fix-ind struct parents)
17686 (org-list-struct-fix-bul struct prevs)
17687 (setq block-item
17688 (org-list-struct-fix-box struct parents prevs orderedp))
17689 (when block-item
17690 (message
17691 "Checkboxes were removed due to unchecked box at line %d"
17692 (org-current-line block-item)))
17693 (org-list-struct-apply-struct struct old-struct)
17694 (org-update-checkbox-count-maybe)
17695 (when firstp (org-list-send-list 'maybe))))
17696 ((org-at-item-p)
17697 ;; Cursor at an item: repair list. Do checkbox related actions
17698 ;; only if function was called with an argument. Send list only
17699 ;; if at top item.
17700 (let* ((struct (org-list-struct))
17701 (old-struct (copy-tree struct))
17702 (parents (org-list-parents-alist struct))
17703 (prevs (org-list-prevs-alist struct))
17704 (firstp (= (org-list-get-top-point struct) (point-at-bol))))
17705 (org-list-struct-fix-ind struct parents)
17706 (org-list-struct-fix-bul struct prevs)
17707 (when arg
17708 (org-list-set-checkbox (point-at-bol) struct "[ ]")
17709 (org-list-struct-fix-box struct parents prevs))
17710 (org-list-struct-apply-struct struct old-struct)
17711 (when arg (org-update-checkbox-count-maybe))
17712 (when firstp (org-list-send-list 'maybe))))
17713 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
17714 ;; Dynamic block
17715 (beginning-of-line 1)
17716 (save-excursion (org-update-dblock)))
17717 ((save-excursion
17718 (beginning-of-line 1)
17719 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
17720 (cond
17721 ((equal (match-string 1) "TBLFM")
17722 ;; Recalculate the table before this line
17723 (save-excursion
17724 (beginning-of-line 1)
17725 (skip-chars-backward " \r\n\t")
17726 (if (org-at-table-p)
17727 (org-call-with-arg 'org-table-recalculate (or arg t)))))
17729 (let ((org-inhibit-startup-visibility-stuff t)
17730 (org-startup-align-all-tables nil))
17731 (org-save-outline-visibility 'use-markers (org-mode-restart)))
17732 (message "Local setup has been refreshed"))))
17733 ((org-clock-update-time-maybe))
17734 (t (error "C-c C-c can do nothing useful at this location")))))
17736 (defun org-mode-restart ()
17737 "Restart Org-mode, to scan again for special lines.
17738 Also updates the keyword regular expressions."
17739 (interactive)
17740 (org-mode)
17741 (message "Org-mode restarted"))
17743 (defun org-kill-note-or-show-branches ()
17744 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
17745 (interactive)
17746 (if (not org-finish-function)
17747 (progn
17748 (hide-subtree)
17749 (call-interactively 'show-branches))
17750 (let ((org-note-abort t))
17751 (funcall org-finish-function))))
17753 (defun org-return (&optional indent)
17754 "Goto next table row or insert a newline.
17755 Calls `org-table-next-row' or `newline', depending on context.
17756 See the individual commands for more information."
17757 (interactive)
17758 (cond
17759 ((bobp) (if indent (newline-and-indent) (newline)))
17760 ((org-at-table-p)
17761 (org-table-justify-field-maybe)
17762 (call-interactively 'org-table-next-row))
17763 ;; when `newline-and-indent' is called within a list, make sure
17764 ;; text moved stays inside the item.
17765 ((and (org-in-item-p) indent)
17766 (if (and (org-at-item-p) (>= (point) (match-end 0)))
17767 (progn
17768 (newline)
17769 (org-indent-line-to (length (match-string 0))))
17770 (let ((ind (org-get-indentation)))
17771 (newline)
17772 (if (org-looking-back org-list-end-re)
17773 (org-indent-line-function)
17774 (org-indent-line-to ind)))))
17775 ((and org-return-follows-link
17776 (eq (get-text-property (point) 'face) 'org-link))
17777 (call-interactively 'org-open-at-point))
17778 ((and (org-at-heading-p)
17779 (looking-at
17780 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
17781 (org-show-entry)
17782 (end-of-line 1)
17783 (newline))
17784 (t (if indent (newline-and-indent) (newline)))))
17786 (defun org-return-indent ()
17787 "Goto next table row or insert a newline and indent.
17788 Calls `org-table-next-row' or `newline-and-indent', depending on
17789 context. See the individual commands for more information."
17790 (interactive)
17791 (org-return t))
17793 (defun org-ctrl-c-star ()
17794 "Compute table, or change heading status of lines.
17795 Calls `org-table-recalculate' or `org-toggle-heading',
17796 depending on context."
17797 (interactive)
17798 (cond
17799 ((org-at-table-p)
17800 (call-interactively 'org-table-recalculate))
17802 ;; Convert all lines in region to list items
17803 (call-interactively 'org-toggle-heading))))
17805 (defun org-ctrl-c-minus ()
17806 "Insert separator line in table or modify bullet status of line.
17807 Also turns a plain line or a region of lines into list items.
17808 Calls `org-table-insert-hline', `org-toggle-item', or
17809 `org-cycle-list-bullet', depending on context."
17810 (interactive)
17811 (cond
17812 ((org-at-table-p)
17813 (call-interactively 'org-table-insert-hline))
17814 ((org-region-active-p)
17815 (call-interactively 'org-toggle-item))
17816 ((org-in-item-p)
17817 (call-interactively 'org-cycle-list-bullet))
17819 (call-interactively 'org-toggle-item))))
17821 (defun org-toggle-item (arg)
17822 "Convert headings or normal lines to items, items to normal lines.
17823 If there is no active region, only the current line is considered.
17825 If the first non blank line in the region is an headline, convert
17826 all headlines to items, shifting text accordingly.
17828 If it is an item, convert all items to normal lines.
17830 If it is normal text, change region into an item. With a prefix
17831 argument ARG, change each line in region into an item."
17832 (interactive "P")
17833 (let ((shift-text
17834 (function
17835 ;; Shift text in current section to IND, from point to END.
17836 ;; The function leaves point to END line.
17837 (lambda (ind end)
17838 (let ((min-i 1000) (end (copy-marker end)))
17839 ;; First determine the minimum indentation (MIN-I) of
17840 ;; the text.
17841 (save-excursion
17842 (catch 'exit
17843 (while (< (point) end)
17844 (let ((i (org-get-indentation)))
17845 (cond
17846 ;; Skip blank lines and inline tasks.
17847 ((looking-at "^[ \t]*$"))
17848 ((looking-at "^\\*+ "))
17849 ;; We can't find less than 0 indentation.
17850 ((zerop i) (throw 'exit (setq min-i 0)))
17851 ((< i min-i) (setq min-i i))))
17852 (forward-line))))
17853 ;; Then indent each line so that a line indented to
17854 ;; MIN-I becomes indented to IND. Ignore blank lines
17855 ;; and inline tasks in the process.
17856 (let ((delta (- ind min-i)))
17857 (while (< (point) end)
17858 (unless (or (looking-at "^[ \t]*$")
17859 (looking-at "^\\*+ "))
17860 (org-indent-line-to (+ (org-get-indentation) delta)))
17861 (forward-line)))))))
17862 (skip-blanks
17863 (function
17864 ;; Return beginning of first non-blank line, starting from
17865 ;; line at POS.
17866 (lambda (pos)
17867 (save-excursion
17868 (goto-char pos)
17869 (skip-chars-forward " \r\t\n")
17870 (point-at-bol)))))
17871 beg end)
17872 ;; Determine boundaries of changes.
17873 (if (org-region-active-p)
17874 (setq beg (funcall skip-blanks (region-beginning))
17875 end (copy-marker (region-end)))
17876 (setq beg (funcall skip-blanks (point-at-bol))
17877 end (copy-marker (point-at-eol))))
17878 ;; Depending on the starting line, choose an action on the text
17879 ;; between BEG and END.
17880 (org-with-limited-levels
17881 (save-excursion
17882 (goto-char beg)
17883 (cond
17884 ;; Case 1. Start at an item: de-itemize. Note that it only
17885 ;; happens when a region is active: `org-ctrl-c-minus'
17886 ;; would call `org-cycle-list-bullet' otherwise.
17887 ((org-at-item-p)
17888 (while (< (point) end)
17889 (when (org-at-item-p)
17890 (skip-chars-forward " \t")
17891 (delete-region (point) (match-end 0)))
17892 (forward-line)))
17893 ;; Case 2. Start at an heading: convert to items.
17894 ((org-on-heading-p)
17895 (let* ((bul (org-list-bullet-string "-"))
17896 (bul-len (length bul))
17897 ;; Indentation of the first heading. It should be
17898 ;; relative to the indentation of its parent, if any.
17899 (start-ind (save-excursion
17900 (cond
17901 ((not org-adapt-indentation) 0)
17902 ((not (outline-previous-heading)) 0)
17903 (t (length (match-string 0))))))
17904 ;; Level of first heading. Further headings will be
17905 ;; compared to it to determine hierarchy in the list.
17906 (ref-level (org-reduced-level (org-outline-level))))
17907 (while (< (point) end)
17908 (let* ((level (org-reduced-level (org-outline-level)))
17909 (delta (max 0 (- level ref-level))))
17910 ;; If current headline is less indented than the first
17911 ;; one, set it as reference, in order to preserve
17912 ;; subtrees.
17913 (when (< level ref-level) (setq ref-level level))
17914 (replace-match bul t t)
17915 (org-indent-line-to (+ start-ind (* delta bul-len)))
17916 ;; Ensure all text down to END (or SECTION-END) belongs
17917 ;; to the newly created item.
17918 (let ((section-end (save-excursion
17919 (or (outline-next-heading) (point)))))
17920 (forward-line)
17921 (funcall shift-text
17922 (+ start-ind (* (1+ delta) bul-len))
17923 (min end section-end)))))))
17924 ;; Case 3. Normal line with ARG: turn each non-item line into
17925 ;; an item.
17926 (arg
17927 (while (< (point) end)
17928 (unless (or (org-on-heading-p) (org-at-item-p))
17929 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
17930 (replace-match
17931 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
17932 (forward-line)))
17933 ;; Case 4. Normal line without ARG: make the first line of
17934 ;; region an item, and shift indentation of others
17935 ;; lines to set them as item's body.
17936 (t (let* ((bul (org-list-bullet-string "-"))
17937 (bul-len (length bul))
17938 (ref-ind (org-get-indentation)))
17939 (skip-chars-forward " \t")
17940 (insert bul)
17941 (forward-line)
17942 (while (< (point) end)
17943 ;; Ensure that lines less indented than first one
17944 ;; still get included in item body.
17945 (funcall shift-text
17946 (+ ref-ind bul-len)
17947 (min end (save-excursion (or (outline-next-heading)
17948 (point)))))
17949 (forward-line)))))))))
17951 (defun org-toggle-heading (&optional nstars)
17952 "Convert headings to normal text, or items or text to headings.
17953 If there is no active region, only the current line is considered.
17955 If the first non blank line is an headline, remove the stars from
17956 all headlines in the region.
17958 If it is a plain list item, turn all plain list items into headings.
17960 If it is a normal line, turn each and every normal line (i.e. not
17961 an heading or an item) in the region into a heading.
17963 When converting a line into a heading, the number of stars is chosen
17964 such that the lines become children of the current entry. However,
17965 when a prefix argument is given, its value determines the number of
17966 stars to add."
17967 (interactive "P")
17968 (let ((skip-blanks
17969 (function
17970 ;; Return beginning of first non-blank line, starting from
17971 ;; line at POS.
17972 (lambda (pos)
17973 (save-excursion
17974 (goto-char pos)
17975 (skip-chars-forward " \r\t\n")
17976 (point-at-bol)))))
17977 beg end)
17978 ;; Determine boundaries of changes. If region ends at a bol, do
17979 ;; not consider the last line to be in the region.
17980 (if (org-region-active-p)
17981 (setq beg (funcall skip-blanks (region-beginning))
17982 end (copy-marker (save-excursion
17983 (goto-char (region-end))
17984 (if (bolp) (point) (point-at-eol)))))
17985 (setq beg (funcall skip-blanks (point-at-bol))
17986 end (copy-marker (point-at-eol))))
17987 ;; Ensure inline tasks don't count as headings.
17988 (org-with-limited-levels
17989 (save-excursion
17990 (goto-char beg)
17991 (cond
17992 ;; Case 1. Started at an heading: de-star headings.
17993 ((org-on-heading-p)
17994 (while (< (point) end)
17995 (when (org-on-heading-p t)
17996 (looking-at outline-regexp) (replace-match ""))
17997 (forward-line)))
17998 ;; Case 2. Started at an item: change items into headlines.
17999 ;; One star will be added by `org-list-to-subtree'.
18000 ((org-at-item-p)
18001 (let* ((stars (make-string
18002 (if nstars
18003 ;; subtract the star that will be added again by
18004 ;; `org-list-to-subtree'
18005 (1- (prefix-numeric-value current-prefix-arg))
18006 (or (org-current-level) 0))
18007 ?*))
18008 (add-stars
18009 (cond (nstars "") ; stars from prefix only
18010 ((equal stars "") "") ; before first heading
18011 (org-odd-levels-only "*") ; inside heading, odd
18012 (t "")))) ; inside heading, oddeven
18013 (while (< (point) end)
18014 (when (org-at-item-p)
18015 ;; Pay attention to cases when region ends before list.
18016 (let* ((struct (org-list-struct))
18017 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
18018 (save-restriction
18019 (narrow-to-region (point) list-end)
18020 (insert
18021 (org-list-to-subtree
18022 (org-list-parse-list t)
18023 '(:istart (concat stars add-stars (funcall get-stars depth))
18024 :icount (concat stars add-stars (funcall get-stars depth))))))))
18025 (forward-line))))
18026 ;; Case 3. Started at normal text: make every line an heading,
18027 ;; skipping headlines and items.
18028 (t (let* ((stars (make-string
18029 (if nstars
18030 (prefix-numeric-value current-prefix-arg)
18031 (or (org-current-level) 0))
18032 ?*))
18033 (add-stars
18034 (cond (nstars "") ; stars from prefix only
18035 ((equal stars "") "*") ; before first heading
18036 (org-odd-levels-only "**") ; inside heading, odd
18037 (t "*"))) ; inside heading, oddeven
18038 (rpl (concat stars add-stars " ")))
18039 (while (< (point) end)
18040 (when (and (not (org-on-heading-p)) (not (org-at-item-p))
18041 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
18042 (replace-match (concat rpl (match-string 2))))
18043 (forward-line)))))))))
18045 (defun org-meta-return (&optional arg)
18046 "Insert a new heading or wrap a region in a table.
18047 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
18048 See the individual commands for more information."
18049 (interactive "P")
18050 (cond
18051 ((run-hook-with-args-until-success 'org-metareturn-hook))
18052 ((org-at-table-p)
18053 (call-interactively 'org-table-wrap-region))
18054 (t (call-interactively 'org-insert-heading))))
18056 ;;; Menu entries
18058 ;; Define the Org-mode menus
18059 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
18060 '("Tbl"
18061 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
18062 ["Next Field" org-cycle (org-at-table-p)]
18063 ["Previous Field" org-shifttab (org-at-table-p)]
18064 ["Next Row" org-return (org-at-table-p)]
18065 "--"
18066 ["Blank Field" org-table-blank-field (org-at-table-p)]
18067 ["Edit Field" org-table-edit-field (org-at-table-p)]
18068 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
18069 "--"
18070 ("Column"
18071 ["Move Column Left" org-metaleft (org-at-table-p)]
18072 ["Move Column Right" org-metaright (org-at-table-p)]
18073 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
18074 ["Insert Column" org-shiftmetaright (org-at-table-p)])
18075 ("Row"
18076 ["Move Row Up" org-metaup (org-at-table-p)]
18077 ["Move Row Down" org-metadown (org-at-table-p)]
18078 ["Delete Row" org-shiftmetaup (org-at-table-p)]
18079 ["Insert Row" org-shiftmetadown (org-at-table-p)]
18080 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
18081 "--"
18082 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
18083 ("Rectangle"
18084 ["Copy Rectangle" org-copy-special (org-at-table-p)]
18085 ["Cut Rectangle" org-cut-special (org-at-table-p)]
18086 ["Paste Rectangle" org-paste-special (org-at-table-p)]
18087 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
18088 "--"
18089 ("Calculate"
18090 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
18091 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
18092 ["Edit Formulas" org-edit-special (org-at-table-p)]
18093 "--"
18094 ["Recalculate line" org-table-recalculate (org-at-table-p)]
18095 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
18096 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
18097 "--"
18098 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
18099 "--"
18100 ["Sum Column/Rectangle" org-table-sum
18101 (or (org-at-table-p) (org-region-active-p))]
18102 ["Which Column?" org-table-current-column (org-at-table-p)])
18103 ["Debug Formulas"
18104 org-table-toggle-formula-debugger
18105 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
18106 ["Show Col/Row Numbers"
18107 org-table-toggle-coordinate-overlays
18108 :style toggle
18109 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
18110 "--"
18111 ["Create" org-table-create (and (not (org-at-table-p))
18112 org-enable-table-editor)]
18113 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
18114 ["Import from File" org-table-import (not (org-at-table-p))]
18115 ["Export to File" org-table-export (org-at-table-p)]
18116 "--"
18117 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
18119 (easy-menu-define org-org-menu org-mode-map "Org menu"
18120 '("Org"
18121 ("Show/Hide"
18122 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
18123 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
18124 ["Sparse Tree..." org-sparse-tree t]
18125 ["Reveal Context" org-reveal t]
18126 ["Show All" show-all t]
18127 "--"
18128 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
18129 "--"
18130 ["New Heading" org-insert-heading t]
18131 ("Navigate Headings"
18132 ["Up" outline-up-heading t]
18133 ["Next" outline-next-visible-heading t]
18134 ["Previous" outline-previous-visible-heading t]
18135 ["Next Same Level" outline-forward-same-level t]
18136 ["Previous Same Level" outline-backward-same-level t]
18137 "--"
18138 ["Jump" org-goto t])
18139 ("Edit Structure"
18140 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
18141 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
18142 "--"
18143 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
18144 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
18145 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
18146 "--"
18147 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
18148 "--"
18149 ["Promote Heading" org-metaleft (not (org-at-table-p))]
18150 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
18151 ["Demote Heading" org-metaright (not (org-at-table-p))]
18152 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
18153 "--"
18154 ["Sort Region/Children" org-sort (not (org-at-table-p))]
18155 "--"
18156 ["Convert to odd levels" org-convert-to-odd-levels t]
18157 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
18158 ("Editing"
18159 ["Emphasis..." org-emphasize t]
18160 ["Edit Source Example" org-edit-special t]
18161 "--"
18162 ["Footnote new/jump" org-footnote-action t]
18163 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
18164 ("Archive"
18165 ["Archive (default method)" org-archive-subtree-default t]
18166 "--"
18167 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
18168 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
18169 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
18171 "--"
18172 ("Hyperlinks"
18173 ["Store Link (Global)" org-store-link t]
18174 ["Find existing link to here" org-occur-link-in-agenda-files t]
18175 ["Insert Link" org-insert-link t]
18176 ["Follow Link" org-open-at-point t]
18177 "--"
18178 ["Next link" org-next-link t]
18179 ["Previous link" org-previous-link t]
18180 "--"
18181 ["Descriptive Links"
18182 (progn (add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
18183 :style radio
18184 :selected (member '(org-link) buffer-invisibility-spec)]
18185 ["Literal Links"
18186 (progn
18187 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
18188 :style radio
18189 :selected (not (member '(org-link) buffer-invisibility-spec))])
18190 "--"
18191 ("TODO Lists"
18192 ["TODO/DONE/-" org-todo t]
18193 ("Select keyword"
18194 ["Next keyword" org-shiftright (org-on-heading-p)]
18195 ["Previous keyword" org-shiftleft (org-on-heading-p)]
18196 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
18197 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
18198 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
18199 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
18200 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
18201 "--"
18202 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
18203 :selected org-enforce-todo-dependencies :style toggle :active t]
18204 "Settings for tree at point"
18205 ["Do Children sequentially" org-toggle-ordered-property :style radio
18206 :selected (org-entry-get nil "ORDERED")
18207 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18208 ["Do Children parallel" org-toggle-ordered-property :style radio
18209 :selected (not (org-entry-get nil "ORDERED"))
18210 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
18211 "--"
18212 ["Set Priority" org-priority t]
18213 ["Priority Up" org-shiftup t]
18214 ["Priority Down" org-shiftdown t]
18215 "--"
18216 ["Get news from all feeds" org-feed-update-all t]
18217 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
18218 ["Customize feeds" (customize-variable 'org-feed-alist) t])
18219 ("TAGS and Properties"
18220 ["Set Tags" org-set-tags-command t]
18221 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
18222 "--"
18223 ["Set property" org-set-property t]
18224 ["Column view of properties" org-columns t]
18225 ["Insert Column View DBlock" org-insert-columns-dblock t])
18226 ("Dates and Scheduling"
18227 ["Timestamp" org-time-stamp t]
18228 ["Timestamp (inactive)" org-time-stamp-inactive t]
18229 ("Change Date"
18230 ["1 Day Later" org-shiftright t]
18231 ["1 Day Earlier" org-shiftleft t]
18232 ["1 ... Later" org-shiftup t]
18233 ["1 ... Earlier" org-shiftdown t])
18234 ["Compute Time Range" org-evaluate-time-range t]
18235 ["Schedule Item" org-schedule t]
18236 ["Deadline" org-deadline t]
18237 "--"
18238 ["Custom time format" org-toggle-time-stamp-overlays
18239 :style radio :selected org-display-custom-times]
18240 "--"
18241 ["Goto Calendar" org-goto-calendar t]
18242 ["Date from Calendar" org-date-from-calendar t]
18243 "--"
18244 ["Start/Restart Timer" org-timer-start t]
18245 ["Pause/Continue Timer" org-timer-pause-or-continue t]
18246 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
18247 ["Insert Timer String" org-timer t]
18248 ["Insert Timer Item" org-timer-item t])
18249 ("Logging work"
18250 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
18251 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
18252 ["Clock out" org-clock-out t]
18253 ["Clock cancel" org-clock-cancel t]
18254 "--"
18255 ["Mark as default task" org-clock-mark-default-task t]
18256 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
18257 ["Goto running clock" org-clock-goto t]
18258 "--"
18259 ["Display times" org-clock-display t]
18260 ["Create clock table" org-clock-report t]
18261 "--"
18262 ["Record DONE time"
18263 (progn (setq org-log-done (not org-log-done))
18264 (message "Switching to %s will %s record a timestamp"
18265 (car org-done-keywords)
18266 (if org-log-done "automatically" "not")))
18267 :style toggle :selected org-log-done])
18268 "--"
18269 ["Agenda Command..." org-agenda t]
18270 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
18271 ("File List for Agenda")
18272 ("Special views current file"
18273 ["TODO Tree" org-show-todo-tree t]
18274 ["Check Deadlines" org-check-deadlines t]
18275 ["Timeline" org-timeline t]
18276 ["Tags/Property tree" org-match-sparse-tree t])
18277 "--"
18278 ["Export/Publish..." org-export t]
18279 ("LaTeX"
18280 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
18281 :selected org-cdlatex-mode]
18282 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
18283 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
18284 ["Modify math symbol" org-cdlatex-math-modify
18285 (org-inside-LaTeX-fragment-p)]
18286 ["Insert citation" org-reftex-citation t]
18287 "--"
18288 ["Template for BEAMER" org-insert-beamer-options-template t])
18289 "--"
18290 ("MobileOrg"
18291 ["Push Files and Views" org-mobile-push t]
18292 ["Get Captured and Flagged" org-mobile-pull t]
18293 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
18294 "--"
18295 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
18296 "--"
18297 ("Documentation"
18298 ["Show Version" org-version t]
18299 ["Info Documentation" org-info t])
18300 ("Customize"
18301 ["Browse Org Group" org-customize t]
18302 "--"
18303 ["Expand This Menu" org-create-customize-menu
18304 (fboundp 'customize-menu-create)])
18305 ["Send bug report" org-submit-bug-report t]
18306 "--"
18307 ("Refresh/Reload"
18308 ["Refresh setup current buffer" org-mode-restart t]
18309 ["Reload Org (after update)" org-reload t]
18310 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
18313 (defun org-info (&optional node)
18314 "Read documentation for Org-mode in the info system.
18315 With optional NODE, go directly to that node."
18316 (interactive)
18317 (info (format "(org)%s" (or node ""))))
18319 ;;;###autoload
18320 (defun org-submit-bug-report ()
18321 "Submit a bug report on Org-mode via mail.
18323 Don't hesitate to report any problems or inaccurate documentation.
18325 If you don't have setup sending mail from (X)Emacs, please copy the
18326 output buffer into your mail program, as it gives us important
18327 information about your Org-mode version and configuration."
18328 (interactive)
18329 (require 'reporter)
18330 (org-load-modules-maybe)
18331 (org-require-autoloaded-modules)
18332 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
18333 (reporter-submit-bug-report
18334 "emacs-orgmode@gnu.org"
18335 (org-version)
18336 (let (list)
18337 (save-window-excursion
18338 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
18339 (delete-other-windows)
18340 (erase-buffer)
18341 (insert "You are about to submit a bug report to the Org-mode mailing list.
18343 We would like to add your full Org-mode and Outline configuration to the
18344 bug report. This greatly simplifies the work of the maintainer and
18345 other experts on the mailing list.
18347 HOWEVER, some variables you have customized may contain private
18348 information. The names of customers, colleagues, or friends, might
18349 appear in the form of file names, tags, todo states, or search strings.
18350 If you answer yes to the prompt, you might want to check and remove
18351 such private information before sending the email.")
18352 (add-text-properties (point-min) (point-max) '(face org-warning))
18353 (when (yes-or-no-p "Include your Org-mode configuration ")
18354 (mapatoms
18355 (lambda (v)
18356 (and (boundp v)
18357 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
18358 (or (and (symbol-value v)
18359 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
18360 (and
18361 (get v 'custom-type) (get v 'standard-value)
18362 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
18363 (push v list)))))
18364 (kill-buffer (get-buffer "*Warn about privacy*"))
18365 list))
18366 nil nil
18367 "Remember to cover the basics, that is, what you expected to happen and
18368 what in fact did happen. You don't know how to make a good report? See
18370 http://orgmode.org/manual/Feedback.html#Feedback
18372 Your bug report will be posted to the Org-mode mailing list.
18373 ------------------------------------------------------------------------")
18374 (save-excursion
18375 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
18376 (replace-match "\\1Bug: \\3 [\\2]")))))
18379 (defun org-install-agenda-files-menu ()
18380 (let ((bl (buffer-list)))
18381 (save-excursion
18382 (while bl
18383 (set-buffer (pop bl))
18384 (if (org-mode-p) (setq bl nil)))
18385 (when (org-mode-p)
18386 (easy-menu-change
18387 '("Org") "File List for Agenda"
18388 (append
18389 (list
18390 ["Edit File List" (org-edit-agenda-file-list) t]
18391 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
18392 ["Remove Current File from List" org-remove-file t]
18393 ["Cycle through agenda files" org-cycle-agenda-files t]
18394 ["Occur in all agenda files" org-occur-in-agenda-files t]
18395 "--")
18396 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
18398 ;;;; Documentation
18400 ;;;###autoload
18401 (defun org-require-autoloaded-modules ()
18402 (interactive)
18403 (mapc 'require
18404 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
18405 org-docbook org-exp org-html org-icalendar
18406 org-id org-latex
18407 org-publish org-remember org-table
18408 org-timer org-xoxo)))
18410 ;;;###autoload
18411 (defun org-reload (&optional uncompiled)
18412 "Reload all org lisp files.
18413 With prefix arg UNCOMPILED, load the uncompiled versions."
18414 (interactive "P")
18415 (require 'find-func)
18416 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
18417 (dir-org (file-name-directory (org-find-library-name "org")))
18418 (dir-org-contrib (ignore-errors
18419 (file-name-directory
18420 (org-find-library-name "org-contribdir"))))
18421 (babel-files
18422 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
18423 (append (list nil "comint" "eval" "exp" "keys"
18424 "lob" "ref" "table" "tangle")
18425 (delq nil
18426 (mapcar
18427 (lambda (lang)
18428 (when (cdr lang) (symbol-name (car lang))))
18429 org-babel-load-languages)))))
18430 (files
18431 (append (directory-files dir-org t file-re)
18432 babel-files
18433 (and dir-org-contrib
18434 (directory-files dir-org-contrib t file-re))))
18435 (remove-re (concat (if (featurep 'xemacs)
18436 "org-colview" "org-colview-xemacs")
18437 "\\'")))
18438 (setq files (mapcar 'file-name-sans-extension files))
18439 (setq files (mapcar
18440 (lambda (x) (if (string-match remove-re x) nil x))
18441 files))
18442 (setq files (delq nil files))
18443 (mapc
18444 (lambda (f)
18445 (when (featurep (intern (file-name-nondirectory f)))
18446 (if (and (not uncompiled)
18447 (file-exists-p (concat f ".elc")))
18448 (load (concat f ".elc") nil nil t)
18449 (load (concat f ".el") nil nil t))))
18450 files))
18451 (org-version))
18453 ;;;###autoload
18454 (defun org-customize ()
18455 "Call the customize function with org as argument."
18456 (interactive)
18457 (org-load-modules-maybe)
18458 (org-require-autoloaded-modules)
18459 (customize-browse 'org))
18461 (defun org-create-customize-menu ()
18462 "Create a full customization menu for Org-mode, insert it into the menu."
18463 (interactive)
18464 (org-load-modules-maybe)
18465 (org-require-autoloaded-modules)
18466 (if (fboundp 'customize-menu-create)
18467 (progn
18468 (easy-menu-change
18469 '("Org") "Customize"
18470 `(["Browse Org group" org-customize t]
18471 "--"
18472 ,(customize-menu-create 'org)
18473 ["Set" Custom-set t]
18474 ["Save" Custom-save t]
18475 ["Reset to Current" Custom-reset-current t]
18476 ["Reset to Saved" Custom-reset-saved t]
18477 ["Reset to Standard Settings" Custom-reset-standard t]))
18478 (message "\"Org\"-menu now contains full customization menu"))
18479 (error "Cannot expand menu (outdated version of cus-edit.el)")))
18481 ;;;; Miscellaneous stuff
18483 ;;; Generally useful functions
18485 (defun org-get-at-bol (property)
18486 "Get text property PROPERTY at beginning of line."
18487 (get-text-property (point-at-bol) property))
18489 (defun org-find-text-property-in-string (prop s)
18490 "Return the first non-nil value of property PROP in string S."
18491 (or (get-text-property 0 prop s)
18492 (get-text-property (or (next-single-property-change 0 prop s) 0)
18493 prop s)))
18495 (defun org-display-warning (message) ;; Copied from Emacs-Muse
18496 "Display the given MESSAGE as a warning."
18497 (if (fboundp 'display-warning)
18498 (display-warning 'org message
18499 (if (featurep 'xemacs) 'warning :warning))
18500 (let ((buf (get-buffer-create "*Org warnings*")))
18501 (with-current-buffer buf
18502 (goto-char (point-max))
18503 (insert "Warning (Org): " message)
18504 (unless (bolp)
18505 (newline)))
18506 (display-buffer buf)
18507 (sit-for 0))))
18509 (defun org-eval (form)
18510 "Eval FORM and return result."
18511 (condition-case error
18512 (eval form)
18513 (error (format "%%![Error: %s]" error))))
18515 (defun org-in-commented-line ()
18516 "Is point in a line starting with `#'?"
18517 (equal (char-after (point-at-bol)) ?#))
18519 (defun org-in-indented-comment-line ()
18520 "Is point in a line starting with `#' after some white space?"
18521 (save-excursion
18522 (save-match-data
18523 (goto-char (point-at-bol))
18524 (looking-at "[ \t]*#"))))
18526 (defun org-in-verbatim-emphasis ()
18527 (save-match-data
18528 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
18530 (defun org-goto-marker-or-bmk (marker &optional bookmark)
18531 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
18532 (if (and marker (marker-buffer marker)
18533 (buffer-live-p (marker-buffer marker)))
18534 (progn
18535 (switch-to-buffer (marker-buffer marker))
18536 (if (or (> marker (point-max)) (< marker (point-min)))
18537 (widen))
18538 (goto-char marker)
18539 (org-show-context 'org-goto))
18540 (if bookmark
18541 (bookmark-jump bookmark)
18542 (error "Cannot find location"))))
18544 (defun org-quote-csv-field (s)
18545 "Quote field for inclusion in CSV material."
18546 (if (string-match "[\",]" s)
18547 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
18550 (defun org-force-self-insert (N)
18551 "Needed to enforce self-insert under remapping."
18552 (interactive "p")
18553 (self-insert-command N))
18555 (defun org-string-width (s)
18556 "Compute width of string, ignoring invisible characters.
18557 This ignores character with invisibility property `org-link', and also
18558 characters with property `org-cwidth', because these will become invisible
18559 upon the next fontification round."
18560 (let (b l)
18561 (when (or (eq t buffer-invisibility-spec)
18562 (assq 'org-link buffer-invisibility-spec))
18563 (while (setq b (text-property-any 0 (length s)
18564 'invisible 'org-link s))
18565 (setq s (concat (substring s 0 b)
18566 (substring s (or (next-single-property-change
18567 b 'invisible s) (length s)))))))
18568 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
18569 (setq s (concat (substring s 0 b)
18570 (substring s (or (next-single-property-change
18571 b 'org-cwidth s) (length s))))))
18572 (setq l (string-width s) b -1)
18573 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
18574 (setq l (- l (get-text-property b 'org-dwidth-n s))))
18577 (defun org-shorten-string (s maxlength)
18578 "Shorten string S so tht it is no longer than MAXLENGTH characters.
18579 If the string is shorter or has length MAXLENGTH, just return the
18580 original string. If it is longer, the functions finds a space in the
18581 string, breaks this string off at that locations and adds three dots
18582 as ellipsis. Including the ellipsis, the string will not be longer
18583 than MAXLENGTH. If finding a good breaking point in the string does
18584 not work, the string is just chopped off in the middle of a word
18585 if necessary."
18586 (if (<= (length s) maxlength)
18588 (let* ((n (max (- maxlength 4) 1))
18589 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
18590 (if (string-match re s)
18591 (concat (match-string 1 s) "...")
18592 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
18594 (defun org-get-indentation (&optional line)
18595 "Get the indentation of the current line, interpreting tabs.
18596 When LINE is given, assume it represents a line and compute its indentation."
18597 (if line
18598 (if (string-match "^ *" (org-remove-tabs line))
18599 (match-end 0))
18600 (save-excursion
18601 (beginning-of-line 1)
18602 (skip-chars-forward " \t")
18603 (current-column))))
18605 (defun org-get-string-indentation (s)
18606 "What indentation has S due to SPACE and TAB at the beginning of the string?"
18607 (let ((n -1) (i 0) (w tab-width) c)
18608 (catch 'exit
18609 (while (< (setq n (1+ n)) (length s))
18610 (setq c (aref s n))
18611 (cond ((= c ?\ ) (setq i (1+ i)))
18612 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
18613 (t (throw 'exit t)))))
18616 (defun org-remove-tabs (s &optional width)
18617 "Replace tabulators in S with spaces.
18618 Assumes that s is a single line, starting in column 0."
18619 (setq width (or width tab-width))
18620 (while (string-match "\t" s)
18621 (setq s (replace-match
18622 (make-string
18623 (- (* width (/ (+ (match-beginning 0) width) width))
18624 (match-beginning 0)) ?\ )
18625 t t s)))
18628 (defun org-fix-indentation (line ind)
18629 "Fix indentation in LINE.
18630 IND is a cons cell with target and minimum indentation.
18631 If the current indentation in LINE is smaller than the minimum,
18632 leave it alone. If it is larger than ind, set it to the target."
18633 (let* ((l (org-remove-tabs line))
18634 (i (org-get-indentation l))
18635 (i1 (car ind)) (i2 (cdr ind)))
18636 (if (>= i i2) (setq l (substring line i2)))
18637 (if (> i1 0)
18638 (concat (make-string i1 ?\ ) l)
18639 l)))
18641 (defun org-remove-indentation (code &optional n)
18642 "Remove the maximum common indentation from the lines in CODE.
18643 N may optionally be the number of spaces to remove."
18644 (with-temp-buffer
18645 (insert code)
18646 (org-do-remove-indentation n)
18647 (buffer-string)))
18649 (defun org-do-remove-indentation (&optional n)
18650 "Remove the maximum common indentation from the buffer."
18651 (untabify (point-min) (point-max))
18652 (let ((min 10000) re)
18653 (if n
18654 (setq min n)
18655 (goto-char (point-min))
18656 (while (re-search-forward "^ *[^ \n]" nil t)
18657 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
18658 (unless (or (= min 0) (= min 10000))
18659 (setq re (format "^ \\{%d\\}" min))
18660 (goto-char (point-min))
18661 (while (re-search-forward re nil t)
18662 (replace-match "")
18663 (end-of-line 1))
18664 min)))
18666 (defun org-fill-template (template alist)
18667 "Find each %key of ALIST in TEMPLATE and replace it."
18668 (let ((case-fold-search nil)
18669 entry key value)
18670 (setq alist (sort (copy-sequence alist)
18671 (lambda (a b) (< (length (car a)) (length (car b))))))
18672 (while (setq entry (pop alist))
18673 (setq template
18674 (replace-regexp-in-string
18675 (concat "%" (regexp-quote (car entry)))
18676 (cdr entry) template t t)))
18677 template))
18679 (defun org-base-buffer (buffer)
18680 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
18681 (if (not buffer)
18682 buffer
18683 (or (buffer-base-buffer buffer)
18684 buffer)))
18686 (defun org-trim (s)
18687 "Remove whitespace at beginning and end of string."
18688 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
18689 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
18692 (defun org-wrap (string &optional width lines)
18693 "Wrap string to either a number of lines, or a width in characters.
18694 If WIDTH is non-nil, the string is wrapped to that width, however many lines
18695 that costs. If there is a word longer than WIDTH, the text is actually
18696 wrapped to the length of that word.
18697 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
18698 many lines, whatever width that takes.
18699 The return value is a list of lines, without newlines at the end."
18700 (let* ((words (org-split-string string "[ \t\n]+"))
18701 (maxword (apply 'max (mapcar 'org-string-width words)))
18702 w ll)
18703 (cond (width
18704 (org-do-wrap words (max maxword width)))
18705 (lines
18706 (setq w maxword)
18707 (setq ll (org-do-wrap words maxword))
18708 (if (<= (length ll) lines)
18710 (setq ll words)
18711 (while (> (length ll) lines)
18712 (setq w (1+ w))
18713 (setq ll (org-do-wrap words w)))
18714 ll))
18715 (t (error "Cannot wrap this")))))
18717 (defun org-do-wrap (words width)
18718 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
18719 (let (lines line)
18720 (while words
18721 (setq line (pop words))
18722 (while (and words (< (+ (length line) (length (car words))) width))
18723 (setq line (concat line " " (pop words))))
18724 (setq lines (push line lines)))
18725 (nreverse lines)))
18727 (defun org-split-string (string &optional separators)
18728 "Splits STRING into substrings at SEPARATORS.
18729 No empty strings are returned if there are matches at the beginning
18730 and end of string."
18731 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
18732 (start 0)
18733 notfirst
18734 (list nil))
18735 (while (and (string-match rexp string
18736 (if (and notfirst
18737 (= start (match-beginning 0))
18738 (< start (length string)))
18739 (1+ start) start))
18740 (< (match-beginning 0) (length string)))
18741 (setq notfirst t)
18742 (or (eq (match-beginning 0) 0)
18743 (and (eq (match-beginning 0) (match-end 0))
18744 (eq (match-beginning 0) start))
18745 (setq list
18746 (cons (substring string start (match-beginning 0))
18747 list)))
18748 (setq start (match-end 0)))
18749 (or (eq start (length string))
18750 (setq list
18751 (cons (substring string start)
18752 list)))
18753 (nreverse list)))
18755 (defun org-quote-vert (s)
18756 "Replace \"|\" with \"\\vert\"."
18757 (while (string-match "|" s)
18758 (setq s (replace-match "\\vert" t t s)))
18761 (defun org-uuidgen-p (s)
18762 "Is S an ID created by UUIDGEN?"
18763 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
18765 (defun org-context ()
18766 "Return a list of contexts of the current cursor position.
18767 If several contexts apply, all are returned.
18768 Each context entry is a list with a symbol naming the context, and
18769 two positions indicating start and end of the context. Possible
18770 contexts are:
18772 :headline anywhere in a headline
18773 :headline-stars on the leading stars in a headline
18774 :todo-keyword on a TODO keyword (including DONE) in a headline
18775 :tags on the TAGS in a headline
18776 :priority on the priority cookie in a headline
18777 :item on the first line of a plain list item
18778 :item-bullet on the bullet/number of a plain list item
18779 :checkbox on the checkbox in a plain list item
18780 :table in an org-mode table
18781 :table-special on a special filed in a table
18782 :table-table in a table.el table
18783 :link on a hyperlink
18784 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
18785 :target on a <<target>>
18786 :radio-target on a <<<radio-target>>>
18787 :latex-fragment on a LaTeX fragment
18788 :latex-preview on a LaTeX fragment with overlayed preview image
18790 This function expects the position to be visible because it uses font-lock
18791 faces as a help to recognize the following contexts: :table-special, :link,
18792 and :keyword."
18793 (let* ((f (get-text-property (point) 'face))
18794 (faces (if (listp f) f (list f)))
18795 (p (point)) clist o)
18796 ;; First the large context
18797 (cond
18798 ((org-on-heading-p t)
18799 (push (list :headline (point-at-bol) (point-at-eol)) clist)
18800 (when (progn
18801 (beginning-of-line 1)
18802 (looking-at org-todo-line-tags-regexp))
18803 (push (org-point-in-group p 1 :headline-stars) clist)
18804 (push (org-point-in-group p 2 :todo-keyword) clist)
18805 (push (org-point-in-group p 4 :tags) clist))
18806 (goto-char p)
18807 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
18808 (if (looking-at "\\[#[A-Z0-9]\\]")
18809 (push (org-point-in-group p 0 :priority) clist)))
18811 ((org-at-item-p)
18812 (push (org-point-in-group p 2 :item-bullet) clist)
18813 (push (list :item (point-at-bol)
18814 (save-excursion (org-end-of-item) (point)))
18815 clist)
18816 (and (org-at-item-checkbox-p)
18817 (push (org-point-in-group p 0 :checkbox) clist)))
18819 ((org-at-table-p)
18820 (push (list :table (org-table-begin) (org-table-end)) clist)
18821 (if (memq 'org-formula faces)
18822 (push (list :table-special
18823 (previous-single-property-change p 'face)
18824 (next-single-property-change p 'face)) clist)))
18825 ((org-at-table-p 'any)
18826 (push (list :table-table) clist)))
18827 (goto-char p)
18829 ;; Now the small context
18830 (cond
18831 ((org-at-timestamp-p)
18832 (push (org-point-in-group p 0 :timestamp) clist))
18833 ((memq 'org-link faces)
18834 (push (list :link
18835 (previous-single-property-change p 'face)
18836 (next-single-property-change p 'face)) clist))
18837 ((memq 'org-special-keyword faces)
18838 (push (list :keyword
18839 (previous-single-property-change p 'face)
18840 (next-single-property-change p 'face)) clist))
18841 ((org-on-target-p)
18842 (push (org-point-in-group p 0 :target) clist)
18843 (goto-char (1- (match-beginning 0)))
18844 (if (looking-at org-radio-target-regexp)
18845 (push (org-point-in-group p 0 :radio-target) clist))
18846 (goto-char p))
18847 ((setq o (car (delq nil
18848 (mapcar
18849 (lambda (x)
18850 (if (memq x org-latex-fragment-image-overlays) x))
18851 (overlays-at (point))))))
18852 (push (list :latex-fragment
18853 (overlay-start o) (overlay-end o)) clist)
18854 (push (list :latex-preview
18855 (overlay-start o) (overlay-end o)) clist))
18856 ((org-inside-LaTeX-fragment-p)
18857 ;; FIXME: positions wrong.
18858 (push (list :latex-fragment (point) (point)) clist)))
18860 (setq clist (nreverse (delq nil clist)))
18861 clist))
18863 ;; FIXME: Compare with at-regexp-p Do we need both?
18864 (defun org-in-regexp (re &optional nlines visually)
18865 "Check if point is inside a match of regexp.
18866 Normally only the current line is checked, but you can include NLINES extra
18867 lines both before and after point into the search.
18868 If VISUALLY is set, require that the cursor is not after the match but
18869 really on, so that the block visually is on the match."
18870 (catch 'exit
18871 (let ((pos (point))
18872 (eol (point-at-eol (+ 1 (or nlines 0))))
18873 (inc (if visually 1 0)))
18874 (save-excursion
18875 (beginning-of-line (- 1 (or nlines 0)))
18876 (while (re-search-forward re eol t)
18877 (if (and (<= (match-beginning 0) pos)
18878 (>= (+ inc (match-end 0)) pos))
18879 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
18881 (defun org-at-regexp-p (regexp)
18882 "Is point inside a match of REGEXP in the current line?"
18883 (catch 'exit
18884 (save-excursion
18885 (let ((pos (point)) (end (point-at-eol)))
18886 (beginning-of-line 1)
18887 (while (re-search-forward regexp end t)
18888 (if (and (<= (match-beginning 0) pos)
18889 (>= (match-end 0) pos))
18890 (throw 'exit t)))
18891 nil))))
18893 (defun org-in-regexps-block-p (start-re end-re &optional bound)
18894 "Return t if the current point is between matches of START-RE and END-RE.
18895 This will also return t if point is on one of the two matches or
18896 in an unfinished block. END-RE can be a string or a form
18897 returning a string.
18899 An optional third argument bounds the search for START-RE. It
18900 defaults to previous heading or `point-min'."
18901 (let ((pos (point))
18902 (limit (or bound (save-excursion (outline-previous-heading)))))
18903 (save-excursion
18904 ;; we're on a block when point is on start-re...
18905 (or (org-at-regexp-p start-re)
18906 ;; ... or start-re can be found above...
18907 (and (re-search-backward start-re limit t)
18908 ;; ... but no end-re between start-re and point.
18909 (not (re-search-forward (eval end-re) pos t)))))))
18911 (defun org-occur-in-agenda-files (regexp &optional nlines)
18912 "Call `multi-occur' with buffers for all agenda files."
18913 (interactive "sOrg-files matching: \np")
18914 (let* ((files (org-agenda-files))
18915 (tnames (mapcar 'file-truename files))
18916 (extra org-agenda-text-search-extra-files)
18918 (when (eq (car extra) 'agenda-archives)
18919 (setq extra (cdr extra))
18920 (setq files (org-add-archive-files files)))
18921 (while (setq f (pop extra))
18922 (unless (member (file-truename f) tnames)
18923 (add-to-list 'files f 'append)
18924 (add-to-list 'tnames (file-truename f) 'append)))
18925 (multi-occur
18926 (mapcar (lambda (x)
18927 (with-current-buffer
18928 (or (get-file-buffer x) (find-file-noselect x))
18929 (widen)
18930 (current-buffer)))
18931 files)
18932 regexp)))
18934 (if (boundp 'occur-mode-find-occurrence-hook)
18935 ;; Emacs 23
18936 (add-hook 'occur-mode-find-occurrence-hook
18937 (lambda ()
18938 (when (org-mode-p)
18939 (org-reveal))))
18940 ;; Emacs 22
18941 (defadvice occur-mode-goto-occurrence
18942 (after org-occur-reveal activate)
18943 (and (org-mode-p) (org-reveal)))
18944 (defadvice occur-mode-goto-occurrence-other-window
18945 (after org-occur-reveal activate)
18946 (and (org-mode-p) (org-reveal)))
18947 (defadvice occur-mode-display-occurrence
18948 (after org-occur-reveal activate)
18949 (when (org-mode-p)
18950 (let ((pos (occur-mode-find-occurrence)))
18951 (with-current-buffer (marker-buffer pos)
18952 (save-excursion
18953 (goto-char pos)
18954 (org-reveal)))))))
18956 (defun org-occur-link-in-agenda-files ()
18957 "Create a link and search for it in the agendas.
18958 The link is not stored in `org-stored-links', it is just created
18959 for the search purpose."
18960 (interactive)
18961 (let ((link (condition-case nil
18962 (org-store-link nil)
18963 (error "Unable to create a link to here"))))
18964 (org-occur-in-agenda-files (regexp-quote link))))
18966 (defun org-uniquify (list)
18967 "Remove duplicate elements from LIST."
18968 (let (res)
18969 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
18970 res))
18972 (defun org-delete-all (elts list)
18973 "Remove all elements in ELTS from LIST."
18974 (while elts
18975 (setq list (delete (pop elts) list)))
18976 list)
18978 (defun org-count (cl-item cl-seq)
18979 "Count the number of occurrences of ITEM in SEQ.
18980 Taken from `count' in cl-seq.el with all keyword arguments removed."
18981 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
18982 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
18983 (while (< cl-start cl-end)
18984 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
18985 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
18986 (setq cl-start (1+ cl-start)))
18987 cl-count))
18989 (defun org-remove-if (predicate seq)
18990 "Remove everything from SEQ that fulfills PREDICATE."
18991 (let (res e)
18992 (while seq
18993 (setq e (pop seq))
18994 (if (not (funcall predicate e)) (push e res)))
18995 (nreverse res)))
18997 (defun org-remove-if-not (predicate seq)
18998 "Remove everything from SEQ that does not fulfill PREDICATE."
18999 (let (res e)
19000 (while seq
19001 (setq e (pop seq))
19002 (if (funcall predicate e) (push e res)))
19003 (nreverse res)))
19005 (defun org-back-over-empty-lines ()
19006 "Move backwards over whitespace, to the beginning of the first empty line.
19007 Returns the number of empty lines passed."
19008 (let ((pos (point)))
19009 (if (cdr (assoc 'heading org-blank-before-new-entry))
19010 (skip-chars-backward " \t\n\r")
19011 (forward-line -1))
19012 (beginning-of-line 2)
19013 (goto-char (min (point) pos))
19014 (count-lines (point) pos)))
19016 (defun org-skip-whitespace ()
19017 (skip-chars-forward " \t\n\r"))
19019 (defun org-point-in-group (point group &optional context)
19020 "Check if POINT is in match-group GROUP.
19021 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
19022 match. If the match group does not exist or point is not inside it,
19023 return nil."
19024 (and (match-beginning group)
19025 (>= point (match-beginning group))
19026 (<= point (match-end group))
19027 (if context
19028 (list context (match-beginning group) (match-end group))
19029 t)))
19031 (defun org-switch-to-buffer-other-window (&rest args)
19032 "Switch to buffer in a second window on the current frame.
19033 In particular, do not allow pop-up frames.
19034 Returns the newly created buffer."
19035 (let (pop-up-frames special-display-buffer-names special-display-regexps
19036 special-display-function)
19037 (apply 'switch-to-buffer-other-window args)))
19039 (defun org-combine-plists (&rest plists)
19040 "Create a single property list from all plists in PLISTS.
19041 The process starts by copying the first list, and then setting properties
19042 from the other lists. Settings in the last list are the most significant
19043 ones and overrule settings in the other lists."
19044 (let ((rtn (copy-sequence (pop plists)))
19045 p v ls)
19046 (while plists
19047 (setq ls (pop plists))
19048 (while ls
19049 (setq p (pop ls) v (pop ls))
19050 (setq rtn (plist-put rtn p v))))
19051 rtn))
19053 (defun org-move-line-down (arg)
19054 "Move the current line down. With prefix argument, move it past ARG lines."
19055 (interactive "p")
19056 (let ((col (current-column))
19057 beg end pos)
19058 (beginning-of-line 1) (setq beg (point))
19059 (beginning-of-line 2) (setq end (point))
19060 (beginning-of-line (+ 1 arg))
19061 (setq pos (move-marker (make-marker) (point)))
19062 (insert (delete-and-extract-region beg end))
19063 (goto-char pos)
19064 (org-move-to-column col)))
19066 (defun org-move-line-up (arg)
19067 "Move the current line up. With prefix argument, move it past ARG lines."
19068 (interactive "p")
19069 (let ((col (current-column))
19070 beg end pos)
19071 (beginning-of-line 1) (setq beg (point))
19072 (beginning-of-line 2) (setq end (point))
19073 (beginning-of-line (- arg))
19074 (setq pos (move-marker (make-marker) (point)))
19075 (insert (delete-and-extract-region beg end))
19076 (goto-char pos)
19077 (org-move-to-column col)))
19079 (defun org-replace-escapes (string table)
19080 "Replace %-escapes in STRING with values in TABLE.
19081 TABLE is an association list with keys like \"%a\" and string values.
19082 The sequences in STRING may contain normal field width and padding information,
19083 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
19084 so values can contain further %-escapes if they are define later in TABLE."
19085 (let ((tbl (copy-alist table))
19086 (case-fold-search nil)
19087 (pchg 0)
19088 e re rpl)
19089 (while (setq e (pop tbl))
19090 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
19091 (when (and (cdr e) (string-match re (cdr e)))
19092 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
19093 (safe "SREF"))
19094 (add-text-properties 0 3 (list 'sref sref) safe)
19095 (setcdr e (replace-match safe t t (cdr e)))))
19096 (while (string-match re string)
19097 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
19098 (cdr e)))
19099 (setq string (replace-match rpl t t string))))
19100 (while (setq pchg (next-property-change pchg string))
19101 (let ((sref (get-text-property pchg 'sref string)))
19102 (when (and sref (string-match "SREF" string pchg))
19103 (setq string (replace-match sref t t string)))))
19104 string))
19106 (defun org-sublist (list start end)
19107 "Return a section of LIST, from START to END.
19108 Counting starts at 1."
19109 (let (rtn (c start))
19110 (setq list (nthcdr (1- start) list))
19111 (while (and list (<= c end))
19112 (push (pop list) rtn)
19113 (setq c (1+ c)))
19114 (nreverse rtn)))
19116 (defun org-find-base-buffer-visiting (file)
19117 "Like `find-buffer-visiting' but always return the base buffer and
19118 not an indirect buffer."
19119 (let ((buf (or (get-file-buffer file)
19120 (find-buffer-visiting file))))
19121 (if buf
19122 (or (buffer-base-buffer buf) buf)
19123 nil)))
19125 (defun org-image-file-name-regexp (&optional extensions)
19126 "Return regexp matching the file names of images.
19127 If EXTENSIONS is given, only match these."
19128 (if (and (not extensions) (fboundp 'image-file-name-regexp))
19129 (image-file-name-regexp)
19130 (let ((image-file-name-extensions
19131 (or extensions
19132 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
19133 "xbm" "xpm" "pbm" "pgm" "ppm"))))
19134 (concat "\\."
19135 (regexp-opt (nconc (mapcar 'upcase
19136 image-file-name-extensions)
19137 image-file-name-extensions)
19139 "\\'"))))
19141 (defun org-file-image-p (file &optional extensions)
19142 "Return non-nil if FILE is an image."
19143 (save-match-data
19144 (string-match (org-image-file-name-regexp extensions) file)))
19146 (defun org-get-cursor-date ()
19147 "Return the date at cursor in as a time.
19148 This works in the calendar and in the agenda, anywhere else it just
19149 returns the current time."
19150 (let (date day defd)
19151 (cond
19152 ((eq major-mode 'calendar-mode)
19153 (setq date (calendar-cursor-to-date)
19154 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
19155 ((eq major-mode 'org-agenda-mode)
19156 (setq day (get-text-property (point) 'day))
19157 (if day
19158 (setq date (calendar-gregorian-from-absolute day)
19159 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
19160 (nth 2 date))))))
19161 (or defd (current-time))))
19163 (defvar org-agenda-action-marker (make-marker)
19164 "Marker pointing to the entry for the next agenda action.")
19166 (defun org-mark-entry-for-agenda-action ()
19167 "Mark the current entry as target of an agenda action.
19168 Agenda actions are actions executed from the agenda with the key `k',
19169 which make use of the date at the cursor."
19170 (interactive)
19171 (move-marker org-agenda-action-marker
19172 (save-excursion (org-back-to-heading t) (point))
19173 (current-buffer))
19174 (message
19175 "Entry marked for action; press `k' at desired date in agenda or calendar"))
19177 (defun org-mark-subtree ()
19178 "Mark the current subtree.
19179 This puts point at the start of the current subtree, and mark at the end.
19181 If point is in an inline task, mark that task instead."
19182 (interactive)
19183 (let ((inline-task-p
19184 (and (featurep 'org-inlinetask)
19185 (org-inlinetask-in-task-p)))
19186 (beg))
19187 ;; Get beginning of subtree
19188 (cond
19189 (inline-task-p (org-inlinetask-goto-beginning))
19190 ((org-at-heading-p) (beginning-of-line))
19191 (t (org-with-limited-levels (outline-previous-visible-heading 1))))
19192 (setq beg (point))
19193 ;; Get end of it
19194 (if inline-task-p
19195 (org-inlinetask-goto-end)
19196 (org-end-of-subtree))
19197 ;; Mark zone
19198 (push-mark (point) nil t)
19199 (goto-char beg)))
19201 ;;; Paragraph filling stuff.
19202 ;; We want this to be just right, so use the full arsenal.
19204 (defun org-indent-line-function ()
19205 "Indent line depending on context."
19206 (interactive)
19207 (let* ((pos (point))
19208 (itemp (org-at-item-p))
19209 (case-fold-search t)
19210 (org-drawer-regexp (or org-drawer-regexp "\000"))
19211 (inline-task-p (and (featurep 'org-inlinetask)
19212 (org-inlinetask-in-task-p)))
19213 (inline-re (and inline-task-p
19214 (org-inlinetask-outline-regexp)))
19215 column)
19216 (beginning-of-line 1)
19217 (cond
19218 ;; Comments
19219 ((looking-at "# ") (setq column 0))
19220 ;; Headings
19221 ((looking-at "\\*+ ") (setq column 0))
19222 ;; Included files
19223 ((looking-at "#\\+include:") (setq column 0))
19224 ;; Footnote definition
19225 ((looking-at org-footnote-definition-re) (setq column 0))
19226 ;; Literal examples
19227 ((looking-at "[ \t]*:[ \t]")
19228 (setq column (org-get-indentation))) ; do nothing
19229 ;; Lists
19230 ((ignore-errors (goto-char (org-in-item-p)))
19231 (setq column (if itemp
19232 (org-get-indentation)
19233 (org-list-item-body-column (point))))
19234 (goto-char pos))
19235 ;; Drawers
19236 ((and (looking-at "[ \t]*:END:")
19237 (save-excursion (re-search-backward org-drawer-regexp nil t)))
19238 (save-excursion
19239 (goto-char (1- (match-beginning 1)))
19240 (setq column (current-column))))
19241 ;; Special blocks
19242 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
19243 (save-excursion
19244 (re-search-backward
19245 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
19246 (setq column (org-get-indentation (match-string 0))))
19247 ((and (not (looking-at "[ \t]*#\\+begin_"))
19248 (org-in-regexps-block-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
19249 (save-excursion
19250 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
19251 (setq column
19252 (if (equal (downcase (match-string 1)) "src")
19253 ;; src blocks: let `org-edit-src-exit' handle them
19254 (org-get-indentation)
19255 (org-get-indentation (match-string 0)))))
19256 ;; This line has nothing special, look at the previous relevant
19257 ;; line to compute indentation
19259 (beginning-of-line 0)
19260 (while (and (not (bobp))
19261 (not (looking-at org-drawer-regexp))
19262 ;; When point started in an inline task, do not move
19263 ;; above task starting line.
19264 (not (and inline-task-p (looking-at inline-re)))
19265 ;; Skip drawers, blocks, empty lines, verbatim,
19266 ;; comments, tables, footnotes definitions, lists,
19267 ;; inline tasks.
19268 (or (and (looking-at "[ \t]*:END:")
19269 (re-search-backward org-drawer-regexp nil t))
19270 (and (looking-at "[ \t]*#\\+end_")
19271 (re-search-backward "[ \t]*#\\+begin_"nil t))
19272 (looking-at "[ \t]*[\n:#|]")
19273 (looking-at org-footnote-definition-re)
19274 (and (ignore-errors (goto-char (org-in-item-p)))
19275 (goto-char
19276 (org-list-get-top-point (org-list-struct))))
19277 (and (not inline-task-p)
19278 (featurep 'org-inlinetask)
19279 (org-inlinetask-in-task-p)
19280 (or (org-inlinetask-goto-beginning) t))))
19281 (beginning-of-line 0))
19282 (cond
19283 ;; There was an heading above.
19284 ((looking-at "\\*+[ \t]+")
19285 (if (not org-adapt-indentation)
19286 (setq column 0)
19287 (goto-char (match-end 0))
19288 (setq column (current-column))))
19289 ;; A drawer had started and is unfinished
19290 ((looking-at org-drawer-regexp)
19291 (goto-char (1- (match-beginning 1)))
19292 (setq column (current-column)))
19293 ;; Else, nothing noticeable found: get indentation and go on.
19294 (t (setq column (org-get-indentation))))))
19295 ;; Now apply indentation and move cursor accordingly
19296 (goto-char pos)
19297 (if (<= (current-column) (current-indentation))
19298 (org-indent-line-to column)
19299 (save-excursion (org-indent-line-to column)))
19300 ;; Special polishing for properties, see `org-property-format'
19301 (setq column (current-column))
19302 (beginning-of-line 1)
19303 (if (looking-at
19304 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
19305 (replace-match (concat (match-string 1)
19306 (format org-property-format
19307 (match-string 2) (match-string 3)))
19308 t t))
19309 (org-move-to-column column)))
19311 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
19312 "Variable to store copy of `adaptive-fill-regexp'.
19313 Since `adaptive-fill-regexp' is set to never match, we need to
19314 store a backup of its value before entering `org-mode' so that
19315 the functionality can be provided as a fall-back.")
19317 (defun org-set-autofill-regexps ()
19318 (interactive)
19319 ;; In the paragraph separator we include headlines, because filling
19320 ;; text in a line directly attached to a headline would otherwise
19321 ;; fill the headline as well.
19322 (org-set-local 'comment-start-skip "^#+[ \t]*")
19323 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
19324 ;; The paragraph starter includes hand-formatted lists.
19325 (org-set-local
19326 'paragraph-start
19327 (concat
19328 "\f" "\\|"
19329 "[ ]*$" "\\|"
19330 "\\*+ " "\\|"
19331 "[ \t]*#" "\\|"
19332 (org-item-re) "\\|"
19333 "[ \t]*[:|]" "\\|"
19334 "\\$\\$" "\\|"
19335 "\\\\\\(begin\\|end\\|[][]\\)"))
19336 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
19337 ;; But only if the user has not turned off tables or fixed-width regions
19338 (org-set-local
19339 'auto-fill-inhibit-regexp
19340 (concat "\\*+ \\|#\\+"
19341 "\\|[ \t]*" org-keyword-time-regexp
19342 (if (or org-enable-table-editor org-enable-fixed-width-editor)
19343 (concat
19344 "\\|[ \t]*["
19345 (if org-enable-table-editor "|" "")
19346 (if org-enable-fixed-width-editor ":" "")
19347 "]"))))
19348 ;; We use our own fill-paragraph function, to make sure that tables
19349 ;; and fixed-width regions are not wrapped. That function will pass
19350 ;; through to `fill-paragraph' when appropriate.
19351 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
19352 ;; Prevent auto-fill from inserting unwanted new items.
19353 (org-set-local 'fill-nobreak-predicate
19354 (if (memq 'org-fill-item-nobreak-p fill-nobreak-predicate)
19355 fill-nobreak-predicate
19356 (cons 'org-fill-item-nobreak-p fill-nobreak-predicate)))
19357 ;; Adaptive filling: To get full control, first make sure that
19358 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
19359 (unless (local-variable-p 'adaptive-fill-regexp (current-buffer))
19360 (org-set-local 'org-adaptive-fill-regexp-backup
19361 adaptive-fill-regexp))
19362 (org-set-local 'adaptive-fill-regexp "\000")
19363 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
19364 (org-set-local 'adaptive-fill-function
19365 'org-adaptive-fill-function)
19366 (org-set-local
19367 'align-mode-rules-list
19368 '((org-in-buffer-settings
19369 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
19370 (modes . '(org-mode))))))
19372 (defun org-fill-item-nobreak-p ()
19373 "Non-nil when a line break at point would insert a new item."
19374 (and (looking-at (org-item-re)) (org-list-in-valid-context-p)))
19376 (defun org-fill-paragraph (&optional justify)
19377 "Re-align a table, pass through to fill-paragraph if no table."
19378 (let ((table-p (org-at-table-p))
19379 (table.el-p (org-at-table.el-p))
19380 (itemp (org-in-item-p)))
19381 (cond ((and (equal (char-after (point-at-bol)) ?*)
19382 (save-excursion (goto-char (point-at-bol))
19383 (looking-at outline-regexp)))
19384 t) ; skip headlines
19385 (table.el-p t) ; skip table.el tables
19386 (table-p (org-table-align) t) ; align Org tables
19387 (itemp ; align text in items
19388 (let* ((struct (save-excursion (goto-char itemp)
19389 (org-list-struct)))
19390 (parents (org-list-parents-alist struct))
19391 (children (org-list-get-children itemp struct parents))
19392 beg end prev next prefix)
19393 ;; Determine in which part of item point is: before
19394 ;; first child, after last child, between two
19395 ;; sub-lists, or simply in item if there's no child.
19396 (cond
19397 ((not children)
19398 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19399 beg itemp
19400 end (org-list-get-item-end itemp struct)))
19401 ((< (point) (setq next (car children)))
19402 (setq prefix (make-string (org-list-item-body-column itemp) ?\ )
19403 beg itemp
19404 end next))
19405 ((> (point) (setq prev (car (last children))))
19406 (setq beg (org-list-get-item-end prev struct)
19407 end (org-list-get-item-end itemp struct)
19408 prefix (save-excursion
19409 (goto-char beg)
19410 (skip-chars-forward " \t")
19411 (make-string (current-column) ?\ ))))
19412 (t (catch 'exit
19413 (while (setq next (pop children))
19414 (if (> (point) next)
19415 (setq prev next)
19416 (setq beg (org-list-get-item-end prev struct)
19417 end next
19418 prefix (save-excursion
19419 (goto-char beg)
19420 (skip-chars-forward " \t")
19421 (make-string (current-column) ?\ )))
19422 (throw 'exit nil))))))
19423 ;; Use `fill-paragraph' with buffer narrowed to item
19424 ;; without any child, and with our computed PREFIX.
19425 (flet ((fill-context-prefix (from to &optional flr) prefix))
19426 (save-restriction
19427 (narrow-to-region beg end)
19428 (save-excursion (fill-paragraph justify)))) t))
19429 ;; Special case where point is not in a list but is on
19430 ;; a paragraph adjacent to a list: make sure this paragraph
19431 ;; doesn't get merged with the end of the list by narrowing
19432 ;; buffer first.
19433 ((save-excursion (forward-paragraph -1)
19434 (setq itemp (org-in-item-p)))
19435 (let ((struct (save-excursion (goto-char itemp)
19436 (org-list-struct))))
19437 (save-restriction
19438 (narrow-to-region (org-list-get-bottom-point struct)
19439 (save-excursion (forward-paragraph 1)
19440 (point)))
19441 (fill-paragraph justify) t)))
19442 ;; Else simply call `fill-paragraph'.
19443 (t nil))))
19445 ;; For reference, this is the default value of adaptive-fill-regexp
19446 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
19448 (defun org-adaptive-fill-function ()
19449 "Return a fill prefix for org-mode files."
19450 (let (itemp)
19451 (save-excursion
19452 (cond
19453 ;; Comment line
19454 ((looking-at "#[ \t]+")
19455 (match-string-no-properties 0))
19456 ;; Plain list item
19457 ((org-at-item-p)
19458 (make-string (org-list-item-body-column (point-at-bol)) ?\ ))
19459 ;; Point is in a list after `backward-paragraph': original
19460 ;; point wasn't in the list, or filling would have been taken
19461 ;; care of by `org-auto-fill-function', but the list and the
19462 ;; real paragraph are not separated by a blank line. Thus, move
19463 ;; point after the list to go back to real paragraph and
19464 ;; determine fill-prefix.
19465 ((setq itemp (org-in-item-p))
19466 (goto-char itemp)
19467 (let* ((struct (org-list-struct))
19468 (bottom (org-list-get-bottom-point struct)))
19469 (goto-char bottom)
19470 (make-string (org-get-indentation) ?\ )))
19471 ;; Other text
19472 ((looking-at org-adaptive-fill-regexp-backup)
19473 (match-string-no-properties 0))))))
19475 (defun org-auto-fill-function ()
19476 "Auto-fill function."
19477 (let (itemp prefix)
19478 ;; When in a list, compute an appropriate fill-prefix and make
19479 ;; sure it will be used by `do-auto-fill'.
19480 (if (setq itemp (org-in-item-p))
19481 (progn
19482 (setq prefix (make-string (org-list-item-body-column itemp) ?\ ))
19483 (flet ((fill-context-prefix (from to &optional flr) prefix))
19484 (do-auto-fill)))
19485 ;; Else just use `do-auto-fill'.
19486 (do-auto-fill))))
19488 ;;; Other stuff.
19490 (defun org-toggle-fixed-width-section (arg)
19491 "Toggle the fixed-width export.
19492 If there is no active region, the QUOTE keyword at the current headline is
19493 inserted or removed. When present, it causes the text between this headline
19494 and the next to be exported as fixed-width text, and unmodified.
19495 If there is an active region, this command adds or removes a colon as the
19496 first character of this line. If the first character of a line is a colon,
19497 this line is also exported in fixed-width font."
19498 (interactive "P")
19499 (let* ((cc 0)
19500 (regionp (org-region-active-p))
19501 (beg (if regionp (region-beginning) (point)))
19502 (end (if regionp (region-end)))
19503 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
19504 (case-fold-search nil)
19505 (re "[ \t]*\\(: \\)")
19506 off)
19507 (if regionp
19508 (save-excursion
19509 (goto-char beg)
19510 (setq cc (current-column))
19511 (beginning-of-line 1)
19512 (setq off (looking-at re))
19513 (while (> nlines 0)
19514 (setq nlines (1- nlines))
19515 (beginning-of-line 1)
19516 (cond
19517 (arg
19518 (org-move-to-column cc t)
19519 (insert ": \n")
19520 (forward-line -1))
19521 ((and off (looking-at re))
19522 (replace-match "" t t nil 1))
19523 ((not off) (org-move-to-column cc t) (insert ": ")))
19524 (forward-line 1)))
19525 (save-excursion
19526 (org-back-to-heading)
19527 (if (looking-at (concat outline-regexp
19528 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
19529 (replace-match "" t t nil 1)
19530 (if (looking-at outline-regexp)
19531 (progn
19532 (goto-char (match-end 0))
19533 (insert org-quote-string " "))))))))
19535 (defun org-reftex-citation ()
19536 "Use reftex-citation to insert a citation into the buffer.
19537 This looks for a line like
19539 #+BIBLIOGRAPHY: foo plain option:-d
19541 and derives from it that foo.bib is the bibliography file relevant
19542 for this document. It then installs the necessary environment for RefTeX
19543 to work in this buffer and calls `reftex-citation' to insert a citation
19544 into the buffer.
19546 Export of such citations to both LaTeX and HTML is handled by the contributed
19547 package org-exp-bibtex by Taru Karttunen."
19548 (interactive)
19549 (let ((reftex-docstruct-symbol 'rds)
19550 (reftex-cite-format "\\cite{%l}")
19551 rds bib)
19552 (save-excursion
19553 (save-restriction
19554 (widen)
19555 (let ((case-fold-search t)
19556 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
19557 (if (not (save-excursion
19558 (or (re-search-forward re nil t)
19559 (re-search-backward re nil t))))
19560 (error "No bibliography defined in file")
19561 (setq bib (concat (match-string 1) ".bib")
19562 rds (list (list 'bib bib)))))))
19563 (call-interactively 'reftex-citation)))
19565 ;;;; Functions extending outline functionality
19567 (defun org-beginning-of-line (&optional arg)
19568 "Go to the beginning of the current line. If that is invisible, continue
19569 to a visible line beginning. This makes the function of C-a more intuitive.
19570 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
19571 first attempt, and only move to after the tags when the cursor is already
19572 beyond the end of the headline."
19573 (interactive "P")
19574 (let ((pos (point))
19575 (special (if (consp org-special-ctrl-a/e)
19576 (car org-special-ctrl-a/e)
19577 org-special-ctrl-a/e))
19578 refpos)
19579 (if (org-bound-and-true-p line-move-visual)
19580 (beginning-of-visual-line 1)
19581 (beginning-of-line 1))
19582 (if (and arg (fboundp 'move-beginning-of-line))
19583 (call-interactively 'move-beginning-of-line)
19584 (if (bobp)
19586 (backward-char 1)
19587 (if (org-truely-invisible-p)
19588 (while (and (not (bobp)) (org-truely-invisible-p))
19589 (backward-char 1)
19590 (beginning-of-line 1))
19591 (forward-char 1))))
19592 (when special
19593 (cond
19594 ((and (looking-at org-complex-heading-regexp)
19595 (= (char-after (match-end 1)) ?\ ))
19596 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
19597 (point-at-eol)))
19598 (goto-char
19599 (if (eq special t)
19600 (cond ((> pos refpos) refpos)
19601 ((= pos (point)) refpos)
19602 (t (point)))
19603 (cond ((> pos (point)) (point))
19604 ((not (eq last-command this-command)) (point))
19605 (t refpos)))))
19606 ((org-at-item-p)
19607 (goto-char
19608 (if (eq special t)
19609 (cond ((> pos (match-end 0)) (match-end 0))
19610 ((= pos (point)) (match-end 0))
19611 (t (point)))
19612 (cond ((> pos (point)) (point))
19613 ((not (eq last-command this-command)) (point))
19614 (t (match-end 0))))))))
19615 (org-no-warnings
19616 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
19618 (defun org-end-of-line (&optional arg)
19619 "Go to the end of the line.
19620 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
19621 first attempt, and only move to after the tags when the cursor is already
19622 beyond the end of the headline."
19623 (interactive "P")
19624 (let ((special (if (consp org-special-ctrl-a/e)
19625 (cdr org-special-ctrl-a/e)
19626 org-special-ctrl-a/e)))
19627 (if (or (not special)
19628 (not (org-on-heading-p))
19629 arg)
19630 (call-interactively
19631 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
19632 ((fboundp 'move-end-of-line) 'move-end-of-line)
19633 (t 'end-of-line)))
19634 (let ((pos (point)))
19635 (beginning-of-line 1)
19636 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
19637 (if (eq special t)
19638 (if (or (< pos (match-beginning 1))
19639 (= pos (match-end 0)))
19640 (goto-char (match-beginning 1))
19641 (goto-char (match-end 0)))
19642 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
19643 (goto-char (match-end 0))
19644 (goto-char (match-beginning 1))))
19645 (call-interactively (if (fboundp 'move-end-of-line)
19646 'move-end-of-line
19647 'end-of-line)))))
19648 (org-no-warnings
19649 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
19651 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
19652 (define-key org-mode-map "\C-e" 'org-end-of-line)
19654 (defun org-backward-sentence (&optional arg)
19655 "Go to beginning of sentence, or beginning of table field.
19656 This will call `backward-sentence' or `org-table-beginning-of-field',
19657 depending on context."
19658 (interactive "P")
19659 (cond
19660 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
19661 (t (call-interactively 'backward-sentence))))
19663 (defun org-forward-sentence (&optional arg)
19664 "Go to end of sentence, or end of table field.
19665 This will call `forward-sentence' or `org-table-end-of-field',
19666 depending on context."
19667 (interactive "P")
19668 (cond
19669 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
19670 (t (call-interactively 'forward-sentence))))
19672 (define-key org-mode-map "\M-a" 'org-backward-sentence)
19673 (define-key org-mode-map "\M-e" 'org-forward-sentence)
19675 (defun org-kill-line (&optional arg)
19676 "Kill line, to tags or end of line."
19677 (interactive "P")
19678 (cond
19679 ((or (not org-special-ctrl-k)
19680 (bolp)
19681 (not (org-on-heading-p)))
19682 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
19683 org-ctrl-k-protect-subtree)
19684 (if (or (eq org-ctrl-k-protect-subtree 'error)
19685 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
19686 (error "C-k aborted - would kill hidden subtree")))
19687 (call-interactively 'kill-line))
19688 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
19689 (kill-region (point) (match-beginning 1))
19690 (org-set-tags nil t))
19691 (t (kill-region (point) (point-at-eol)))))
19693 (define-key org-mode-map "\C-k" 'org-kill-line)
19695 (defun org-yank (&optional arg)
19696 "Yank. If the kill is a subtree, treat it specially.
19697 This command will look at the current kill and check if is a single
19698 subtree, or a series of subtrees[1]. If it passes the test, and if the
19699 cursor is at the beginning of a line or after the stars of a currently
19700 empty headline, then the yank is handled specially. How exactly depends
19701 on the value of the following variables, both set by default.
19703 org-yank-folded-subtrees
19704 When set, the subtree(s) will be folded after insertion, but only
19705 if doing so would now swallow text after the yanked text.
19707 org-yank-adjusted-subtrees
19708 When set, the subtree will be promoted or demoted in order to
19709 fit into the local outline tree structure, which means that the level
19710 will be adjusted so that it becomes the smaller one of the two
19711 *visible* surrounding headings.
19713 Any prefix to this command will cause `yank' to be called directly with
19714 no special treatment. In particular, a simple \\[universal-argument] prefix \
19715 will just
19716 plainly yank the text as it is.
19718 \[1] The test checks if the first non-white line is a heading
19719 and if there are no other headings with fewer stars."
19720 (interactive "P")
19721 (org-yank-generic 'yank arg))
19723 (defun org-yank-generic (command arg)
19724 "Perform some yank-like command.
19726 This function implements the behavior described in the `org-yank'
19727 documentation. However, it has been generalized to work for any
19728 interactive command with similar behavior."
19730 ;; pretend to be command COMMAND
19731 (setq this-command command)
19733 (if arg
19734 (call-interactively command)
19736 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
19737 (and (org-kill-is-subtree-p)
19738 (or (bolp)
19739 (and (looking-at "[ \t]*$")
19740 (string-match
19741 "\\`\\*+\\'"
19742 (buffer-substring (point-at-bol) (point)))))))
19743 swallowp)
19744 (cond
19745 ((and subtreep org-yank-folded-subtrees)
19746 (let ((beg (point))
19747 end)
19748 (if (and subtreep org-yank-adjusted-subtrees)
19749 (org-paste-subtree nil nil 'for-yank)
19750 (call-interactively command))
19752 (setq end (point))
19753 (goto-char beg)
19754 (when (and (bolp) subtreep
19755 (not (setq swallowp
19756 (org-yank-folding-would-swallow-text beg end))))
19757 (or (looking-at outline-regexp)
19758 (re-search-forward (concat "^" outline-regexp) end t))
19759 (while (and (< (point) end) (looking-at outline-regexp))
19760 (hide-subtree)
19761 (org-cycle-show-empty-lines 'folded)
19762 (condition-case nil
19763 (outline-forward-same-level 1)
19764 (error (goto-char end)))))
19765 (when swallowp
19766 (message
19767 "Inserted text not folded because that would swallow text"))
19769 (goto-char end)
19770 (skip-chars-forward " \t\n\r")
19771 (beginning-of-line 1)
19772 (push-mark beg 'nomsg)))
19773 ((and subtreep org-yank-adjusted-subtrees)
19774 (let ((beg (point-at-bol)))
19775 (org-paste-subtree nil nil 'for-yank)
19776 (push-mark beg 'nomsg)))
19778 (call-interactively command))))))
19780 (defun org-yank-folding-would-swallow-text (beg end)
19781 "Would hide-subtree at BEG swallow any text after END?"
19782 (let (level)
19783 (save-excursion
19784 (goto-char beg)
19785 (when (or (looking-at outline-regexp)
19786 (re-search-forward (concat "^" outline-regexp) end t))
19787 (setq level (org-outline-level)))
19788 (goto-char end)
19789 (skip-chars-forward " \t\r\n\v\f")
19790 (if (or (eobp)
19791 (and (bolp) (looking-at org-outline-regexp)
19792 (<= (org-outline-level) level)))
19793 nil ; Nothing would be swallowed
19794 t)))) ; something would swallow
19796 (define-key org-mode-map "\C-y" 'org-yank)
19798 (defun org-truely-invisible-p ()
19799 "Check if point is at a character currently not visible.
19800 This version does not only check the character property, but also
19801 `visible-mode'."
19802 ;; Early versions of noutline don't have `outline-invisible-p'.
19803 (if (org-bound-and-true-p visible-mode)
19805 (outline-invisible-p)))
19807 (defun org-invisible-p2 ()
19808 "Check if point is at a character currently not visible."
19809 (save-excursion
19810 (if (and (eolp) (not (bobp))) (backward-char 1))
19811 ;; Early versions of noutline don't have `outline-invisible-p'.
19812 (outline-invisible-p)))
19814 (defun org-back-to-heading (&optional invisible-ok)
19815 "Call `outline-back-to-heading', but provide a better error message."
19816 (condition-case nil
19817 (outline-back-to-heading invisible-ok)
19818 (error (error "Before first headline at position %d in buffer %s"
19819 (point) (current-buffer)))))
19821 (defun org-beginning-of-defun ()
19822 "Go to the beginning of the subtree, i.e. back to the heading."
19823 (org-back-to-heading))
19824 (defun org-end-of-defun ()
19825 "Go to the end of the subtree."
19826 (org-end-of-subtree nil t))
19828 (defun org-before-first-heading-p ()
19829 "Before first heading?"
19830 (save-excursion
19831 (end-of-line)
19832 (null (re-search-backward "^\\*+ " nil t))))
19834 (defun org-on-heading-p (&optional ignored)
19835 (outline-on-heading-p t))
19836 (defun org-at-heading-p (&optional ignored)
19837 (outline-on-heading-p t))
19839 (defun org-point-at-end-of-empty-headline ()
19840 "If point is at the end of an empty headline, return t, else nil.
19841 If the heading only contains a TODO keyword, it is still still considered
19842 empty."
19843 (and (looking-at "[ \t]*$")
19844 (save-excursion
19845 (beginning-of-line 1)
19846 (let ((case-fold-search nil))
19847 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
19848 "\\)?[ \t]*$"))))))
19849 (defun org-at-heading-or-item-p ()
19850 (or (org-on-heading-p) (org-at-item-p)))
19852 (defun org-on-target-p ()
19853 (or (org-in-regexp org-radio-target-regexp)
19854 (org-in-regexp org-target-regexp)))
19856 (defun org-up-heading-all (arg)
19857 "Move to the heading line of which the present line is a subheading.
19858 This function considers both visible and invisible heading lines.
19859 With argument, move up ARG levels."
19860 (if (fboundp 'outline-up-heading-all)
19861 (outline-up-heading-all arg) ; emacs 21 version of outline.el
19862 (outline-up-heading arg t))) ; emacs 22 version of outline.el
19864 (defun org-up-heading-safe ()
19865 "Move to the heading line of which the present line is a subheading.
19866 This version will not throw an error. It will return the level of the
19867 headline found, or nil if no higher level is found.
19869 Also, this function will be a lot faster than `outline-up-heading',
19870 because it relies on stars being the outline starters. This can really
19871 make a significant difference in outlines with very many siblings."
19872 (let (start-level re)
19873 (org-back-to-heading t)
19874 (setq start-level (funcall outline-level))
19875 (if (equal start-level 1)
19877 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
19878 (if (re-search-backward re nil t)
19879 (funcall outline-level)))))
19881 (defun org-first-sibling-p ()
19882 "Is this heading the first child of its parents?"
19883 (interactive)
19884 (let ((re (concat "^" outline-regexp))
19885 level l)
19886 (unless (org-at-heading-p t)
19887 (error "Not at a heading"))
19888 (setq level (funcall outline-level))
19889 (save-excursion
19890 (if (not (re-search-backward re nil t))
19892 (setq l (funcall outline-level))
19893 (< l level)))))
19895 (defun org-goto-sibling (&optional previous)
19896 "Goto the next sibling, even if it is invisible.
19897 When PREVIOUS is set, go to the previous sibling instead. Returns t
19898 when a sibling was found. When none is found, return nil and don't
19899 move point."
19900 (let ((fun (if previous 're-search-backward 're-search-forward))
19901 (pos (point))
19902 (re (concat "^" outline-regexp))
19903 level l)
19904 (when (condition-case nil (org-back-to-heading t) (error nil))
19905 (setq level (funcall outline-level))
19906 (catch 'exit
19907 (or previous (forward-char 1))
19908 (while (funcall fun re nil t)
19909 (setq l (funcall outline-level))
19910 (when (< l level) (goto-char pos) (throw 'exit nil))
19911 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
19912 (goto-char pos)
19913 nil))))
19915 (defun org-show-siblings ()
19916 "Show all siblings of the current headline."
19917 (save-excursion
19918 (while (org-goto-sibling) (org-flag-heading nil)))
19919 (save-excursion
19920 (while (org-goto-sibling 'previous)
19921 (org-flag-heading nil))))
19923 (defun org-goto-first-child ()
19924 "Goto the first child, even if it is invisible.
19925 Return t when a child was found. Otherwise don't move point and
19926 return nil."
19927 (let (level (pos (point)) (re (concat "^" outline-regexp)))
19928 (when (condition-case nil (org-back-to-heading t) (error nil))
19929 (setq level (outline-level))
19930 (forward-char 1)
19931 (if (and (re-search-forward re nil t) (> (outline-level) level))
19932 (progn (goto-char (match-beginning 0)) t)
19933 (goto-char pos) nil))))
19935 (defun org-show-hidden-entry ()
19936 "Show an entry where even the heading is hidden."
19937 (save-excursion
19938 (org-show-entry)))
19940 (defun org-flag-heading (flag &optional entry)
19941 "Flag the current heading. FLAG non-nil means make invisible.
19942 When ENTRY is non-nil, show the entire entry."
19943 (save-excursion
19944 (org-back-to-heading t)
19945 ;; Check if we should show the entire entry
19946 (if entry
19947 (progn
19948 (org-show-entry)
19949 (save-excursion
19950 (and (outline-next-heading)
19951 (org-flag-heading nil))))
19952 (outline-flag-region (max (point-min) (1- (point)))
19953 (save-excursion (outline-end-of-heading) (point))
19954 flag))))
19956 (defun org-get-next-sibling ()
19957 "Move to next heading of the same level, and return point.
19958 If there is no such heading, return nil.
19959 This is like outline-next-sibling, but invisible headings are ok."
19960 (let ((level (funcall outline-level)))
19961 (outline-next-heading)
19962 (while (and (not (eobp)) (> (funcall outline-level) level))
19963 (outline-next-heading))
19964 (if (or (eobp) (< (funcall outline-level) level))
19966 (point))))
19968 (defun org-get-last-sibling ()
19969 "Move to previous heading of the same level, and return point.
19970 If there is no such heading, return nil."
19971 (let ((opoint (point))
19972 (level (funcall outline-level)))
19973 (outline-previous-heading)
19974 (when (and (/= (point) opoint) (outline-on-heading-p t))
19975 (while (and (> (funcall outline-level) level)
19976 (not (bobp)))
19977 (outline-previous-heading))
19978 (if (< (funcall outline-level) level)
19980 (point)))))
19982 (defun org-end-of-subtree (&optional invisible-OK to-heading)
19983 ;; This contains an exact copy of the original function, but it uses
19984 ;; `org-back-to-heading', to make it work also in invisible
19985 ;; trees. And is uses an invisible-OK argument.
19986 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
19987 ;; Furthermore, when used inside Org, finding the end of a large subtree
19988 ;; with many children and grandchildren etc, this can be much faster
19989 ;; than the outline version.
19990 (org-back-to-heading invisible-OK)
19991 (let ((first t)
19992 (level (funcall outline-level)))
19993 (if (and (org-mode-p) (< level 1000))
19994 ;; A true heading (not a plain list item), in Org-mode
19995 ;; This means we can easily find the end by looking
19996 ;; only for the right number of stars. Using a regexp to do
19997 ;; this is so much faster than using a Lisp loop.
19998 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
19999 (forward-char 1)
20000 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
20001 ;; something else, do it the slow way
20002 (while (and (not (eobp))
20003 (or first (> (funcall outline-level) level)))
20004 (setq first nil)
20005 (outline-next-heading)))
20006 (unless to-heading
20007 (if (memq (preceding-char) '(?\n ?\^M))
20008 (progn
20009 ;; Go to end of line before heading
20010 (forward-char -1)
20011 (if (memq (preceding-char) '(?\n ?\^M))
20012 ;; leave blank line before heading
20013 (forward-char -1))))))
20014 (point))
20016 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
20017 "Use Org version in org-mode, for dramatic speed-up."
20018 (if (org-mode-p)
20019 (progn
20020 (org-end-of-subtree nil t)
20021 (unless (eobp) (backward-char 1)))
20022 ad-do-it))
20024 (defun org-end-of-meta-data-and-drawers ()
20025 "Jump to the first text after meta data and drawers in the current entry.
20026 This will move over empty lines, lines with planning time stamps,
20027 clocking lines, and drawers."
20028 (org-back-to-heading t)
20029 (let ((end (save-excursion (outline-next-heading) (point)))
20030 (re (concat "[ \t]*$"
20031 "\\|"
20032 "\\(" org-drawer-regexp "\\)" ; group 1 are drawers
20033 "\\|"
20034 "\\([ \t]*\\(" org-keyword-time-regexp "\\)\\)")))
20035 (forward-line 1)
20036 (while (looking-at (concat "[ \t]*\\(" org-keyword-time-regexp "\\)"))
20037 (if (not (match-end 1))
20038 ;; empty or planning line
20039 (forward-line 1)
20040 ;; a drawer, find the end
20041 (re-search-forward "^[ \t]*:END:" end 'move)
20042 (forward-line 1)))
20043 (point)))
20045 (defun org-forward-same-level (arg &optional invisible-ok)
20046 "Move forward to the arg'th subheading at same level as this one.
20047 Stop at the first and last subheadings of a superior heading.
20048 Normally this only looks at visible headings, but when INVISIBLE-OK is non-nil
20049 it wil also look at invisible ones."
20050 (interactive "p")
20051 (org-back-to-heading invisible-ok)
20052 (org-on-heading-p)
20053 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20054 (re (format "^\\*\\{1,%d\\} " level))
20056 (forward-char 1)
20057 (while (> arg 0)
20058 (while (and (re-search-forward re nil 'move)
20059 (setq l (- (match-end 0) (match-beginning 0) 1))
20060 (= l level)
20061 (not invisible-ok)
20062 (progn (backward-char 1) (outline-invisible-p)))
20063 (if (< l level) (setq arg 1)))
20064 (setq arg (1- arg)))
20065 (beginning-of-line 1)))
20067 (defun org-backward-same-level (arg &optional invisible-ok)
20068 "Move backward to the arg'th subheading at same level as this one.
20069 Stop at the first and last subheadings of a superior heading."
20070 (interactive "p")
20071 (org-back-to-heading)
20072 (org-on-heading-p)
20073 (let* ((level (- (match-end 0) (match-beginning 0) 1))
20074 (re (format "^\\*\\{1,%d\\} " level))
20076 (while (> arg 0)
20077 (while (and (re-search-backward re nil 'move)
20078 (setq l (- (match-end 0) (match-beginning 0) 1))
20079 (= l level)
20080 (not invisible-ok)
20081 (outline-invisible-p))
20082 (if (< l level) (setq arg 1)))
20083 (setq arg (1- arg)))))
20085 (defun org-show-subtree ()
20086 "Show everything after this heading at deeper levels."
20087 (outline-flag-region
20088 (point)
20089 (save-excursion
20090 (org-end-of-subtree t t))
20091 nil))
20093 (defun org-show-entry ()
20094 "Show the body directly following this heading.
20095 Show the heading too, if it is currently invisible."
20096 (interactive)
20097 (save-excursion
20098 (condition-case nil
20099 (progn
20100 (org-back-to-heading t)
20101 (outline-flag-region
20102 (max (point-min) (1- (point)))
20103 (save-excursion
20104 (if (re-search-forward
20105 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
20106 (match-beginning 1)
20107 (point-max)))
20108 nil)
20109 (org-cycle-hide-drawers 'children))
20110 (error nil))))
20112 (defun org-make-options-regexp (kwds &optional extra)
20113 "Make a regular expression for keyword lines."
20114 (concat
20116 "#?[ \t]*\\+\\("
20117 (mapconcat 'regexp-quote kwds "\\|")
20118 (if extra (concat "\\|" extra))
20119 "\\):[ \t]*"
20120 "\\(.*\\)"))
20122 ;; Make isearch reveal the necessary context
20123 (defun org-isearch-end ()
20124 "Reveal context after isearch exits."
20125 (when isearch-success ; only if search was successful
20126 (if (featurep 'xemacs)
20127 ;; Under XEmacs, the hook is run in the correct place,
20128 ;; we directly show the context.
20129 (org-show-context 'isearch)
20130 ;; In Emacs the hook runs *before* restoring the overlays.
20131 ;; So we have to use a one-time post-command-hook to do this.
20132 ;; (Emacs 22 has a special variable, see function `org-mode')
20133 (unless (and (boundp 'isearch-mode-end-hook-quit)
20134 isearch-mode-end-hook-quit)
20135 ;; Only when the isearch was not quitted.
20136 (org-add-hook 'post-command-hook 'org-isearch-post-command
20137 'append 'local)))))
20139 (defun org-isearch-post-command ()
20140 "Remove self from hook, and show context."
20141 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
20142 (org-show-context 'isearch))
20145 ;;;; Integration with and fixes for other packages
20147 ;;; Imenu support
20149 (defvar org-imenu-markers nil
20150 "All markers currently used by Imenu.")
20151 (make-variable-buffer-local 'org-imenu-markers)
20153 (defun org-imenu-new-marker (&optional pos)
20154 "Return a new marker for use by Imenu, and remember the marker."
20155 (let ((m (make-marker)))
20156 (move-marker m (or pos (point)))
20157 (push m org-imenu-markers)
20160 (defun org-imenu-get-tree ()
20161 "Produce the index for Imenu."
20162 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
20163 (setq org-imenu-markers nil)
20164 (let* ((n org-imenu-depth)
20165 (re (concat "^" outline-regexp))
20166 (subs (make-vector (1+ n) nil))
20167 (last-level 0)
20168 m level head)
20169 (save-excursion
20170 (save-restriction
20171 (widen)
20172 (goto-char (point-max))
20173 (while (re-search-backward re nil t)
20174 (setq level (org-reduced-level (funcall outline-level)))
20175 (when (<= level n)
20176 (looking-at org-complex-heading-regexp)
20177 (setq head (org-link-display-format
20178 (org-match-string-no-properties 4))
20179 m (org-imenu-new-marker))
20180 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
20181 (if (>= level last-level)
20182 (push (cons head m) (aref subs level))
20183 (push (cons head (aref subs (1+ level))) (aref subs level))
20184 (loop for i from (1+ level) to n do (aset subs i nil)))
20185 (setq last-level level)))))
20186 (aref subs 1)))
20188 (eval-after-load "imenu"
20189 '(progn
20190 (add-hook 'imenu-after-jump-hook
20191 (lambda ()
20192 (if (org-mode-p)
20193 (org-show-context 'org-goto))))))
20195 (defun org-link-display-format (link)
20196 "Replace a link with either the description, or the link target
20197 if no description is present"
20198 (save-match-data
20199 (if (string-match org-bracket-link-analytic-regexp link)
20200 (replace-match (if (match-end 5)
20201 (match-string 5 link)
20202 (concat (match-string 1 link)
20203 (match-string 3 link)))
20204 nil t link)
20205 link)))
20207 ;; Speedbar support
20209 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
20210 "Overlay marking the agenda restriction line in speedbar.")
20211 (overlay-put org-speedbar-restriction-lock-overlay
20212 'face 'org-agenda-restriction-lock)
20213 (overlay-put org-speedbar-restriction-lock-overlay
20214 'help-echo "Agendas are currently limited to this item.")
20215 (org-detach-overlay org-speedbar-restriction-lock-overlay)
20217 (defun org-speedbar-set-agenda-restriction ()
20218 "Restrict future agenda commands to the location at point in speedbar.
20219 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
20220 (interactive)
20221 (require 'org-agenda)
20222 (let (p m tp np dir txt)
20223 (cond
20224 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20225 'org-imenu t))
20226 (setq m (get-text-property p 'org-imenu-marker))
20227 (with-current-buffer (marker-buffer m)
20228 (goto-char m)
20229 (org-agenda-set-restriction-lock 'subtree)))
20230 ((setq p (text-property-any (point-at-bol) (point-at-eol)
20231 'speedbar-function 'speedbar-find-file))
20232 (setq tp (previous-single-property-change
20233 (1+ p) 'speedbar-function)
20234 np (next-single-property-change
20235 tp 'speedbar-function)
20236 dir (speedbar-line-directory)
20237 txt (buffer-substring-no-properties (or tp (point-min))
20238 (or np (point-max))))
20239 (with-current-buffer (find-file-noselect
20240 (let ((default-directory dir))
20241 (expand-file-name txt)))
20242 (unless (org-mode-p)
20243 (error "Cannot restrict to non-Org-mode file"))
20244 (org-agenda-set-restriction-lock 'file)))
20245 (t (error "Don't know how to restrict Org-mode's agenda")))
20246 (move-overlay org-speedbar-restriction-lock-overlay
20247 (point-at-bol) (point-at-eol))
20248 (setq current-prefix-arg nil)
20249 (org-agenda-maybe-redo)))
20251 (eval-after-load "speedbar"
20252 '(progn
20253 (speedbar-add-supported-extension ".org")
20254 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
20255 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
20256 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
20257 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
20258 (add-hook 'speedbar-visiting-tag-hook
20259 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
20261 ;;; Fixes and Hacks for problems with other packages
20263 ;; Make flyspell not check words in links, to not mess up our keymap
20264 (defun org-mode-flyspell-verify ()
20265 "Don't let flyspell put overlays at active buttons, or on
20266 {todo,all-time,additional-option-like}-keywords."
20267 (let ((pos (max (1- (point)) (point-min)))
20268 (word (thing-at-point 'word)))
20269 (and (not (get-text-property pos 'keymap))
20270 (not (get-text-property pos 'org-no-flyspell))
20271 (not (member word org-todo-keywords-1))
20272 (not (member word org-all-time-keywords))
20273 (not (member word org-additional-option-like-keywords)))))
20275 (defun org-remove-flyspell-overlays-in (beg end)
20276 "Remove flyspell overlays in region."
20277 (and (org-bound-and-true-p flyspell-mode)
20278 (fboundp 'flyspell-delete-region-overlays)
20279 (flyspell-delete-region-overlays beg end))
20280 (add-text-properties beg end '(org-no-flyspell t)))
20282 ;; Make `bookmark-jump' shows the jump location if it was hidden.
20283 (eval-after-load "bookmark"
20284 '(if (boundp 'bookmark-after-jump-hook)
20285 ;; We can use the hook
20286 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
20287 ;; Hook not available, use advice
20288 (defadvice bookmark-jump (after org-make-visible activate)
20289 "Make the position visible."
20290 (org-bookmark-jump-unhide))))
20292 ;; Make sure saveplace shows the location if it was hidden
20293 (eval-after-load "saveplace"
20294 '(defadvice save-place-find-file-hook (after org-make-visible activate)
20295 "Make the position visible."
20296 (org-bookmark-jump-unhide)))
20298 ;; Make sure ecb shows the location if it was hidden
20299 (eval-after-load "ecb"
20300 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
20301 "Make hierarchy visible when jumping into location from ECB tree buffer."
20302 (if (org-mode-p)
20303 (org-show-context))))
20305 (defun org-bookmark-jump-unhide ()
20306 "Unhide the current position, to show the bookmark location."
20307 (and (org-mode-p)
20308 (or (outline-invisible-p)
20309 (save-excursion (goto-char (max (point-min) (1- (point))))
20310 (outline-invisible-p)))
20311 (org-show-context 'bookmark-jump)))
20313 ;; Make session.el ignore our circular variable
20314 (eval-after-load "session"
20315 '(add-to-list 'session-globals-exclude 'org-mark-ring))
20317 ;;;; Experimental code
20319 (defun org-closed-in-range ()
20320 "Sparse tree of items closed in a certain time range.
20321 Still experimental, may disappear in the future."
20322 (interactive)
20323 ;; Get the time interval from the user.
20324 (let* ((time1 (org-float-time
20325 (org-read-date nil 'to-time nil "Starting date: ")))
20326 (time2 (org-float-time
20327 (org-read-date nil 'to-time nil "End date:")))
20328 ;; callback function
20329 (callback (lambda ()
20330 (let ((time
20331 (org-float-time
20332 (apply 'encode-time
20333 (org-parse-time-string
20334 (match-string 1))))))
20335 ;; check if time in interval
20336 (and (>= time time1) (<= time time2))))))
20337 ;; make tree, check each match with the callback
20338 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
20340 ;;;; Finish up
20342 (provide 'org)
20344 (run-hooks 'org-load-hook)
20346 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
20348 ;;; org.el ends here